text:
package alluxio.client;

import alluxio.AlluxioURI;
import alluxio.BaseIntegrationTest;
import alluxio.IntegrationTestConstants;
import alluxio.LocalAlluxioClusterResource;
import alluxio.PropertyKey;
import alluxio.client.block.AlluxioBlockStore;
import alluxio.client.block.stream.BlockInStream;
import alluxio.client.block.stream.BlockInStream.BlockInStreamSource;
import alluxio.client.file.FileInStream;
import alluxio.client.file.FileOutStream;
import alluxio.client.file.FileSystem;
import alluxio.client.file.FileSystemContext;
import alluxio.client.file.FileSystemTestUtils;
import alluxio.client.file.options.CreateFileOptions;
import alluxio.client.file.options.InStreamOptions;
import alluxio.client.file.options.OpenFileOptions;
import alluxio.exception.PreconditionMessage;
import alluxio.exception.status.NotFoundException;
import alluxio.heartbeat.HeartbeatContext;
import alluxio.heartbeat.HeartbeatScheduler;
import alluxio.heartbeat.ManuallyScheduleHeartbeat;
import alluxio.util.CommonUtils;
import alluxio.util.io.BufferUtils;
import alluxio.util.io.PathUtils;
import alluxio.wire.BlockInfo;
import alluxio.wire.WorkerNetAddress;

import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Integration tests for reading from a remote worker.
 */
@RunWith(Parameterized.class)
public class RemoteReadIntegrationTest extends BaseIntegrationTest {
  private static final int MIN_LEN = 0;
  private static final int MAX_LEN = 255;
  private static final int DELTA = 33;

  @ClassRule
  public static ManuallyScheduleHeartbeat sManuallySchedule =
      new ManuallyScheduleHeartbeat(HeartbeatContext.WORKER_BLOCK_SYNC);

  @Rule
  public LocalAlluxioClusterResource mLocalAlluxioClusterResource;
  private FileSystem mFileSystem = null;
  private CreateFileOptions mWriteAlluxio;
  private CreateFileOptions mWriteUnderStore;
  private OpenFileOptions mReadNoCache;
  private OpenFileOptions mReadCache;

  @Parameterized.Parameters
  public static Collection<Object[]> data() {
    // creates a new instance of RemoteBlockInStreamTest for each network type
    List<Object[]> list = new ArrayList<>();
    list.add(new Object[] {IntegrationTestConstants.NETTY_DATA_SERVER,
        IntegrationTestConstants.MAPPED_TRANSFER});
    list.add(new Object[] {IntegrationTestConstants.NETTY_DATA_SERVER,
        IntegrationTestConstants.FILE_CHANNEL_TRANSFER});
    return list;
  }

  /**
   * Constructor for {@link RemoteReadIntegrationTest}.
   *
   * @param dataServer the address of the worker's data server
   * @param transferType the file transfer type used by the worker
   */
  public RemoteReadIntegrationTest(String dataServer, String transferType) {
    mLocalAlluxioClusterResource = new LocalAlluxioClusterResource.Builder()
        .setProperty(PropertyKey.WORKER_DATA_SERVER_CLASS, dataServer)
        .setProperty(PropertyKey.WORKER_NETWORK_NETTY_FILE_TRANSFER_TYPE, transferType)
        .setProperty(PropertyKey.USER_BLOCK_REMOTE_READ_BUFFER_SIZE_BYTES, "100")
        .setProperty(PropertyKey.USER_UFS_BLOCK_READ_CONCURRENCY_MAX, 2)
        .build();
  }

  @Rule
  public ExpectedException mThrown = ExpectedException.none();

  @Before
  public final void before() throws Exception {
    mFileSystem = mLocalAlluxioClusterResource.get().getClient();
    mWriteAlluxio = CreateFileOptions.defaults().setWriteType(WriteType.MUST_CACHE);
    mWriteUnderStore = CreateFileOptions.defaults().setWriteType(WriteType.THROUGH);
    mReadCache = OpenFileOptions.defaults().setReadType(ReadType.CACHE_PROMOTE);
    mReadNoCache = OpenFileOptions.defaults().setReadType(ReadType.NO_CACHE);
  }

  /**
   * Tests the single byte read API from a remote location when the data is only in the
   * underlying storage.
   */
  @Test
  public void readTest1() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteUnderStore, k);

      FileInStream is = mFileSystem.openFile(uri, mReadNoCache);
      byte[] ret = new byte[k];
      int value = is.read();
      int cnt = 0;
      while (value != -1) {
        Assert.assertTrue(value >= 0);
        Assert.assertTrue(value < 256);
        ret[cnt++] = (byte) value;
        value = is.read();
      }
      Assert.assertEquals(cnt, k);
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(k, ret));
      is.close();
      if (k == 0) {
        Assert.assertEquals(100, mFileSystem.getStatus(uri).getInAlluxioPercentage());
      } else {
        Assert.assertNotEquals(100, mFileSystem.getStatus(uri).getInAlluxioPercentage());
      }

      is = mFileSystem.openFile(uri, mReadCache);
      ret = new byte[k];
      value = is.read();
      cnt = 0;
      while (value != -1) {
        Assert.assertTrue(value >= 0);
        Assert.assertTrue(value < 256);
        ret[cnt++] = (byte) value;
        value = is.read();
      }
      Assert.assertEquals(cnt, k);
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertEquals(100, mFileSystem.getStatus(uri).getInAlluxioPercentage());

      is = mFileSystem.openFile(uri, mReadCache);
      ret = new byte[k];
      value = is.read();
      cnt = 0;
      while (value != -1) {
        Assert.assertTrue(value >= 0);
        Assert.assertTrue(value < 256);
        ret[cnt++] = (byte) value;
        value = is.read();
      }
      Assert.assertEquals(cnt, k);
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertEquals(100, mFileSystem.getStatus(uri).getInAlluxioPercentage());
    }
  }

  /**
   * Tests the batch read API from a remote location when the data is only in the underlying
   * storage.
   */
  @Test
  public void readTest2() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteUnderStore, k);

      FileInStream is = mFileSystem.openFile(uri, mReadNoCache);
      byte[] ret = new byte[k];
      Assert.assertEquals(k, is.read(ret));
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(k, ret));
      is.close();
      if (k == 0) {
        Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
      } else {
        Assert.assertFalse(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
      }

      is = mFileSystem.openFile(uri, mReadCache);
      ret = new byte[k];
      Assert.assertEquals(k, is.read(ret));
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);

      is = mFileSystem.openFile(uri, mReadCache);
      ret = new byte[k];
      Assert.assertEquals(k, is.read(ret));
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
    }
  }

  /**
   * Tests the batch read API with offset and length from a remote location when the data is only in
   * the underlying storage.
   */
  @Test
  public void readTest3() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteUnderStore, k);

      FileInStream is = mFileSystem.openFile(uri, mReadNoCache);
      byte[] ret = new byte[k / 2];
      Assert.assertEquals(k / 2, is.read(ret, 0, k / 2));
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(k / 2, ret));
      is.close();
      if (k == 0) {
        Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
      } else {
        Assert.assertFalse(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
      }

      is = mFileSystem.openFile(uri, mReadCache);
      ret = new byte[k];
      Assert.assertEquals(k, is.read(ret, 0, k));
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);

      is = mFileSystem.openFile(uri, mReadCache);
      ret = new byte[k];
      Assert.assertEquals(k, is.read(ret));
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
    }
  }

  /**
   * Tests the single byte read API from a remote location when the data is in an Alluxio worker.
   */
  @Test
  public void readTest4() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteAlluxio, k);

      long blockId = mFileSystem.getStatus(uri).getBlockIds().get(0);
      AlluxioBlockStore blockStore = AlluxioBlockStore.create();
      BlockInfo info = blockStore.getInfo(blockId);
      WorkerNetAddress workerAddr = info.getLocations().get(0).getWorkerAddress();
      BlockInStream is =
          BlockInStream.create(FileSystemContext.INSTANCE, info.getBlockId(), info.getLength(),
              workerAddr, BlockInStreamSource.REMOTE, null, InStreamOptions.defaults());
      byte[] ret = new byte[k];
      int value = is.read();
      int cnt = 0;
      while (value != -1) {
        Assert.assertTrue(value >= 0);
        Assert.assertTrue(value < 256);
        ret[cnt++] = (byte) value;
        value = is.read();
      }
      Assert.assertEquals(cnt, k);
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
    }
  }

  /**
   * Tests the batch read API from a remote location when the data is only in an Alluxio worker.
   */
  @Test
  public void readTest5() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteAlluxio, k);

      long blockId = mFileSystem.getStatus(uri).getBlockIds().get(0);
      BlockInfo info = AlluxioBlockStore.create().getInfo(blockId);
      WorkerNetAddress workerAddr = info.getLocations().get(0).getWorkerAddress();
      BlockInStream is =
          BlockInStream.create(FileSystemContext.INSTANCE, info.getBlockId(), info.getLength(),
              workerAddr, BlockInStreamSource.REMOTE, null, InStreamOptions.defaults());
      byte[] ret = new byte[k];
      int read = is.read(ret);
      Assert
          .assertTrue(BufferUtils.equalIncreasingByteArray(read, Arrays.copyOfRange(ret, 0, read)));
      is.close();
      Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
    }
  }

  /**
   * Tests the batch read API with offset and length from a remote location when the data is in an
   * Alluxio worker.
   */
  @Test
  public void readTest6() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteAlluxio, k);

      long blockId = mFileSystem.getStatus(uri).getBlockIds().get(0);
      BlockInfo info = AlluxioBlockStore.create().getInfo(blockId);
      WorkerNetAddress workerAddr = info.getLocations().get(0).getWorkerAddress();
      BlockInStream is =
          BlockInStream.create(FileSystemContext.INSTANCE, info.getBlockId(), info.getLength(),
              workerAddr, BlockInStreamSource.REMOTE, null, InStreamOptions.defaults());
      byte[] ret = new byte[k / 2];
      int read = 0;
      while (read < k / 2) {
        read += is.read(ret, read, k / 2 - read);
      }
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(read, ret));
      is.close();
      Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
    }
  }

  /**
   * Tests the batch read API from a remote location when the data is only in the underlying
   * storage.
   */
  @Test
  public void readTest7() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteUnderStore, k);

      FileInStream is = mFileSystem.openFile(uri, mReadNoCache);
      byte[] ret = new byte[k];
      Assert.assertEquals(k, is.read(ret));
      Assert.assertTrue(BufferUtils.equalIncreasingByteArray(k, ret));
      Assert.assertEquals(-1, is.read(ret));
      is.close();
      Assert.assertFalse(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
    }
  }

  /**
   * Tests the read API from a remote location after a delay longer than the netty heartbeat
   * timeout.
   */
  @Test
  @LocalAlluxioClusterResource.Config(confParams = {
      PropertyKey.Name.NETWORK_NETTY_HEARTBEAT_TIMEOUT_MS, "1sec"})
  public void heartbeat1() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    int size = 100;
    AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + size);
    FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteUnderStore, size);

    FileInStream is = mFileSystem.openFile(uri, mReadNoCache);
    CommonUtils.sleepMs(2000);
    byte[] ret = new byte[size];
    Assert.assertEquals(size, is.read(ret));
    Assert.assertTrue(BufferUtils.equalIncreasingByteArray(size, ret));
    Assert.assertEquals(-1, is.read(ret));
    is.close();
    Assert.assertFalse(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
  }

  /**
   * Validates the expected exception for seeking a negative position.
   */
  @Test
  public void seekExceptionTest1() throws Exception {
    mThrown.expect(IllegalArgumentException.class);
    mThrown.expectMessage(String.format(PreconditionMessage.ERR_SEEK_NEGATIVE.toString(), -1));
    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteUnderStore, k);

      try (FileInStream is = mFileSystem.openFile(uri, mReadNoCache)) {
        is.seek(-1);
      }
    }
  }

  /**
   * Validates the expected exception for seeking a position that is past block size.
   */
  @Test
  public void seekExceptionTest2() throws Exception {
    mThrown.expect(IllegalArgumentException.class);
    mThrown
        .expectMessage(String.format(PreconditionMessage.ERR_SEEK_PAST_END_OF_FILE.toString(), 1));
    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteUnderStore, k);

      try (FileInStream is = mFileSystem.openFile(uri, mReadNoCache)) {
        is.seek(k + 1);
      }
    }
  }

  /**
   * Tests seeking through data which is in a remote location.
   */
  @Test
  public void seek() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteUnderStore, k);

      FileInStream is = mFileSystem.openFile(uri, mReadNoCache);

      Assert.assertEquals(0, is.read());
      is.seek(k / 3);
      Assert.assertEquals(k / 3, is.read());
      is.seek(k / 2);
      Assert.assertEquals(k / 2, is.read());
      is.seek(k / 4);
      Assert.assertEquals(k / 4, is.read());
      is.close();
    }
  }

  /**
   * Tests skipping through data which is in a remote location.
   */
  @Test
  public void skip() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteUnderStore, k);

      FileInStream is = mFileSystem.openFile(uri, mReadCache);
      Assert.assertEquals(k / 2, is.skip(k / 2));
      Assert.assertEquals(k / 2, is.read());
      is.close();
      Assert.assertEquals(100, mFileSystem.getStatus(uri).getInAlluxioPercentage());

      if (k >= 3) {
        is = mFileSystem.openFile(uri, mReadCache);
        int t = k / 3;
        Assert.assertEquals(t, is.skip(t));
        Assert.assertEquals(t, is.read());
        Assert.assertEquals(t, is.skip(t));
        Assert.assertEquals(2 * t + 1, is.read());
        is.close();
        Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
      }
    }
  }

  /**
   * Tests that reading a file the whole way through with the STORE ReadType will recache it.
   */
  @Test
  public void completeFileReadTriggersRecache() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    int len = 2;
    AlluxioURI uri = new AlluxioURI(uniqPath);
    FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteUnderStore, len);

    FileInStream is = mFileSystem.openFile(uri, mReadCache);
    for (int i = 0; i < len; ++i) {
      Assert.assertEquals(i, is.read());
    }
    is.close();
    Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
  }

  /**
   * Tests that not reading a file the whole way through then closing it will cause it to not
   * recache.
   */
  @Test
  public void incompleteFileReadCancelsRecache() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    AlluxioURI uri = new AlluxioURI(uniqPath);
    FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteUnderStore, 2);

    FileInStream is = mFileSystem.openFile(uri, mReadNoCache);
    Assert.assertEquals(0, is.read());
    is.close();
    Assert.assertFalse(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
    is = mFileSystem.openFile(uri, mReadNoCache);
    is.close();
  }

  /**
   * Tests that reading a file consisting of more than one block from the underfs works.
   */
  @Test
  public void readMultiBlockFile() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    int blockSizeByte = 10;
    int numBlocks = 10;
    AlluxioURI uri = new AlluxioURI(uniqPath);
    FileOutStream os = mFileSystem.createFile(uri, mWriteUnderStore);
    for (int i = 0; i < numBlocks; i++) {
      for (int j = 0; j < blockSizeByte; j++) {
        os.write((byte) (i * blockSizeByte + j));
      }
    }
    os.close();

    FileInStream is = mFileSystem.openFile(uri, mReadCache);
    for (int i = 0; i < blockSizeByte * numBlocks; i++) {
      Assert.assertEquals((byte) i, is.read());
    }
    is.close();
    Assert.assertTrue(mFileSystem.getStatus(uri).getInAlluxioPercentage() == 100);
  }

  /**
   * Tests that seeking around a file cached locally works.
   */
  @Test
  public void seekAroundLocalBlock() throws Exception {
    String uniqPath = PathUtils.uniqPath();
    // The number of bytes per remote block read should be set to 100 in the before function
    FileSystemTestUtils.createByteFile(mFileSystem, uniqPath, 200, mWriteAlluxio);
    FileInStream is = mFileSystem.openFile(new AlluxioURI(uniqPath), mReadNoCache);
    Assert.assertEquals(0, is.read());
    is.seek(199);
    Assert.assertEquals(199, is.read());
    is.seek(99);
    Assert.assertEquals(99, is.read());
    is.close();
  }

  /**
   * Tests remote reads lock blocks correctly.
   */
  @Test
  public void remoteReadLock() throws Exception {
    HeartbeatScheduler.await(HeartbeatContext.WORKER_BLOCK_SYNC, 10, TimeUnit.SECONDS);

    String uniqPath = PathUtils.uniqPath();
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      AlluxioURI uri = new AlluxioURI(uniqPath + "/file_" + k);
      FileSystemTestUtils.createByteFile(mFileSystem, uri, mWriteAlluxio, k);
      HeartbeatScheduler.execute(HeartbeatContext.WORKER_BLOCK_SYNC);

      long blockId = mFileSystem.getStatus(uri).getBlockIds().get(0);
      BlockInfo info = AlluxioBlockStore.create().getInfo(blockId);

      WorkerNetAddress workerAddr = info.getLocations().get(0).getWorkerAddress();
      BlockInStream is =
          BlockInStream.create(FileSystemContext.INSTANCE, info.getBlockId(), info.getLength(),
              workerAddr, BlockInStreamSource.REMOTE, null, InStreamOptions.defaults());
      Assert.assertEquals(0, is.read());
      mFileSystem.delete(uri);
      HeartbeatScheduler.execute(HeartbeatContext.WORKER_BLOCK_SYNC);

      // The file has been deleted.
      Assert.assertFalse(mFileSystem.exists(uri));
      // Look! We can still read the deleted file since we have a lock!
      byte[] ret = new byte[k / 2];
      Assert.assertTrue(is.read(ret, 0, k / 2) > 0);
      is.close();
      Assert.assertFalse(mFileSystem.exists(uri));

      // Try to create an in stream again, and it should fail.
      BlockInStream is2 = null;
      try {
        is2 = BlockInStream.create(FileSystemContext.INSTANCE, info.getBlockId(), info.getLength(),
            workerAddr, BlockInStreamSource.REMOTE, null, InStreamOptions.defaults());
      } catch (NotFoundException e) {
        // Expected since the file has been deleted.
      } finally {
        if (is2 != null) {
          is2.close();
        }
      }
    }
  }
}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview.common.crash;

