text:
package org.apache.beam.fn.harness;

import static org.apache.beam.sdk.util.WindowedValue.valueInGlobalWindow;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.beam.fn.harness.MapFnRunners.ValueMapFnFactory;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.model.pipeline.v1.RunnerApi.PTransform;
import org.apache.beam.runners.core.construction.CoderTranslation;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.function.ThrowingFunction;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.transforms.windowing.IntervalWindow;
import org.apache.beam.sdk.transforms.windowing.PaneInfo;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link MapFnRunners}. */
@RunWith(JUnit4.class)
public class MapFnRunnersTest {
  private static final String EXPECTED_ID = "pTransformId";
  private static final RunnerApi.PTransform EXPECTED_PTRANSFORM =
      RunnerApi.PTransform.newBuilder()
          .putInputs("input", "inputPC")
          .putOutputs("output", "outputPC")
          .build();
  private static final RunnerApi.PCollection INPUT_PCOLLECTION =
      RunnerApi.PCollection.newBuilder().setUniqueName("inputPC").setCoderId("coder-id").build();
  private static RunnerApi.Coder valueCoder;

  static {
    try {
      valueCoder = CoderTranslation.toProto(StringUtf8Coder.of()).getCoder();
    } catch (IOException e) {
      throw new ExceptionInInitializerError(e);
    }
  }

  @Test
  public void testValueOnlyMapping() throws Exception {
    PTransformRunnerFactoryTestContext context =
        PTransformRunnerFactoryTestContext.builder(EXPECTED_ID, EXPECTED_PTRANSFORM)
            .processBundleInstructionId("57")
            .pCollections(Collections.singletonMap("inputPC", INPUT_PCOLLECTION))
            .coders(Collections.singletonMap("coder-id", valueCoder))
            .build();
    List<WindowedValue<?>> outputConsumer = new ArrayList<>();
    context.addPCollectionConsumer("outputPC", outputConsumer::add, StringUtf8Coder.of());

    ValueMapFnFactory<String, String> factory = (ptId, pt) -> String::toUpperCase;
    MapFnRunners.forValueMapFnFactory(factory).createRunnerForPTransform(context);

    assertThat(context.getStartBundleFunctions(), empty());
    assertThat(context.getFinishBundleFunctions(), empty());
    assertThat(context.getTearDownFunctions(), empty());

    assertThat(
        context.getPCollectionConsumers().keySet(), containsInAnyOrder("inputPC", "outputPC"));

    context.getPCollectionConsumer("inputPC").accept(valueInGlobalWindow("abc"));

    assertThat(outputConsumer, contains(valueInGlobalWindow("ABC")));
  }

  @Test
  public void testFullWindowedValueMapping() throws Exception {
    PTransformRunnerFactoryTestContext context =
        PTransformRunnerFactoryTestContext.builder(EXPECTED_ID, EXPECTED_PTRANSFORM)
            .processBundleInstructionId("57")
            .pCollections(Collections.singletonMap("inputPC", INPUT_PCOLLECTION))
            .coders(Collections.singletonMap("coder-id", valueCoder))
            .build();
    List<WindowedValue<?>> outputConsumer = new ArrayList<>();
    context.addPCollectionConsumer("outputPC", outputConsumer::add, StringUtf8Coder.of());
    MapFnRunners.forWindowedValueMapFnFactory(this::createMapFunctionForPTransform)
        .createRunnerForPTransform(context);

    assertThat(context.getStartBundleFunctions(), empty());
    assertThat(context.getFinishBundleFunctions(), empty());
    assertThat(context.getTearDownFunctions(), empty());

    assertThat(
        context.getPCollectionConsumers().keySet(), containsInAnyOrder("inputPC", "outputPC"));

    context.getPCollectionConsumer("inputPC").accept(valueInGlobalWindow("abc"));

    assertThat(outputConsumer, contains(valueInGlobalWindow("ABC")));
  }

  @Test
  public void testFullWindowedValueMappingWithCompressedWindow() throws Exception {
    PTransformRunnerFactoryTestContext context =
        PTransformRunnerFactoryTestContext.builder(EXPECTED_ID, EXPECTED_PTRANSFORM)
            .processBundleInstructionId("57")
            .pCollections(Collections.singletonMap("inputPC", INPUT_PCOLLECTION))
            .coders(Collections.singletonMap("coder-id", valueCoder))
            .build();
    List<WindowedValue<?>> outputConsumer = new ArrayList<>();
    context.addPCollectionConsumer("outputPC", outputConsumer::add, StringUtf8Coder.of());

    MapFnRunners.forWindowedValueMapFnFactory(this::createMapFunctionForPTransform)
        .createRunnerForPTransform(context);

    assertThat(context.getStartBundleFunctions(), empty());
    assertThat(context.getFinishBundleFunctions(), empty());
    assertThat(context.getTearDownFunctions(), empty());

    assertThat(
        context.getPCollectionConsumers().keySet(), containsInAnyOrder("inputPC", "outputPC"));

    IntervalWindow firstWindow = new IntervalWindow(new Instant(0L), Duration.standardMinutes(10L));
    IntervalWindow secondWindow =
        new IntervalWindow(new Instant(-10L), Duration.standardSeconds(22L));
    context
        .getPCollectionConsumer("inputPC")
        .accept(
            WindowedValue.of(
                "abc",
                new Instant(12),
                ImmutableSet.of(firstWindow, GlobalWindow.INSTANCE, secondWindow),
                PaneInfo.NO_FIRING));

    assertThat(
        outputConsumer,
        containsInAnyOrder(
            WindowedValue.timestampedValueInGlobalWindow("ABC", new Instant(12)),
            WindowedValue.of("ABC", new Instant(12), secondWindow, PaneInfo.NO_FIRING),
            WindowedValue.of("ABC", new Instant(12), firstWindow, PaneInfo.NO_FIRING)));
  }

  public ThrowingFunction<WindowedValue<String>, WindowedValue<String>>
      createMapFunctionForPTransform(String ptransformId, PTransform pTransform) {
    assertEquals(EXPECTED_ID, ptransformId);
    assertEquals(EXPECTED_PTRANSFORM, pTransform);
    return (WindowedValue<String> str) -> str.withValue(str.getValue().toUpperCase());
  }
}


text:
Changes by Version
==================
Release Notes.

8.8.0
------------------

#### Project

* Split javaagent into skywalking-java repository. https://github.com/apache/skywalking-java
* Merge `Dockerfile`s from apache/skywalking-docker into this codebase.

#### OAP Server

* Fix CVE-2021-35515, CVE-2021-35516, CVE-2021-35517, CVE-2021-36090. Upgrade org.apache.commons:commons-compress to
  1.21.
* kubernetes java client upgrade from 12.0.1 to 13.0.0
* Add `event` http receiver
* Support Metric level function `serviceRelation` in `MAL`.
* Support envoy metrics binding into the topology.
* Fix openapi-definitions folder not being read correctly.
* Trace segment wouldn't be recognized as a TopN sample service. Add through #4694 experimentally, but it caused
  performance impact.
* Remove `version` and `endTime` in the segment entity. Reduce indexing payload.
* Fix `mapper_parsing_exception` in ElasticSearch 7.14.
* Support component IDs for Go-Kratos framework.
* [Break Change] Remove endpoint name in the trace query condition. Only support `query by endpoint id`.
* Fix `ProfileSnapshotExporterTest` case on `OpenJDK Runtime Environment AdoptOpenJDK-11.0.11+9 (build 11.0.11+9)`,
  MacOS.
* [Break Change] Remove page path in the browser log query condition. Only support `query by page path id`.
* [Break Change] Remove endpoint name in the backend log query condition. Only support `query by endpoint id`.
* [Break Change] Fix typo for a column `page_path_id`(was `pate_path_id`) of storage entity `browser_error_log`.
* Add component id for Python falcon plugin.
* Add `rpcStatusCode` for `rpc.status_code` tag. The `responseCode` field is marked as deprecated and replaced by `httpResponseStatusCode` field.
* Remove the duplicated tags to reduce the storage payload.
* Add a new API to test log analysis language.
* Harden the security of Groovy-based DSL, MAL and LAL.
* Fix distinct in Service/Instance/Endpoint query is not working.
* Support collection type in dynamic configuration core.
* Support zookeeper grouped dynamic configurations.
* Fix NPE when OAP nodes synchronize events with each other in cluster mode.
* Support k8s configmap grouped dynamic configurations.
* Add desc sort function in H2 and ElasticSearch implementations of IBrowserLogQueryDAO
* Support configure sampling policy by `configuration module` dynamically and static configuration
  file `trace-sampling-policy-settings.yml` for service dimension on the backend side. Dynamic
  configurations `agent-analyzer.default.sampleRate` and `agent-analyzer.default.slowTraceSegmentThreshold` are replaced
  by `agent-analyzer.default.traceSamplingPolicy`. Static configurations `agent-analyzer.default.sampleRate`
  and `agent-analyzer.default.slowTraceSegmentThreshold` are replaced
  by `agent-analyzer.default.traceSamplingPolicySettingsFile`.
* Fix dynamic configuration watch implementation current value not null when the config is deleted.
* Fix `LoggingConfigWatcher` return `watch.value` would not consistent with the real configuration content.
* Fix `ZookeeperConfigWatcherRegister.readConfig()` could cause `NPE` when `data.getData()` is null.
* Support nacos grouped dynamic configurations.
* Support for filter function filtering of int type values.
* Support mTLS for gRPC channel.
* Add yaml file suffix limit when reading ui templates.
* Support consul grouped dynamic configurations.
* Fix `H2MetadataQueryDAO.searchService` doesn't support auto grouping.
* Rebuilt ElasticSearch client on top of their REST API.
* Fix ElasticSearch storage plugin doesn't work when hot reloading from `secretsManagementFile`.
* Support etcd grouped dynamic configurations.
* Unified the config word `namespace` in the project.
* Switch JRE base image for dev images.
* Support apollo grouped dynamic configurations.
* Fix `ProfileThreadSnapshotQuery.queryProfiledSegments` adopts a wrong sort function
* Support gRPC sync grouped dynamic configurations.

#### UI

* Fix not found error when refresh UI.
* Update endpointName to endpointId in the query trace condition.
* Add Python falcon icon on the UI.
* Fix searching endpoints with keywords.
* Support clicking the service name in the chart to link to the trace or log page.
* Implement the Log Analysis Language text regexp debugger.
* Fix fetching nodes and calls with serviceIds on the topology side.

#### Documentation

