text:
package org.apache.hadoop.hbase.client;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.MetaTableAccessor;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.exceptions.MergeRegionException;
import org.apache.hadoop.hbase.master.HMaster;
import org.apache.hadoop.hbase.master.janitor.CatalogJanitor;
import org.apache.hadoop.hbase.regionserver.DisabledRegionSplitPolicy;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.HStore;
import org.apache.hadoop.hbase.regionserver.HStoreFile;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.CommonFSUtils;
import org.apache.hadoop.hbase.util.FutureUtils;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.hbase.util.Threads;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MergeTableRegionsRequest;

/**
 * Class to test HBaseAdmin. Spins up the minicluster once at test start and then takes it down
 * afterward. Add any testing of HBaseAdmin functionality here.
 */
@Category({ LargeTests.class, ClientTests.class })
public class TestAdmin1 extends TestAdminBase {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestAdmin1.class);

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

  @Test
  public void testSplitFlushCompactUnknownTable() throws InterruptedException {
    final TableName unknowntable = TableName.valueOf(name.getMethodName());
    Exception exception = null;
    try {
      ADMIN.compact(unknowntable);
    } catch (IOException e) {
      exception = e;
    }
    assertTrue(exception instanceof TableNotFoundException);

    exception = null;
    try {
      ADMIN.flush(unknowntable);
    } catch (IOException e) {
      exception = e;
    }
    assertTrue(exception instanceof TableNotFoundException);

    exception = null;
    try {
      ADMIN.split(unknowntable);
    } catch (IOException e) {
      exception = e;
    }
    assertTrue(exception instanceof TableNotFoundException);
  }

  @Test
  public void testCompactATableWithSuperLongTableName() throws Exception {
    TableName tableName = TableName.valueOf(name.getMethodName());
    TableDescriptor htd = TableDescriptorBuilder.newBuilder(tableName)
      .setColumnFamily(ColumnFamilyDescriptorBuilder.of("fam1")).build();
    try {
      ADMIN.createTable(htd);
      assertThrows(IllegalArgumentException.class,
        () -> ADMIN.majorCompactRegion(tableName.getName()));

      assertThrows(IllegalArgumentException.class,
        () -> ADMIN.majorCompactRegion(Bytes.toBytes("abcd")));
    } finally {
      ADMIN.disableTable(tableName);
      ADMIN.deleteTable(tableName);
    }
  }

  @Test
  public void testCompactionTimestamps() throws Exception {
    TableName tableName = TableName.valueOf(name.getMethodName());
    TableDescriptor htd = TableDescriptorBuilder.newBuilder(tableName)
      .setColumnFamily(ColumnFamilyDescriptorBuilder.of("fam1")).build();
    ADMIN.createTable(htd);
    Table table = TEST_UTIL.getConnection().getTable(htd.getTableName());
    long ts = ADMIN.getLastMajorCompactionTimestamp(tableName);
    assertEquals(0, ts);
    Put p = new Put(Bytes.toBytes("row1"));
    p.addColumn(Bytes.toBytes("fam1"), Bytes.toBytes("fam1"), Bytes.toBytes("fam1"));
    table.put(p);
    ts = ADMIN.getLastMajorCompactionTimestamp(tableName);
    // no files written -> no data
    assertEquals(0, ts);

    ADMIN.flush(tableName);
    ts = ADMIN.getLastMajorCompactionTimestamp(tableName);
    // still 0, we flushed a file, but no major compaction happened
    assertEquals(0, ts);

    byte[] regionName;
    try (RegionLocator l = TEST_UTIL.getConnection().getRegionLocator(tableName)) {
      regionName = l.getAllRegionLocations().get(0).getRegion().getRegionName();
    }
    long ts1 = ADMIN.getLastMajorCompactionTimestampForRegion(regionName);
    assertEquals(ts, ts1);
    p = new Put(Bytes.toBytes("row2"));
    p.addColumn(Bytes.toBytes("fam1"), Bytes.toBytes("fam1"), Bytes.toBytes("fam1"));
    table.put(p);
    ADMIN.flush(tableName);
    ts = ADMIN.getLastMajorCompactionTimestamp(tableName);
    // make sure the region API returns the same value, as the old file is still around
    assertEquals(ts1, ts);

    TEST_UTIL.compact(tableName, true);
    table.put(p);
    // forces a wait for the compaction
    ADMIN.flush(tableName);
    ts = ADMIN.getLastMajorCompactionTimestamp(tableName);
    // after a compaction our earliest timestamp will have progressed forward
    assertTrue(ts > ts1);

    // region api still the same
    ts1 = ADMIN.getLastMajorCompactionTimestampForRegion(regionName);
    assertEquals(ts, ts1);
    table.put(p);
    ADMIN.flush(tableName);
    ts = ADMIN.getLastMajorCompactionTimestamp(tableName);
    assertEquals(ts, ts1);
    table.close();
  }

  @Test(expected = IllegalArgumentException.class)
  public void testColumnValidName() {
    ColumnFamilyDescriptorBuilder.of("\\test\\abc");
  }

  @Test
  public void testTableExist() throws IOException {
    final TableName table = TableName.valueOf(name.getMethodName());
    boolean exist;
    exist = ADMIN.tableExists(table);
    assertEquals(false, exist);
    TEST_UTIL.createTable(table, HConstants.CATALOG_FAMILY);
    exist = ADMIN.tableExists(table);
    assertEquals(true, exist);
  }

  /**
   * Tests forcing split from client and having scanners successfully ride over split.
   */
  @Test
  public void testForceSplit() throws Exception {
    byte[][] familyNames = new byte[][] { Bytes.toBytes("cf") };
    int[] rowCounts = new int[] { 6000 };
    int numVersions = ColumnFamilyDescriptorBuilder.DEFAULT_MAX_VERSIONS;
    int blockSize = 256;
    splitTest(null, familyNames, rowCounts, numVersions, blockSize, true);

    byte[] splitKey = Bytes.toBytes(3500);
    splitTest(splitKey, familyNames, rowCounts, numVersions, blockSize, true);
    // test regionSplitSync
    splitTest(splitKey, familyNames, rowCounts, numVersions, blockSize, false);
  }

  /**
   * Multi-family scenario. Tests forcing split from client and having scanners successfully ride
   * over split.
   */
  @Test
  public void testForceSplitMultiFamily() throws Exception {
    int numVersions = ColumnFamilyDescriptorBuilder.DEFAULT_MAX_VERSIONS;

    // use small HFile block size so that we can have lots of blocks in HFile
    // Otherwise, if there is only one block,
    // HFileBlockIndex.midKey()'s value == startKey
    int blockSize = 256;
    byte[][] familyNames = new byte[][] { Bytes.toBytes("cf1"), Bytes.toBytes("cf2") };

    // one of the column families isn't splittable
    int[] rowCounts = new int[] { 6000, 1 };
    splitTest(null, familyNames, rowCounts, numVersions, blockSize, true);

    rowCounts = new int[] { 1, 6000 };
    splitTest(null, familyNames, rowCounts, numVersions, blockSize, true);

    // one column family has much smaller data than the other
    // the split key should be based on the largest column family
    rowCounts = new int[] { 6000, 300 };
    splitTest(null, familyNames, rowCounts, numVersions, blockSize, true);

    rowCounts = new int[] { 300, 6000 };
    splitTest(null, familyNames, rowCounts, numVersions, blockSize, true);
  }

  private int count(ResultScanner scanner) throws IOException {
    int rows = 0;
    while (scanner.next() != null) {
      rows++;
    }
    return rows;
  }

  private void splitTest(byte[] splitPoint, byte[][] familyNames, int[] rowCounts, int numVersions,
    int blockSize, boolean async) throws Exception {
    TableName tableName = TableName.valueOf("testForceSplit");
    StringBuilder sb = new StringBuilder();
    // Add tail to String so can see better in logs where a test is running.
    for (int i = 0; i < rowCounts.length; i++) {
      sb.append("_").append(Integer.toString(rowCounts[i]));
    }
    assertFalse(ADMIN.tableExists(tableName));
    try (final Table table = TEST_UTIL.createTable(tableName, familyNames, numVersions, blockSize);
      final RegionLocator locator = TEST_UTIL.getConnection().getRegionLocator(tableName)) {

      int rowCount = 0;
      byte[] q = new byte[0];

      // insert rows into column families. The number of rows that have values
      // in a specific column family is decided by rowCounts[familyIndex]
      for (int index = 0; index < familyNames.length; index++) {
        ArrayList<Put> puts = new ArrayList<>(rowCounts[index]);
        for (int i = 0; i < rowCounts[index]; i++) {
          byte[] k = Bytes.toBytes(i);
          Put put = new Put(k);
          put.addColumn(familyNames[index], q, k);
          puts.add(put);
        }
        table.put(puts);

        if (rowCount < rowCounts[index]) {
          rowCount = rowCounts[index];
        }
      }

      // get the initial layout (should just be one region)
      List<HRegionLocation> m = locator.getAllRegionLocations();
      LOG.info("Initial regions (" + m.size() + "): " + m);
      assertTrue(m.size() == 1);

      // Verify row count
      Scan scan = new Scan();
      int rows;
      try (ResultScanner scanner = table.getScanner(scan)) {
        rows = count(scanner);
      }
      assertEquals(rowCount, rows);

      // Have an outstanding scan going on to make sure we can scan over splits.
      scan = new Scan();
      try (ResultScanner scanner = table.getScanner(scan)) {
        // Scan first row so we are into first region before split happens.
        scanner.next();

        // Split the table
        if (async) {
          if (splitPoint != null) {
            ADMIN.split(tableName, splitPoint);
          } else {
            ADMIN.split(tableName);
          }
          final AtomicInteger count = new AtomicInteger(0);
          Thread t = new Thread("CheckForSplit") {
            @Override
            public void run() {
              for (int i = 0; i < 45; i++) {
                try {
                  sleep(1000);
                } catch (InterruptedException e) {
                  continue;
                }
                // check again
                List<HRegionLocation> regions = null;
                try {
                  regions = locator.getAllRegionLocations();
                } catch (IOException e) {
                  LOG.warn("get location failed", e);
                }
                if (regions == null) {
                  continue;
                }
                count.set(regions.size());
                if (count.get() >= 2) {
                  LOG.info("Found: " + regions);
                  break;
                }
                LOG.debug("Cycle waiting on split");
              }
              LOG.debug("CheckForSplit thread exited, current region count: " + count.get());
            }
          };
          t.setPriority(Thread.NORM_PRIORITY - 2);
          t.start();
          t.join();
        } else {
          // Sync split region, no need to create a thread to check
          ADMIN.splitRegionAsync(m.get(0).getRegion().getRegionName(), splitPoint).get();
        }
        // Verify row count
        rows = 1 + count(scanner); // We counted one row above.
      }
      assertEquals(rowCount, rows);

      List<HRegionLocation> regions = null;
      try {
        regions = locator.getAllRegionLocations();
      } catch (IOException e) {
        e.printStackTrace();
      }
      assertEquals(2, regions.size());
      if (splitPoint != null) {
        // make sure the split point matches our explicit configuration
        assertEquals(Bytes.toString(splitPoint),
          Bytes.toString(regions.get(0).getRegion().getEndKey()));
        assertEquals(Bytes.toString(splitPoint),
          Bytes.toString(regions.get(1).getRegion().getStartKey()));
        LOG.debug("Properly split on " + Bytes.toString(splitPoint));
      } else {
        if (familyNames.length > 1) {
          int splitKey = Bytes.toInt(regions.get(0).getRegion().getEndKey());
          // check if splitKey is based on the largest column family
          // in terms of it store size
          int deltaForLargestFamily = Math.abs(rowCount / 2 - splitKey);
          LOG.debug("SplitKey=" + splitKey + "&deltaForLargestFamily=" + deltaForLargestFamily
            + ", r=" + regions.get(0).getRegion());
          for (int index = 0; index < familyNames.length; index++) {
            int delta = Math.abs(rowCounts[index] / 2 - splitKey);
            if (delta < deltaForLargestFamily) {
              assertTrue("Delta " + delta + " for family " + index + " should be at least "
                + "deltaForLargestFamily " + deltaForLargestFamily, false);
            }
          }
        }
      }
      TEST_UTIL.deleteTable(tableName);
    }
  }

  @Test
  public void testSplitAndMergeWithReplicaTable() throws Exception {
    // The test tries to directly split replica regions and directly merge replica regions. These
    // are not allowed. The test validates that. Then the test does a valid split/merge of allowed
    // regions.
    // Set up a table with 3 regions and replication set to 3
    TableName tableName = TableName.valueOf(name.getMethodName());
    byte[] cf = Bytes.toBytes("f");
    TableDescriptor desc = TableDescriptorBuilder.newBuilder(tableName).setRegionReplication(3)
      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(cf)).build();
    byte[][] splitRows = new byte[2][];
    splitRows[0] = new byte[] { (byte) '4' };
    splitRows[1] = new byte[] { (byte) '7' };
    TEST_UTIL.getAdmin().createTable(desc, splitRows);
    List<HRegion> oldRegions;
    do {
      oldRegions = TEST_UTIL.getHBaseCluster().getRegions(tableName);
      Thread.sleep(10);
    } while (oldRegions.size() != 9); // 3 regions * 3 replicas
    // write some data to the table
    Table ht = TEST_UTIL.getConnection().getTable(tableName);
    List<Put> puts = new ArrayList<>();
    byte[] qualifier = Bytes.toBytes("c");
    Put put = new Put(new byte[] { (byte) '1' });
    put.addColumn(cf, qualifier, Bytes.toBytes("100"));
    puts.add(put);
    put = new Put(new byte[] { (byte) '6' });
    put.addColumn(cf, qualifier, Bytes.toBytes("100"));
    puts.add(put);
    put = new Put(new byte[] { (byte) '8' });
    put.addColumn(cf, qualifier, Bytes.toBytes("100"));
    puts.add(put);
    ht.put(puts);
    ht.close();
    List<Pair<RegionInfo, ServerName>> regions =
      MetaTableAccessor.getTableRegionsAndLocations(TEST_UTIL.getConnection(), tableName);
    boolean gotException = false;
    // the element at index 1 would be a replica (since the metareader gives us ordered
    // regions). Try splitting that region via the split API . Should fail
    try {
      FutureUtils
        .get(TEST_UTIL.getAdmin().splitRegionAsync(regions.get(1).getFirst().getRegionName()));
    } catch (IllegalArgumentException ex) {
      gotException = true;
    }
    assertTrue(gotException);
    gotException = false;
    // the element at index 1 would be a replica (since the metareader gives us ordered
    // regions). Try splitting that region via a different split API (the difference is
    // this API goes direct to the regionserver skipping any checks in the admin). Should fail
    try {
      FutureUtils.get(TEST_UTIL.getAdmin().splitRegionAsync(
        regions.get(1).getFirst().getEncodedNameAsBytes(), new byte[] { (byte) '1' }));
    } catch (IllegalArgumentException ex) {
      gotException = true;
    }
    assertTrue(gotException);

    gotException = false;
    // testing Sync split operation
    try {
      FutureUtils.get(TEST_UTIL.getAdmin()
        .splitRegionAsync(regions.get(1).getFirst().getRegionName(), new byte[] { (byte) '1' }));
    } catch (IllegalArgumentException ex) {
      gotException = true;
    }
    assertTrue(gotException);

    gotException = false;
    // Try merging a replica with another. Should fail.
    try {
      FutureUtils.get(
        TEST_UTIL.getAdmin().mergeRegionsAsync(regions.get(1).getFirst().getEncodedNameAsBytes(),
          regions.get(2).getFirst().getEncodedNameAsBytes(), true));
    } catch (IllegalArgumentException m) {
      gotException = true;
    }
    assertTrue(gotException);
    // Try going to the master directly (that will skip the check in admin)
    try {
      byte[][] nameofRegionsToMerge = new byte[2][];
      nameofRegionsToMerge[0] = regions.get(1).getFirst().getEncodedNameAsBytes();
      nameofRegionsToMerge[1] = regions.get(2).getFirst().getEncodedNameAsBytes();
      MergeTableRegionsRequest request = RequestConverter.buildMergeTableRegionsRequest(
        nameofRegionsToMerge, true, HConstants.NO_NONCE, HConstants.NO_NONCE);
      TEST_UTIL.getMiniHBaseCluster().getMaster().getMasterRpcServices().mergeTableRegions(null,
        request);
    } catch (org.apache.hbase.thirdparty.com.google.protobuf.ServiceException m) {
      Throwable t = m.getCause();
      do {
        if (t instanceof MergeRegionException) {
          gotException = true;
          break;
        }
        t = t.getCause();
      } while (t != null);
    }
    assertTrue(gotException);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testInvalidColumnDescriptor() throws IOException {
    ColumnFamilyDescriptorBuilder.of("/cfamily/name");
  }

  /**
   * Test DFS replication for column families, where one CF has default replication(3) and the other
   * is set to 1.
   */
  @Test
  public void testHFileReplication() throws Exception {
    final TableName tableName = TableName.valueOf(this.name.getMethodName());
    String fn1 = "rep1";
    String fn = "defaultRep";
    TableDescriptor htd = TableDescriptorBuilder.newBuilder(tableName)
      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(fn))
      .setColumnFamily(ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(fn1))
        .setDFSReplication((short) 1).build())
      .build();
    Table table = TEST_UTIL.createTable(htd, null);
    TEST_UTIL.waitTableAvailable(tableName);
    Put p = new Put(Bytes.toBytes("defaultRep_rk"));
    byte[] q1 = Bytes.toBytes("q1");
    byte[] v1 = Bytes.toBytes("v1");
    p.addColumn(Bytes.toBytes(fn), q1, v1);
    List<Put> puts = new ArrayList<>(2);
    puts.add(p);
    p = new Put(Bytes.toBytes("rep1_rk"));
    p.addColumn(Bytes.toBytes(fn1), q1, v1);
    puts.add(p);
    try {
      table.put(puts);
      ADMIN.flush(tableName);

      List<HRegion> regions = TEST_UTIL.getMiniHBaseCluster().getRegions(tableName);
      for (HRegion r : regions) {
        HStore store = r.getStore(Bytes.toBytes(fn));
        for (HStoreFile sf : store.getStorefiles()) {
          assertTrue(sf.toString().contains(fn));
          assertTrue("Column family " + fn + " should have 3 copies",
            CommonFSUtils.getDefaultReplication(TEST_UTIL.getTestFileSystem(), sf.getPath())
                == (sf.getFileInfo().getFileStatus().getReplication()));
        }

        store = r.getStore(Bytes.toBytes(fn1));
        for (HStoreFile sf : store.getStorefiles()) {
          assertTrue(sf.toString().contains(fn1));
          assertTrue("Column family " + fn1 + " should have only 1 copy",
            1 == sf.getFileInfo().getFileStatus().getReplication());
        }
      }
    } finally {
      if (ADMIN.isTableEnabled(tableName)) {
        ADMIN.disableTable(tableName);
        ADMIN.deleteTable(tableName);
      }
    }
  }

  @Test
  public void testMergeRegions() throws Exception {
    final TableName tableName = TableName.valueOf(name.getMethodName());
    TableDescriptor td = TableDescriptorBuilder.newBuilder(tableName)
      .setColumnFamily(ColumnFamilyDescriptorBuilder.of("d")).build();
    byte[][] splitRows = new byte[2][];
    splitRows[0] = new byte[] { (byte) '3' };
    splitRows[1] = new byte[] { (byte) '6' };
    try {
      TEST_UTIL.createTable(td, splitRows);
      TEST_UTIL.waitTableAvailable(tableName);

      List<RegionInfo> tableRegions;
      RegionInfo regionA;
      RegionInfo regionB;
      RegionInfo regionC;
      RegionInfo mergedChildRegion = null;

      // merge with full name
      tableRegions = ADMIN.getRegions(tableName);
      assertEquals(3, ADMIN.getRegions(tableName).size());
      regionA = tableRegions.get(0);
      regionB = tableRegions.get(1);
      regionC = tableRegions.get(2);
      // TODO convert this to version that is synchronous (See HBASE-16668)
      ADMIN.mergeRegionsAsync(regionA.getRegionName(), regionB.getRegionName(), false).get(60,
        TimeUnit.SECONDS);

      tableRegions = ADMIN.getRegions(tableName);

      assertEquals(2, tableRegions.size());
      for (RegionInfo ri : tableRegions) {
        if (regionC.compareTo(ri) != 0) {
          mergedChildRegion = ri;
          break;
        }
      }

      assertNotNull(mergedChildRegion);
      // Need to wait GC for merged child region is done.
      HMaster services = TEST_UTIL.getHBaseCluster().getMaster();
      CatalogJanitor cj = services.getCatalogJanitor();
      assertTrue(cj.scan() > 0);
      // Wait until all procedures settled down
      while (!services.getMasterProcedureExecutor().getActiveProcIds().isEmpty()) {
        Thread.sleep(200);
      }

      // TODO convert this to version that is synchronous (See HBASE-16668)
      ADMIN.mergeRegionsAsync(regionC.getEncodedNameAsBytes(),
        mergedChildRegion.getEncodedNameAsBytes(), false).get(60, TimeUnit.SECONDS);

      assertEquals(1, ADMIN.getRegions(tableName).size());
    } finally {
      ADMIN.disableTable(tableName);
      ADMIN.deleteTable(tableName);
    }
  }

  @Test
  public void testMergeRegionsInvalidRegionCount()
    throws IOException, InterruptedException, ExecutionException {
    TableName tableName = TableName.valueOf(name.getMethodName());
    TableDescriptor td = TableDescriptorBuilder.newBuilder(tableName)
      .setColumnFamily(ColumnFamilyDescriptorBuilder.of("d")).build();
    byte[][] splitRows = new byte[2][];
    splitRows[0] = new byte[] { (byte) '3' };
    splitRows[1] = new byte[] { (byte) '6' };
    try {
      TEST_UTIL.createTable(td, splitRows);
      TEST_UTIL.waitTableAvailable(tableName);

      List<RegionInfo> tableRegions = ADMIN.getRegions(tableName);
      // 0
      try {
        FutureUtils.get(ADMIN.mergeRegionsAsync(new byte[0][0], false));
        fail();
      } catch (IllegalArgumentException e) {
        // expected
      }
      // 1
      try {
        FutureUtils.get(ADMIN
          .mergeRegionsAsync(new byte[][] { tableRegions.get(0).getEncodedNameAsBytes() }, false));
        fail();
      } catch (IllegalArgumentException e) {
        // expected
      }
    } finally {
      ADMIN.disableTable(tableName);
      ADMIN.deleteTable(tableName);
    }
  }

  @Test
  public void testSplitShouldNotHappenIfSplitIsDisabledForTable() throws Exception {
    final TableName tableName = TableName.valueOf(name.getMethodName());
    TableDescriptor htd = TableDescriptorBuilder.newBuilder(tableName)
      .setRegionSplitPolicyClassName(DisabledRegionSplitPolicy.class.getName())
      .setColumnFamily(ColumnFamilyDescriptorBuilder.of("f")).build();
    Table table = TEST_UTIL.createTable(htd, null);
    for (int i = 0; i < 10; i++) {
      Put p = new Put(Bytes.toBytes("row" + i));
      byte[] q1 = Bytes.toBytes("q1");
      byte[] v1 = Bytes.toBytes("v1");
      p.addColumn(Bytes.toBytes("f"), q1, v1);
      table.put(p);
    }
    ADMIN.flush(tableName);
    try {
      ADMIN.split(tableName, Bytes.toBytes("row5"));
      Threads.sleep(10000);
    } catch (Exception e) {
      // Nothing to do.
    }
    // Split should not happen.
    List<RegionInfo> allRegions =
      MetaTableAccessor.getTableRegions(ADMIN.getConnection(), tableName, true);
    assertEquals(1, allRegions.size());
  }
}