import android.app.job.JobInfo;
import android.content.ComponentName;
import android.content.Context;
import android.net.ConnectivityManager;

import androidx.annotation.NonNull;
import androidx.annotation.UiThread;
import androidx.annotation.VisibleForTesting;

import org.chromium.android_webview.common.services.ServiceNames;
import org.chromium.base.Log;
import org.chromium.components.background_task_scheduler.TaskIds;
import org.chromium.components.minidump_uploader.CrashFileManager;
import org.chromium.components.minidump_uploader.MinidumpUploadJobService;
import org.chromium.components.minidump_uploader.util.NetworkPermissionUtil;

import java.io.File;

/**
 * A util class for request uploading crash reports.
 */
public final class CrashUploadUtil {
    private static final String TAG = "CrashUploadUtil";

    /**
     * Delegate interface to mock network status check and scheduling upload jobs for testing.
     */
    @VisibleForTesting
    public static interface CrashUploadDelegate {
        /**
         * Schedule a MinidumpUploadJobService to attempt uploading all ready crash minidumps.
         */
        void scheduleNewJob(@NonNull Context context);

        /**
         * Check if network is unmetered or not.
         */
        boolean isNetworkUnmetered(@NonNull Context context);
    }

    private static CrashUploadDelegate sDelegate = new CrashUploadDelegate() {
        @Override
        public void scheduleNewJob(@NonNull Context context) {
            JobInfo.Builder builder = new JobInfo.Builder(TaskIds.WEBVIEW_MINIDUMP_UPLOADING_JOB_ID,
                    new ComponentName(context, ServiceNames.AW_MINIDUMP_UPLOAD_JOB_SERVICE));
            MinidumpUploadJobService.scheduleUpload(builder);
        }

        @Override
        public boolean isNetworkUnmetered(@NonNull Context context) {
            ConnectivityManager connectivityManager =
                    (ConnectivityManager) context.getApplicationContext().getSystemService(
                            Context.CONNECTIVITY_SERVICE);
            return NetworkPermissionUtil.isNetworkUnmetered(connectivityManager);
        }
    };

    /**
     * Schedule a MinidumpUploadJobService to attempt uploading all ready crash minidumps.
     */
    public static void scheduleNewJob(@NonNull Context context) {
        sDelegate.scheduleNewJob(context);
    }

    /**
     * Attempts to upload a crash report with the given local ID.
     *
     * Note that this method is asynchronous. All that is guaranteed is that upload attempts will be
     * enqueued. It marks the file as requested to be uploaded and then schedule an upload job that
     * attempts uploading all files available to upload (including the given minidump file).
     *
     * @param context the context where the upload job will be scheduled from.
     * @param localId The local ID of the crash report.
     */
    @UiThread
    public static void tryUploadCrashDumpWithLocalId(
            @NonNull Context context, @NonNull String localId) {
        CrashFileManager fileManager =
                new CrashFileManager(SystemWideCrashDirectories.getWebViewCrashDir());
        File minidumpFile = fileManager.getCrashFileWithLocalId(localId);
        if (minidumpFile == null) {
            Log.e(TAG, "Could not find a crash dump with local ID " + localId);
            return;
        }
        File renamedMinidumpFile = CrashFileManager.trySetForcedUpload(minidumpFile);
        if (renamedMinidumpFile == null) {
            Log.e(TAG, "Could not rename the file " + minidumpFile.getName() + " for re-upload");
            return;
        }

        scheduleNewJob(context);
    }

    public static boolean isNetworkUnmetered(@NonNull Context context) {
        return sDelegate.isNetworkUnmetered(context);
    }

    @VisibleForTesting
    public static void setCrashUploadDelegateForTesting(CrashUploadDelegate delegate) {
        sDelegate = delegate;
    }

    // Do not instantiate this class.
    private CrashUploadUtil() {}
}

redpajama_set_name: RedPajamaGithub


text:
package me.devphp.CrystalCounter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;

public class Core extends JavaPlugin {
	private Core plugin;
	public Config config;
	public String playerList[];
	public HashMap<String, PlayerData> playerdata = new HashMap();

	public String prefix = ChatColor.GRAY + "[" + ChatColor.GREEN + "Bansql" + ChatColor.GRAY + "] " + ChatColor.RESET;
	String url = "jdbc:mysql://localhost:3306/test";
	String user = "root";
	String passwd = "root";