* Add a section in `Log Collecting And Analysis` doc, introducing the new Python agent log reporter.
* Add one missing step in `otel-receiver` doc about how to activate the default receiver.
* Reorganize dynamic configuration doc.
* Add more description about meter configurations in `backend-meter` doc.

All issues and pull requests are [here](https://github.com/apache/skywalking/milestone/96?closed=1)

------------------
Find change logs of all versions [here](changes).

redpajama_set_name: RedPajamaGithub


text:
package ylabs.play.common.services

import javax.inject.{Inject, Singleton}

import com.typesafe.config.ConfigFactory
import springnz.util.Logging
import ylabs.play.common.dal.UserRepository
import ylabs.play.common.models.Notify.Notify
import ylabs.play.common.models.User.Phone
import ylabs.play.common.models.{PushNotification, Sms}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Random

@Singleton
class NotifyService @Inject() (repoUser: UserRepository, pushService: PushNotificationService, smsService: SmsService)(implicit ec: ExecutionContext) extends Logging {
  lazy val config = ConfigFactory.load()

  def notify(phone: Phone, notify: Notify, smsFallback: Boolean = false): Future[Unit] = {
    repoUser.getFromPhone(phone) map {
      case Some(user) if user.deviceEndpoint.isDefined && user.deviceEndpoint.get.value.nonEmpty ⇒
        val notifId = notify.notificationId.getOrElse(PushNotification.Id(Random.nextInt(Int.MaxValue)))
        val notif = PushNotification.Notification(
          user.deviceEndpoint.get,
          PushNotification.Id(notifId.value),
          PushNotification.Name(notify.name.value),
          PushNotification.Title(notify.title.value),
          PushNotification.Text(notify.text.value),
          PushNotification.Link(notify.link.map(_.value).getOrElse("")),
          PushNotification.LinkName(notify.linkName.map(_.value).getOrElse("")),
          notify.formattedMessage.map(f => PushNotification.FormattedMessage(f.value)))
        pushService.publish(notif)
        log.debug(s"push notification sent to $phone via ${user.deviceEndpoint.get}")
      case Some(user) if smsFallback ⇒
        val text = notify.formattedMessage match {
          case Some(t) => Sms.Text(t.value)
          case _ => smsService.format(notify.text, notify.title)
        }
        smsService.send(Phone(phone.value), text)
        log.debug(s"sms sent to $phone")
      case None ⇒
        log.error(s"notify failed as the user does not exist ($phone)")
      case user ⇒
        log.info(s"doing nothing for $notify and $user")
    }
  }
}


text:
package org.knowhowlab.configvalidator.service.internal.helpers;

import org.knowhowlab.configvalidator.api.annotations.ConfigurationClass;

/**
 * @author dpishchukhin
 */
@ConfigurationClass("test")
public @interface SimpleConfiguration2 {
}


text:
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.nguage governing permissions and
// limitations under the License.
// /////////////////////////////////////////////////////////////////////////

define([
  'dojo/_base/declare',
  'dojo/_base/lang',
  'jimu/BaseWidget'
],
  function(
    declare,
    lang,
    BaseWidget) {
    var clazz = declare([BaseWidget], {
      baseClass: 'jimu-widget-customcss',
      name: 'CustomCSS',
      styleTag: null,

      startup: function() {
        var css = this.config.css;

        if (this.styleTag) {
          this.styleTag.innerText = css;
        } else {
          this.styleTag = document.createElement('style');
          this.styleTag.type = 'text/css';
          this.styleTag.appendChild(document.createTextNode(css));
          document.head.appendChild(this.styleTag);
        }
      },

      destroy: function destroyCustomCSSWidget() {
        this.styleTag.parentNode.removeChild(this.styleTag);
        this.inherited(arguments);
      }

    });

    return clazz;
  });


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// 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.

package com.google.devtools.build.lib.bazel.rules.android;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;

import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.packages.BuildFileNotFoundException;
import com.google.devtools.build.lib.packages.util.ResourceLoader;
import com.google.devtools.build.lib.rules.android.AndroidSdkProvider;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link AndroidSdkRepositoryFunction}. */
@RunWith(JUnit4.class)
public class AndroidSdkRepositoryTest extends BuildViewTestCase {
  @Before
  public void setup() throws Exception {
    scratch.file(
        "/bazel_tools_workspace/tools/android/android_sdk_repository_template.bzl",
        ResourceLoader.readFromResources("tools/android/android_sdk_repository_template.bzl"));
  }

  private void scratchPlatformsDirectories(int... apiLevels) throws Exception {
    for (int apiLevel : apiLevels) {
      scratch.dir("/sdk/platforms/android-" + apiLevel);
      scratch.file("/sdk/platforms/android-" + apiLevel + "/android.jar");
    }
  }

  private void scratchSystemImagesDirectories(String... pathFragments) throws Exception {
    for (String pathFragment : pathFragments) {
      scratch.dir("/sdk/system-images/" + pathFragment);
      scratch.file("/sdk/system-images/" + pathFragment + "/system.img");
    }
  }

  private void scratchBuildToolsDirectories(String... versions) throws Exception {
    for (String version : versions) {
      scratch.dir("/sdk/build-tools/" + version);
    }
  }

  private void scratchExtrasLibrary(
      String mavenRepoPath, String groupId, String artifactId, String version, String packaging)
      throws Exception {
    scratch.file(
        String.format(
            "/sdk/%s/%s/%s/%s/%s.pom",
            mavenRepoPath,
            groupId.replace(".", "/"),
            artifactId,
            version,
            artifactId),
        "<project>",
        "  <groupId>" + groupId + "</groupId>",
        "  <artifactId>" + artifactId + "</artifactId>",
        "  <version>" + version + "</version>",
        "  <packaging>" + packaging + "</packaging>",
        "</project>");
  }

  @Test
  public void testGeneratedAarImport() throws Exception {
    scratchPlatformsDirectories(25);
    scratchBuildToolsDirectories("26.0.1");
    scratchExtrasLibrary("extras/google/m2repository", "com.google.android", "foo", "1.0.0", "aar");
    FileSystemUtils.appendIsoLatin1(scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        ")");
    invalidatePackages();

    ConfiguredTarget aarImportTarget =
        getConfiguredTarget("@androidsdk//com.google.android:foo-1.0.0");
    assertThat(aarImportTarget).isNotNull();
    assertThat(aarImportTarget.getTarget().getAssociatedRule().getRuleClass())
        .isEqualTo("aar_import");
  }

  @Test
  public void testExportsExtrasLibraryArtifacts() throws Exception {
    scratchPlatformsDirectories(25);
    scratchBuildToolsDirectories("26.0.1");
    scratchExtrasLibrary("extras/google/m2repository", "com.google.android", "foo", "1.0.0", "aar");
    FileSystemUtils.appendIsoLatin1(scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        ")");
    invalidatePackages();

    ConfiguredTarget aarTarget = getConfiguredTarget(
        "@androidsdk//:extras/google/m2repository/com/google/android/foo/1.0.0/foo.aar");
    assertThat(aarTarget).isNotNull();
  }

  @Test
  public void testKnownSdkMavenRepositories() throws Exception {
    scratchPlatformsDirectories(25);
    scratchBuildToolsDirectories("26.0.1");
    scratchExtrasLibrary("extras/google/m2repository", "com.google.android", "a", "1.0.0", "jar");
    scratchExtrasLibrary("extras/android/m2repository", "com.android.support", "b", "1.0.0", "aar");
    scratchExtrasLibrary("extras/m2repository", "com.android.support", "c", "1.0.1", "aar");
    FileSystemUtils.appendIsoLatin1(scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        ")");
    invalidatePackages();

    assertThat(
            getConfiguredTarget(
                "@androidsdk//:extras/google/m2repository/com/google/android/a/1.0.0/a.jar"))
        .isNotNull();
    assertThat(
            getConfiguredTarget(
                "@androidsdk//:extras/android/m2repository/com/android/support/b/1.0.0/b.aar"))
        .isNotNull();
    assertThat(
            getConfiguredTarget(
                "@androidsdk//:extras/m2repository/com/android/support/c/1.0.1/c.aar"))
        .isNotNull();
  }

  @Test
  public void testSystemImageDirectoriesAreFound() throws Exception {
    scratchPlatformsDirectories(25);
    scratchBuildToolsDirectories("26.0.1");
    FileSystemUtils.appendIsoLatin1(scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        ")");
    scratchSystemImagesDirectories("android-25/default/armeabi-v7a", "android-24/google_apis/x86");
    invalidatePackages();

    ConfiguredTarget android25ArmFilegroup =
        getConfiguredTarget("@androidsdk//:emulator_images_android_25_arm");
    assertThat(android25ArmFilegroup).isNotNull();
    assertThat(
        artifactsToStrings(
            android25ArmFilegroup.getProvider(FilesToRunProvider.class).getFilesToRun()))
        .containsExactly(
            "src external/androidsdk/system-images/android-25/default/armeabi-v7a/system.img");

    ConfiguredTarget android24X86Filegroup =
        getConfiguredTarget("@androidsdk//:emulator_images_google_24_x86");
    assertThat(android24X86Filegroup).isNotNull();
    assertThat(
        artifactsToStrings(
            android24X86Filegroup.getProvider(FilesToRunProvider.class).getFilesToRun()))
        .containsExactly(
            "src external/androidsdk/system-images/android-24/google_apis/x86/system.img");
  }

  // Regression test for https://github.com/bazelbuild/bazel/issues/3672.
  @Test
  public void testMalformedSystemImageDirectories() throws Exception {
    scratchPlatformsDirectories(25, 26);
    scratchBuildToolsDirectories("26.0.1");
    scratchSystemImagesDirectories("android-25/default/armeabi-v7a", "android-O/google_apis/x86");
    FileSystemUtils.appendIsoLatin1(scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        ")");
    invalidatePackages();
    assertThat(getConfiguredTarget("@androidsdk//:emulator_images_android_25_arm")).isNotNull();
  }

  @Test
  public void testBuildToolsHighestVersionDetection() throws Exception {
    scratchPlatformsDirectories(25);
    scratchBuildToolsDirectories("26.0.1", "26.0.2");
    FileSystemUtils.appendIsoLatin1(
        scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        "    api_level = 25,",
        ")");
    invalidatePackages();

    ConfiguredTarget androidSdk = getConfiguredTarget("@androidsdk//:sdk");
    assertThat(androidSdk).isNotNull();
    assertThat(androidSdk.getProvider(AndroidSdkProvider.class).getBuildToolsVersion())
        .isEqualTo("26.0.2");
  }