text:
<root>
  <tools dockable="false">
    <tool name="AjaxSpellCheck"  />
    <tool separator="true" />
    <tool name="Cut" shortcut="CTRL+X" />
    <tool name="Copy" shortcut="CTRL+C" />
    <tool name="Paste" shortcut="CTRL+V" />
    <tool separator="true" />
    <tool name="Undo" shortcut="CTRL+Z" />
    <tool name="Redo" shortcut="CTRL+Y" />
    <tool separator="true" />
    <tool name="Bold" shortcut="CTRL+B" />
    <tool name="Italic" shortcut="CTRL+I" />
    <tool name="Underline" shortcut="CTRL+U" />
    <tool separator="true" />

  </tools>

</root>

redpajama_set_name: RedPajamaGithub


text:
//--------------------------------------------------------------------------------
// This file is a portion of the Hieroglyph 3 Rendering Engine.  It is distributed
// under the MIT License, available in the root of this distribution and
// at the following URL:
//
// http://www.opensource.org/licenses/mit-license.php
//
// Copyright (c) Jason Zink
//--------------------------------------------------------------------------------

#include "GlyphWPF.h"

namespace System { namespace Windows { namespace Interop
{
	static D3DImageEx::D3DImageEx()
	{
		HRESULT hr;
		HWND hWnd = GetDesktopWindow();

		IDirect3D9Ex* pD3D9;
		Direct3DCreate9Ex( D3D_SDK_VERSION, &pD3D9 );

		m_D3D9 = pD3D9;

		if (!m_D3D9)
			throw gcnew Exception("Could not acquire D3D9 interface.");

		m_D3D9 = pD3D9;

		D3DPRESENT_PARAMETERS		d3dpp;
		ZeroMemory(&d3dpp, sizeof(d3dpp));
		d3dpp.Windowed				= TRUE;
		d3dpp.SwapEffect			= D3DSWAPEFFECT_DISCARD;
		d3dpp.hDeviceWindow			= hWnd;
		d3dpp.PresentationInterval	= D3DPRESENT_INTERVAL_IMMEDIATE;

		IDirect3DDevice9Ex *d3D9Device;

		hr = m_D3D9->CreateDeviceEx(D3DADAPTER_DEFAULT,
									D3DDEVTYPE_HAL,
									hWnd,
									D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE,
									&d3dpp,
									NULL,
									&d3D9Device);

		if (FAILED(hr))
		{
			m_D3D9->Release();
			m_D3D9 = nullptr;
			throw gcnew Exception("Could not acquire D3D9 device interface.");
		}

		m_D3D9Device = d3D9Device;
	}