	Connection connection;
	Statement state;

	public void onEnable() {
		this.config = new Config(this);
		this.url = "jdbc:mysql://" + Config.getConfig().getString("config.database.host") + ":3306/" + Config.getConfig().getString("config.database.dbname");
		this.user = Config.getConfig().getString("config.database.username");
		this.passwd = Config.getConfig().getString("config.database.password");
	    // EvenetListener
		EventListener listener = new EventListener(this);
		getServer().getPluginManager().registerEvents(listener, this);

		//getCommand("ban").setExecutor(new Ban(this));
		//getCommand("pardon").setExecutor(new Pardon(this));
		this.getServer().getPluginManager().registerEvents(new EventListener(this), this);

		this.plugin = this;

		// Configuration
		this.config = new Config(this.plugin);
		Config.makeDefaultConfig();

		// Thread
		BukkitScheduler scheduler = Bukkit.getServer().getScheduler();
		scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
			@Override
			public void run() {
			// THREAD 100 = 5sec

			}
		}, 0L, 600L);

		connect();
	}

	/**
	 *
	 */
	public void connect() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e1) {
			this.getLogger().severe("Class  not found: com.mysql.jdbc.Driver");
		}

		try {
			this.connection = DriverManager.getConnection(this.url, this.user,
					this.passwd);
			this.state = this.connection.createStatement();
			java.util.Date currentDate = new java.util.Date();
	        long currenttimeInMillis = currentDate.getTime();

			this.state.execute("CREATE TABLE IF NOT EXISTS `" + config.getConfig().getString("config.database.tablename") + "` ("
							+ "`id` int(11) NOT NULL AUTO_INCREMENT,"
							+ "`uid` varchar(255) NOT NULL," // mc Userid
							+ "`uname` varchar(16) NOT NULL," // mc username
							+ "`blockbreak` int(11)  NOT NULL DEFAULT '0'," // Block break counter
							+ "`blockplaced` int(11)  NOT NULL DEFAULT '0'," // Blockplaced  counter
							+ "`kill` int(11)  NOT NULL DEFAULT '0'," // Kill  counter
							+ "`perfectKill` int(11) NOT NULL DEFAULT '0'," // Kill perfect

							+ "`death` int(11)  NOT NULL DEFAULT '0'," // Death  counter
							+ "`connectTime` int(11) NOT NULL DEFAULT '0'," // Kill perfect
							+ "PRIMARY KEY (`id`)"
							+ ") ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;");
			/*
			 * try {
			 *
			 * this.state.executeUpdate(
			 * "INSERT INTO test_table1 (pseudo, block, x, y, z) VALUES ('"
			 * +pname+"', '"+bname+"', "+x+", "+y+", "+z+")");
			 *
			 * // Statement state = conn.createStatement(); ResultSet result =
			 * this
			 * .state.executeQuery("SELECT * FROM test_table1 WHERE Pseudo = '"
			 * +args[0]+"'");
			 *
			 * } catch (SQLException e) {
			 *
			 * e.printStackTrace(); }//
			 */
		} catch (SQLException e) {
			this.getLogger().severe(e.getMessage());
			this.getLogger().severe(this.url + " " + this.user + " *******");
			this.getServer().getPluginManager().disablePlugins();
		}
	}
}