  @Test
  public void testApiLevelHighestVersionDetection() throws Exception {
    scratchPlatformsDirectories(24, 25, 23);
    scratchBuildToolsDirectories("26.0.1");
    FileSystemUtils.appendIsoLatin1(
        scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        "    build_tools_version = '26.0.1',",
        ")");
    invalidatePackages();

    ConfiguredTarget androidSdk = getConfiguredTarget("@androidsdk//:sdk");
    assertThat(androidSdk).isNotNull();
    assertThat(androidSdk.getProvider(AndroidSdkProvider.class).getAndroidJar().getExecPathString())
        .isEqualTo("external/androidsdk/platforms/android-25/android.jar");
  }

  @Test
  public void testMultipleAndroidSdkApiLevels() throws Exception {
    int[] apiLevels = {23, 24, 25};
    scratchPlatformsDirectories(apiLevels);
    scratchBuildToolsDirectories("26.0.1");
    FileSystemUtils.appendIsoLatin1(
        scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        "    api_level = 24,",
        "    build_tools_version = '26.0.1',",
        ")");
    invalidatePackages();

    for (int apiLevel : apiLevels) {
      ConfiguredTarget androidSdk = getConfiguredTarget("@androidsdk//:sdk-" + apiLevel);
      assertThat(androidSdk).isNotNull();
      assertThat(
          androidSdk.getProvider(AndroidSdkProvider.class).getAndroidJar().getExecPathString())
          .isEqualTo(
              String.format("external/androidsdk/platforms/android-%d/android.jar", apiLevel));
    }
  }

  @Test
  public void testMissingApiLevel() throws Exception {
    scratchPlatformsDirectories(24);
    scratchBuildToolsDirectories("26.0.1");
    FileSystemUtils.appendIsoLatin1(
        scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        "    api_level = 25,",
        "    build_tools_version = '26.0.1',",
        ")");
    invalidatePackages();

    try {
      getTarget("@androidsdk//:files");
      fail("android_sdk_repository should have failed due to missing SDK api level.");
    } catch (BuildFileNotFoundException e) {
      assertThat(e.getMessage())
          .contains(
              "Android SDK api level 25 was requested but it is not installed in the Android SDK "
                  + "at /sdk. The api levels found were [24]. Please choose an available api level "
                  + "or install api level 25 from the Android SDK Manager.");
    }
  }

  // Regression test for https://github.com/bazelbuild/bazel/issues/2739.
  @Test
  public void testFilesInSystemImagesDirectories() throws Exception {
    scratchPlatformsDirectories(24);
    scratchBuildToolsDirectories("26.0.1");
    scratch.file("/sdk/system-images/.DS_Store");
    FileSystemUtils.appendIsoLatin1(scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        ")");
    invalidatePackages();

    assertThat(getConfiguredTarget("@androidsdk//:sdk")).isNotNull();
  }

  @Test
  public void testMissingPlatformsDirectory() throws Exception {
    scratchBuildToolsDirectories("26.0.1");
    FileSystemUtils.appendIsoLatin1(
        scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        ")");
    invalidatePackages();

    try {
      getTarget("@androidsdk//:files");
      fail("android_sdk_repository should have failed due to missing SDK platforms dir.");
    } catch (BuildFileNotFoundException e) {
      assertThat(e.getMessage())
          .contains("Expected directory at /sdk/platforms but it is not a directory or it does "
              + "not exist.");
    }
  }

  @Test
  public void testMissingBuildToolsDirectory() throws Exception {
    scratchPlatformsDirectories(24);
    FileSystemUtils.appendIsoLatin1(
        scratch.resolve("WORKSPACE"),
        "local_repository(name = 'bazel_tools', path = '/bazel_tools_workspace')",
        "android_sdk_repository(",
        "    name = 'androidsdk',",
        "    path = '/sdk',",
        ")");
    invalidatePackages();

    try {
      getTarget("@androidsdk//:files");
      fail("android_sdk_repository should have failed due to missing SDK build tools dir.");
    } catch (BuildFileNotFoundException e) {
      assertThat(e.getMessage())
          .contains("Expected directory at /sdk/build-tools but it is not a directory or it does "
              + "not exist.");
    }
  }
}


text:
using System.Collections.Generic;
using Enigma.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Enigma.Test.Serialization.Fakes
{
    public class ReadStatistics : IReadStatistics
    {

        private readonly List<VisitArgs> _visitedArgs;

        public int VisitCount { get; set; }
        public int LeaveCount { get; set; }
        public int ExpectedLeaveCount { get; set; }

        public int VisitByteCount { get; set; }
        public int VisitInt16Count { get; set; }
        public int VisitInt32Count { get; set; }
        public int VisitInt64Count { get; set; }
        public int VisitUInt16Count { get; set; }
        public int VisitUInt32Count { get; set; }
        public int VisitUInt64Count { get; set; }
        public int VisitBooleanCount { get; set; }
        public int VisitSingleCount { get; set; }
        public int VisitDoubleCount { get; set; }
        public int VisitDecimalCount { get; set; }
        public int VisitTimeSpanCount { get; set; }
        public int VisitDateTimeCount { get; set; }
        public int VisitStringCount { get; set; }
        public int VisitGuidCount { get; set; }
        public int VisitBlobCount { get; set; }

        public ReadStatistics()
        {
            _visitedArgs = new List<VisitArgs>();
        }

        public int VisitValueCount
        {
            get
            {
                return VisitByteCount
                       + VisitInt16Count + VisitInt32Count + VisitInt64Count
                       + VisitUInt16Count + VisitUInt32Count + VisitUInt64Count
                       + VisitBooleanCount + VisitSingleCount + VisitDoubleCount
                       + VisitDecimalCount + VisitTimeSpanCount + VisitDateTimeCount
                       + VisitStringCount + VisitGuidCount + VisitBlobCount;
            }
        }

        public void AckVisited(VisitArgs args)
        {
            _visitedArgs.Add(args);
        }

        public void AssertHiearchy()
        {
            Assert.AreEqual(ExpectedLeaveCount, LeaveCount);
        }

        public void AssertVisitOrderExact(params LevelType[] expectedLevels)
        {
            Assert.AreEqual(expectedLevels.Length, _visitedArgs.Count, "Visited args count is not equal the expected count");
            AssertVisitOrderBeginsWith(expectedLevels);
        }

        public void AssertVisitOrderBeginsWith(params LevelType[] expectedLevels)
        {
            Assert.IsTrue(expectedLevels.Length <= _visitedArgs.Count, "Visited args count is lesser than the expected count");
            for (var i = 0; i < expectedLevels.Length; i++) {
                var args = _visitedArgs[i];
                var expectedLevel = expectedLevels[i];
                Assert.AreEqual(expectedLevel, args.Type);
            }
        }

    }
}


text:
package com.github.tminglei.slickpg

import java.sql.{Date, Timestamp}
import slick.jdbc.{JdbcType, PositionedResult, PostgresProfile}
import scala.reflect.classTag

// edge type definitions
sealed trait EdgeType
case object `[_,_)` extends EdgeType
case object `(_,_]` extends EdgeType
case object `(_,_)` extends EdgeType
case object `[_,_]` extends EdgeType
case object `empty` extends EdgeType

import PgRangeSupportUtils._

case class Range[T](start: Option[T], end: Option[T], edge: EdgeType) {

  def as[A](convert: (T => A)): Range[A] = {
    new Range[A](start.map(convert), end.map(convert), edge)
  }

  override def toString = edge match {
    case `[_,_)` => s"[${oToString(start)},${oToString(end)})"
    case `(_,_]` => s"(${oToString(start)},${oToString(end)}]"
    case `(_,_)` => s"(${oToString(start)},${oToString(end)})"
    case `[_,_]` => s"[${oToString(start)},${oToString(end)}]"
    case `empty` => Range.empty_str
  }
}

object Range {
  def emptyRange[T]: Range[T] = Range[T](None, None, `empty`)
  val empty_str = "empty"

  def apply[T](start: T, end: T, edge: EdgeType = `[_,_)`): Range[T] = Range(Some(start), Some(end), edge)
}

/**
 * simple range support; if all you want is just getting from / saving to db, and using pg range operations/methods, it should be enough
 */
trait PgRangeSupport extends range.PgRangeExtensions with utils.PgCommonJdbcTypes { driver: PostgresProfile =>
  import driver.api._

  private def toTimestamp(str: String) = Timestamp.valueOf(str)
  private def toSQLDate(str: String) = Date.valueOf(str)

  trait SimpleRangeCodeGenSupport {
    // register types to let `ExModelBuilder` find them
    if (driver.isInstanceOf[ExPostgresProfile]) {
      driver.asInstanceOf[ExPostgresProfile].bindPgTypeToScala("int4range", classTag[Range[Int]])
      driver.asInstanceOf[ExPostgresProfile].bindPgTypeToScala("int8range", classTag[Range[Long]])
      driver.asInstanceOf[ExPostgresProfile].bindPgTypeToScala("numrange", classTag[Range[Float]])
      driver.asInstanceOf[ExPostgresProfile].bindPgTypeToScala("tsrange", classTag[Range[Timestamp]])
      driver.asInstanceOf[ExPostgresProfile].bindPgTypeToScala("daterange", classTag[Range[Date]])
    }
  }

  /// alias
  trait RangeImplicits extends SimpleRangeImplicits

  trait SimpleRangeImplicits extends SimpleRangeCodeGenSupport {
    implicit val simpleIntRangeTypeMapper: JdbcType[Range[Int]] = new GenericJdbcType[Range[Int]]("int4range", mkRangeFn(_.toInt))
    implicit val simpleLongRangeTypeMapper: JdbcType[Range[Long]] = new GenericJdbcType[Range[Long]]("int8range", mkRangeFn(_.toLong))
    implicit val simpleFloatRangeTypeMapper: JdbcType[Range[Float]] = new GenericJdbcType[Range[Float]]("numrange", mkRangeFn(_.toFloat))
    implicit val simpleTimestampRangeTypeMapper: JdbcType[Range[Timestamp]] = new GenericJdbcType[Range[Timestamp]]("tsrange", mkRangeFn(toTimestamp))
    implicit val simpleDateRangeTypeMapper: JdbcType[Range[Date]] = new GenericJdbcType[Range[Date]]("daterange", mkRangeFn(toSQLDate))