	void D3DImageEx::SetBackBufferEx(IntPtr pResource)
	{
		/* Check if the user just wants to clear the D3DImage backbuffer */
		if(pResource == IntPtr::Zero)
		{
			SetBackBuffer(D3DResourceType::IDirect3DSurface9, IntPtr::Zero);
			return;
		}

		IUnknown *pUnk = (IUnknown*)pResource.ToPointer();
		IUnknown *pUnkResource = NULL;

		UINT width = 0;
		UINT height = 0;
		DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;

		::ID3D11Texture2D *pTexture2D = NULL;

		/* Query for IUNKNOWN for ID3D11Texture2D */
		if(FAILED(pUnk->QueryInterface(__uuidof(::ID3D11Texture2D), (void**)&pTexture2D)))
			throw gcnew ArgumentException("Must pass a valid resource","pResource");

		/* Get the texture description.  This is needed to recreate
			* the surface in the 9Ex device */
		D3D11_TEXTURE2D_DESC textureDesc;
		pTexture2D->GetDesc(&textureDesc);

		width = textureDesc.Width;
		height = textureDesc.Height;
		format = textureDesc.Format;

		pUnkResource = pTexture2D;
		pTexture2D->Release();

		/* The shared handle of the D3D resource */
		HANDLE hSharedHandle = NULL;

		/* Shared texture pulled through the 9Ex device */
		IDirect3DTexture9* pTexture = NULL;

		/* Shared surface, pulled through the shared texture */
		IDirect3DSurface9* pSurface;

		/* Get the shared handle for the given resource */
		if(FAILED(GetSharedHandle(pUnkResource, &hSharedHandle)))
			throw gcnew Exception("Could not aquire shared resource handle");

		/* Get the shared surface.  In this case its really a texture =X */
		if(FAILED(GetSharedSurface(hSharedHandle, (void**)&pTexture, width, height, format)))
			throw gcnew Exception("Could not create shared resource");

		/* Get surface level 0, which we need for the D3DImage */
		if (FAILED(pTexture->GetSurfaceLevel(0, &pSurface)))
			throw gcnew Exception("Could not get surface level");

		/* Done with the texture */
		pTexture->Release();

		Lock();
		/* Set the backbuffer of the D3DImage */
		SetBackBuffer(D3DResourceType::IDirect3DSurface9, IntPtr(pSurface));
		Unlock();

		pSurface->Release();
	}

	D3DFORMAT D3DImageEx::ConvertDXGIToD3D9Format(DXGI_FORMAT format)
	{
		switch (format)
		{
			case DXGI_FORMAT_B8G8R8A8_UNORM:
				return D3DFMT_A8R8G8B8;
			case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
				return D3DFMT_A8R8G8B8;
			case DXGI_FORMAT_B8G8R8X8_UNORM:
				return D3DFMT_X8R8G8B8;
			case DXGI_FORMAT_R8G8B8A8_UNORM:
				return D3DFMT_A8B8G8R8;
			case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
				return D3DFMT_A8B8G8R8;
			default:
				return D3DFMT_UNKNOWN;
		};
	}

	HRESULT D3DImageEx::GetSharedSurface(HANDLE hSharedHandle, void** ppUnknown, UINT width, UINT height, DXGI_FORMAT format)
	{
		D3DFORMAT D3D9Format;

		/* Convert the DXGI format to a D3D9 format */
		if ((D3D9Format = ConvertDXGIToD3D9Format(format)) == D3DFMT_UNKNOWN)
			/* We're boned =X */
			return E_INVALIDARG;

		HRESULT hr = S_OK;
		IDirect3DTexture9** ppTexture = (IDirect3DTexture9**)ppUnknown;

		/* Create the texture locally, but provide the shared handle.
		 * This doesn't really create a new texture, but simply
		 * pulls the D3D10/11 resource in the 9Ex device */
		hr = m_D3D9Device->CreateTexture( width, height, 1,
										  D3DUSAGE_RENDERTARGET,
										  D3D9Format,
										  D3DPOOL_DEFAULT,
										  ppTexture,
										  &hSharedHandle );

		return hr;
	}

	HRESULT D3DImageEx::GetSharedHandle(IUnknown *pUnknown, HANDLE * pHandle)
	{
		HRESULT hr = S_OK;

		*pHandle = NULL;
		IDXGIResource* pSurface;

		if (FAILED(hr = pUnknown->QueryInterface(__uuidof(IDXGIResource), (void**)&pSurface)))
			return hr;

		hr = pSurface->GetSharedHandle(pHandle);
		pSurface->Release();

		return hr;
	}

}}}


text:
<?php

declare(strict_types=1);

namespace League\Flysystem\AsyncAwsS3;

use AsyncAws\Core\Exception\Http\ClientException;
use AsyncAws\Core\Stream\ResultStream;
use AsyncAws\S3\Result\HeadObjectOutput;
use AsyncAws\S3\S3Client;
use AsyncAws\S3\ValueObject\AwsObject;
use AsyncAws\S3\ValueObject\CommonPrefix;
use AsyncAws\S3\ValueObject\ObjectIdentifier;
use AsyncAws\SimpleS3\SimpleS3Client;
use DateTimeImmutable;
use DateTimeInterface;
use Generator;
use League\Flysystem\ChecksumAlgoIsNotSupported;
use League\Flysystem\ChecksumProvider;
use League\Flysystem\Config;
use League\Flysystem\DirectoryAttributes;
use League\Flysystem\FileAttributes;
use League\Flysystem\FilesystemAdapter;
use League\Flysystem\PathPrefixer;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToCheckDirectoryExistence;
use League\Flysystem\UnableToCheckFileExistence;
use League\Flysystem\UnableToCopyFile;
use League\Flysystem\UnableToDeleteFile;
use League\Flysystem\UnableToGeneratePublicUrl;
use League\Flysystem\UnableToGenerateTemporaryUrl;
use League\Flysystem\UnableToMoveFile;
use League\Flysystem\UnableToProvideChecksum;
use League\Flysystem\UnableToReadFile;
use League\Flysystem\UnableToRetrieveMetadata;
use League\Flysystem\UnableToSetVisibility;
use League\Flysystem\UrlGeneration\PublicUrlGenerator;
use League\Flysystem\UrlGeneration\TemporaryUrlGenerator;
use League\Flysystem\Visibility;
use League\MimeTypeDetection\FinfoMimeTypeDetector;
use League\MimeTypeDetection\MimeTypeDetector;
use Throwable;
use function trim;

class AsyncAwsS3Adapter implements FilesystemAdapter, PublicUrlGenerator, ChecksumProvider, TemporaryUrlGenerator
{
    /**
     * @var string[]
     */
    public const AVAILABLE_OPTIONS = [
        'ACL',
        'CacheControl',
        'ContentDisposition',
        'ContentEncoding',
        'ContentLength',
        'ContentType',
        'ContentMD5',
        'Expires',
        'GrantFullControl',
        'GrantRead',
        'GrantReadACP',
        'GrantWriteACP',
        'Metadata',
        'MetadataDirective',
        'RequestPayer',
        'SSECustomerAlgorithm',
        'SSECustomerKey',
        'SSECustomerKeyMD5',
        'SSEKMSKeyId',
        'ServerSideEncryption',
        'StorageClass',
        'Tagging',
        'WebsiteRedirectLocation',
        'ChecksumAlgorithm',
    ];

    /**
     * @var string[]
     */
    protected const EXTRA_METADATA_FIELDS = [
        'Metadata',
        'StorageClass',
        'ETag',
        'VersionId',
    ];

    private PathPrefixer $prefixer;
    private VisibilityConverter $visibility;
    private MimeTypeDetector $mimeTypeDetector;

    /**
     * @var array|string[]
     */
    private array $forwardedOptions;

    /**
     * @var array|string[]
     */
    private array $metadataFields;

    /**
     * @param S3Client|SimpleS3Client $client Uploading of files larger than 5GB is only supported with SimpleS3Client
     */
    public function __construct(
        private S3Client $client,
        private string $bucket,
        string $prefix = '',
        VisibilityConverter $visibility = null,
        MimeTypeDetector $mimeTypeDetector = null,
        array $forwardedOptions = self::AVAILABLE_OPTIONS,
        array $metadataFields = self::EXTRA_METADATA_FIELDS,
    ) {
        $this->prefixer = new PathPrefixer($prefix);
        $this->visibility = $visibility ?: new PortableVisibilityConverter();
        $this->mimeTypeDetector = $mimeTypeDetector ?: new FinfoMimeTypeDetector();
        $this->forwardedOptions = $forwardedOptions;
        $this->metadataFields = $metadataFields;
    }