text:
function(ctkFunctionGeneratePluginUseFile filename)
  set(CTK_PLUGIN_INCLUDE_DIRS_CONFIG)

  foreach(plugin ${${CMAKE_PROJECT_NAME}_PLUGIN_LIBRARIES})
    set(${plugin}_INCLUDE_DIRS )

    # The call to ctkFunctionGetIncludeDirs returns all include dirs
    # the plugin itself needs. This does not include the plugin's
    # source dir, so we add it explicitly.
    if(${plugin}_INCLUDE_SUFFIXES)
      foreach(_suffix ${${plugin}_INCLUDE_SUFFIXES})
        list(APPEND ${plugin}_INCLUDE_DIRS ${${plugin}_SOURCE_DIR}/${_suffix})
      endforeach()
    else()
      list(APPEND ${plugin}_INCLUDE_DIRS ${${plugin}_SOURCE_DIR})
    endif()

    list(APPEND ${plugin}_INCLUDE_DIRS ${${plugin}_BINARY_DIR})

    ctkFunctionGetIncludeDirs(${plugin}_INCLUDE_DIRS ${plugin})

    set(CTK_PLUGIN_INCLUDE_DIRS_CONFIG "${CTK_PLUGIN_INCLUDE_DIRS_CONFIG}
set(${plugin}_INCLUDE_DIRS \"${${plugin}_INCLUDE_DIRS}\")")

    ctkFunctionGetLibraryDirs(${plugin}_LIBRARY_DIRS ${plugin})
    set(CTK_PLUGIN_LIBRARY_DIRS_CONFIG "${CTK_PLUGIN_LIBRARY_DIRS_CONFIG}
set(${plugin}_LIBRARY_DIRS \"${${plugin}_LIBRARY_DIRS}\")")
  endforeach()

  set(_ctk_plugin_libraries_variable ${CMAKE_PROJECT_NAME}_PLUGIN_LIBRARIES)
  set(_ctk_plugin_libraries ${${CMAKE_PROJECT_NAME}_PLUGIN_LIBRARIES})

  configure_file("${CTK_CMAKE_DIR}/../CMake/CTKPluginUseFile.cmake.in" "${filename}" @ONLY)
endfunction()


text:
'use strict';

const models = require('./index');

/**
 * The properties of the price sheet.
 *
 */
class PriceSheetProperties {
  /**
   * Create a PriceSheetProperties.
   * @member {string} [billingPeriodId] The id of the billing period resource
   * that the usage belongs to.
   * @member {string} [meterId] The meter id
   * @member {object} [meterDetails] The details about the meter. By default
   * this is not populated, unless it's specified in $expand.
   * @member {string} [meterDetails.meterName] The name of the meter, within
   * the given meter category
   * @member {string} [meterDetails.meterCategory] The category of the meter,
   * for example, 'Cloud services', 'Networking', etc..
   * @member {string} [meterDetails.meterSubCategory] The subcategory of the
   * meter, for example, 'A6 Cloud services', 'ExpressRoute (IXP)', etc..
   * @member {string} [meterDetails.unit] The unit in which the meter
   * consumption is charged, for example, 'Hours', 'GB', etc.
   * @member {string} [meterDetails.meterLocation] The location in which the
   * Azure service is available.
   * @member {number} [meterDetails.totalIncludedQuantity] The total included
   * quantity associated with the offer.
   * @member {number} [meterDetails.pretaxStandardRate] The pretax listing
   * price.
   * @member {string} [unitOfMeasure] Unit of measure
   * @member {number} [includedQuantity] Included quality for an offer
   * @member {string} [partNumber] Part Number
   * @member {number} [unitPrice] Unit Price
   * @member {string} [currencyCode] Currency Code
   */
  constructor() {
  }

  /**
   * Defines the metadata of PriceSheetProperties
   *
   * @returns {object} metadata of PriceSheetProperties
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'PriceSheetProperties',
      type: {
        name: 'Composite',
        className: 'PriceSheetProperties',
        modelProperties: {
          billingPeriodId: {
            required: false,
            readOnly: true,
            serializedName: 'billingPeriodId',
            type: {
              name: 'String'
            }
          },
          meterId: {
            required: false,
            readOnly: true,
            serializedName: 'meterId',
            type: {
              name: 'String'
            }
          },
          meterDetails: {
            required: false,
            readOnly: true,
            serializedName: 'meterDetails',
            type: {
              name: 'Composite',
              className: 'MeterDetails'
            }
          },
          unitOfMeasure: {
            required: false,
            readOnly: true,
            serializedName: 'unitOfMeasure',
            type: {
              name: 'String'
            }
          },
          includedQuantity: {
            required: false,
            readOnly: true,
            serializedName: 'includedQuantity',
            type: {
              name: 'Number'
            }
          },
          partNumber: {
            required: false,
            readOnly: true,
            serializedName: 'partNumber',
            type: {
              name: 'String'
            }
          },
          unitPrice: {
            required: false,
            readOnly: true,
            serializedName: 'unitPrice',
            type: {
              name: 'Number'
            }
          },
          currencyCode: {
            required: false,
            readOnly: true,
            serializedName: 'currencyCode',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = PriceSheetProperties;


text:
import org.junit.Test;

import java.util.*;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * Implement a MyCalendarTwo class to store your events. A new event can be added if adding the
 * event will not cause a triple booking.
 *

 * Your class will have one method, book(int start, int end). Formally, this represents a booking on
 * the half open interval [start, end), the range of real numbers x such that start <= x < end.
 *

 * A triple booking happens when three events have some non-empty intersection (ie., there is some
 * time that is common to all 3 events.)
 *

 * For each call to the method MyCalendar.book, return true if the event can be added to the
 * calendar successfully without causing a triple booking. Otherwise, return false and do not add
 * the event to the calendar.
 *

 * Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start,
 * end)
 *

 * Example 1:
 *

 * MyCalendar();
 * MyCalendar.book(10, 20); // returns true
 * MyCalendar.book(50, 60); // returns true
 * MyCalendar.book(10, 40); // returns true
 * MyCalendar.book(5, 15); // returns false
 * MyCalendar.book(5, 10); // returns true
 * MyCalendar.book(25, 55); // returns true
 * Explanation:
 * The first two events can be booked.  The third event can be double booked.
 * The fourth event (5, 15) can't be booked, because it would result in a triple booking.
 * The fifth event (5, 10) can be booked, as it does not use time 10 which is already double
 * booked.
 * The sixth event (25, 55) can be booked, as the time in [25, 40) will be double booked with the
 * third event;
 * the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the
 * second event.
 *

 *

 * Note:
 *

 * The number of calls to MyCalendar.book per test case will be at most 1000. In calls to
 * MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].
 */
public class L731 {
    @Test
    public void book() throws Exception {
        MyCalendarTwo myCalendar = new MyCalendarTwo();

        assertTrue(myCalendar.book(10, 20));
        assertTrue(myCalendar.book(50, 60));
        assertTrue(myCalendar.book(10, 40));
        assertFalse(myCalendar.book(5, 15));
        assertTrue(myCalendar.book(5, 10));
        assertTrue(myCalendar.book(25, 55));
    }

    class MyCalendarTwo {

        List<Tuple> c;
        Set<Integer> d;
        L729.MyCalendar my;

        public MyCalendarTwo() {
            this.c = new LinkedList<>();
            this.d = new TreeSet<>();
            this.my = new L729.MyCalendar();
        }

        public boolean book(int start, int end) {
            L729.MyCalendar tmp = new L729.MyCalendar(my);

            for (Tuple e : this.c) {
                if (end <= e.end && start >= e.start) {
                    if (!tmp.book(start, end))
                        return false;
                    continue;
                }

                if (start < e.end && start >= e.start) {
                    if (!tmp.book(start, e.end))
                        return false;
                    continue;
                }

                if (end <= e.end && end > e.start) {
                    if (!tmp.book(e.start, end))
                        return false;
                    continue;
                }

                if (start < e.start && end > e.end) {
                    if (!tmp.book(e.start, e.end))
                        return false;
                }
            }

            this.my = tmp;
            this.c.add(new Tuple(start, end));

            return true;
        }

        private class Tuple {
            int start, end;

            public Tuple(int start, int end) {
                this.start = start;
                this.end = end;
            }
        }
    }
}


text:
<?php

namespace Seeder\Heuristics;

/**
 * Class Condition
 * @package Seeder\Heuristics
 */
class Condition
{
    /**
     * @var
     */
    private $property;

    /**
     * @var array
     */
    private $matchers = array();

    /**
     * @param $property
     */
    public function __construct($property)
    {
        $this->property = $property;
    }

    /**
     * @param Matcher $matcher
     */
    public function addMatcher(Matcher $matcher)
    {
        $this->matchers[] = $matcher;
    }

    /**
     * @param $field
     * @return bool
     */
    public function match($field)
    {
        $properties = explode('.', $this->property);

        $value = $field;
        foreach ($properties as $property) {
            if (!is_object($value) || !isset($value->$property)) {
                return false;
            }
            $value = $value->$property;
        }

        $isMatch = false;
        foreach ($this->matchers as $matcher) {
            $isMatch = $isMatch || $matcher->match($value);
        }

        return $isMatch;
    }
}


text:
'use strict';

const toString = Object.prototype.toString;

const validationCondition = (
  option: any,
  validOption: any,
): boolean => {
  return (
    option === null ||
    option === undefined ||
    toString.call(option) === toString.call(validOption)
  );
};

module.exports = validationCondition;


text:
Helper classes
==============

This section provides a definition for several classes included in this project.

.. _CommunicationType:

CommunicationType
-----------------

.. autoclass:: udsoncan.CommunicationType

-----

.. _MemoryLocation:

MemoryLocation
--------------

.. autoclass:: udsoncan.MemoryLocation

-----

.. _DidCodec:

DidCodec
--------

.. autoclass:: udsoncan.DidCodec

-----

.. _Baudrate:

Baudrate
--------

.. autoclass:: udsoncan.Baudrate

-----

.. _DataFormatIdentifier:

DataFormatIdentifier
--------------------

.. autoclass:: udsoncan.DataFormatIdentifier

-----

.. _AddressAndLengthFormatIdentifier:

AddressAndLengthFormatIdentifier
--------------------------------

.. autoclass:: udsoncan.AddressAndLengthFormatIdentifier

-----

.. _Filesize:

Filesize
--------

.. autoclass:: udsoncan.Filesize

-----

.. _DTC:

DTC
---

.. autoclass:: udsoncan.Dtc

-----

.. _DTC_Status:

DTC.Status
----------

.. autoclass:: udsoncan::Dtc.Status

-----

.. _DTC_Severity:

DTC.Severity
------------

.. autoclass:: udsoncan::Dtc.Severity

-----

.. _DTC_Format:

DTC.Format
----------

.. autoclass:: udsoncan::Dtc.Format
   :members:
   :undoc-members:
   :member-order: bysource
   :exclude-members:  get_name

-----

.. _IOValues:

IOValues
--------

.. autoclass:: udsoncan.IOValues

-----

.. _IOMask:

IOMasks
-------

.. autoclass:: udsoncan.IOMasks

-----

.. _Routine:

Routine
-------

.. autoclass:: udsoncan.Routine
   :members:
   :undoc-members:
   :member-order: bysource
   :exclude-members: name_from_id

-----

.. _DataIdentifier:

DataIdentifier
--------------

.. autoclass:: udsoncan.DataIdentifier
   :members:
   :undoc-members:
   :member-order: bysource
   :exclude-members: name_from_id

.. _DynamicDidDefinition:

DynamicDidDefinition
--------------------

.. autoclass:: udsoncan.DynamicDidDefinition
   :members:


text:
package com.netflix.astyanax.mapping;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Deprecated
/**
 * This is a marker annotation for the field that should act as the ID column
 * @deprecated please use javax.persistence.Id instead
 */
public @interface Id {
    /**
     * The name by which this particular field should be persisted as. By
     * default, the name of the field is used
     *
     * @return column name
     */
    String value() default "";
}


text:
define(function(){ return '\
/* For testing of delite/css! plugin */\
.test3 {\
	color: blue;\
	border: 3px solid black;\
}'; } );


text:
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;

namespace Erwine.Leonard.T.RexT.ViewModel.Builder
{
    public class CharacterNode : RegexNode
    {
        public static readonly Regex TextReplaceRegex = new Regex(@"[\\*+?|{\[\]()\^\$.#]");

        public static readonly Regex NonPrintableReplaceRegex = new Regex(@"[\\*+?|{\[\]()\^\$.#]");

        public override RegexNodeType NodeType { get { return RegexNodeType.Character; } }

        private string _rawText = "";

        private string _openingText = "";

        private ReadOnlyObservableCollection<RegexNode> _items;

        public string RawText
        {
            get { return this._rawText; }
            set
            {
                string s = (value == null) ? "" : value;
                if (this._rawText == s)
                    return;

                this.RaisePropertyChanged("RawText");

                string t = CharacterNode.NonPrintableReplaceRegex.Replace(CharacterNode.TextReplaceRegex.Replace(s, (Match m) => "\\" + m.Value),
                    (Match m) => "\\x" + ((int)(m.Value[0])).ToString("X2"));

                if (this._openingText == t)
                    return;

                this._openingText = t;
                this.RaisePropertyChanged("OpeningText");
            }
        }

        public override string OpeningText { get { return this._openingText; } }

        public override string ClosingText { get { return ""; } }

        public override ReadOnlyObservableCollection<RegexNode> Items { get { return this._items; } }

        public CharacterNode()
            : base()
        {
            this._items = new ReadOnlyObservableCollection<RegexNode>(new ObservableCollection<RegexNode>());
        }
    }
}


text:
package com.orange.atk.phone.detection;

public interface DeviceDetectionListener {
	public void devicesConnectedChanged();
	public void deviceSelectedChanged();
}


text:
#pragma once
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Container/Vector.h>
#include <StatesEngine/StateObject.hpp>

class TestObject : public StatesEngine::StateObject
{
URHO3D_OBJECT (TestObject, StatesEngine::StateObject)
protected:
    bool isInitialized_;
    bool isUpdatePassed_;
    bool isDisposed_;
    float lastUpdateTimeStep_;
public:
    TestObject (Urho3D::Context *context);
    bool Init();
    bool Update(float timeStep);
    bool Dispose();

    bool IsInitialized ();
    bool IsUpdatePassed ();
    bool IsDisposed ();
    float GetLastUpdateTimeStep ();
    virtual ~TestObject ();
};

class TestStatesEngineCXX : public Urho3D::Application
{
URHO3D_OBJECT (TestStatesEngineCXX, Urho3D::Application)
public:
    TestStatesEngineCXX (Urho3D::Context *context);
    virtual void Setup ();
    virtual void Start ();
    virtual void Stop ();
    virtual ~TestStatesEngineCXX();
};


text:
if __name__ == '__main__':
    #read input
    n = int(input())
    grades = []#list of all grades achieved
    students = {}#maps a grade to a list of students having that grade
    for i in range(n):
        name = input()
        grade = float(input())
        grades.append(grade)
        if grade in students:
            students[grade].append(name)
        else:
            students[grade] = [name]
    #print result
    for name in sorted(students[sorted(set(grades))[1]]):
        print(name)


text:
using namespace OC;
using namespace OIC::Service;

constexpr int CREATE_REMOTE_SCENE_LIST = 1;

constexpr int CREATE_REMOTE_SCENE_COLLECTION = 1;
constexpr int SHOW_REMOTE_SCENE_COLLECTION = 2;

constexpr int CREATE_REMOTE_SCENE = 1;
constexpr int CREATE_REMOTE_SCENE_ACTION = 1;

constexpr int EXECUTE_REMOTE_SCENE = 1;

constexpr int SCENE_RESULT_OK = 200;

constexpr int numCreatedSceneAction = 2;
static int numRecvSceneActionCreationResp = 0;

typedef std::function< void() > Run;
Run g_currentRun;

const std::string scene_name = "Night mode";
const std::string relativetUri = OC_RSRVD_WELL_KNOWN_URI;
const std::vector<std::string> resourceTypes{ "oic.wk.sceneList", "core.light", "core.fan" };

std::mutex g_mtx;
std::mutex g_discoverymtx;
std::condition_variable g_cond;

std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> g_discoveryTask;

RCSRemoteResourceObject::Ptr g_foundListResource;
RCSRemoteResourceObject::Ptr g_foundLightResource;
RCSRemoteResourceObject::Ptr g_foundFanResource;

RemoteSceneList::Ptr g_sceneList;
RemoteSceneCollection::Ptr g_sceneCollection;
RemoteScene::Ptr g_scene;

void displaySceneList();
void runCreateRemoteSceneList();
void runRemoteSceneCollection();
void runCreateRemoteScene();
void runCreateRemoteSceneAction();
void runExecuteCreatedRemoteScene();
void runExecuteExistingRemoteScene();

// Scene Manager Remote API sample ---
void onRemoteSceneListCreated(RemoteSceneList::Ptr remoteSceneList, int eCode)
{
    std::cout << __func__ << " - error code : " << eCode << std::endl;

    if (eCode == SCENE_RESULT_OK)
    {
        g_sceneList = std::move(remoteSceneList);
        g_currentRun = runRemoteSceneCollection;
    }
    else
    {
        std::cout << "Create Remote scene list failed." << std::endl;
        g_currentRun = runCreateRemoteSceneList;
    }
    g_currentRun();
}

void onRemoteSceneCollectionCreated(RemoteSceneCollection::Ptr remoteSceneCol, int eCode)
{
    std::cout << __func__ << " - error code : " << eCode << std::endl;

    if (eCode == SCENE_RESULT_OK)
    {
        g_sceneCollection = remoteSceneCol;
        g_currentRun = runCreateRemoteScene;
    }
    else
    {
        std::cout << "Create Remote scene collection failed." << std::endl;
        g_currentRun = runRemoteSceneCollection;
    }

    g_currentRun();
}

void onRemoteSceneCreated(RemoteScene::Ptr remoteScene, int eCode)
{
    std::cout << __func__ << " - error code : " << eCode << std::endl;

    if (eCode == SCENE_RESULT_OK)
    {
        g_scene = remoteScene;

        g_currentRun = runCreateRemoteSceneAction;
    }
    else
    {
        std::cout << "Create Remote scene failed." << std::endl;
        g_currentRun = runCreateRemoteScene;
    }

    g_currentRun();
}

void onRemoteSceneActionCreated(RemoteSceneAction::Ptr, int eCode)
{
    std::cout << __func__ << " - error code : " << eCode << std::endl;

    if (eCode == SCENE_RESULT_OK)
    {
        g_currentRun = runExecuteCreatedRemoteScene;
    }
    else
    {
        std::cout << "Create Remote scene action failed." << std::endl;
        g_currentRun = runCreateRemoteSceneAction;
    }

    numRecvSceneActionCreationResp++;

    if(numCreatedSceneAction == numRecvSceneActionCreationResp)
    {
        g_currentRun();
    }
}

void onRemoteSceneExecuted(const std::string &sceneName, int eCode)
{
    std::cout << __func__ << " - scene name : " << sceneName
              <<  ", error code : " << eCode << std::endl;

    if (eCode != SCENE_RESULT_OK)
    {
        std::cout << "Execute scene failed." << std::endl;
    }

    g_currentRun();
}

// --- Scene Manager Remote API sample

void createRemoteSceneList()
{
    if (g_foundListResource)
    {
        RemoteSceneList::createInstance(g_foundListResource, onRemoteSceneListCreated);
    }
    else
    {
        std::cout << "Scene List Resource is not discovered." << std::endl;
        g_currentRun();
    }
}

void createRemoteSceneCollection()
{
    if (!g_sceneList)
    {
        return;
    }

    g_sceneList->addNewSceneCollection(onRemoteSceneCollectionCreated);
}

void showRemoteSceneCollection()
{
    if (!g_sceneList)
    {
        return;
    }

    if (g_sceneList->getRemoteSceneCollections().size() == 0)
    {
        return;
    }

    g_sceneCollection = g_sceneList->getRemoteSceneCollections().at(0);

    if( g_sceneCollection->getRemoteScenes().size() == 0)
    {
        return;
    }

    g_scene = g_sceneCollection->getRemoteScenes().begin()->second;
}

void createRemoteScene()
{
    if (!g_sceneCollection)
    {
        return;
    }

    g_sceneCollection->addNewScene(scene_name, onRemoteSceneCreated);
}

void createRemoteSceneAction(
    RemoteScene::Ptr scene, RCSRemoteResourceObject::Ptr member,
    const std::string &key, const std::string &value)
{
    if (scene && member)
    {
        g_scene->addNewSceneAction(member, key, RCSResourceAttributes::Value(value),
            onRemoteSceneActionCreated);
    }
}

void createRemoteSceneActions()
{
    createRemoteSceneAction(g_scene, g_foundLightResource, "power", "on");
    createRemoteSceneAction(g_scene, g_foundFanResource, "speed", "50");
}

void executeScene()
{
    displaySceneList();

    if (g_scene)
    {
        g_scene->execute(onRemoteSceneExecuted);
        std::cout << "\n\t'" << g_scene->getName() << "' is executed!\n" << std::endl;
    }
}

// --- Scene Manager Remote API sample
void configurePlatform()
{
    PlatformConfig config
    {
        OC::ServiceType::InProc, ModeType::Both, OC_DEFAULT_ADAPTER, OC::QualityOfService::LowQos
    };
    OCPlatform::Configure(config);
}

int processUserInput(int min, int max)
{
    assert(min <= max);

    int input = 0;

    std::cin >> input;

    if (!std::cin.fail())
    {
        if (input == max + 1)
        {
            exit(0);
        }
        if (min <= input && input <= max)
        {
            return input;
        }
    }

    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    throw std::runtime_error("Invalid Input, please try again");
}

void displaySceneList()
{
    if (!g_sceneList)
    {
        return;
    }

    std::cout << "\t" << g_sceneList->getName() << "(SceneList)" << std::endl;

    if (!g_sceneCollection)
    {
        return;
    }

    std::cout << "\t\t   |_ _ _ " << g_sceneCollection->getId() << " (SceneCollection)" << std::endl;

    for( const auto &it_scene : g_sceneCollection->getRemoteScenes() )
    {
        std::cout << "\t\t\t   |_ _ _ " << it_scene.first << " (Scene)" << std::endl;

        auto sceneActionList = it_scene.second->getRemoteSceneActions();
        for (const auto &it : sceneActionList)
        {
            auto attr = it->getExecutionParameter();
            for (const auto &att : attr)
            {
                std::cout << "\t\t\t      \t\t|_ _ _ ";
                std::cout << it->getRemoteResourceObject()->getUri() << " : ";
                std::cout << att.key() << " - " << att.value().toString() << std::endl;
            }
        }
    }
}

void displayClear(Run runFunc)
{
    auto ret = std::system("/usr/bin/clear");
    if(ret == -1)
    {
        std::cout << "clear error!" << std::endl;
    }
    g_currentRun = runFunc;
}

void displayCreateRemoteSceneListMenu()
{
    std::cout << "========================================================\n";
    std::cout << CREATE_REMOTE_SCENE_LIST  << ". Create a RemoteSceneList \n";
    std::cout << CREATE_REMOTE_SCENE_LIST + 1  << ". Quit                 \n";
    std::cout << "========================================================\n";
}

void displayRemoteSceneCollectionMenu()
{
    std::cout << "========================================================               \n";
    std::cout << CREATE_REMOTE_SCENE_COLLECTION  << ". Create a RemoteSceneCollection    \n";
    std::cout << SHOW_REMOTE_SCENE_COLLECTION  << ". Show existing RemoteSceneCollection \n";
    std::cout << SHOW_REMOTE_SCENE_COLLECTION + 1  << ". Quit                            \n";
    std::cout << "========================================================               \n";
}

void displayRemoteSceneCreationMenu()
{
    std::cout << "========================================================\n";
    std::cout << CREATE_REMOTE_SCENE  << ". Create a RemoteScene          \n";
    std::cout << CREATE_REMOTE_SCENE + 1  << ". Quit                      \n";
    std::cout << "========================================================\n";
}

void displayRemoteSceneActionCreationMenu()
{
    std::cout << "========================================================   \n";
    std::cout << CREATE_REMOTE_SCENE_ACTION  << ". Create RemoteSceneActions \n";
    std::cout << CREATE_REMOTE_SCENE_ACTION + 1  << ". Quit                  \n";
    std::cout << "========================================================   \n";
}

void displayExecuteCreatedRemoteSceneCreationMenu()
{
    std::cout << "========================================================\n";
    std::cout << EXECUTE_REMOTE_SCENE  << ". Execute RemoteScene          \n";
    std::cout << EXECUTE_REMOTE_SCENE + 1  << ". Quit                     \n";
    std::cout << "========================================================\n";
}

void displayExecuteExistingRemoteSceneCreationMenu()
{
    std::cout << "========================================================\n";
    std::cout << EXECUTE_REMOTE_SCENE  << ". Execute a first RemoteScene  \n";
    std::cout << EXECUTE_REMOTE_SCENE + 1  << ". Quit                     \n";
    std::cout << "========================================================\n";
}

void runExecuteExistingRemoteScene()
{
    displaySceneList();

    displayExecuteExistingRemoteSceneCreationMenu();

    try
    {
        int command = processUserInput(EXECUTE_REMOTE_SCENE, EXECUTE_REMOTE_SCENE);
        switch(command)
        {
            case EXECUTE_REMOTE_SCENE:
                executeScene();
                displayClear(runExecuteExistingRemoteScene);
                break;
        }
    } catch (std::exception &e)
    {
        std::cout << e.what() << std::endl;
        g_currentRun();
    }
}

void runExecuteCreatedRemoteScene()
{
    displaySceneList();

    displayExecuteCreatedRemoteSceneCreationMenu();

    try
    {
        int command = processUserInput(EXECUTE_REMOTE_SCENE, EXECUTE_REMOTE_SCENE);
        switch(command)
        {
            case EXECUTE_REMOTE_SCENE:
                executeScene();
                displayClear(runExecuteCreatedRemoteScene);
                break;
        }
    } catch (std::exception &e)
    {
        std::cout << e.what() << std::endl;
        g_currentRun();
    }
}

void runCreateRemoteSceneAction()
{
    displaySceneList();

    displayRemoteSceneActionCreationMenu();

    try
    {
        int command = processUserInput(CREATE_REMOTE_SCENE_ACTION, CREATE_REMOTE_SCENE_ACTION);
        switch(command)
        {
            case CREATE_REMOTE_SCENE_ACTION:
                createRemoteSceneActions();
                displayClear(runExecuteCreatedRemoteScene);
                break;
        }
    } catch (std::exception &e)
    {
        std::cout << e.what() << std::endl;
        g_currentRun();
    }
}

void runCreateRemoteScene()
{
    displaySceneList();

    displayRemoteSceneCreationMenu();

    try
    {
        int command = processUserInput(CREATE_REMOTE_SCENE, CREATE_REMOTE_SCENE);
        switch(command)
        {
            case CREATE_REMOTE_SCENE:
                createRemoteScene();
                displayClear(runCreateRemoteSceneAction);
                break;
        }
    } catch (std::exception &e)
    {
        std::cout << e.what() << std::endl;
        g_currentRun();
    }
}

void runRemoteSceneCollection()
{
    displaySceneList();

    displayRemoteSceneCollectionMenu();

    try
    {
        int command = processUserInput(CREATE_REMOTE_SCENE_COLLECTION, SHOW_REMOTE_SCENE_COLLECTION);
        switch(command)
        {
            case CREATE_REMOTE_SCENE_COLLECTION:
                createRemoteSceneCollection();
                displayClear(runCreateRemoteScene);
                break;
            case SHOW_REMOTE_SCENE_COLLECTION:
                showRemoteSceneCollection();
                displayClear(runExecuteExistingRemoteScene);
                g_currentRun();
                break;
        }
    } catch (std::exception &e)
    {
        std::cout << e.what() << std::endl;
        g_currentRun();
    }
}

void runCreateRemoteSceneList()
{
    displayCreateRemoteSceneListMenu();

    try
    {
        int command = processUserInput(CREATE_REMOTE_SCENE_LIST, CREATE_REMOTE_SCENE_LIST);
        switch(command)
        {
            case CREATE_REMOTE_SCENE_LIST:
                createRemoteSceneList();
                displayClear(runRemoteSceneCollection);
                break;
        }
    }
    catch (std::exception &e)
    {
        std::cout << e.what() << std::endl;
        g_currentRun();
    }
}

void onResourceDiscovered(std::shared_ptr<RCSRemoteResourceObject> foundResource)
{
    std::lock_guard< std::mutex > lock(g_discoverymtx);
    std::cout << "onResourceDiscovered callback" << std::endl;

    std::string resourceURI = foundResource->getUri();
    std::string hostAddress = foundResource->getAddress();
    std::vector< std::string > vecRTs = foundResource->getTypes();

    std::cout << "\t\tResource URI : " << resourceURI << std::endl;
    std::cout << "\t\tResource Host : " << hostAddress << std::endl;

    // if the found resource is a scene list resource
    if (std::find(vecRTs.begin(), vecRTs.end(), "oic.wk.sceneList") != vecRTs.end())
    {
        g_foundListResource = foundResource;
    }

    // if the found resource is a light resource
    else if (std::find(vecRTs.begin(), vecRTs.end(), "core.light") != vecRTs.end())
    {
        g_foundLightResource = foundResource;
    }

    // if the found resource is a fan resource
    else if (std::find(vecRTs.begin(), vecRTs.end(), "core.fan") != vecRTs.end())
    {
        g_foundFanResource = foundResource;
    }

    if (g_foundListResource && g_foundLightResource && g_foundFanResource)
    {
        g_discoveryTask->cancel();
        return;
    }

    g_cond.notify_all();
}

void discoverResource()
{
    std::cout << "Wait 4 seconds until discovered." << std::endl;

    try
    {
        g_discoveryTask
            = RCSDiscoveryManager::getInstance()->discoverResourceByTypes(RCSAddress::multicast(),
                    relativetUri, resourceTypes, &onResourceDiscovered);
    }
    catch (const RCSPlatformException &e)
    {
        std::cout << e.what() << std::endl;
    }
    std::unique_lock<std::mutex> lck(g_mtx);

    g_cond.wait_for(lck, std::chrono::seconds(4));
    return;
}

int main()
{
    configurePlatform();

    try
    {
        discoverResource();

        g_currentRun = runCreateRemoteSceneList;
        g_currentRun();
    }
    catch(std::exception &e)
    {
        std::cout << e.what() << std::endl;
        return 0;
    }

    while (true)
    {
    }

    std::cout << "Stopping the scene client" << std::endl;

    return 0;
}


text:
package xxx.screwdriver.forsakenscissors.ui;

import java.util.ArrayList;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Rectangle;

import xxx.screwdriver.forsakenscissors.Game;

public class DialogueOverlay {

	protected float x;
	protected float y;
	protected int width;
	protected int height;
	protected static int WINDOW_WIDTH = Game.RESOLUTION_WIDTH / 4;
	protected static int WINDOW_HEIGHT = 100;
	protected static int WINDOW_X = 0;
	protected static int WINDOW_Y = Game.RESOLUTION_HEIGHT - WINDOW_HEIGHT;
	protected static int CHARACTER_RECTANGLE_X = 20;
	protected static int CHARACTER_RECTANGLE_Y = WINDOW_Y - 20;
	protected static int CHARACTER_RECTANGLE_SIZE = 80;
	protected static int CHARACTER_NAME_X = CHARACTER_RECTANGLE_X + CHARACTER_RECTANGLE_SIZE + 20;
	protected static int CHARACTER_NAME_Y = CHARACTER_RECTANGLE_Y;
	protected static int TEXT_X = CHARACTER_NAME_X;
	protected static int TEXT_Y = CHARACTER_NAME_Y + 20;
	protected static Rectangle CHARACTER_ICON_RECTANGLE = new Rectangle(CHARACTER_RECTANGLE_X, CHARACTER_RECTANGLE_Y,
																		CHARACTER_RECTANGLE_SIZE, CHARACTER_RECTANGLE_SIZE);
	protected String character_name = "NULL";
	protected String line = "NULL";
	protected boolean active = false;
	private String rendered;
	private ArrayList<String> variants;
	private int selected_variant = 0;
	private int character_index = 0;
	private int typewriter_timer_initial = 3;
	private int typewriter_timer = typewriter_timer_initial;

	public DialogueOverlay(WindowManager window_manager) {
		this.variants = new ArrayList<String>();
	}

	public void update(GameContainer container) {
		//typewriter effect
		if (this.active) {
			if (this.typewriter_timer == 0) {
				if (this.character_index < line.length()) {
					//3 lines!
					if (Game.getInstance().getResourceManager().getFont().getHeight(this.rendered) > 40) {
						this.rendered = this.rendered.replaceFirst(".*\n", "");
					}
					this.rendered += this.line.charAt(this.character_index++);
					this.typewriter_timer = typewriter_timer_initial;
				}
			} else {
				this.typewriter_timer--;
			}
		} else {
			this.rendered = "";
		}
	}

	public void render(Graphics g) {
		if (!this.active) return;
		g.draw(CHARACTER_ICON_RECTANGLE);
		g.drawString(this.character_name, CHARACTER_NAME_X, CHARACTER_NAME_Y);
		g.drawString(this.rendered, TEXT_X, TEXT_Y);
		for (int i=0; i<this.variants.size(); i++) {
			if (i == this.selected_variant) {
				g.setColor(new Color(0,0,0,100));
				g.fillRect(TEXT_X, TEXT_Y+40+i*20, WINDOW_WIDTH, 20);
				g.setColor(new Color(0,0,0));
			}
			g.drawString("\u25B7 "+this.variants.get(i), TEXT_X, TEXT_Y+40+i*20);
		}
	}

	public void setTextLine(String line) {
		ArrayList<String> lines = new ArrayList<String>();
		String[] words = line.split(" ");
		String result = "";
		for (int i=0; i<words.length; i++) {
			if (Game.getInstance().getResourceManager().getFont().getWidth(result + words[i] + " ") <= WINDOW_WIDTH) {
				result += words[i] + " ";
			} else {
				lines.add(result);
				result = "";
			}
		}
		this.line = String.join("\n", lines);
	}

	public void setCharacterName(String character_name) {
		this.character_name = character_name;
	}

	public void setVariants(ArrayList<String> variants) {
		this.variants = variants;
	}

	public int getVariantsCount() {
		return this.variants.size();
	}

	public void setActive(boolean flag) {
		this.active = flag;
		if (!this.active) {
			this.reset();
		}
	}

	public void setSelectedVariant(int variant) {
		if (variant <= this.variants.size() - 1) {
			this.selected_variant = variant;
		}
	}

	private void reset() {
		this.rendered = "";
		this.selected_variant = 0;
		this.character_index = 0;
		this.typewriter_timer = this.typewriter_timer_initial;
	}

	public boolean isActive() {
		return this.active;
	}

	public int getSelectedVariant() {
		return this.selected_variant;
	}
}


text:
layout: post
title: Find out if Google's mod_pagespeed is working on your site
date: 2014-10-18T00:00:00.000Z
---

Google have built a free server add-on called **mod_pagespeed**, which implements a few of their recommended improvements to boost the speed of your site.

The tool supports *Nginx* and *Apache*, and in my experience is pretty straightforward to install.

Naturally, once you've installed it you'll want to check it's working...and how you do that might not be immediately obvious.

Thankfully, Google have included a few simple HTTP headers, which are:

- nginx
	- `X-Page-Speed`
- Apache
	- `X-Mod-Pagespeed`

To find them, you'll have to:

1. Open your browser's developer tools
2. Switch to the network view (where you should be able to inspect each network request)
3. Inspect the headers of the request you want to check **mod_pagespeed** for (probably just the / or index page)..

If that sounds waaay to complicated for you, you're free to use my free site: [Is mod_pagespeed working](https://ismodpagespeedworking.com)

Enjoy! Post here in the comments if you find anything wrong with the site.


text:
def test_syntax(code):
    try:
        exec(code)
    except SyntaxError:
        print("SyntaxError")

# invalid micropython decorators
test_syntax("@micropython.a\ndef f(): pass")
test_syntax("@micropython.a.b\ndef f(): pass")


text:
package httprequest_test

import (
	"net/http"
	"net/http/httptest"

	"github.com/julienschmidt/httprouter"
	gc "gopkg.in/check.v1"

	"github.com/juju/httprequest"
)

type contextSuite struct{}

var _ = gc.Suite(&contextSuite{})

type testRequest struct {
	httprequest.Route `httprequest:"GET /foo"`
}

func (s *contextSuite) TestContextCancelledWhenDone(c *gc.C) {
	var ch <-chan struct{}
	hnd := testServer.Handle(func(p httprequest.Params, req *testRequest) {
		ch = p.Context.Done()
	})
	router := httprouter.New()
	router.Handle(hnd.Method, hnd.Path, hnd.Handle)
	srv := httptest.NewServer(router)
	_, err := http.Get(srv.URL + "/foo")
	c.Assert(err, gc.Equals, nil)
	select {
	case <-ch:
	default:
		c.Fatal("context not canceled at end of handler.")
	}
}


text:
package com.guardtime.ksi.service.client.http;

import com.guardtime.ksi.pdu.PduVersion;
import com.guardtime.ksi.service.client.ServiceCredentials;

import java.net.URL;

/**
 * Abstract class for HTTP client configuration.
 */
public abstract class AbstractHttpClientSettings {

    private static final int UNDEFINED_TIMEOUT = -1;

    /**
     * @return The signing service URL.
     */
    public abstract URL getSigningUrl();

    /**
     * @return The extender service URL.
     */
    public abstract URL getExtendingUrl();

    /**
     * @return The publications file URL.
     */
    public abstract URL getPublicationsFileUrl();

    /**
     * @return The service credentials.
     */
    public abstract ServiceCredentials getCredentials();

    /**
     * @return The PDU version.
     */
    public abstract PduVersion getPduVersion();

    /**
     * @return The proxy URL. By default proxy isn't used and null is returned.
     */
    public URL getProxyUrl() {
        return null;
    }

    /**
     * @return The proxy username. By default proxy isn't used and null is returned.
     */
    public String getProxyUser() {
        return null;
    }

    /**
     * @return The proxy user password. By default proxy isn't used and null is returned.
     */
    public String getProxyPassword() {
        return null;
    }

    /**
     * Determines the timeout in milliseconds until a connection is established.
     *

     * A timeout value of zero is interpreted as an infinite timeout. A negative value is interpreted as undefined
     * (system default).
     *

     * Default value is -1.
     *

     *
     * @return Connection timeout in milliseconds as int.
     */
    public int getConnectionTimeout() {
        return UNDEFINED_TIMEOUT;
    }

    /**
     * Defines the socket read timeout in milliseconds, which is the timeout for waiting for data or a maximum period
     * inactivity between two consecutive data packets.
     *

     * A timeout value of zero is interpreted as an infinite timeout. A negative value is interpreted as undefined
     * (system default).
     *

     * Default value is -1.
     *

     *
     * @return Read timeout in milliseconds as int.
     */
    public int getReadTimeout() {
        return UNDEFINED_TIMEOUT;
    }

}


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

using CatFight.Data;
using CatFight.Items.Weapons;
using CatFight.Players.Schematics;
using CatFight.Util;

using JetBrains.Annotations;

namespace CatFight.Fighters.Loadouts
{
    [Serializable]
    public sealed class WeaponLoadoutSlot : LoadoutSlot
    {
        private readonly Dictionary<int, int> _weaponTypeVotes = new Dictionary<int, int>();

        [CanBeNull]
        public Weapon Weapon { get; private set; }

        public WeaponLoadoutSlot(Fighter fighter, SchematicSlotData slotData)
            : base(fighter, slotData)
        {
        }

        public override void Process(SchematicSlot schematicSlot)
        {
            WeaponSchematicSlot weaponSlot = (WeaponSchematicSlot)schematicSlot;
            if(null == weaponSlot.WeaponItem) {
                return;
            }

            int currentCount = _weaponTypeVotes.GetOrDefault(weaponSlot.WeaponItem.Id);
            _weaponTypeVotes[weaponSlot.WeaponItem.Id] = currentCount + 1;
        }

        public override void Complete()
        {
            int winnerType = VoteHelper.GetWinner(_weaponTypeVotes);
            WeaponData.WeaponDataEntry weaponData = DataManager.Instance.GameData.Weapons.Entries.GetOrDefault(winnerType);
            if(null == weaponData) {
                return;
            }

            Weapon = WeaponFactory.Create(Fighter, SlotData.Id, weaponData);
            if(null != Weapon) {
                Weapon.Strength = _weaponTypeVotes[winnerType];
            }
        }

        public override LoadoutSlotItem GetSlotItemPrefab()
        {
            return null == Weapon ? null : SlotData.SlotItemPrefabs.OfType<WeaponLoadoutSlotItem>().FirstOrDefault(weaponSlotItemPrefab => weaponSlotItemPrefab.Type == Weapon.WeaponType);
        }
    }
}


text:
package controlP5;

import processing.core.PApplet;

public class SplitPanelController extends Controller {

	public class Divider extends Controller {

		protected Divider(ControlP5 theControlP5, ControllerGroup theParent,
				String theName, float theX, float theY, int theWidth,
				int theHeight) {
			super(theControlP5, theParent, theName, theX, theY, theWidth, theHeight);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void setValue(float theValue) {
			// TODO Auto-generated method stub
		}

		@Override
		public void addToXMLElement(ControlP5XMLElement theXMLElement) {
			// TODO Auto-generated method stub

		}

		public void draw(PApplet theApplet)
		{
			float[] divCoords = new float[4];
			getDividerCoords(divCoords);

			CColor col = getColor();
			theApplet.noStroke();//stroke(col.getForeground());
			if (theApplet.mouseX > divCoords[0] && theApplet.mouseX < divCoords[2] &&
			    theApplet.mouseY > divCoords[1] && theApplet.mouseY < divCoords[3]) {
				theApplet.fill(col.getBackground());
			} else {
				theApplet.noFill();
			}
			theApplet.rect(divCoords[0], divCoords[1], divCoords[2] - divCoords[0], divCoords[3] - divCoords[1]);
		}
		boolean m_PreviousMouseInside = false;
		boolean m_bIsDraggingDivider = false;
		boolean m_PreviousMousePressed = false;
		@Override
		public void updateInternalEvents(PApplet theApplet)
		{
			float[] divCoords = new float[4];
			getDividerCoords(divCoords);

			boolean isMouseInside = theApplet.mouseX >= divCoords[0] && theApplet.mouseY >= divCoords[1] &&
				theApplet.mouseX <= divCoords[2] && theApplet.mouseY <= divCoords[3];
	        if (m_bIsDraggingDivider)
	        {
	        	m_bIsDraggingDivider = theApplet.mousePressed;
	        	if (m_bIsDraggingDivider)
	        	{
	        		m_DividerLocation =	(m_SplitType == HORIZONTAL?
						(theApplet.mouseX - SplitPanelController.this.position.x()) / SplitPanelController.this.width :
		    			(theApplet.mouseY - SplitPanelController.this.position.y()) / SplitPanelController.this.height);
	        	}

		        if (isFastUpdate() || !m_bIsDraggingDivider)
		        {// update the panes
		        	setDividerLocation(m_DividerLocation);
		        	theApplet.loop();
		        	//theApplet.redraw();
		        }
	        }
	        else if (isMouseInside && !m_PreviousMousePressed)
	        {
	        	if (theApplet.mousePressed && !ControlP5.keyHandler.isAltDown)
	        	{
	            	m_bIsDraggingDivider = true;
	        	}
	        	theApplet.cursor(PApplet.CROSS);
	        }
	        else if (m_PreviousMouseInside)
	        {
	        	theApplet.cursor(PApplet.ARROW);
	        }

	        m_PreviousMouseInside = isMouseInside;
	        m_PreviousMousePressed = theApplet.mousePressed;
		}

	}

	public static final int HORIZONTAL	= 0;
	public static final int VERTICAL 	= 1;
	public static final int LEFT		= 0;
	public static final int TOP			= 0;
	public static final int RIGHT      	= 1;
	public static final int BOTTOM     	= 1;

//	float _x;
//	float _y;
//	int _width;
//	int _height;

	int 	m_SplitType = HORIZONTAL;		///< split type: VERTICAL or HORIZONTAL
	double 	m_DividerLocation = 0.5; 	///< initial location of divider
	int		m_DividerThickness = 7; 	///< thickness of divider bar
	PanelController m_Panes[]; 			///< 2 panes: left, right  or top, bottom
	private boolean	m_bFastUpdate	= false; 	///< update the child panes while the split page is changing (e.g resize)

	public SplitPanelController(ControlP5 theControlP5, String theName, float theX, float theY, int theWidth, int theHeight)
	{
	    super(theControlP5,  (Tab)(theControlP5.getTab("default")), theName, theX, theY, theWidth, theHeight);
//	    _x = theX; _y = theY; _width = theWidth; _height = theHeight;
	    m_Panes = new PanelController[2];
	    m_Panes[LEFT] = new PanelController(theControlP5, theName+"0", 0, 0, 1, 1);
	    m_Panes[RIGHT] = new PanelController(theControlP5, theName+"1", 0, 0, 1, 1);
	    setDividerLocation(0.5);
	    theControlP5.register(this);
	}

	public void setSplitType(int st)
	{
		if (m_SplitType != st)
		{
			m_SplitType = st;
			setDividerLocation(m_DividerLocation);
		}
	}

	public void setDividerLocation(double dProportionalLocation)
	{
		m_DividerLocation = Math.min(Math.max(dProportionalLocation, 0.0), 1.0);
		if (m_SplitType == HORIZONTAL)
		{
			m_Panes[LEFT].setPosition(position.x(), position.y());
			m_Panes[RIGHT].setPosition(position.x() + (float)(width * m_DividerLocation) + m_DividerThickness / 2, position.y());
			m_Panes[LEFT].setSize((int)(width * m_DividerLocation - m_DividerThickness / 2), height);
			m_Panes[RIGHT].setSize((int)(width * (1.f - m_DividerLocation) - m_DividerThickness / 2), height);
		}
		else
		{
			m_Panes[TOP].setPosition(position.x(), position.y());
			m_Panes[BOTTOM].setPosition(position.x() , position.y() + (float)(height * m_DividerLocation) + m_DividerThickness / 2);
			m_Panes[TOP].setSize(width, (int)(height * m_DividerLocation - m_DividerThickness / 2));
			m_Panes[BOTTOM].setSize(width, (int)(height * (1.f - m_DividerLocation) - m_DividerThickness / 2));
		}
	}

	Divider m_Divider;
	public void addDivider()
	{
		m_Divider = new Divider(this.controlP5, this.getTab(), this.name()+"_divider", 0, 0, 1, 1);
	}

	public PanelController getPane(int side)
	{
		return m_Panes[side];
	}

	@Override
	public void setValue(float arg0) {
	}
	@Override
	public void addToXMLElement(ControlP5XMLElement arg0) {
	}

	/// left, top, right, bottom
	void getDividerCoords(float[] coords)
	{
		if (m_SplitType == HORIZONTAL)
		{
			coords[0] = (position.x() + width * (float)m_DividerLocation - m_DividerThickness/2);
			coords[1] = position.y();
			coords[2] = coords[0] + m_DividerThickness;
			coords[3] = coords[1] + height;
		}
		else
		{
			coords[0] = position.x();
			coords[1] = (position.y() + height * (float)m_DividerLocation - m_DividerThickness/2);
			coords[2] = coords[0] + width;
			coords[3] = coords[1] + m_DividerThickness;
		}
	}

	@Override
	public void draw(PApplet theApplet)
	{
	}

	@Override
	public void setSize(int theWidth, int theHeight) {
		super.setSize(theWidth, theHeight);
		setDividerLocation(m_DividerLocation); // update panes
	}

	@Override
	public void setPosition(float x, float y) {
		super.setPosition(x, y);
		setDividerLocation(m_DividerLocation); // update panes
	}

	@Override
	public void setVisible(boolean theFlag)
	{
		super.setVisible(theFlag);
		m_Panes[0].setVisible(theFlag);
		m_Panes[1].setVisible(theFlag);
		if (m_Divider != null)
			m_Divider.setVisible(theFlag);
	}

	@Override
	public void hide()
	{
		setVisible(false);
	}

	@Override
	public void show()
	{
		setVisible(true);
	}

	@Override
	public void moveTo(java.lang.String theTabName)
	{
		super.moveTo(theTabName);
		m_Panes[0].moveTo(theTabName);
		m_Panes[1].moveTo(theTabName);
		if (m_Divider != null)
			m_Divider.moveTo(theTabName);
	}

	public void setFastUpdate(boolean m_bFastUpdate) {
		this.m_bFastUpdate = m_bFastUpdate;
	}

	public boolean isFastUpdate() {
		return m_bFastUpdate;
	}
}


text:
#ifndef VICE_VSIDUIUNIX_H
#define VICE_VSIDUIUNIX_H

#include "ui.h"

extern void vsid_ctrl_widget_set_parent(ui_window_t p);
extern ui_window_t build_vsid_ctrl_widget(void);
extern void ui_vsid_setpsid(const char *psid);
extern void ui_vsid_settune(const int tune);
extern void ui_vsid_setcopyright(const char *c);
extern void ui_vsid_setauthor(const char *a);
extern void ui_vsid_setsync(const char *a);
extern void ui_vsid_setmodel(const char *a);
extern void ui_vsid_setirq(const char *a);

#endif


text:
layout: post
title: fat asses compilation part 2
titleinfo: pornvd
desc: Watch fat asses compilation part 2. Pornhub is the ultimate xxx porn and sex site.
---

fat asses compilation part 2

Watch fat asses compilation part 2. Pornhub is the ultimate xxx porn and sex site.


text:
echo
echo -n "Set of return codes so far: [ "
cat ompl_run_test_codes | sort | uniq | tr "\\n" " "
echo "]"
cat ompl_run_test_count && cat ompl_run_test_codes | perl -e 'print reverse <>'


text:
package org.codarama.diet.packaging;

import com.google.common.collect.Sets;
import org.apache.maven.artifact.Artifact;
import org.zeroturnaround.zip.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * An {@link ArtifactPackager} for .war artifacts.
 */
public class WarArtifactPackager extends AbstractArtifactPackager implements ArtifactPackager {

    public File packageArtifact(Artifact currentArtifact, JarFile minimizedJar) throws IOException {

        final Set<ZipEntrySource> resultEntriesSet = Sets.newHashSet();
        ZipUtil.iterate(currentArtifact.getFile(), new ZipEntryCallback() {

            public void process(InputStream in, ZipEntry warEntry) throws IOException {

                final String warEntryName = warEntry.getName();
                final boolean entryIsNotInLibDirs =
                        !warEntry.isDirectory() && (warEntryName.startsWith("lib") || warEntryName.startsWith("WEB-INF/lib"));

                if (entryIsNotInLibDirs) {
                    resultEntriesSet.add(new ByteSource(warEntryName, readBytes(in)));
                }
            }
        });
        resultEntriesSet.add(new FileSource("lib/minimized.jar", new File(minimizedJar.getName())));

        final ZipFile warFile = new ZipFile(currentArtifact.getFile());
        final File result = new File(appendUnderscoreMinimizedToArtifactName(warFile.getName()));

        final ZipEntrySource[] newEntries = resultEntriesSet.toArray(new ZipEntrySource[resultEntriesSet.size()]);
        ZipUtil.addEntries(
                currentArtifact.getFile(),
                newEntries,
                result
        );

        return result;
    }
}


text:
"use strict";
var chai = require("chai");
var sinon = require("sinon");
var sinonChai = require("sinon-chai");
var expect = chai.expect;
chai.use(sinonChai);

var proxyquire =  require('proxyquire').noPreserveCache();

var expressRouter = require('../../glue').aDummyRouter();

var required = {
    'express': {Router: sinon.stub().returns(expressRouter)},
    './operations/login': sinon.spy(),
    './user': sinon.spy()
};

describe('api', function(){

    it('should get an express.Router()', function() {
        var api = proxyquire("../../main/routes/api", required);

        expect( required['express'].Router ).to.have.been.called;
    });

    it('should return the express.Router()', function(){
        var api = proxyquire("../../main/routes/api", required);

        expect( api ).to.equal( expressRouter );
    });

    it('pass /user to the router at "./user"', function(){
        var api = proxyquire("../../main/routes/api", required);

        expect( expressRouter.use ).to.have.been.calledWith( '/user', required['./user'] );
    });

});


text:
package backtype.storm.utils;

import junit.framework.TestCase;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StormBoundedExponentialBackoffRetryTest extends TestCase {
    private static final Logger LOG = LoggerFactory.getLogger(StormBoundedExponentialBackoffRetryTest.class);

    @Test
    public void testExponentialSleepLargeRetries() throws Exception {
        int baseSleepMs = 10;
        int maxSleepMs = 1000;
        int maxRetries = 900;
        validateSleepTimes(baseSleepMs, maxSleepMs, maxRetries);

    }

    @Test
    public void testExponentialSleep() throws Exception {
        int baseSleepMs = 10;
        int maxSleepMs = 100;
        int maxRetries = 40;
        validateSleepTimes(baseSleepMs, maxSleepMs, maxRetries);
    }

    @Test
    public void testExponentialSleepSmallMaxRetries() throws Exception {
        int baseSleepMs = 1000;
        int maxSleepMs = 5000;
        int maxRetries = 10;
        validateSleepTimes(baseSleepMs, maxSleepMs, maxRetries);
    }

    @Test
    public void testExponentialSleepZeroMaxTries() throws Exception {
        int baseSleepMs = 10;
        int maxSleepMs = 100;
        int maxRetries = 0;
        validateSleepTimes(baseSleepMs, maxSleepMs, maxRetries);
    }

    @Test
    public void testExponentialSleepSmallMaxTries() throws Exception {
        int baseSleepMs = 10;
        int maxSleepMs = 100;
        int maxRetries = 10;
        validateSleepTimes(baseSleepMs, maxSleepMs, maxRetries);
    }

    private void validateSleepTimes(int baseSleepMs, int maxSleepMs, int maxRetries) {
        StormBoundedExponentialBackoffRetry retryPolicy = new StormBoundedExponentialBackoffRetry(baseSleepMs, maxSleepMs, maxRetries);
        int retryCount = 0;
        int prevSleepMs = 0;
        LOG.info("The baseSleepMs [" + baseSleepMs + "] the maxSleepMs [" + maxSleepMs +
                "] the maxRetries [" + maxRetries + "]");
        while (retryCount <= maxRetries) {
            int currSleepMs = retryPolicy.getSleepTimeMs(retryCount, 0);
            LOG.info("For retryCount [" + retryCount + "] the previousSleepMs [" + prevSleepMs +
                    "] the currentSleepMs [" + currSleepMs + "]");
            assertTrue("For retryCount [" + retryCount + "] the previousSleepMs [" + prevSleepMs +
                            "] is not less than currentSleepMs [" + currSleepMs + "]",
                    (prevSleepMs < currSleepMs) || (currSleepMs == maxSleepMs));
            assertTrue("For retryCount [" + retryCount + "] the currentSleepMs [" + currSleepMs +
                            "] is less than baseSleepMs [" + baseSleepMs + "].",
                    (baseSleepMs <= currSleepMs) || (currSleepMs == maxSleepMs));
            assertTrue("For retryCount [" + retryCount + "] the currentSleepMs [" + currSleepMs +
                            "] is greater than maxSleepMs [" + maxSleepMs + "]",
                    maxSleepMs >= currSleepMs);
            prevSleepMs = currSleepMs;
            retryCount++;
        }
        int badRetryCount = maxRetries + 10;
        int currSleepMs = retryPolicy.getSleepTimeMs(badRetryCount, 0);
        LOG.info("For badRetryCount [" + badRetryCount + "] the previousSleepMs [" + prevSleepMs +
                "] the currentSleepMs [" + currSleepMs + "]");
        assertTrue("For the badRetryCount [" + badRetryCount + "] that's greater than maxRetries [" +
                        maxRetries + "]the currentSleepMs [" + currSleepMs + "] " +
                        "is greater than maxSleepMs [" + maxSleepMs + "]",
                maxSleepMs >= currSleepMs);
    }
}


text:
class Chef
  module RVM
    module SetHelpers
      def rvm_do(user = nil)
        # Use Gem's version comparing code to compare the two strings
        if Gem::Version.new(VersionCache.fetch_version(user)) < Gem::Version.new("1.8.6")
          "exec"
        else
          "do"
        end
      end

    end
  end
end


text:
package app.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import app.domain.entities.Person;

@Repository
public interface PersonRepository extends JpaRepository<Person, Long>{

	@Query("SELECT p FROM Person AS p WHERE CONCAT(p.firstName, ' ', p.middleName, ' ', p.lastName) = :fullName")
	Person findByFullName(@Param("fullName") String fullName);

}


text:
{-

This file is part of the Haskell package distinfo. It is subject to
the license terms in the LICENSE file found in the top-level directory
of this distribution and at git://pmade.com/distinfo/LICENSE. No part
of the distinfo package, including this file, may be copied, modified,
propagated, or distributed except according to the terms contained in
the LICENSE file.

-}

--------------------------------------------------------------------------------
module DistInfo.Info (Info (..)) where

--------------------------------------------------------------------------------
import Control.Concurrent.STM (TVar)
import Control.Distributed.Process (ProcessId)
import Data.Map (Map)
import DistInfo.Node

--------------------------------------------------------------------------------
-- | Information about the local server and its peers.
data Info = Info
  { serverNode :: Node
  , peerNodes  :: TVar (Map ProcessId Node)
  }


text:
package javasmmr.zoowsome.services.factories.animals;

import javasmmr.zoowsome.models.animals.Animal;

public abstract class SpeciesFactory {
	public abstract Animal getAnimal(String type) throws Exception;
}


text:
"""
* *******************************************************
* Copyright VMware, Inc. 2016. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""

__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.0+'

from com.vmware.content.library_client import StorageBacking
from com.vmware.content_client import LibraryModel

from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.vim.helpers.get_datastore_by_name import get_datastore_id
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient

class LibraryCrud(SampleBase):
    """
    Demonstrates the basic operations of a content library. The sample also
    demonstrates the interoperability of the VIM and vAPI.

    Note: the workflow needs an existing VC DS with available storage.

    """

    def __init__(self):
        SampleBase.__init__(self, self.__doc__)
        self.servicemanager = None
        self.client = None
        self.datastore_name = None
        self.lib_name = "demo-local-lib"
        self.local_library = None

    def _options(self):
        self.argparser.add_argument('-datastorename',
                                    '--datastorename',
                                    help='The name of the datastore.')

    def _setup(self):
        if not self.datastore_name:
            self.datastore_name = self.args.datastorename
        assert self.datastore_name is not None

        if not self.servicemanager:
            self.servicemanager = self.get_service_manager()

        self.client = ClsApiClient(self.servicemanager)

    def _execute(self):
        # List of visible content libraries
        visible_cls = self.client.local_library_service.list()
        if len(visible_cls) > 0:
            for visible_cl in visible_cls:
                get_visible_cl = self.client.local_library_service.get(visible_cl)
                print('Visible content library: {0} with id: {1}'.format(get_visible_cl.name, visible_cl))

        # Find the datastore by the given datastore name using property collector
        self.datastore_id = get_datastore_id(service_manager=self.servicemanager, datastore_name=self.datastore_name)
        assert self.datastore_id is not None
        print('DataStore: {0} ID: {1}'.format(self.datastore_name, self.datastore_id))

        # Build the storage backing for the library to be created
        storage_backings = []
        storage_backing = StorageBacking(type=StorageBacking.Type.DATASTORE, datastore_id=self.datastore_id)
        storage_backings.append(storage_backing)

        # Build the specification for the library to be created
        create_spec = LibraryModel()
        create_spec.name = self.lib_name
        create_spec.description = "Local library backed by VC datastore"
        create_spec.type = create_spec.LibraryType.LOCAL
        create_spec.storage_backings = storage_backings

        # Create a local content library backed the VC datastore using vAPIs
        library_id = self.client.local_library_service.create(create_spec=create_spec,
                                                              client_token=generate_random_uuid())
        print('Local library created: ID: {0}'.format(library_id))

        # Retrieve the local content library
        self.local_library = self.client.local_library_service.get(library_id)
        print('Retrieved library: ID: {0}'.format(self.local_library.id))

        # Update the local content library
        update_spec = LibraryModel()
        update_spec.description = "new description"
        self.client.local_library_service.update(library_id, update_spec)
        print('Updated library description')

    def _cleanup(self):
        if self.local_library:
            self.client.local_library_service.delete(library_id=self.local_library.id)
            print('Deleted Library Id: {0}'.format(self.local_library.id))

def main():
    sample = LibraryCrud()
    sample.main()

if __name__ == '__main__':
    main()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. Amer. Acad. Arts & Sci. 28: 183 (1893)

#### Original name
Dichomyces furciferus Thaxt.

### Remarks
null


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Russula emetica subsp. alpina A. Blytt

### Remarks
null


text:
'use strict';

var recursive = require('recursive-readdir');

module.exports = function findFiles(path, suffix, cb) {
    recursive(path, function (err, files) {
        if (err) {
            return cb ? cb(err) : null;
        }

        var routers = files.filter(function (f) {
            var len = suffix.length;
            return f.substr(f.length - len, len) === suffix;
        });

        return cb(null, routers);
    });
};


text:
const controllers = require('../controllers')
const auth = require('../config/auth')

module.exports = (app) => {
  app.get('/', controllers.home.index)
  app.get('/about', controllers.home.about)

  app.get('/users/register', controllers.users.register)
  app.post('/users/create', controllers.users.create)
  app.get('/users/login', controllers.users.login)
  app.post('/users/authenticate', controllers.users.authenticate)
  app.post('/users/logout', auth.isAuthenticated, controllers.users.logout)
  app.get('/users/profile', auth.isAuthenticated, controllers.users.profile)
  app.post('/users/update', auth.isAuthenticated, controllers.users.update)

  app.get('/movies/index', auth.isAuthenticated, controllers.movies.index)
  app.get('/movies/create', auth.isAuthenticated, controllers.movies.create)
  app.post('/movies/store', auth.isAuthenticated, controllers.movies.store)

  app.get('/categories/index', auth.isAuthenticated, controllers.categories.index)
  app.post('/categories/store', auth.isAuthenticated, controllers.categories.store)
  app.get('/categories/:method/:id?', (req, res) => {
    console.log(req.params.method)
    controllers.categories[req.params.method](req, res)
    // controllers.categories.req.params.method(req.query.id)
  })
//   app.get('/categories/:name', (req, res) => {
//     controllers.categories.genre(req.params.name)
//   })

// TODO: attach /users/login?returnUrl=..... to return after login

// TODO: To catch all routes with this logic
//   app.all('/:controller/:method/:id', (req, res) => {
//     controllers[req.params.controllers].req.params.method(req.params.id)
//   })

  app.all('*', (req, res) => {
    res.status(404)
    res.render('shared/404')
    res.end()
  })
}