    implicit def simpleRangeColumnExtensionMethods[B0](c: Rep[Range[B0]])(
      implicit tm: JdbcType[B0], tm1: JdbcType[Range[B0]]) = {
        new RangeColumnExtensionMethods[Range[B0], B0, Range[B0]](c)
      }
    implicit def simpleRangeOptionColumnExtensionMethods[B0](c: Rep[Option[Range[B0]]])(
      implicit tm: JdbcType[B0], tm1: JdbcType[Range[B0]]) = {
        new RangeColumnExtensionMethods[Range[B0], B0, Option[Range[B0]]](c)
      }
  }

  trait SimpleRangePlainImplicits extends SimpleRangeCodeGenSupport {
    import utils.PlainSQLUtils._

    // to support 'nextArray[T]/nextArrayOption[T]' in PgArraySupport
    {
      addNextArrayConverter((r) => utils.SimpleArrayUtils.fromString(mkRangeFn(_.toInt))(r.nextString()))
      addNextArrayConverter((r) => utils.SimpleArrayUtils.fromString(mkRangeFn(_.toLong))(r.nextString()))
      addNextArrayConverter((r) => utils.SimpleArrayUtils.fromString(mkRangeFn(_.toFloat))(r.nextString()))
      addNextArrayConverter((r) => utils.SimpleArrayUtils.fromString(mkRangeFn(toTimestamp))(r.nextString()))
      addNextArrayConverter((r) => utils.SimpleArrayUtils.fromString(mkRangeFn(toSQLDate))(r.nextString()))
    }

    implicit class PgRangePositionedResult(r: PositionedResult) {
      def nextIntRange() = nextIntRangeOption().orNull
      def nextIntRangeOption() = r.nextStringOption().map(mkRangeFn(_.toInt))
      def nextLongRange() = nextLongRangeOption().orNull
      def nextLongRangeOption() = r.nextStringOption().map(mkRangeFn(_.toLong))
      def nextFloatRange() = nextFloatRangeOption().orNull
      def nextFloatRangeOption() = r.nextStringOption().map(mkRangeFn(_.toFloat))
      def nextTimestampRange() = nextTimestampRangeOption().orNull
      def nextTimestampRangeOption() = r.nextStringOption().map(mkRangeFn(toTimestamp))
      def nextDateRange() = nextDateRangeOption().orNull
      def nextDateRangeOption() = r.nextStringOption().map(mkRangeFn(toSQLDate))
    }

    ////////////////////////////////////////////////////////////////////
    implicit val getIntRange = mkGetResult(_.nextIntRange())
    implicit val getIntRangeOption = mkGetResult(_.nextIntRangeOption())
    implicit val setIntRange = mkSetParameter[Range[Int]]("int4range")
    implicit val setIntRangeOption = mkOptionSetParameter[Range[Int]]("int4range")

    implicit val getLongRange = mkGetResult(_.nextLongRange())
    implicit val getLongRangeOption = mkGetResult(_.nextLongRangeOption())
    implicit val setLongRange = mkSetParameter[Range[Long]]("int8range")
    implicit val setLongRangeOption = mkOptionSetParameter[Range[Long]]("int8range")

    implicit val getFloatRange = mkGetResult(_.nextFloatRange())
    implicit val getFloatRangeOption = mkGetResult(_.nextFloatRangeOption())
    implicit val setFloatRange = mkSetParameter[Range[Float]]("numrange")
    implicit val setFloatRangeOption = mkOptionSetParameter[Range[Float]]("numrange")

    implicit val getTimestampRange = mkGetResult(_.nextTimestamp())
    implicit val getTimestampRangeOption = mkGetResult(_.nextTimestampRangeOption())
    implicit val setTimestampRange = mkSetParameter[Range[Timestamp]]("tsrange")
    implicit val setTimestampRangeOption = mkOptionSetParameter[Range[Timestamp]]("tsrange")

    implicit val getDateRange = mkGetResult(_.nextDateRange())
    implicit val getDateRangeOption = mkGetResult(_.nextDateRangeOption())
    implicit val setDateRange = mkSetParameter[Range[Date]]("daterange")
    implicit val setDateRangeOption = mkOptionSetParameter[Range[Date]]("daterange")
  }
}

object PgRangeSupportUtils {

  // regular expr matchers to range string
  val `[_,_)Range`  = """\["?([^,"]*)"?,[ ]*"?([^,"]*)"?\)""".r   // matches: [_,_)
  val `(_,_]Range`  = """\("?([^,"]*)"?,[ ]*"?([^,"]*)"?\]""".r   // matches: (_,_]
  val `(_,_)Range`  = """\("?([^,"]*)"?,[ ]*"?([^,"]*)"?\)""".r   // matches: (_,_)
  val `[_,_]Range`  = """\["?([^,"]*)"?,[ ]*"?([^,"]*)"?\]""".r   // matches: [_,_]

  def mkRangeFn[T](convert: (String => T)): (String => Range[T]) = {
    def conv[T](str: String, convert: (String => T)): Option[T] =
      Option(str).filterNot(_.isEmpty).map(convert)

    (str: String) => str match {
      case Range.`empty_str` => Range.emptyRange[T]
      case `[_,_)Range`(start, end) => Range(conv(start, convert), conv(end, convert), `[_,_)`)
      case `(_,_]Range`(start, end) => Range(conv(start, convert), conv(end, convert), `(_,_]`)
      case `(_,_)Range`(start, end) => Range(conv(start, convert), conv(end, convert), `(_,_)`)
      case `[_,_]Range`(start, end) => Range(conv(start, convert), conv(end, convert), `[_,_]`)
    }
  }

  def toStringFn[T](toString: (T => String)): (Range[T] => String) =
    (r: Range[T]) => r.edge match {
      case `empty` => Range.empty_str
      case `[_,_)` => s"[${oToString(r.start, toString)},${oToString(r.end, toString)})"
      case `(_,_]` => s"(${oToString(r.start, toString)},${oToString(r.end, toString)}]"
      case `(_,_)` => s"(${oToString(r.start, toString)},${oToString(r.end, toString)})"
      case `[_,_]` => s"[${oToString(r.start, toString)},${oToString(r.end, toString)}]"
    }

  ///
  def mkWithLength[T](start: T, length: Double, edge: EdgeType = `[_,_)`) = {
    val upper = (start.asInstanceOf[Double] + length).asInstanceOf[T]
    new Range[T](Some(start), Some(upper), edge)
  }

  def mkWithInterval[T <: java.util.Date](start: T, interval: Interval, edge: EdgeType = `[_,_)`) = {
    val end = (start +: interval).asInstanceOf[T]
    new Range[T](Some(start), Some(end), edge)
  }

  ////// helper methods
  private[slickpg] def oToString[T](o: Option[T], toString: (T => String) = (r: T) => r.toString) =
    o.map(toString).getOrElse("")
}


text:
using System;
using System.Linq;
using BrightstarDB.PerformanceTests.Model;
using NUnit.Framework;

namespace BrightstarDB.PerformanceTests
{
    [TestFixture]
    public class LinqQueryPerformance : PerformanceTestBase
    {
        private const string StoresDirectory = "C:\\brightstar";
        private const string StoreName = "BrightstarDB.PerformanceTests";
        private static string _embeddedConnectionString;
        private static MyEntityContext _context;

        [TestFixtureSetUp]
        public void StoreSetup()
        {
            _embeddedConnectionString = String.Format("type=embedded;storesdirectory={0};storename={1}",
                                                     StoresDirectory, StoreName);
            _context = CreateStore(_embeddedConnectionString, StoreName);
        }

        [Test]
        public void CountInstances()
        {
            Assert.AreEqual(1000, _context.Skills.Count());
            Assert.AreEqual(1000, _context.Persons.Count());
            Assert.AreEqual(100, _context.Departments.Count());
            Assert.AreEqual(5, _context.JobRoles.Count());
            Assert.AreEqual(2, _context.Websites.Count());
            Assert.AreEqual(10000, _context.Articles.Count());
        }

        [Test]
        public void TestQuery1()
        {
            var personsWithHighSalaryUnderAgeOf30 = (from person in _context.Persons where person.Salary > 300000 && person.Age < 30 select person);
            var results = personsWithHighSalaryUnderAgeOf30.ToList();
            Assert.AreEqual(49, results.Count);
        }

        [Test]
        public void TestQuery1WithRetrieval()
        {
            var personsWithHighSalaryUnderAgeOf30 = (from person in _context.Persons where person.Salary > 300000 && person.Age < 30 select person);
            foreach(var p in personsWithHighSalaryUnderAgeOf30)
            {
                var pname = p.Fullname;
            }
        }

        [Test]
        public void TestQuery2()
        {
            var personsOrdered = (from person in _context.Persons orderby person.Fullname descending select person);
            var results = personsOrdered.ToList();
            Assert.AreEqual(1000, results.Count);
        }

        [Test]
        public void TestQuery2WithRetrieval()
        {
            var personsOrdered = (from person in _context.Persons orderby person.Fullname descending select person);
            foreach(var p in personsOrdered)
            {
                var pname = p.Fullname;
            }
        }

        [Test]
        public void TestQuery3()
        {
            var personsHavingSkill = _context.Skills.Where(s => s.Title.Contains("7")).SelectMany(s => s.SkilledPeople);
            var results = personsHavingSkill.ToList();
            Assert.AreEqual(271, results.Count);
        }

        [Test]
        public void TestQuery3WithRetrieval()
        {
            var personsHavingSkill = _context.Skills.Where(s => s.Title.Contains("7")).SelectMany(s => s.SkilledPeople);
            foreach(var p in personsHavingSkill)
            {
                var pname = p.Fullname;
            }
        }

        [Test]
        public void TestQuery4()
        {
            var managers =
                        _context.JobRoles.Where(jr => jr.Description.Equals("management")).SelectMany(jr => jr.Persons).
                            OrderBy(p => p.Salary);
            var results = managers.ToList();
            Assert.AreEqual(200, results.Count);
        }

        [Test]
        public void TestQuery4WithRetrieval()
        {
            var managers =
                        _context.JobRoles.Where(jr => jr.Description.Equals("management")).SelectMany(jr => jr.Persons).
                            OrderBy(p => p.Salary);
            foreach(var m in managers)
            {
                var mname = m.Fullname;
            }
        }

        [Test]
        public void TestQuery5()
        {
            var articles = _context.Articles.Where(a => a.Publisher.Age > 30 && a.Website.Name.Equals("website2")).Distinct();
            var results = articles.ToList();
            Assert.AreEqual(3900, results.Count);
        }