    public function fileExists(string $path): bool
    {
        try {
            return $this->client->objectExists(
                [
                    'Bucket' => $this->bucket,
                    'Key' => $this->prefixer->prefixPath($path),
                ]
            )->isSuccess();
        } catch (ClientException $e) {
            throw UnableToCheckFileExistence::forLocation($path, $e);
        }
    }

    public function write(string $path, string $contents, Config $config): void
    {
        $this->upload($path, $contents, $config);
    }

    public function writeStream(string $path, $contents, Config $config): void
    {
        $this->upload($path, $contents, $config);
    }

    public function read(string $path): string
    {
        $body = $this->readObject($path);

        return $body->getContentAsString();
    }

    public function readStream(string $path)
    {
        $body = $this->readObject($path);

        return $body->getContentAsResource();
    }

    public function delete(string $path): void
    {
        $arguments = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)];

        try {
            $this->client->deleteObject($arguments);
        } catch (Throwable $exception) {
            throw UnableToDeleteFile::atLocation($path, '', $exception);
        }
    }

    public function deleteDirectory(string $path): void
    {
        $prefix = $this->prefixer->prefixDirectoryPath($path);
        $prefix = ltrim($prefix, '/');

        $objects = [];
        $params = ['Bucket' => $this->bucket, 'Prefix' => $prefix];
        $result = $this->client->listObjectsV2($params);
        /** @var AwsObject $item */
        foreach ($result->getContents() as $item) {
            $key = $item->getKey();
            if (null !== $key) {
                $objects[] = new ObjectIdentifier(['Key' => $key]);
            }
        }

        if (empty($objects)) {
            return;
        }

        $this->client->deleteObjects(['Bucket' => $this->bucket, 'Delete' => ['Objects' => $objects]]);
    }

    public function createDirectory(string $path, Config $config): void
    {
        $defaultVisibility = $config->get('directory_visibility', $this->visibility->defaultForDirectories());
        $config = $config->withDefaults(['visibility' => $defaultVisibility]);
        $this->upload(rtrim($path, '/') . '/', '', $config);
    }

    public function setVisibility(string $path, string $visibility): void
    {
        $arguments = [
            'Bucket' => $this->bucket,
            'Key' => $this->prefixer->prefixPath($path),
            'ACL' => $this->visibility->visibilityToAcl($visibility),
        ];

        try {
            $this->client->putObjectAcl($arguments);
        } catch (Throwable $exception) {
            throw UnableToSetVisibility::atLocation($path, $exception->getMessage(), $exception);
        }
    }

    public function visibility(string $path): FileAttributes
    {
        $arguments = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)];

        try {
            $result = $this->client->getObjectAcl($arguments);
            $grants = $result->getGrants();
        } catch (Throwable $exception) {
            throw UnableToRetrieveMetadata::visibility($path, $exception->getMessage(), $exception);
        }

        $visibility = $this->visibility->aclToVisibility($grants);

        return new FileAttributes($path, null, $visibility);
    }

    public function mimeType(string $path): FileAttributes
    {
        $attributes = $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_MIME_TYPE);

        if (null === $attributes->mimeType()) {
            throw UnableToRetrieveMetadata::mimeType($path);
        }

        return $attributes;
    }

    public function lastModified(string $path): FileAttributes
    {
        $attributes = $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_LAST_MODIFIED);

        if (null === $attributes->lastModified()) {
            throw UnableToRetrieveMetadata::lastModified($path);
        }

        return $attributes;
    }

    public function fileSize(string $path): FileAttributes
    {
        $attributes = $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_FILE_SIZE);

        if (null === $attributes->fileSize()) {
            throw UnableToRetrieveMetadata::fileSize($path);
        }

        return $attributes;
    }

    public function directoryExists(string $path): bool
    {
        try {
            $prefix = $this->prefixer->prefixDirectoryPath($path);
            $options = ['Bucket' => $this->bucket, 'Prefix' => $prefix, 'MaxKeys' => 1, 'Delimiter' => '/'];

            return $this->client->listObjectsV2($options)->getKeyCount() > 0;
        } catch (Throwable $exception) {
            throw UnableToCheckDirectoryExistence::forLocation($path, $exception);
        }
    }

    public function listContents(string $path, bool $deep): iterable
    {
        $prefix = trim($this->prefixer->prefixPath($path), '/');
        $prefix = empty($prefix) ? '' : $prefix . '/';
        $options = ['Bucket' => $this->bucket, 'Prefix' => $prefix];

        if (false === $deep) {
            $options['Delimiter'] = '/';
        }

        $listing = $this->retrievePaginatedListing($options);

        foreach ($listing as $item) {
            yield $this->mapS3ObjectMetadata($item);
        }
    }

    public function move(string $source, string $destination, Config $config): void
    {
        try {
            $this->copy($source, $destination, $config);
            $this->delete($source);
        } catch (Throwable $exception) {
            throw UnableToMoveFile::fromLocationTo($source, $destination, $exception);
        }
    }

    public function copy(string $source, string $destination, Config $config): void
    {
        try {
            /** @var string $visibility */
            $visibility = $config->get(Config::OPTION_VISIBILITY) ?: $this->visibility($source)->visibility();
        } catch (Throwable $exception) {
            throw UnableToCopyFile::fromLocationTo($source, $destination, $exception);
        }

        $arguments = [
            'ACL' => $this->visibility->visibilityToAcl($visibility),
            'Bucket' => $this->bucket,
            'Key' => $this->prefixer->prefixPath($destination),
            'CopySource' => $this->bucket . '/' . $this->prefixer->prefixPath($source),
        ];

        try {
            $this->client->copyObject($arguments);
        } catch (Throwable $exception) {
            throw UnableToCopyFile::fromLocationTo($source, $destination, $exception);
        }
    }

    /**
     * @param string|resource $body
     */
    private function upload(string $path, $body, Config $config): void
    {
        $key = $this->prefixer->prefixPath($path);
        $acl = $this->determineAcl($config);
        $options = $this->createOptionsFromConfig($config);
        $shouldDetermineMimetype = '' !== $body && ! \array_key_exists('ContentType', $options);

        if ($shouldDetermineMimetype && $mimeType = $this->mimeTypeDetector->detectMimeType($key, $body)) {
            $options['ContentType'] = $mimeType;
        }

        if ($this->client instanceof SimpleS3Client) {
            // Supports upload of files larger than 5GB
            $this->client->upload($this->bucket, $key, $body, array_merge($options, ['ACL' => $acl]));
        } else {
            $this->client->putObject(array_merge($options, [
                'Bucket' => $this->bucket,
                'Key' => $key,
                'Body' => $body,
                'ACL' => $acl,
            ]));
        }
    }

    private function determineAcl(Config $config): string
    {
        $visibility = (string) $config->get(Config::OPTION_VISIBILITY, Visibility::PRIVATE);

        return $this->visibility->visibilityToAcl($visibility);
    }

    private function createOptionsFromConfig(Config $config): array
    {
        $options = [];

        foreach ($this->forwardedOptions as $option) {
            $value = $config->get($option, '__NOT_SET__');

            if ('__NOT_SET__' !== $value) {
                $options[$option] = $value;
            }
        }

        return $options;
    }

    private function fetchFileMetadata(string $path, string $type): FileAttributes
    {
        $arguments = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)];

        try {
            $result = $this->client->headObject($arguments);
            $result->resolve();
        } catch (Throwable $exception) {
            throw UnableToRetrieveMetadata::create($path, $type, $exception->getMessage(), $exception);
        }

        $attributes = $this->mapS3ObjectMetadata($result, $path);

        if ( ! $attributes instanceof FileAttributes) {
            throw UnableToRetrieveMetadata::create($path, $type, 'Unable to retrieve file attributes, directory attributes received.');
        }

        return $attributes;
    }

    /**
     * @param HeadObjectOutput|AwsObject|CommonPrefix $item
     */
    private function mapS3ObjectMetadata($item, string $path = null): StorageAttributes
    {
        if (null === $path) {
            if ($item instanceof AwsObject) {
                $path = $this->prefixer->stripPrefix($item->getKey() ?? '');
            } elseif ($item instanceof CommonPrefix) {
                $path = $this->prefixer->stripPrefix($item->getPrefix() ?? '');
            } else {
                throw new \RuntimeException(sprintf('Argument 2 of "%s" cannot be null when $item is not instance of "%s" or %s', __METHOD__, AwsObject::class, CommonPrefix::class));
            }
        }

        if ('/' === substr($path, -1)) {
            return new DirectoryAttributes(rtrim($path, '/'));
        }

        $mimeType = null;
        $fileSize = null;
        $lastModified = null;
        $dateTime = null;
        $metadata = [];

        if ($item instanceof AwsObject) {
            $dateTime = $item->getLastModified();
            $fileSize = $item->getSize();
        } elseif ($item instanceof CommonPrefix) {
            // No data available
        } elseif ($item instanceof HeadObjectOutput) {
            $mimeType = $item->getContentType();
            $fileSize = $item->getContentLength();
            $dateTime = $item->getLastModified();
            $metadata = $this->extractExtraMetadata($item);
        } else {
            throw new \RuntimeException(sprintf('Object of class "%s" is not supported in %s()', \get_class($item), __METHOD__));
        }

        if ($dateTime instanceof \DateTimeInterface) {
            $lastModified = $dateTime->getTimestamp();
        }

        return new FileAttributes($path, $fileSize !== null ? (int) $fileSize : null, null, $lastModified, $mimeType, $metadata);
    }

    /**
     * @param HeadObjectOutput $metadata
     */
    private function extractExtraMetadata($metadata): array
    {
        $extracted = [];

        foreach ($this->metadataFields as $field) {
            $method = 'get' . $field;
            if ( ! method_exists($metadata, $method)) {
                continue;
            }
            $value = $metadata->$method();
            if (null !== $value) {
                $extracted[$field] = $value;
            }
        }

        return $extracted;
    }

    private function retrievePaginatedListing(array $options): Generator
    {
        $result = $this->client->listObjectsV2($options);

        foreach ($result as $item) {
            yield $item;
        }
    }

    private function readObject(string $path): ResultStream
    {
        $options = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)];

        try {
            return $this->client->getObject($options)->getBody();
        } catch (Throwable $exception) {
            throw UnableToReadFile::fromLocation($path, $exception->getMessage(), $exception);
        }
    }

    public function publicUrl(string $path, Config $config): string
    {
        if ( ! $this->client instanceof SimpleS3Client) {
            throw UnableToGeneratePublicUrl::noGeneratorConfigured($path, 'Client needs to be instance of SimpleS3Client');
        }

        try {
            return $this->client->getUrl($this->bucket, $this->prefixer->prefixPath($path));
        } catch (Throwable $exception) {
            throw UnableToGeneratePublicUrl::dueToError($path, $exception);
        }
    }

    public function checksum(string $path, Config $config): string
    {
        $algo = $config->get('checksum_algo', 'etag');

        if ($algo !== 'etag') {
            throw new ChecksumAlgoIsNotSupported();
        }

        try {
            $metadata = $this->fetchFileMetadata($path, 'checksum')->extraMetadata();
        } catch (UnableToRetrieveMetadata $exception) {
            throw new UnableToProvideChecksum($exception->reason(), $path, $exception);
        }

        if ( ! isset($metadata['ETag'])) {
            throw new UnableToProvideChecksum('ETag header not available.', $path);
        }

        return trim($metadata['ETag'], '"');
    }

    public function temporaryUrl(string $path, DateTimeInterface $expiresAt, Config $config): string
    {
        $location = $this->prefixer->prefixPath($path);

        try {
            return $this->client->getPresignedUrl($this->bucket, $location, DateTimeImmutable::createFromInterface($expiresAt));
        } catch (Throwable $exception) {
            throw UnableToGenerateTemporaryUrl::dueToError($path, $exception);
        }
    }
}