        [Test]
        public void TestQuery5WithRetrieval()
        {
            var articles = _context.Articles.Where(a => a.Publisher.Age > 30 && a.Website.Name.Equals("website2")).Distinct();
            foreach(var a in articles)
            {
                var atitle = a.Title;
            }
        }

        [Test]
        public void TestQuery6()
        {
            var average = _context.Articles.Select(a => a.Publisher).Average(p => p.Age);
            Assert.AreEqual(44.5, average);
        }

        [Test]
        public void TestQuery7()
        {
            var deptArticles = _context.Articles.Where(a => a.Publisher.Department.Name.Equals("Department4")).OrderBy(a => a.Title)
                            .ToList();
            Assert.AreEqual(100, deptArticles.Count);
        }

        [Test]
        public void TestQuery7WithRetrieval()
        {
            var deptArticles =
                _context.Articles.Where(a => a.Publisher.Department.Name.Equals("Department4")).OrderBy(a => a.Title).
                    ToList();
            foreach (var group in deptArticles.GroupBy(da=>da.Publisher))
            {
                var publisher = group.Key.Fullname;
                foreach(var article in group)
                {
                    var atitle = article.Title;
                }
            }
        }

        [Test]
        public void TestQuery8()
        {
            var articlesByOldPeople = _context.Articles.Where(a => a.Publisher.Age > 50).Distinct();
            var results = articlesByOldPeople.ToList();
            Assert.AreEqual(3800, results.Count);
        }

        [Test]
        public void TestQuery8WithRetrieval()
        {
            var articlesByOldPeople = _context.Articles.Where(a => a.Publisher.Age > 50).Distinct();
            foreach(var a in articlesByOldPeople)
            {
                var atitle = a.Title;
            }
        }

        [Test]
        public void TestQuery9()
        {
            var firstArticle = _context.Articles.First();
            var singleArticle = new { A = firstArticle.Title, B = firstArticle.Publisher.Fullname };
            string tests = singleArticle.A; //make sure it is retrieved and not lazy loaded cached somehow
        }

        [Test]
        public void TestQuery11()
        {
            var youngpeople = (from person in _context.Persons where person.Age < 30 select person);
            var results = youngpeople.ToList();
            Assert.AreEqual(200, results.Count);
        }

        [Test]
        public void TestQuery11WithRetrieval()
        {
            var youngpeople = (from person in _context.Persons where person.Age < 30 select person);
            foreach(var p in youngpeople)
            {
                var pname = p.Fullname;
            }
        }
    }
}


text:
package com.microsoft.azure.management.network.v2019_06_01.implementation;

import com.microsoft.azure.management.network.v2019_06_01.PacketCaptureStorageLocation;
import java.util.List;
import com.microsoft.azure.management.network.v2019_06_01.PacketCaptureFilter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;

/**
 * Parameters that define the create packet capture operation.
 */
@JsonFlatten
public class PacketCaptureInner {
    /**
     * The ID of the targeted resource, only VM is currently supported.
     */
    @JsonProperty(value = "properties.target", required = true)
    private String target;

    /**
     * Number of bytes captured per packet, the remaining bytes are truncated.
     */
    @JsonProperty(value = "properties.bytesToCapturePerPacket")
    private Integer bytesToCapturePerPacket;

    /**
     * Maximum size of the capture output.
     */
    @JsonProperty(value = "properties.totalBytesPerSession")
    private Integer totalBytesPerSession;

    /**
     * Maximum duration of the capture session in seconds.
     */
    @JsonProperty(value = "properties.timeLimitInSeconds")
    private Integer timeLimitInSeconds;

    /**
     * Describes the storage location for a packet capture session.
     */
    @JsonProperty(value = "properties.storageLocation", required = true)
    private PacketCaptureStorageLocation storageLocation;

    /**
     * A list of packet capture filters.
     */
    @JsonProperty(value = "properties.filters")
    private List<PacketCaptureFilter> filters;

    /**
     * Get the ID of the targeted resource, only VM is currently supported.
     *
     * @return the target value
     */
    public String target() {
        return this.target;
    }

    /**
     * Set the ID of the targeted resource, only VM is currently supported.
     *
     * @param target the target value to set
     * @return the PacketCaptureInner object itself.
     */
    public PacketCaptureInner withTarget(String target) {
        this.target = target;
        return this;
    }

    /**
     * Get number of bytes captured per packet, the remaining bytes are truncated.
     *
     * @return the bytesToCapturePerPacket value
     */
    public Integer bytesToCapturePerPacket() {
        return this.bytesToCapturePerPacket;
    }

    /**
     * Set number of bytes captured per packet, the remaining bytes are truncated.
     *
     * @param bytesToCapturePerPacket the bytesToCapturePerPacket value to set
     * @return the PacketCaptureInner object itself.
     */
    public PacketCaptureInner withBytesToCapturePerPacket(Integer bytesToCapturePerPacket) {
        this.bytesToCapturePerPacket = bytesToCapturePerPacket;
        return this;
    }

    /**
     * Get maximum size of the capture output.
     *
     * @return the totalBytesPerSession value
     */
    public Integer totalBytesPerSession() {
        return this.totalBytesPerSession;
    }

    /**
     * Set maximum size of the capture output.
     *
     * @param totalBytesPerSession the totalBytesPerSession value to set
     * @return the PacketCaptureInner object itself.
     */
    public PacketCaptureInner withTotalBytesPerSession(Integer totalBytesPerSession) {
        this.totalBytesPerSession = totalBytesPerSession;
        return this;
    }

    /**
     * Get maximum duration of the capture session in seconds.
     *
     * @return the timeLimitInSeconds value
     */
    public Integer timeLimitInSeconds() {
        return this.timeLimitInSeconds;
    }

    /**
     * Set maximum duration of the capture session in seconds.
     *
     * @param timeLimitInSeconds the timeLimitInSeconds value to set
     * @return the PacketCaptureInner object itself.
     */
    public PacketCaptureInner withTimeLimitInSeconds(Integer timeLimitInSeconds) {
        this.timeLimitInSeconds = timeLimitInSeconds;
        return this;
    }

    /**
     * Get describes the storage location for a packet capture session.
     *
     * @return the storageLocation value
     */
    public PacketCaptureStorageLocation storageLocation() {
        return this.storageLocation;
    }

    /**
     * Set describes the storage location for a packet capture session.
     *
     * @param storageLocation the storageLocation value to set
     * @return the PacketCaptureInner object itself.
     */
    public PacketCaptureInner withStorageLocation(PacketCaptureStorageLocation storageLocation) {
        this.storageLocation = storageLocation;
        return this;
    }

    /**
     * Get a list of packet capture filters.
     *
     * @return the filters value
     */
    public List<PacketCaptureFilter> filters() {
        return this.filters;
    }

    /**
     * Set a list of packet capture filters.
     *
     * @param filters the filters value to set
     * @return the PacketCaptureInner object itself.
     */
    public PacketCaptureInner withFilters(List<PacketCaptureFilter> filters) {
        this.filters = filters;
        return this;
    }

}


text:
namespace ash {

class UsbPrinterNotificationController;

class AutomaticUsbPrinterConfigurer : public CupsPrintersManager::Observer {
 public:
  AutomaticUsbPrinterConfigurer(
      std::unique_ptr<PrinterConfigurer> printer_configurer,
      PrinterInstallationManager* installation_manager,
      UsbPrinterNotificationController* notification_controller);

  AutomaticUsbPrinterConfigurer(const AutomaticUsbPrinterConfigurer&) = delete;
  AutomaticUsbPrinterConfigurer& operator=(
      const AutomaticUsbPrinterConfigurer&) = delete;

  ~AutomaticUsbPrinterConfigurer() override;

  // CupsPrintersManager::Observer override.
  void OnPrintersChanged(
      chromeos::PrinterClass printer_class,
      const std::vector<chromeos::Printer>& printers) override;

 private:
  FRIEND_TEST_ALL_PREFIXES(AutomaticUsbPrinterConfigurerTest,
                           UsbPrinterAddedToSet);

  // Uses |printer_configurer_| to setup |printer| if it is not yet setup.
  void SetupPrinter(const chromeos::Printer& printer);

  // Callback for PrinterConfiguer::SetUpPrinter().
  void OnSetupComplete(const chromeos::Printer& printer,
                       PrinterSetupResult result);

  // Completes the configuration for |printer|. Saves printer in
  // |configured_printers_|.
  void CompleteConfiguration(const chromeos::Printer& printer);

  // Removes any printers from |configured_printers_| that are no longer in
  // |automatic_printers|.
  void PruneRemovedAutomaticPrinters(
      const std::vector<chromeos::Printer>& automatic_printers);

  // Removes any printers from |unconfigured_printers_| that are no longer in
  // |discovered_printers|.
  void PruneRemovedDiscoveredPrinters(
      const std::vector<chromeos::Printer>& discovered_printers);

  // Helper function that removes printers that are no longer in
  // |current_printers|. If |use_configured_printers|, |configured_printers_| is
  // pruned. Otherwise, |unconfigured_printers_| is pruned.
  void PruneRemovedPrinters(
      const std::vector<chromeos::Printer>& current_printers,
      bool use_configured_printers);

  SEQUENCE_CHECKER(sequence_);

  std::unique_ptr<PrinterConfigurer> printer_configurer_;
  PrinterInstallationManager* installation_manager_;           // Not owned.
  UsbPrinterNotificationController* notification_controller_;  // Not owned.
  base::flat_set<std::string> configured_printers_;
  base::flat_set<std::string> unconfigured_printers_;

  base::WeakPtrFactory<AutomaticUsbPrinterConfigurer> weak_factory_{this};
};

}  // namespace ash

#endif  // CHROME_BROWSER_ASH_PRINTING_AUTOMATIC_USB_PRINTER_CONFIGURER_H_


text:
/*
 * QueryResult.java
 *
 * Created on October 28, 2005, 11:01 AM
 */

package ORG.oclc.os.SRW;

import gov.loc.www.zing.srw.ExtraDataType;
import java.util.Hashtable;

/**
 *
 * @author levan
 */
public abstract class QueryResult extends SRWDiagnosticsHolder {
    public abstract long getNumberOfRecords();
    public abstract RecordIterator newRecordIterator(long index, int numRecs,
            String schemaId, ExtraDataType edt) throws InstantiationException;

    Hashtable<String, QueryResult> sortedResults=null;
    private int       resultSetIdleTime;
    RecordIterator recordIterator=null;