text:
package com.softuni.realestate.repository;

import com.softuni.realestate.domain.entities.Offer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface OfferRepository extends JpaRepository<Offer, String> {
}


text:
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
/* dbus-mempool.h Memory pools
 *
 * Copyright (C) 2002  Red Hat, Inc.
 *
 * Licensed under the Academic Free License version 2.1
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#ifndef DBUS_MEMPOOL_H
#define DBUS_MEMPOOL_H

#include <dbus/dbus-internals.h>
#include <dbus/dbus-memory.h>
#include <dbus/dbus-types.h>

DBUS_BEGIN_DECLS

typedef struct DBusMemPool DBusMemPool;

DBusMemPool* _dbus_mem_pool_new     (int          element_size,
                                     dbus_bool_t  zero_elements);
void         _dbus_mem_pool_free    (DBusMemPool *pool);
void*        _dbus_mem_pool_alloc   (DBusMemPool *pool);
dbus_bool_t  _dbus_mem_pool_dealloc (DBusMemPool *pool,
                                     void        *element);

DBUS_END_DECLS

#endif /* DBUS_MEMPOOL_H */


text:
package events

const (
	// Container event reason list
	CreatedContainer        = "Created"
	StartedContainer        = "Started"
	FailedToCreateContainer = "Failed"
	FailedToStartContainer  = "Failed"
	KillingContainer        = "Killing"
	PreemptContainer        = "Preempting"
	BackOffStartContainer   = "BackOff"
	ExceededGracePeriod     = "ExceededGracePeriod"

	// Pod event reason list
	FailedToKillPod                = "FailedKillPod"
	FailedToCreatePodContainer     = "FailedCreatePodContainer"
	FailedToMakePodDataDirectories = "Failed"
	NetworkNotReady                = "NetworkNotReady"

	// Image event reason list
	PullingImage            = "Pulling"
	PulledImage             = "Pulled"
	FailedToPullImage       = "Failed"
	FailedToInspectImage    = "InspectFailed"
	ErrImageNeverPullPolicy = "ErrImageNeverPull"
	BackOffPullImage        = "BackOff"

	// kubelet event reason list
	NodeReady                            = "NodeReady"
	NodeNotReady                         = "NodeNotReady"
	NodeSchedulable                      = "NodeSchedulable"
	NodeNotSchedulable                   = "NodeNotSchedulable"
	StartingKubelet                      = "Starting"
	KubeletSetupFailed                   = "KubeletSetupFailed"
	FailedAttachVolume                   = "FailedAttachVolume"
	FailedMountVolume                    = "FailedMount"
	VolumeResizeFailed                   = "VolumeResizeFailed"
	VolumeResizeSuccess                  = "VolumeResizeSuccessful"
	FileSystemResizeFailed               = "FileSystemResizeFailed"
	FileSystemResizeSuccess              = "FileSystemResizeSuccessful"
	FailedMapVolume                      = "FailedMapVolume"
	WarnAlreadyMountedVolume             = "AlreadyMountedVolume"
	SuccessfulAttachVolume               = "SuccessfulAttachVolume"
	SuccessfulMountVolume                = "SuccessfulMountVolume"
	NodeRebooted                         = "Rebooted"
	ContainerGCFailed                    = "ContainerGCFailed"
	ImageGCFailed                        = "ImageGCFailed"
	FailedNodeAllocatableEnforcement     = "FailedNodeAllocatableEnforcement"
	SuccessfulNodeAllocatableEnforcement = "NodeAllocatableEnforced"
	SandboxChanged                       = "SandboxChanged"
	FailedCreatePodSandBox               = "FailedCreatePodSandBox"
	FailedStatusPodSandBox               = "FailedPodSandBoxStatus"

	// Image manager event reason list
	InvalidDiskCapacity = "InvalidDiskCapacity"
	FreeDiskSpaceFailed = "FreeDiskSpaceFailed"

	// Probe event reason list
	ContainerUnhealthy    = "Unhealthy"
	ContainerProbeWarning = "ProbeWarning"

	// Pod worker event reason list
	FailedSync = "FailedSync"

	// Config event reason list
	FailedValidation = "FailedValidation"

	// Lifecycle hooks
	FailedPostStartHook = "FailedPostStartHook"
	FailedPreStopHook   = "FailedPreStopHook"
)


text:
package godot

import (
	"github.com/shadowapex/godot-go/gdnative"
)

/*------------------------------------------------------------------------------
//   This code was generated by a tool.
//
//   Changes to this file may cause incorrect behavior and will be lost if
//   the code is regenerated. Any updates should be done in
//   "class.go.tmpl" so they can be included in the generated
//   code.
//----------------------------------------------------------------------------*/

//func NewPanelContainerFromPointer(ptr gdnative.Pointer) PanelContainer {
func newPanelContainerFromPointer(ptr gdnative.Pointer) PanelContainer {
	owner := gdnative.NewObjectFromPointer(ptr)
	obj := PanelContainer{}
	obj.SetBaseObject(owner)

	return obj
}

/*
Panel container type. This container fits controls inside of the delimited area of a stylebox. It's useful for giving controls an outline.
*/
type PanelContainer struct {
	Container
	owner gdnative.Object
}

func (o *PanelContainer) BaseClass() string {
	return "PanelContainer"
}