    /**
     *  If you choose to override close(), don't forget to call super.close();
     */
    public void close() {
        if(recordIterator!=null)
            recordIterator.close();
    }

    public int getResultSetIdleTime() {
        return resultSetIdleTime;
    }

    public Hashtable getSortedResults() {
        if(sortedResults==null)
            sortedResults=new Hashtable<String, QueryResult>();
        return sortedResults;
    }

    public QueryResult getSortedResult(String sortKeys) {
        if(sortedResults==null)
            return null;
        return sortedResults.get(sortKeys);
    }

    public void putSortedResult(String sortKeys, QueryResult sortedResult) {
        if(sortedResults==null)
            sortedResults=new Hashtable<String, QueryResult>();
        sortedResults.put(sortKeys, sortedResult);
    }

    public RecordIterator recordIterator(long index, int numRecs,
            String schemaId, ExtraDataType edt) throws InstantiationException {
        recordIterator=newRecordIterator(index, numRecs, schemaId, edt);
        return recordIterator;
    }

    public void setResultSetIdleTime(int resultSetIdleTime) {
        this.resultSetIdleTime = resultSetIdleTime;
    }
}


text:
/**
   @file bench.h A simple real-time benchmarking API.
*/

#ifndef BENCH_H
#define BENCH_H

#define _POSIX_C_SOURCE 199309L

#include <time.h>
#include <sys/time.h>

static inline double
bench_elapsed_s(const struct timespec* start, const struct timespec* end)
{
	return ((end->tv_sec - start->tv_sec)
	        + ((end->tv_nsec - start->tv_nsec) * 0.000000001));
}

static inline struct timespec
bench_start()
{
	struct timespec start_t;
	clock_gettime(CLOCK_REALTIME, &start_t);
	return start_t;
}

static inline double
bench_end(const struct timespec* start_t)
{
	struct timespec end_t;
	clock_gettime(CLOCK_REALTIME, &end_t);
	return bench_elapsed_s(start_t, &end_t);
}

#endif  /* BENCH_H */


text:
<Alloy>
	<TabGroup>
		<Tab id="deliveries" title="Deliveries">
			<Require type="view" src="delivery" id="delTab"/>
		</Tab>
		<Tab id="locations" title="Locations">
			<Require type="view" src="location" id="locTab"/>
		</Tab>
		<Tab id="products" title="Products">
			<Require type="view" src="product" id="proTab"/>
		</Tab>
		<Tab id="users" title="Users">
			<Require type="view" src="user" id="UsrTab"/>
		</Tab>
	</TabGroup>
</Alloy>


text:
Rails.application.routes.draw do
  devise_for :users
  resources :chains
  resources :actuators do
    member do
      post :activate
      post :deactivate
    end
  end
  resources :events, except: :show
  resources :events, only: :show, :constraints => {:format => :json}
  post 'events/:id/start', to: 'events#start', as: 'start_event'
  post 'events/:id/stop', to: 'events#stop', as: 'stop_event'

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"

  get 'reports/current', to: 'reports#current', as: 'current_report'
  get 'reports/present/:report_id', to: 'reports#present', as: 'present_report'
  get 'reports/preview/:report_id', to: 'reports#preview', as: 'preview_report'

  get 'reports/:report_id/chatfuel/:topic', to: 'chatfuel#show'
  # route for chatfuel questions and answers
  get 'reports/:report_id/chatfuel/text_components/:text_component_id/answer_to_question/:index', to: 'chatfuel#answer_to_question', as: 'answer_to_question'

  resources :channels, only: [:edit, :show, :update]

  resources :reports, param: :report_id # shallow nesting to avoid id param like :report_report_id
  resources :reports, only: [] do # only: [] to remove duplicate top level routes
    resources :diary_entries, only: [:index, :show]
    resources :text_components do
      get 'duplicate', on: :member
    end
    resources :triggers
    resources :sensors do
      member do
        put :start_calibration
        put :stop_calibration

        resources :sensor_readings, only:[:show, :create, :index, :destroy], default: { format: :json }
        post 'sensor_readings/debug', to: 'sensor_readings#debug', default: { format: :json }
      end
    end
  end

  root to: redirect('/reports/current')

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end


text:
package org.apache.accumulo.server.conf.store.impl;

import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

import org.apache.accumulo.core.util.threads.ThreadPools;
import org.apache.accumulo.server.conf.codec.VersionedProperties;
import org.apache.accumulo.server.conf.store.PropCache;
import org.apache.accumulo.server.conf.store.PropStoreKey;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.RemovalCause;
import com.github.benmanes.caffeine.cache.Ticker;

public class PropCacheCaffeineImpl implements PropCache {

  public static final TimeUnit BASE_TIME_UNITS = TimeUnit.MINUTES;

  public static final int EXPIRE_MIN = 60;
  private static final Logger log = LoggerFactory.getLogger(PropCacheCaffeineImpl.class);
  private static final Executor executor = ThreadPools.getServerThreadPools().createThreadPool(1,
      20, 60, TimeUnit.SECONDS, "caffeine-tasks", false);

  private final PropStoreMetrics metrics;

  private final LoadingCache<PropStoreKey<?>,VersionedProperties> cache;

  private PropCacheCaffeineImpl(final CacheLoader<PropStoreKey<?>,VersionedProperties> cacheLoader,
      final PropStoreMetrics metrics, final Ticker ticker, boolean runTasksInline) {
    this.metrics = metrics;
    var builder = Caffeine.newBuilder().expireAfterAccess(EXPIRE_MIN, BASE_TIME_UNITS)
        .evictionListener(this::evictionNotifier);
    if (runTasksInline) {
      builder.executor(Runnable::run);
    } else {
      builder.executor(executor);
    }
    if (ticker != null) {
      builder.ticker(ticker);
    }
    cache = builder.build(cacheLoader);
  }

  public PropStoreMetrics getMetrics() {
    return metrics;
  }

  void evictionNotifier(PropStoreKey<?> propStoreKey, VersionedProperties value,
      RemovalCause cause) {
    log.trace("Evicted: ID: {} was evicted from cache. Reason: {}", propStoreKey, cause);
    metrics.incrEviction();
  }

  @Override
  public @Nullable VersionedProperties get(PropStoreKey<?> propStoreKey) {
    log.trace("Called get() for {}", propStoreKey);
    try {
      return cache.get(propStoreKey);
    } catch (Exception ex) {
      log.info("Cache failed to retrieve properties for: " + propStoreKey, ex);
      metrics.incrZkError();
      return null;
    }
  }

  @Override
  public void remove(PropStoreKey<?> propStoreKey) {
    log.trace("clear {} from cache", propStoreKey);
    cache.invalidate(propStoreKey);
  }

  @Override
  public void removeAll() {
    cache.invalidateAll();
  }

  /**
   * Retrieve the version properties if present in the cache, otherwise return null. This prevents
   * caching the properties and should be used when properties will be updated and then committed to
   * the backend store. The process that is updating the values may not need them for additional
   * processing so there is no reason to store them in the cache at this time. If they are used, a
   * normal cache get will load the property into the cache.
   *
   * @param propStoreKey
   *          the property id
   * @return the version properties if cached, otherwise return null.
   */
  public @Nullable VersionedProperties getIfCached(PropStoreKey<?> propStoreKey) {
    return cache.getIfPresent(propStoreKey);
  }

  public static class Builder {

    private final PropStoreMetrics metrics;
    private final ZooPropLoader zooPropLoader;
    private Ticker ticker = null;
    private boolean runTasksInline = false;

    public Builder(final ZooPropLoader zooPropLoader, final PropStoreMetrics metrics) {
      Objects.requireNonNull(zooPropLoader, "A PropStoreChangeMonitor must be provided");
      this.zooPropLoader = zooPropLoader;
      this.metrics = metrics;
    }

    public PropCacheCaffeineImpl build() {
      return new PropCacheCaffeineImpl(zooPropLoader, metrics, ticker, runTasksInline);
    }

    public Builder forTests(final Ticker ticker) {
      this.ticker = ticker;
      this.runTasksInline = true;
      return this;
    }
  }

}


text:
package imj;

import static imj.IMJTools.alpha;
import static imj.IMJTools.blue;
import static imj.IMJTools.channelValue;
import static imj.IMJTools.green;
import static imj.IMJTools.red;
import static imj.IMJTools.square;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.sqrt;
import imj.IMJTools.StatisticsSelector;

/**
 * @author codistmonk (creation 2013-02-08)
 */
public final class VariationStatisticsFilter extends StatisticalFilter {

	private final Variation variation;

	public VariationStatisticsFilter(final Image image, final StatisticsSelector selector, final Variation variation, final int[] structuringElement) {
		super(image, variation.isResultMonoChannel() ? 1 : image.getChannelCount(), selector, structuringElement);

		this.variation = variation;

		this.compute();
	}

	public final Variation getVariation() {
		return this.variation;
	}

	@Override
	protected final Synthesizer newSynthesizer(final int[] structuringElement) {
		return this.new Selector(structuringElement);
	}

	/**
	 * @author codistmonk (creation 2013-02-03)
	 */
	public final class Selector extends StatisticalFilter.Selector {

		private int pixel;

		private int value;

		public Selector(final int... deltas) {
			super(deltas);
		}

		@Override
		protected final void reset(final int pixel) {
			super.reset(pixel);
			this.pixel = pixel;
			this.value = VariationStatisticsFilter.this.getImage().getValue(pixel);
		}

		@Override
		protected final int getValue(final int pixel, int channel, final int value) {
			return VariationStatisticsFilter.this.getVariation().computeValue(
					this.pixel, channelValue(this.value, channel), pixel, channelValue(value, channel));
		}

		@Override
		protected final int getValue(final int pixel, final int value) {
			return VariationStatisticsFilter.this.getVariation().computeValue(this.pixel, this.value, pixel, value);
		}

		@Override
		protected final float getFloatValue(final int pixel, final float value) {
			return this.getValue(pixel, 0, (int) value);
		}

	}

	/**
	 * @author codistmonk (creation 2013-02-08)
	 */
	public static abstract interface Variation {

		public abstract int computeValue(int pixel1, int value1, int pixel2, int value2);

		public abstract boolean isResultMonoChannel();

		/**
		 * @author codistmonk (creation 2013-02-08)
		 */
		public static enum Predefined implements Variation {