// PanelContainerImplementer is an interface that implements the methods
// of the PanelContainer class.
type PanelContainerImplementer interface {
	ContainerImplementer
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pezizellaster similis Höhn.

### Remarks
null


text:
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml;
using System.Xml.Serialization;

namespace MusicXMLUtils.Structure
{
    [GeneratedCode("xsd", "4.0.30319.18020")]
    [Serializable]
    [DebuggerStepThrough]
    [DesignerCategory("code")]
    [XmlType("kind")]
    public class Kind
    {
        #region -- Public Properties --
        [XmlAttribute("use-symbols")]
        public YesNo UseSymbols { get; set; }

        [XmlIgnore]
        public bool UseSymbolsSpecified { get; set; }

        [XmlAttribute("text", DataType = "token")]
        public string Text { get; set; }

        [XmlAttribute("stack-degrees")]
        public YesNo StackDegrees { get; set; }

        [XmlIgnore]
        public bool StackDegreesSpecified { get; set; }

        [XmlAttribute("parentheses-degrees")]
        public YesNo ParenthesesDegrees { get; set; }

        [XmlIgnore]
        public bool ParenthesesDegreesSpecified { get; set; }

        [XmlAttribute("bracket-degrees")]
        public YesNo BracketDegrees { get; set; }

        [XmlIgnore]
        public bool BracketDegreesSpecified { get; set; }

        [XmlAttribute("halign")]
        public LeftCenterRight Halign { get; set; }

        [XmlIgnore]
        public bool HalignSpecified { get; set; }

        [XmlAttribute("valign")]
        public Valign Valign { get; set; }

        [XmlIgnore]
        public bool ValignSpecified { get; set; }

        [XmlText]
        public KindValue Value { get; set; }
        #endregion

        #region -- Constructors --
        public Kind()
        {
        }

        public Kind(KindValue value)
        {
            this.Value = value;
        }
        #endregion
    }
}


text:
package org.fortiss.smg.informationbroker.impl.cache;

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

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.fortiss.smg.containermanager.api.devices.SIUnitType;
import org.fortiss.smg.informationbroker.api.DoublePoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DoubleCache {

	private static final Logger logger = LoggerFactory.getLogger(DoubleCache.class);
	Cache doubleCache;
    String cacheName;

	public DoubleCache(String cacheName) {
		/*
		 * Configuration of the Cache
		 */
		this.cacheName = cacheName;
		int ObjectsInCache = 1000;
		int TTL = 60;  // Time until Object expires in Cache - when not requested
		int TTI = 20; // Time until Object expires in Cache - since last request

		logger.trace("DoubleCache: Configuring DoubleCache with "
				   + "maximum size: " + ObjectsInCache + " objects"
				   + " expiration time: " +TTL+ " s expiration time since last access: " + TTI
				   + " s general Policy: 'Last Frequently Used' "
					);

		doubleCache = new Cache(cacheName, ObjectsInCache, false, false, TTL, TTI);

	}

	public DoublePoint load(CacheKey key) {

	 	if (doubleCache.get(key) != null) {
	 		logger.info("load: Element requested from DoubleCache" + key);
	 		DoublePoint dp = (DoublePoint) doubleCache.get(key).getObjectValue();
	 		CacheKey k = (CacheKey) doubleCache.get(key).getObjectKey();

	 		return dp;
	 		/*
	 		if (k.getUnit().equals(dp.getUnit())) {
	 			logger.debug("load: Element found in DoubleCache: " + key.getUnit()+"-"+ key.getId() + " : " + dp.getValue());
	 			return dp;
	 		}

	 		else {
	 			logger.error("load: Element requested from DoubleCache has different units in key and value: " +  key.getUnit());
	 			doubleCache.remove(key);
	 			return null;
	 		}
	 		*/
    	}
    	else {
    		logger.info("load: Element not found in DoubleCache :" + key + " - requesting from DB");
    	   	return null;
    	}
    }

	/*
	public List<CacheKey> getKeysbyID(String id) {
		logger.info("getKeysbyID: requesting all keys (origin(aka:deviceID)-unit combinations) for deviceID: " + id);
		List<CacheKey> keys = new ArrayList<CacheKey>();
		for (SIUnitType type : SIUnitType.values()) {
			CacheKey key = new CacheKey(type, id);
			if (doubleCache.isKeyInCache(key)) {
				keys.add(key);
			}
		}
		logger.debug("getKeysbyID: found " + keys.size() + " keys for deviceID: " + id);
		return keys;
	}
	*/

	public void store(CacheKey key, DoublePoint doubleDataPoint) {
		logger.info("store: Element stored in DoubleCache: " + key+ " -> " + doubleDataPoint.getValue());
		Element element = new Element(key, doubleDataPoint);
		doubleCache.put(element);
	}

	public Cache getCache() {
		if (doubleCache != null) {
			return doubleCache;
		}
		else {
			return new DoubleCache("DoubleDefault").doubleCache;
		}
	}

	public boolean isKeyInCache(CacheKey key) {
		return doubleCache.isKeyInCache(key);
	}

}


text:
/*!
  \class SoGLViewportRegionElement Inventor/elements/SoGLViewportRegionElement.h
  \brief The SoGLViewportRegionElement class is yet to be documented.
  \ingroup elements

  FIXME: write doc.
*/

#include <Inventor/elements/SoGLViewportRegionElement.h>

#include <cassert>
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H

#include <Inventor/system/gl.h>

#if COIN_DEBUG
#include <Inventor/errors/SoDebugError.h>
#endif // COIN_DEBUG

SO_ELEMENT_SOURCE(SoGLViewportRegionElement);

/*!
  This static method initializes static data for the
  SoGLViewportRegionElement class.
*/

void
SoGLViewportRegionElement::initClass(void)
{
  SO_ELEMENT_INIT_CLASS(SoGLViewportRegionElement, inherited);
}

/*!
  The destructor.
*/

SoGLViewportRegionElement::~SoGLViewportRegionElement()
{
}

//! FIXME: write doc.

void
SoGLViewportRegionElement::init(SoState * state)
{
  inherited::init(state);
  this->initialized = FALSE;
}

//! FIXME: write doc.

void
SoGLViewportRegionElement::push(SoState * state)
{
  inherited::push(state);
  SoGLViewportRegionElement * prev = (SoGLViewportRegionElement*)
    this->getNextInStack();
  this->viewportRegion = prev->viewportRegion;
  this->initialized = TRUE;
}

//! FIXME: write doc.

void
SoGLViewportRegionElement::pop(SoState * state,
                               const SoElement * prevTopElement)
{
  SoGLViewportRegionElement * prev =
    (SoGLViewportRegionElement *)prevTopElement;
  if (!(this->viewportRegion == prev->viewportRegion))
    this->updategl();
  prev->capture(state);
}

//! FIXME: write doc.

void
SoGLViewportRegionElement::setElt(const SbViewportRegion & viewportRegionarg)
{
  this->viewportRegion = viewportRegionarg;
  this->initialized = TRUE;
  this->updategl();
}

//! FIXME: write doc.

void
SoGLViewportRegionElement::updategl() const
{
  if (this->initialized) {
    SbVec2s origin = this->viewportRegion.getViewportOriginPixels();
    SbVec2s size = this->viewportRegion.getViewportSizePixels();
    glViewport(origin[0], origin[1], size[0], size[1]);

#if COIN_DEBUG && 0 // debug
    SoDebugError::postInfo("SoGLViewportRegionElement::updategl",
                           "glViewport: %d %d %d %d",
                           origin[0], origin[1], size[0], size[1]);
#endif // debug
  }
}


text:
package com.BibleQuote.presentation.ui.library;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.BibleQuote.R;
import com.BibleQuote.async.task.AsyncOpenModule;
import com.BibleQuote.async.task.AsyncRefreshModules;
import com.BibleQuote.async.task.LoadModuleFromFile;
import com.BibleQuote.di.component.ActivityComponent;
import com.BibleQuote.domain.controller.ILibraryController;
import com.BibleQuote.domain.entity.BaseModule;
import com.BibleQuote.domain.entity.BibleReference;
import com.BibleQuote.domain.entity.Book;
import com.BibleQuote.domain.exceptions.BookDefinitionException;
import com.BibleQuote.domain.exceptions.BookNotFoundException;
import com.BibleQuote.domain.exceptions.BooksDefinitionException;
import com.BibleQuote.domain.exceptions.ExceptionHelper;
import com.BibleQuote.domain.exceptions.OpenModuleException;
import com.BibleQuote.entity.ItemList;
import com.BibleQuote.managers.Librarian;
import com.BibleQuote.presentation.dialogs.NotifyDialog;
import com.BibleQuote.presentation.ui.base.AsyncTaskActivity;
import com.BibleQuote.utils.Task;

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

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;
import ru.churchtools.deskbible.data.library.LibraryContext;

public class LibraryActivity extends AsyncTaskActivity {

    private static final int ACTION_CODE_GET_FILE = 1;
    private static final int MODULE_VIEW = 1, BOOK_VIEW = 2, CHAPTER_VIEW = 3;
    private static final String TAG = LibraryActivity.class.getSimpleName();

    @BindView(R.id.books) ListView booksList;
    @BindView(R.id.btnBook) Button btnBook;
    @BindView(R.id.btnChapter) Button btnChapter;
    @BindView(R.id.btnModule) Button btnModule;
    @BindView(R.id.chapterChoose) GridView chapterList;
    @BindView(R.id.modules) ListView modulesList;

    @Inject
    Librarian librarian;
    @Inject
    LibraryContext mLibraryContext;
    @Inject
    ILibraryController mILibraryController;

    private String bookID = Librarian.EMPTY_OBJ;
    private ArrayList<ItemList> books = new ArrayList<>();
    private String chapter = Librarian.EMPTY_OBJ;
    private List<String> chapters = new ArrayList<>();
    private String messageRefresh;
    private String moduleID = Librarian.EMPTY_OBJ;
    private int modulePos, bookPos, chapterPos;
    private ArrayList<ItemList> modules = new ArrayList<>();
    private int viewMode = 1;

    public static Intent createIntent(@NonNull Context context) {
        return new Intent(context, LibraryActivity.class);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_library);
        ButterKnife.bind(this);

        messageRefresh = getResources().getString(R.string.messageRefresh);

        BibleReference osisLink = librarian.getCurrentOSISLink();
        if (librarian.isOSISLinkValid(osisLink)) {
            moduleID = osisLink.getModuleID();
            bookID = osisLink.getBookID();
            chapter = String.valueOf(osisLink.getChapter());
            updateView(CHAPTER_VIEW);
        } else {
            updateView(MODULE_VIEW);
        }
        setButtonText();
    }

    @Override
    protected void inject(ActivityComponent component) {
        component.inject(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater infl = getMenuInflater();
        infl.inflate(R.menu.menu_library, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.action_bar_refresh:
                mAsyncManager.setupTask(new AsyncRefreshModules(messageRefresh, false), this);
                return true;
            case R.id.menu_library_add:
                choiceModuleFromFile();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        updateView(viewMode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ACTION_CODE_GET_FILE) {
            if (resultCode == RESULT_OK) {
                getModuleFromFile(data.getData());
            }
        } else {
            Log.e(TAG, "Unknown request code: " + requestCode);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onTaskComplete(Task task) {
        if (task == null || task.isCancelled()) {
            return;
        }

        if (task instanceof AsyncOpenModule) {
            onOpenModuleComplete((AsyncOpenModule) task);
        } else if (task instanceof LoadModuleFromFile) {
            onLoadModuleComplete((LoadModuleFromFile) task);
        } else {
            updateView(MODULE_VIEW);
        }
    }

    @Override
    public Context getContext() {
        return this;
    }

    @OnItemClick(R.id.books)
    void onClickBookItem(int position) {
        bookPos = position;
        bookID = books.get(bookPos).get("ID");
        chapterPos = 0;

        updateView(CHAPTER_VIEW);
        setButtonText();

        if (chapters.size() == 1) {
            chapter = chapters.get(0);
            readChapter();
        }
    }

    @OnItemClick(R.id.chapterChoose)
    void onClickChapterItem(int position) {
        chapterPos = position;
        chapter = chapters.get(position);
        setButtonText();
        readChapter();
    }

    @OnItemClick(R.id.modules)
    void onClickModuleItem(int position2) {
        modules = librarian.getModulesList();
        if (modules.size() <= position2) {
            updateView(MODULE_VIEW);
            return;
        }
        modulePos = position2;
        moduleID = modules.get(modulePos).get(ItemList.ID);
        bookPos = 0;
        chapterPos = 0;

        String message = getResources().getString(R.string.messageLoadBooks);
        BibleReference currentOSISLink = librarian.getCurrentOSISLink();
        BibleReference osisLink1 = new BibleReference(
                currentOSISLink.getModuleDatasource(),
                null,
                moduleID,
                currentOSISLink.getBookID(),
                currentOSISLink.getChapter(),
                currentOSISLink.getFromVerse());

        mAsyncManager.setupTask(new AsyncOpenModule(message, false, osisLink1), this);
    }

    @OnClick({R.id.btnBook, R.id.btnChapter, R.id.btnModule})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBook:
                onClickBook();
                break;
            case R.id.btnChapter:
                onClickChapter();
                break;
            case R.id.btnModule:
                onClickModule();
                break;
        }
    }

    private void choiceModuleFromFile() {
        final Intent target = new Intent(Intent.ACTION_GET_CONTENT)
                .setType("application/zip")
                .addCategory(Intent.CATEGORY_OPENABLE);
        if (target.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(target, ACTION_CODE_GET_FILE);
        } else {
            Toast.makeText(this, R.string.exception_add_module_from_file, Toast.LENGTH_LONG).show();
        }
    }

    private SimpleAdapter getBookAdapter() {
        books = new ArrayList<>();
        if (!librarian.getModulesList().isEmpty()) {
            try {
                books = librarian.getModuleBooksList(moduleID);
            } catch (OpenModuleException e) {
                ExceptionHelper.onOpenModuleException(e, this, TAG);
            } catch (BooksDefinitionException e) {
                ExceptionHelper.onBooksDefinitionException(e, this, TAG);
            } catch (BookDefinitionException e) {
                ExceptionHelper.onBookDefinitionException(e, this, TAG);
            }
        }
        return new SimpleAdapter(this, books,
                R.layout.item_list,
                new String[]{ItemList.ID, ItemList.Name}, new int[]{
                R.id.id, R.id.name});
    }

    private ArrayAdapter<String> getChapterAdapter() {
        try {
            chapters = librarian.getChaptersList(moduleID, bookID);
        } catch (BookNotFoundException e) {
            ExceptionHelper.onBookNotFoundException(e, this, TAG);
        } catch (OpenModuleException e) {
            ExceptionHelper.onOpenModuleException(e, this, TAG);
        }
        return new ArrayAdapter<>(this, R.layout.chapter_item, R.id.chapter, chapters);
    }

    private SimpleAdapter getModuleAdapter() {
        modules = librarian.getModulesList();
        return new SimpleAdapter(this, modules,
                R.layout.item_list,
                new String[]{ItemList.ID, ItemList.Name}, new int[]{
                R.id.id, R.id.name});
    }

    private void getModuleFromFile(Uri uri) {
        mAsyncManager.setupTask(new LoadModuleFromFile(
                this,
                getString(R.string.copy_module_from_file),
                uri,
                mILibraryController,
                mLibraryContext), this);
    }

    private void onClickBook() {
        if (bookID.equals(Librarian.EMPTY_OBJ)) {
            return;
        }
        updateView(BOOK_VIEW);
    }

    private void onClickChapter() {
        if (chapter.equals(Librarian.EMPTY_OBJ)) {
            return;
        }
        updateView(CHAPTER_VIEW);
    }

    private void onClickModule() {
        if (moduleID.equals(Librarian.EMPTY_OBJ)) {
            return;
        }
        updateView(MODULE_VIEW);
    }

    private void onLoadModuleComplete(LoadModuleFromFile task) {
        LoadModuleFromFile.StatusCode statusCode = task.getStatusCode();
        String errorMessage;
        switch (statusCode) {
            case Success:
                updateView(MODULE_VIEW);
                return;
            case FileNotExist:
                errorMessage = getString(R.string.file_not_exist);
                break;
            case FileNotSupported:
                errorMessage = getString(R.string.file_not_supported);
                break;
            case MoveFailed:
                errorMessage = getString(R.string.file_not_moved);
                break;
            case LibraryNotFound:
                errorMessage = getString(R.string.file_not_moved);
                break;
            default:
                errorMessage = getString(R.string.err_load_module_unknown);
        }
        new NotifyDialog(errorMessage, this).show();
    }

    private void onOpenModuleComplete(AsyncOpenModule task) {
        Exception e = task.getException();
        if (e == null) {
            BaseModule module = task.getModule();
            moduleID = module.getID();
            Map<String, Book> books = module.getBooks();
            if (books != null && books.size() != 0 && !books.containsKey(bookID)) {
                Iterator<String> iterator = books.keySet().iterator();
                bookID = iterator.next();
            }
            setButtonText();
            updateView(BOOK_VIEW);
        } else {
            if (e instanceof OpenModuleException) {
                ExceptionHelper.onOpenModuleException((OpenModuleException) e, this, TAG);

            } else if (e instanceof BooksDefinitionException) {
                ExceptionHelper.onBooksDefinitionException((BooksDefinitionException) e, this, TAG);

            } else if (e instanceof BookDefinitionException) {
                ExceptionHelper.onBookDefinitionException((BookDefinitionException) e, this, TAG);
            }
            updateView(MODULE_VIEW);
        }
    }

    private void readChapter() {
        setResult(RESULT_OK, new Intent()
                .putExtra("linkOSIS", String.format("%s.%s.%s", moduleID, bookID, chapter)));
        finish();
    }

    private void setButtonText() {
        String bookShortName = Librarian.EMPTY_OBJ;
        if (!moduleID.equals(Librarian.EMPTY_OBJ) && !bookID.equals(Librarian.EMPTY_OBJ)) {
            try {
                bookShortName = librarian.getBookShortName(moduleID, bookID);
                List<String> chList = librarian.getChaptersList(moduleID, bookID);
                if (!chList.isEmpty()) {
                    chapter = chList.contains(chapter) ? chapter : chList.get(0);
                } else {
                    chapter = Librarian.EMPTY_OBJ;
                }
            } catch (OpenModuleException e) {
                ExceptionHelper.onOpenModuleException(e, this, TAG);
                moduleID = Librarian.EMPTY_OBJ;
                bookID = Librarian.EMPTY_OBJ;
                chapter = Librarian.EMPTY_OBJ;
            } catch (BookNotFoundException e) {
                ExceptionHelper.onBookNotFoundException(e, this, TAG);
                bookID = Librarian.EMPTY_OBJ;
                chapter = Librarian.EMPTY_OBJ;
            }
        }

        btnModule.setText(moduleID);
        btnBook.setText(bookShortName);
        btnChapter.setText(chapter);
    }

    private void updateView(int viewMode) {
        this.viewMode = viewMode;

        btnModule.setEnabled(viewMode != MODULE_VIEW);
        btnBook.setEnabled(viewMode != BOOK_VIEW);
        btnChapter.setEnabled(viewMode != CHAPTER_VIEW);

        modulesList.setVisibility(viewMode == MODULE_VIEW ? View.VISIBLE : View.GONE);
        booksList.setVisibility(viewMode == BOOK_VIEW ? View.VISIBLE : View.GONE);
        chapterList.setVisibility(viewMode == CHAPTER_VIEW ? View.VISIBLE : View.GONE);

        switch (viewMode) {
            case MODULE_VIEW:
                viewModeModule();
                break;
            case BOOK_VIEW:
                viewModeBook();
                break;
            case CHAPTER_VIEW:
                viewModeChapter();
                break;
            default:
                break;
        }
    }

    private void viewModeBook() {
        booksList.setAdapter(getBookAdapter());
        ItemList itemBook;
        try {
            itemBook = new ItemList(bookID, librarian.getBookFullName(moduleID, bookID));
            bookPos = books.indexOf(itemBook);
            if (bookPos >= 0) {
                booksList.setSelection(bookPos);
            }
        } catch (OpenModuleException e) {
            ExceptionHelper.onOpenModuleException(e, this, TAG);
        }
    }

    private void viewModeChapter() {
        chapterList.setAdapter(getChapterAdapter());
        chapterPos = chapters.indexOf(chapter);
        if (chapterPos >= 0) {
            chapterList.setSelection(chapterPos);
        }
    }

    private void viewModeModule() {
        modulesList.setAdapter(getModuleAdapter());
        modulePos = modules.indexOf(new ItemList(moduleID, librarian.getModuleFullName()));
        if (modulePos >= 0) {
            modulesList.setSelection(modulePos);
        }
    }
}


text:
<?php

namespace Bricks\Custom\Twentysteps\AlexaBrick\AlexaBundle\Entity;

use FOS\OAuthServerBundle\Entity\RefreshToken as BaseRefreshToken;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="bricks_custom_twentysteps_alexa_refresh_token")
 * @ORM\Entity
 */
class RefreshToken extends BaseRefreshToken
{
	/**
	 * @ORM\Id
	 * @ORM\Column(type="integer")
	 * @ORM\GeneratedValue(strategy="AUTO")
	 */
	protected $id;

	/**
	 * @ORM\ManyToOne(targetEntity="Client")
	 * @ORM\JoinColumn(nullable=false)
	 */
	protected $client;

	/**
	 * @ORM\ManyToOne(targetEntity="Bricks\Custom\Twentysteps\AlexaBrick\AlexaBundle\Entity\User", inversedBy="refreshTokens", cascade={"persist","merge"})
	 */
	protected $user;
}


text:
<title>OGRE: OgreGLHardwarePixelBuffer.h File Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

File List

File Members

RenderSystems » GL » include

OgreGLHardwarePixelBuffer.h File Reference
#include "OgreGLPrerequisites.h"

#include "OgreHardwarePixelBuffer.h"

Go to the source code of this file.

Classes

class  	Ogre::GLHardwarePixelBuffer

class  	Ogre::GLTextureBuffer

 	Texture surface.  More...

class  	Ogre::GLRenderBuffer

 	Renderbuffer surface.  More...

Namespaces

namespace  	Ogre

----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/

Copyright © 2012 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Sun Sep 2 08:16:12 2012


text:
package com.myconnector.client.domain.interfaces;

import java.util.List;

public interface ITodoList extends HasId, HasTitle, HasPosition, HasContext {

	List<ITodoItem> getTodoItems();

	void setTodoItems(List<ITodoItem> todoItems);

	boolean isTodoItemsLoaded();

	void setTodoItemsLoaded(boolean todoItemsLoaded);

}


text:
/** @module geo */

import Util from '../Util.class'
import * as measurement from '../measurement/'
import Circle from './Circle.class'
import Sphere from './Sphere.class'

/**
 * @summary Mode of calculating integrals.
 */
enum Mode {
  /**
   * Slice the ball vertically, into thin discs, adding up the areas of those discs.
   */
  VERTICAL,
  /**
   * Peel the ball radially, into thin shells, adding up the surface areas of those shells.
   */
  RADIAL,
}

/**
 * An n-sphere is a set of points equidistant from a point, in n dimensions.
 * It is the generalization of a circle or sphere.
 * The number of dimensions, `n`, is not determined during construction;
 * it must be provided during any method calls.
 *
 * A 0-sphere is the pair of points on a line, `r` units away from the center.
 *   Its "surface" is the pair of points and its "volume" is the line segment between them.
 *   A "1-ball" (a line segment) is the region enclosed by a 0-sphere.
 * A 1-sphere is a standard {@link Circle}.
 *   Its "surface" is its circumference and its "volume" is its area.
 *   A "2-ball" (a disc) is the region enclosed by a 1-sphere.
 * A 2-sphere is a standard {@link Sphere}.
 *   A "3-ball" (a standard ball) is the region enclosed by a 2-sphere.
 */
export default class NSphere {
  static readonly Mode = Mode

  private readonly _RADIUS: measurement.Length

  /**
   * @summary Construct a new NSphere object.
   * @param r the radius of this n-sphere
   */
  constructor(r: measurement.Length) {
    this._RADIUS = r
  }

  /**
   * @summary The radius of this n-sphere.
   */
  get radius(): measurement.Length { return this._RADIUS }

  /**
   * @summary The circumference of this n-sphere.
   */
  get circumference(): measurement.Length { return this._RADIUS.scale(Util.TAU) }

  /**
   * @summary Get this n-sphere's circumference/surface area in the desired number of dimensions.
   * @param   n a non-negative integer representing the dimension
   * @returns the value of the circumference/surface area, as a Length, Area, Volume, or primitive number
   * @throws  {Error} dimensions higher than 3 are not yet supported
   */
  surface(n: number): measurement.Measure {
    const returned: { [index: string]: () => measurement.Measure } = {
      0: () => new measurement.Measure(2, ''),
      1: () => new Circle(this._RADIUS).circumference,
      2: () => new Sphere(this._RADIUS).surfaceArea,
      3: () => this._RADIUS.cube().scale(2 * Math.PI * Math.PI),
      default() { throw new Error('not yet supported') }, // TODO general equation for surface area
    }
    return (returned[n] || returned.default).call(this)
  }

  /**
   * @summary Get this n-sphere's area/volume in the desired number of dimensions.
   * @description
   * If n > 3, this function is recursive. There are two modes of calculation:
   * 1. `vertical` - Takes vertical (n-1)-sphere cross sections, calculates their volumes, and then integrates them.
   * 2. `radial`   - Takes radial n-sphere cross sections (like Russian nesting dolls), calculates their surfaces, and then integrates them.
   *
   * @param   n a non-negative integer representing the dimension
   * @param   acc the accuracy of calculation; larger number = more accurate, but slower
   * @param   mode the mode of calculation
   * @returns the value of the area/volume, as a Length, Area, Volume, or primitive number
   */
  volume(n: number, acc = 100, mode = NSphere.Mode.VERTICAL): measurement.Measure {
    const returned: { [index: string]: () => measurement.Measure } = {
      0: () => this._RADIUS.scale(2),
      1: () => new Circle(this._RADIUS).area,
      2: () => new Sphere(this._RADIUS).volume,
      3: () => new measurement.Measure(1/2 * (Math.PI ** 2) * (this._RADIUS.value ** 4), ''),
      default() {
        return new measurement.Measure((mode === NSphere.Mode.RADIAL) ? Util.integrate(
          0,
          this._RADIUS.value,
          (r: number) => new NSphere(new measurement.Length(r)).surface(n).value,
          acc,
        ) : Util.integrate(
          -this._RADIUS.value,
          this._RADIUS.value,
          (x: number) => new NSphere(new measurement.Length(Math.sqrt(this._RADIUS.square().value - x*x))).volume(n-1, acc, mode).value,
          acc,
        ), '')
      },
    }
    return (returned[n] || returned.default).call(this)
  }
}


text:
[![CircleCI](https://circleci.com/gh/MEDIGO/laika.svg?style=shield)](https://circleci.com/gh/MEDIGO/laika) [![Coverage Status](https://coveralls.io/repos/github/MEDIGO/laika/badge.svg)](https://coveralls.io/github/MEDIGO/laika)

Laika is a feature flag/feature toggle service, written in Go, that allows the creation of flags and their activation/deactivation for specific environments. This way it is possible to control in which environments each feature is available. For instance, when a new feature is developed and released, it would make sense if it was only made available, at first, in a testing or Q&A environment, and only later in production. With Laika this can be achieved by simply going to a web page, selecting the feature, and changing its status on the desired environments.

Using Laika in a project thus allows for fast and continuous feature release and deployment.

`laika-php` is a PHP library that handles communication with Laika's API. You can get it [here](https://github.com/MEDIGO/laika-php).

`laika-react` is a React JS module that handles communication with Laika's API. You can get it [here](https://github.com/MEDIGO/laika-react).

## API Reference

Laika uses CQRS, the query endpoints are as follows.

| Method  | Endpoint                            | Description                |
| ------- | ------------------------------------| -------------------------- |
| `GET`   | `/api/health`                       | Check the service health   |
| `GET`   | `/api/features`                     | List all features          |
| `GET`   | `/api/features/:name`               | Get a feature by name      |
| `GET`   | `/api/features/:name/status/:env`   | Get the status of a feature|
|         |                                     | in a particular environment|
| `GET`   | `/api/environments`                 | List all environments      |

The command endpoint is for manipulating data.

| Method  | Endpoint                          | Example body                                                   | Description               |
| ------- | --------------------------------- | -------------------------------------------------------------- | ------------------------- |
| `POST`  | `/api/events/environment_created` | `{"name":"staging"}`                                           | Create a new environment. |
| `POST`  | `/api/events/feature_created`     | `{"name":"feature1"}`                                          | Create a new feature.     |
| `POST`  | `/api/events/user_created`        | `{"username":"admin","password":"secret"}`                     | Create a new user.        |
| `POST`  | `/api/events/feature_toggled`     | `{"feature":"feature1","environment":"staging","status":true}` | Toggle a feature.         |
| `POST`  | `/api/events/feature_deleted`     | `{"name":"feature1"}`                                          | Delete a feature.         |
| `POST`  | `/api/events/environments_ordered`| `{"order":["dev","staging"]}`                                  | Change env display order. |
| `POST`  | `/api/events/environment_deleted` | `{"name":"staging"}`                                           | Delete an environment.    |

## Client

Laika contains a polling HTTP client that allows to easily check for enabled/disabled features on Go code. It can be found in the `client` package.

### Install

```
$ go get -u github.com/MEDIGO/laika/client
```

### Usage

```go
package main

import (
	"log"

	"github.com/MEDIGO/laika/client"
)

func main() {
	c, err := client.NewClient(client.Config{
		Addr:        "127.0.0.1:8000",
		Username:    "my-username",
		Password:    "my-password",
		Environment: "prod",
	})

	if err != nil {
		log.Fatal(err)
	}

	if c.IsEnabled("my-awesome-feature", false) {
		log.Print("IT'S ALIVE!")
	} else {
		log.Print("Move along. Nothing to see here.")
	}
}
```

## Developing

To develop Laika you need to have the following tools installed in your machine:

- [Docker Compose](https://docs.docker.com/compose/install/)

Build and start the docker contaniers and continuously run/build the server and UI with:

```sh
$ make develop
```

And start hacking!

```sh
$ open http://localhost:8000
```

## Testing

The whole test suite can be executed with:

```
$ make test
```

The docker setup starts with a mysql database. If you would like to connect to your own database, you can pass the configuration to them with the following environment variables:

```
LAIKA_TEST_MYSQL_HOST=db
LAIKA_TEST_MYSQL_PORT=3306
LAIKA_TEST_MYSQL_USERNAME=root
LAIKA_TEST_MYSQL_PASSWORD=root
LAIKA_TEST_MYSQL_DBNAME=laika
```

## Current state of the project

In the current release of Laika, it is possible to create feature flags and enable/disable them in the existing environments.

### Wishlist

- Specify country access (e.g. feature only enabled in Germany).
- Specify user access with percentage (e.g. feature only enabled for 30% of the user base).
- Have a field for environment creation on the web page.
- History for flag status changes.

## Copyright and license

Copyright © 2019 MEDIGO GmbH.

Laika is licensed under the MIT License. See [LICENSE](LICENSE) for the full license text.


text:
package riofs // import "go-hep.org/x/hep/groot/riofs"

import (
	"go-hep.org/x/hep/groot/root"
)

//go:generate go run ./gen-code.go
//go:generate go run ./gendata/gen-dirs.go -f ../testdata/dirs.root
//go:generate go run ./gendata/gen-evnt-tree.go -f ../testdata/small-evnt-tree-nosplit.root
//go:generate go run ./gendata/gen-evnt-tree.go -f ../testdata/small-evnt-tree-fullsplit.root -split=99
//go:generate go run ./gendata/gen-flat-tree.go -f ../testdata/leaves.root
//go:generate go run ./gendata/gen-map-tree.go -f ../testdata/std-map-split0.root -split=0
//go:generate go run ./gendata/gen-map-tree.go -f ../testdata/std-map-split1.root -split=1
//go:generate go run ./gendata/gen-map-tree.go -f ../testdata/std-map-split2.root -split=2
//go:generate go run ./gendata/gen-multi-leaves-tree.go -f ../testdata/padding.root
//go:generate go run ./gendata/gen-join-trees.go -d ../testdata
//go:generate go run ./gendata/gen-bitset-tree.go -f ../testdata/std-bitset.root
//go:generate go run ./gendata/gen-std-containers.go -f ../testdata/std-containers-split00.root -split=0
//go:generate go run ./gendata/gen-tlv.go -f ../testdata/tlv-split00.root -split=0
//go:generate go run ./gendata/gen-tlv.go -f ../testdata/tlv-split01.root -split=1
//go:generate go run ./gendata/gen-tlv.go -f ../testdata/tlv-split99.root -split=99
//go:generate go run ./gendata/gen-tntuple.go  -f ../testdata/tntuple.root
//go:generate go run ./gendata/gen-tntupled.go -f ../testdata/tntupled.root
//go:generate go run ./gendata/gen-tformula.go -f ../testdata/tformula.root
//go:generate go run ./gendata/gen-tconflvl.go -f ../testdata/tconfidence-level.root
//go:generate go run ./gendata/gen-tprofile.go -f ../testdata/tprofile.root
//go:generate go run ./gendata/gen-tgme.go -f ../testdata/tgme.root
//go:generate go run ./gendata/gen-tdatime.go -f ../testdata/tdatime.root
//go:generate go run ./gendata/gen-base.go -f ../testdata/tbase.root

// Directory describes a ROOT directory structure in memory.
type Directory interface {
	// Get returns the object identified by namecycle
	//   namecycle has the format name;cycle
	//   name  = * is illegal, cycle = * is illegal
	//   cycle = "" or cycle = 9999 ==> apply to a memory object
	//
	//   examples:
	//     foo   : get object named foo in memory
	//             if object is not in memory, try with highest cycle from file
	//     foo;1 : get cycle 1 of foo on file
	Get(namecycle string) (root.Object, error)

	// Put puts the object v under the key with the given name.
	Put(name string, v root.Object) error

	// Keys returns the list of keys being held by this directory.
	Keys() []Key

	// Mkdir creates a new subdirectory
	Mkdir(name string) (Directory, error)

	// Parent returns the directory holding this directory.
	// Parent returns nil if this is the top-level directory.
	Parent() Directory
}

// SetFiler is a simple interface to establish File ownership.
type SetFiler interface {
	SetFile(f *File)
}


text:
This directory contains several small sample programs that illustrate
various aspects of the Pykmer library.

The example programs use genome data from FASTA files. We have not
packaged here, but two examples which can be readily obtained and used
to try out these example programs can be retrieved from
 - https://www.ncbi.nlm.nih.gov/nuccore/NC_003098
 - https://www.ncbi.nlm.nih.gov/nuccore/NC_008533

### kmer-copy-number.py

    pypy kmer-copy-number.py 25 NC_003098.fasta

This program takes a FASTA format file and extracts *k*-mers of the
given length and records how many times each occurs in the input sequence.

### make-kset.py

    pypy make-kset.py 25 NC_003098.k25 NC_003098.fasta

This program takes a FASTA format file and extracts all the forward and
reverse complement *k*-mers, and aggregates them in to a sorted list,
then uses the kset module to write them out in a compressed form for
use by some of the other example programs.

### kset-prefix-density.py

    pypy kset-prefix-density.py 12 NC_003098.k25

This program takes a compressed *k*-mer set (as produced by make-kset.py),
and counts how many *k*-mers share each prefix of the given length
(e.g. 12 in the above invocation).  These counts are then compiled in
to a histogram.

### kset-jaccard.py

    pypy kset-jaccard.py NC_003098.k25 NC_008533.k25

This program takes two or more ksets and computes the pair-wise Jaccard
distances.  (The Jaccard distance is the size of the intersection divided
by the size of the union of two sets.)

### sample-kset.py

    pypy sample-kset.py 0.05 11 NC_008533.x25 NC_008533.k25

This program takes a probability and a seed and samples an input kset
in a determinist fashion so that any individual *k*-mer is sampled with
the given probability, but the sampling is determinist, in that for the
same seed, the same *k*-mers will always be included in, or excluded
from the output kset. As a result, this may be fuitfully combined with
the Jaccard distance example above to get approximate Jaccard distances
very quickly, by sampling both inputs with the same probability and seed.


text:
<!DOCTYPE  html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>|3lackM III |></title><link rel="stylesheet" type="text/css" href="../../../../Scripts/css/9worlds.css">
Eagle

The man fall down the fall

He jumped on the Horse, taken with him a black sphere.

Ruby spreads the floor, tainted

You just cannot observe the world like that

But when you experienced it

You just live, without knowing.


text:
require "httparty"
require "hashable"
require "phone_number_validation/version"
require "phone_number_validation/validate/validate_options"
require "phone_number_validation/validate/validate_request"
require "phone_number_validation/validate/validate_response"
require "phone_number_validation/validate/validate_exception"
require "phone_number_validation/countries/countries_options"
require "phone_number_validation/countries/countries_request"
require "phone_number_validation/countries/countries_response"
require "phone_number_validation/countries/countries_exception"

module NumverifyLayer

  class Client

    include HTTParty

    base_uri 'apilayer.net/api'

    def initialize(access_key)

      if access_key.nil?
        raise NumverifyLayer::MissingArgumentException.new 'access_key'
      end

      @access_key = access_key

    end

    def validate(number, options = {})

      if number.nil?
        raise NumverifyLayer::MissingArgumentException.new 'number'
        return
      end

      # Create a shallow copy so we don't manipulate the original reference
      q = options.dup

      # Populate the Query
      q.access_key = @access_key
      q.number = number

      # We then create the Request
      req = NumverifyLayer::ValidateRequest.new(q)

      #  We create a Hash of the request so we can send it via HTTP
      req_dto = req.to_dh

      begin

        # We make the actual request
        res = self.class.get('/validate', req_dto)

        # We ensure that we tap the response so we can use the results
        res.inspect

        if (res[NumverifyLayer::ValidateResponse::ERROR_EXPR])
          raise NumverifyLayer::ValidateException.new res[NumverifyLayer::ValidateResponse::ERROR_EXPR]
        end

        # We just return the parsed binary response
        return res.parsed_response

      rescue => e
        puts e.inspect
        return

      end
    end

    def countries(options = {})

      # Create a shallow copy so we don't manipulate the original reference
      q = options.dup

      # Populate the Query
      q.access_key = @access_key

      # We then create the Request
      req = NumverifyLayer::CountriesRequest.new(q)

      #  We create a Hash of the request so we can send it via HTTP
      req_dto = req.to_dh

      begin

        # We make the actual request
        res = self.class.get('/countries', req_dto)

        # We ensure that we tap the response so we can use the results
        res.inspect

        if (res[NumverifyLayer::CountriesResponse::ERROR_EXPR])
          raise NumverifyLayer::CountriesException.new res[NumverifyLayer::CountriesResponse::ERROR_EXPR]
        end

        # We just return the parsed binary response
        return res.parsed_response

      rescue => e
        puts e.inspect
        return

      end
    end

  end

end


text:
package io.fundrequest.platform.github;

import io.fundrequest.platform.github.parser.GithubRateLimit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

@Component
public class GithubRateHealthCheck implements HealthIndicator {

    private final GithubGateway githubGateway;
    private final int threshold;

    public GithubRateHealthCheck(final GithubGateway githubGateway,
                                 @Value("${io.fundrequest.health.github.api-rate-limit.threshold-percentage:20}") final int thresholdPercentage) {
        this.githubGateway = githubGateway;
        this.threshold = thresholdPercentage;
    }

    @Override
    public Health health() {
        final GithubRateLimit rateLimit = githubGateway.getRateLimit().getCore();
        if (rateLimit.getRemaining() == 0) {
            return addDetails(Health.down(), rateLimit).build();
        }
        if (rateLimit.getRemaining() > calculateThreshold(rateLimit.getLimit())) {
            return addDetails(Health.up(), rateLimit).build();
        }
        return addDetails(Health.status(new Status("THRESHOLD REACHED")), rateLimit).build();
    }

    private int calculateThreshold(final int limit) {
        return limit * threshold / 100;
    }

    private Health.Builder addDetails(final Health.Builder healthBuilder, final GithubRateLimit rateLimit) {
        return healthBuilder.withDetail("limit", rateLimit.getLimit())
                            .withDetail("remaining", rateLimit.getRemaining())
                            .withDetail("reset", toZonedDateTime(rateLimit.getReset()));
    }

    private ZonedDateTime toZonedDateTime(final long reset) {
        return ZonedDateTime.ofInstant(Instant.ofEpochSecond(reset), ZoneId.systemDefault());
    }
}