			DIFFERENCE {

				@Override
				public final int computeValue(final int pixel1, final int value1, final int pixel2, final int value2) {
					return value1 - value2;
				}

				@Override
				public final boolean isResultMonoChannel() {
					return false;
				}

			}, SQUARED_DIFFERENCE {

				@Override
				public final int computeValue(final int pixel1, final int value1, final int pixel2, final int value2) {
					return square(value1 - value2);
				}

				@Override
				public final boolean isResultMonoChannel() {
					return false;
				}

			}, ABSOLUTE_DIFFERENCE {

				@Override
				public final int computeValue(final int pixel1, final int value1, final int pixel2, final int value2) {
					return abs(value1 - value2);
				}

				@Override
				public final boolean isResultMonoChannel() {
					return false;
				}

			}, SUM {

				@Override
				public final int computeValue(final int pixel1, final int value1, final int pixel2, final int value2) {
					return value1 + value2;
				}

				@Override
				public final boolean isResultMonoChannel() {
					return false;
				}

			}, PRODUCT {

				@Override
				public final int computeValue(final int pixel1, final int value1, final int pixel2, final int value2) {
					return value1 * value2;
				}

				@Override
				public final boolean isResultMonoChannel() {
					return false;
				}

			}, MININIMUM {

				@Override
				public final int computeValue(final int pixel1, final int value1, final int pixel2, final int value2) {
					return min(value1, value2);
				}

				@Override
				public final boolean isResultMonoChannel() {
					return false;
				}

			}, MAXIMUM {

				@Override
				public final int computeValue(final int pixel1, final int value1, final int pixel2, final int value2) {
					return max(value1, value2);
				}

				@Override
				public final boolean isResultMonoChannel() {
					return false;
				}

			}, RGB_SQUARED_EUCLIDEAN_DISTANCE {

				@Override
				public final int computeValue(final int pixel1, final int value1, final int pixel2, final int value2) {
					final int r1 = red(value1);
					final int g1 = green(value1);
					final int b1 = blue(value1);
					final int r2 = red(value2);
					final int g2 = green(value2);
					final int b2 = blue(value2);

					return (int) square(r2 - r1) + square(g2 - g1) + square(b2 - b1);
				}

				@Override
				public final boolean isResultMonoChannel() {
					return true;
				}

			}, RGB_EUCLIDEAN_DISTANCE {

				@Override
				public final int computeValue(final int pixel1, final int value1, final int pixel2, final int value2) {
					return (int) sqrt(RGB_SQUARED_EUCLIDEAN_DISTANCE.computeValue(pixel1, value1, pixel2, value2));
				}

				@Override
				public final boolean isResultMonoChannel() {
					return true;
				}

			}, RGBA_SQUARED_EUCLIDEAN_DISTANCE {

				@Override
				public final int computeValue(final int pixel1, final int value1, final int pixel2, final int value2) {
					final int r1 = red(value1);
					final int g1 = green(value1);
					final int b1 = blue(value1);
					final int a1 = alpha(value1);
					final int r2 = red(value2);
					final int g2 = green(value2);
					final int b2 = blue(value2);
					final int a2 = alpha(value2);

					return square(r2 - r1) + square(g2 - g1) + square(b2 - b1) + square(a2 - a1);
				}

				@Override
				public final boolean isResultMonoChannel() {
					return true;
				}

			}, RGBA_EUCLIDEAN_DISTANCE {

				@Override
				public final int computeValue(final int pixel1, final int value1, final int pixel2, final int value2) {
					return (int) sqrt(RGBA_SQUARED_EUCLIDEAN_DISTANCE.computeValue(pixel1, value1, pixel2, value2));
				}

				@Override
				public final boolean isResultMonoChannel() {
					return true;
				}

			};

		}

	}

}


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 specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.mongodb;

import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ConnectorPageSource;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.ConnectorSplit;
import com.facebook.presto.spi.SplitContext;
import com.facebook.presto.spi.connector.ConnectorPageSourceProvider;
import com.facebook.presto.spi.connector.ConnectorTransactionHandle;
import com.google.common.collect.ImmutableList;

import javax.inject.Inject;

import java.util.List;

import static java.util.Objects.requireNonNull;

public class MongoPageSourceProvider
        implements ConnectorPageSourceProvider
{
    private final MongoSession mongoSession;

    @Inject
    public MongoPageSourceProvider(MongoSession mongoSession)
    {
        this.mongoSession = requireNonNull(mongoSession, "mongoSession is null");
    }

    @Override
    public ConnectorPageSource createPageSource(
            ConnectorTransactionHandle transactionHandle,
            ConnectorSession session,
            ConnectorSplit split,
            List<ColumnHandle> columns,
            SplitContext splitContext)
    {
        MongoSplit mongodbSplit = (MongoSplit) split;

        ImmutableList.Builder<MongoColumnHandle> handles = ImmutableList.builder();
        for (ColumnHandle handle : requireNonNull(columns, "columns is null")) {
            handles.add((MongoColumnHandle) handle);
        }

        return new MongoPageSource(mongoSession, mongodbSplit, handles.build());
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using GlobalsFramework.Linq.ExpressionProcessing;
using GlobalsFramework.Linq.Helpers;
using InterSystems.Globals;

namespace GlobalsFramework.Linq.QueryProcessing
{
    internal sealed class TakeQueryProcessor : IQueryProcessor
    {
        public bool CanProcess(MethodCallExpression query)
        {
            return query.Method.Name == "Take";
        }

        public ProcessingResult ProcessQuery(MethodCallExpression query, ProcessingResult parentResult, DataContext context)
        {
            var items = parentResult.GetItems();
            var enumerator = items.GetEnumerator();

            var count = (int)((ConstantExpression)query.Arguments[1]).Value;
            var currentIndex = 0;

            var itemType = parentResult.IsDeferred()
                ? typeof(NodeReference)
                : QueryProcessingHelper.GetSourceParameterType(query);

            var resultList = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(itemType));

            while ((currentIndex < count) && enumerator.MoveNext())
            {
                resultList.Add(enumerator.Current);
                currentIndex++;
            }

            return new ProcessingResult(true, resultList);
        }
    }
}


text:
{{list.name}}

                    Name
                    Email

                    {{email.name}}
                    {{email.address}}


text:
namespace Humidifier.SES
{
    using System.Collections.Generic;
    using ReceiptFilterTypes;

    public class ReceiptFilter : Humidifier.Resource
    {
        public override string AWSTypeName
        {
            get
            {
                return @"AWS::SES::ReceiptFilter";
            }
        }

        /// <summary>
        /// Filter
        /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-receiptfilter.html#cfn-ses-receiptfilter-filter
        /// Required: True
        /// UpdateType: Immutable
        /// Type: Filter
        /// </summary>
        public Filter Filter
        {
            get;
            set;
        }
    }

    namespace ReceiptFilterTypes
    {
        public class Filter
        {
            /// <summary>
            /// IpFilter
            /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-receiptfilter-filter.html#cfn-ses-receiptfilter-filter-ipfilter
            /// Required: True
            /// UpdateType: Mutable
            /// Type: IpFilter
            /// </summary>
            public IpFilter IpFilter
            {
                get;
                set;
            }

            /// <summary>
            /// Name
            /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-receiptfilter-filter.html#cfn-ses-receiptfilter-filter-name
            /// Required: False
            /// UpdateType: Mutable
            /// PrimitiveType: String
            /// </summary>
            public dynamic Name
            {
                get;
                set;
            }
        }

        public class IpFilter
        {
            /// <summary>
            /// Policy
            /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-receiptfilter-ipfilter.html#cfn-ses-receiptfilter-ipfilter-policy
            /// Required: True
            /// UpdateType: Mutable
            /// PrimitiveType: String
            /// </summary>
            public dynamic Policy
            {
                get;
                set;
            }

            /// <summary>
            /// Cidr
            /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-receiptfilter-ipfilter.html#cfn-ses-receiptfilter-ipfilter-cidr
            /// Required: True
            /// UpdateType: Mutable
            /// PrimitiveType: String
            /// </summary>
            public dynamic Cidr
            {
                get;
                set;
            }
        }
    }
}


text:
import { Dispatcher } from 'flux';

const AppDispatcher = new Dispatcher();
const dispatch = AppDispatcher.dispatch.bind(AppDispatcher);
const waitFor = AppDispatcher.waitFor.bind(AppDispatcher);

function register(receivers, onComplete) {
  return AppDispatcher.register(payload => {
    if (payload.type in receivers) {
      receivers[payload.type](payload);
      if (onComplete) onComplete(payload);
    }
  });
}

export default AppDispatcher;
export { register, dispatch, waitFor };


text:
const WWWROOT = "../distribution/";
const JS_DEST = WWWROOT + "scripts/";
const CSS_DEST = WWWROOT + "styles/";
const IMG_DEST = WWWROOT + "images/";
const FONTS_DEST = WWWROOT + "styles/fonts/";

const year = new Date().getFullYear();
const VERSION = "2.0.4"
const LICENSE = `

`.replace(/^\s+/m, "")

module.exports = {

  // root folder to less source code
  lessRoot: "./code/styles/**/*.less",

  distFolder: "../distribution/",
  cssDistFolder: "../distribution/styles/",

  license: LICENSE,
  version: VERSION,

  lessToCss: [/*
    {
      src: "./code/styles/dataentry/dataentry.less",
      dest: CSS_DEST
    },
    {
      src: "./code/styles/examples.less",
      dest: CSS_DEST,
      nodist: true
    }*/
  ],

  // less code built only for distribution package
  lessToCssExtras: [],

  esToJs: [
    {
      entry: "./distributionfiles/dataentry.js",
      destfolder: JS_DEST,
      filename: "dataentry",
      comment: "core classes only"
    },
    {
      entry: "./distributionfiles/dataentry-dom.js",
      destfolder: JS_DEST,
      filename: "dataentry-dom",
      comment: "with built-in DOM classes"
    },
    {
      entry: "./distributionfiles/dataentry-context.js",
      destfolder: JS_DEST,
      filename: "dataentry-context",
      comment: "with built-in context classes"
    }
  ],

  toBeCopied: [
    {
      src: "./code/styles/dataentry.css",
      dest: WWWROOT
    }
  ],

  test: {
    karma: "karma.conf.js"
  }
};


text:
<?php

namespace Cake\Test\TestCase\View\Widget;

use Cake\TestSuite\TestCase;
use Cake\View\StringTemplate;
use Cake\View\Widget\ButtonWidget;

/**
 * Basic input test.
 */
class ButtonWidgetTest extends TestCase
{

    public function setUp()
    {
        parent::setUp();
        $templates = [
            'button' => '<button{{attrs}}>{{text}}</button>',
        ];
        $this->templates = new StringTemplate($templates);
        $this->context = $this->getMock('Cake\View\Form\ContextInterface');
    }

    /**
     * Test render in a simple case.
     *
     * @return void
     */
    public function testRenderSimple()
    {
        $button = new ButtonWidget($this->templates);
        $result = $button->render(['name' => 'my_input'], $this->context);
        $expected = [
            'button' => ['type' => 'submit', 'name' => 'my_input'],
            '/button'
        ];
        $this->assertHtml($expected, $result);
    }

    /**
     * Test render with custom type
     *
     * @return void
     */
    public function testRenderType()
    {
        $button = new ButtonWidget($this->templates);
        $data = [
            'name' => 'my_input',
            'type' => 'button',
            'text' => 'Some button'
        ];
        $result = $button->render($data, $this->context);
        $expected = [
            'button' => ['type' => 'button', 'name' => 'my_input'],
            'Some button',
            '/button'
        ];
        $this->assertHtml($expected, $result);
    }

    /**
     * Test render with a text
     *
     * @return void
     */
    public function testRenderWithText()
    {
        $button = new ButtonWidget($this->templates);
        $data = [
            'text' => 'Some <value>'
        ];
        $result = $button->render($data, $this->context);
        $expected = [
            'button' => ['type' => 'submit'],
            'Some <value>',
            '/button'
        ];
        $this->assertHtml($expected, $result);

        $data['escape'] = true;
        $result = $button->render($data, $this->context);
        $expected = [
            'button' => ['type' => 'submit'],
            'Some <value>',
            '/button'
        ];
        $this->assertHtml($expected, $result);
    }

    /**
     * Test render with additional attributes.
     *
     * @return void
     */
    public function testRenderAttributes()
    {
        $button = new ButtonWidget($this->templates);
        $data = [
            'name' => 'my_input',
            'text' => 'Go',
            'class' => 'btn',
            'required' => true
        ];
        $result = $button->render($data, $this->context);
        $expected = [
            'button' => [
                'type' => 'submit',
                'name' => 'my_input',
                'class' => 'btn',
                'required' => 'required'
            ],
            'Go',
            '/button'
        ];
        $this->assertHtml($expected, $result);
    }
}


text:
from south.db import db
from south.v2 import SchemaMigration

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Renaming field 'Snippet.django_version'
        db.rename_column(u'cab_snippet', 'django_version', 'version')

    def backwards(self, orm):
        # Renaming field 'Snippet.version'
        db.rename_column(u'cab_snippet', 'version', 'django_version')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'cab.bookmark': {
            'Meta': {'ordering': "('-date',)", 'object_name': 'Bookmark'},
            'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'snippet': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'bookmarks'", 'to': u"orm['cab.Snippet']"}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'cab_bookmarks'", 'to': u"orm['auth.User']"})
        },
        u'cab.language': {
            'Meta': {'ordering': "('name',)", 'object_name': 'Language'},
            'file_extension': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'language_code': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'mime_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'})
        },
        u'cab.snippet': {
            'Meta': {'ordering': "('-pub_date',)", 'object_name': 'Snippet'},
            'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
            'bookmark_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'code': ('django.db.models.fields.TextField', [], {}),
            'description': ('django.db.models.fields.TextField', [], {}),
            'description_html': ('django.db.models.fields.TextField', [], {}),
            'highlighted_code': ('django.db.models.fields.TextField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'language': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cab.Language']"}),
            'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'rating_score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'version': ('django.db.models.fields.FloatField', [], {'default': '0'})
        },
        u'cab.snippetflag': {
            'Meta': {'object_name': 'SnippetFlag'},
            'flag': ('django.db.models.fields.IntegerField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'snippet': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flags'", 'to': u"orm['cab.Snippet']"}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'taggit.tag': {
            'Meta': {'object_name': 'Tag'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'})
        },
        u'taggit.taggeditem': {
            'Meta': {'object_name': 'TaggedItem'},
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_tagged_items'", 'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
            'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_items'", 'to': u"orm['taggit.Tag']"})
        }
    }

    complete_apps = ['cab']


text:
<!DOCTYPE html>
<html lang="ja">
<head>
  <title>particle universe</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.4.0/animate.min.css ">
  <style>
  body {
    margin: 0px
  }
  </style>
</head>
<body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="http://threejs.org/build/three.min.js"></script>
  <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js/examples/js/controls/OrbitControls.js"></script>
  <script>
  /*Basic threeJS scene with procedurally generated particle arrays.
  Simply pass the desired # of "galaxies" to the generateUniverse function.
  Orbit controls = [mouse move / scroll ]
  URL -> http://codepen.io/citylims/pen/vNRPxK
  */
  generateUniverse(15);

  function generateUniverse(galaxies) {
    /////////////////// Setting the scene //////////////////////
    var space = "#151718";
    var canvas_height = window.innerHeight;
    var canvas_width = window.innerWidth;
    var scene = new THREE.Scene();

    //cam
    var camera = new THREE.PerspectiveCamera(75, canvas_width / canvas_height, 0.1, 1000);
    camera.position.set(0, 50, 1200);
    camera.lookAt(new THREE.Vector3(0, 50, 0));

    //renderer
    var renderer = new THREE.WebGLRenderer({
      alpha: true
    });
    renderer.setSize(canvas_width, canvas_height);
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    renderer.setClearColor(space, 1);
    document.body.appendChild(renderer.domElement);

    //window
    window.onresize = function() {
      canvas_height = window.innerHeight;
      canvas_width = window.innerWidth;
      camera.aspect = canvas_width / canvas_height;
      camera.updateProjectionMatrix();
      renderer.setSize(canvas_width, canvas_height);
    }

    //controls
    controls = new THREE.OrbitControls(camera);
    controls.damping = 0.2;
    controls.maxDistance = 650;

    /////////////////// Particle Objects //////////////////
    THREE.ImageUtils.crossOrigin = true;

    function getRandomColor() {
      var letters = '0123456789ABCDEF'.split('');
      var color = '#';
      for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }

    function Particles(num) {
      this.particleArray = []
      for (var i = 0; i < num; i++) {
        var c = getRandomColor();
        var o = Math.floor(Math.random() * (100 - 0 + 1)) / 100;
        var s = Math.floor(Math.random() * (15 - 5 + 1)) + 5;
        var particleCount = Math.floor(Math.random() * (1000 - 250 + 1)) + 250;
        var particle = {
          color: c,
          opacity: o,
          size: s,
          number: particleCount
        }
        this.particleArray.push(particle);
      }
    }

    function ParticleMaterial(c, s, o) {
      this.material = new THREE.PointsMaterial({
        color: c,
        size: s,
        transparent: true,
        opacity: o,
        map: THREE.ImageUtils.loadTexture(
          "https://s3-us-west-2.amazonaws.com/s.cdpn.io/61062/gradient.png"
        )
      });
    }

    function ParticleSystem(number) {
      this.particles = new THREE.Geometry();
      for (var i = 0; i < number; i++) {
        var x = (Math.random() - 0.5) * 2000;
        var y = (Math.random() - 0.5) * 1100;
        var z = (Math.random() - 0.5) * 2000;
        this.particles.vertices.push(new THREE.Vector3(x, y, z));
      }
    };

    function ParticleUniverse(particles) {
      this.galaxies = [];
      var pArr = particles.particleArray;
      for (var i = 0; i < pArr.length; i++) {
        var customParticle = new ParticleMaterial(pArr[i].color, pArr[i].size, pArr[i].opacity);
        var pMaterial = customParticle.material;
        var customSystem = new ParticleSystem(pArr[i].number);
        var pSystem = customSystem.particles;
        var pObject = {
          material: pMaterial,
          system: pSystem
        };
        this.galaxies.push(pObject);
      }
    }

    function createUniverse(universe) {
      var galaxies = universe.galaxies;
      for (var i = 0; i < galaxies.length; i++) {
        var galaxy = new THREE.Points(galaxies[i].system, galaxies[i].material);
        scene.add(galaxy);
      }
    };

    var particles = new Particles(galaxies);
    var universe = new ParticleUniverse(particles);
    createUniverse(universe);

    /////////////////// Render /////////////////////
    var render = function() {
      requestAnimationFrame(render);
      animation();
      renderer.render(scene, camera);
    };
    //animations
    function animation() {
      scene.rotation.y -= .0005;
    };

    render();
  };
  </script>
</body>
</html>


text:
using System;
using Topics.Radical.Validation;

namespace Topics.Radical.DataBinding
{
    /// <summary>
    /// Represents a mean to bind enuration types to controls treating enumeration types
    /// as a common IList of items.
    /// </summary>
    public class EnumBinder<T>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="EnumBinder<T>"/> class.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="value">The value.</param>
        public EnumBinder( EnumItemDescriptionAttribute attribute, T value )
            : this( attribute.Caption, value, attribute.Index )
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="EnumBinder<T>"/> class.
        /// </summary>
        /// <param name="caption">The caption.</param>
        /// <param name="value">The value.</param>
        public EnumBinder( String caption, T value )
            : this( caption, String.Empty, value, -1 )
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="EnumBinder<T>"/> class.
        /// </summary>
        /// <param name="caption">The caption.</param>
        /// <param name="value">The value.</param>
        /// <param name="index">The index.</param>
        public EnumBinder( String caption, T value, Int32 index )
            : this( caption, String.Empty, value, index )
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="EnumBinder<T>"/> class.
        /// </summary>
        /// <param name="caption">The caption.</param>
        /// <param name="description">The description.</param>
        /// <param name="value">The value.</param>
        /// <param name="index">The index.</param>
        public EnumBinder( String caption, String description, T value, Int32 index )
        {
            Ensure.That( caption ).Named( "caption" ).IsNotNull();
            Ensure.That( description ).Named( "description" ).IsNotNull();
            Ensure.That( value ).Named( "value" ).IsFalse( o => o == null );

            this.Caption = caption;
            this.Description = description;
            this.Value = value;
            this.Index = index;
        }

        /// <summary>
        /// Gets the caption.
        /// </summary>
        /// <value>The caption.</value>
        public String Caption
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the description.
        /// </summary>
        /// <value>The description.</value>
        public String Description
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <value>The value.</value>
        public T Value
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the index.
        /// </summary>
        /// <value>The index.</value>
        public Int32 Index
        {
            get;
            private set;
        }
    }
}


text:
@interface twoViewController : UIViewController
@property (nonatomic,strong) RACSubject * delegateSubject;
@end