text:
package com.pivotal.gemfirexd.transactions;

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLTransactionRollbackException;
import java.sql.Statement;
import java.util.Collection;
import java.util.Properties;

import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.TXManagerImpl;
import com.gemstone.gemfire.internal.cache.TXStateProxy;
import com.gemstone.gemfire.internal.cache.TransactionObserver;
import com.gemstone.gemfire.internal.cache.TransactionObserverAdapter;
import com.pivotal.gemfirexd.DistributedSQLTestBase;
import com.pivotal.gemfirexd.TestUtil;
import com.pivotal.gemfirexd.internal.engine.Misc;
import io.snappydata.test.dunit.SerializableRunnable;
import io.snappydata.test.dunit.VM;

public class SnapshotTransactionDUnit extends DistributedSQLTestBase {

  String tableName = "APP.TABLE1";
  boolean testBatchInsert = false;

  public SnapshotTransactionDUnit(String name) {
    super(name);
  }

  @Override
  protected String reduceLogging() {
    return "fine";
  }

  @Override
  public void setUp() throws Exception {
    System.setProperty("gemfire.cache.ENABLE_DEFAULT_SNAPSHOT_ISOLATION", "true");
    System.setProperty("gemfire.cache.ENABLE_DEFAULT_SNAPSHOT_ISOLATION_TEST", "true");
    invokeInEveryVM(new SerializableRunnable() {
      @Override
      public void run() {
        System.setProperty("gemfire.cache.ENABLE_DEFAULT_SNAPSHOT_ISOLATION", "true");
        System.setProperty("gemfire.cache.ENABLE_DEFAULT_SNAPSHOT_ISOLATION_TEST", "true");
      }
    });
    super.setUp();
  }

  @Override
  public void tearDown2() throws Exception {
    System.setProperty("gemfire.cache.ENABLE_DEFAULT_SNAPSHOT_ISOLATION", "false");
    System.setProperty("gemfire.cache.ENABLE_DEFAULT_SNAPSHOT_ISOLATION_TEST", "false");
    invokeInEveryVM(new SerializableRunnable() {
      @Override
      public void run() {
        System.setProperty("gemfire.cache.ENABLE_DEFAULT_SNAPSHOT_ISOLATION", "false");
        System.setProperty("gemfire.cache.ENABLE_DEFAULT_SNAPSHOT_ISOLATION_TEST", "false");
      }
    });
    super.tearDown2();
  }

  // test for default jdbc snapshot insert

  public void testDefaultJDBCSnapshotInsert() throws Exception {
    Exception[] exception = new Exception[1];
    startVMs(1, 2);
    Properties props = new Properties();
    final Connection conn = TestUtil.getConnection(props);
    clientSQLExecute(1, "create table " + tableName + " (intcol int not null, text varchar" +
        "(100) not null) partition by column(intcol)  buckets 7 redundancy 1 persistent enable concurrency checks");

    VM server1 = this.serverVMs.get(0);
    VM server2 = this.serverVMs.get(1);
    server1.invoke(new SerializableRunnable() {
      @Override
      public void run() {
        TXManagerImpl txMgr = GemFireCacheImpl.getExisting()
            .getCacheTransactionManager();
        txMgr.setObserver(new TransactionObserverAdapter() {
          Object lock1 = new Object();
          Object lock2 = new Object();
          boolean alreadyWaiting = false;
          @Override
          public void duringIndividualCommit(TXStateProxy tx,
              Object callbackArg) {

            if (callbackArg == "test") {
              synchronized (lock1) {
                lock1.notify();
              }
              return;
            }
            if(!alreadyWaiting) {
              alreadyWaiting = true;
              try {
                synchronized (lock1) {
                  lock1.wait();
                }
              } catch (InterruptedException ie) {
                // ignore
              }
            }
          }

          public void notifyCommit() {
            synchronized (lock1) {
              lock1.notify();
            }
          }
        });
      }
    });

    server2.invoke(new SerializableRunnable() {
      @Override
      public void run() {
        TXManagerImpl txMgr = GemFireCacheImpl.getExisting()
            .getCacheTransactionManager();
        txMgr.setObserver(new TransactionObserverAdapter() {
          Object lock1 = new Object();
          Object lock2 = new Object();
          boolean alreadyWaiting = false;
          @Override
          public void duringIndividualCommit(TXStateProxy tx,
              Object callbackArg) {

            if (callbackArg == "test") {
              synchronized (lock1) {
                lock1.notify();
              }
              return;
            }
            if(!alreadyWaiting) {
              alreadyWaiting = true;
              try {
                synchronized (lock1) {
                  lock1.wait();
                }
              } catch (InterruptedException ie) {
                // ignore
              }
            }
          }

          public void notifyCommit() {
            synchronized (lock1) {
              lock1.notify();
            }
          }
        });
      }
    });

    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          final Connection conn = TestUtil.getConnection();
          Statement stmt = conn.createStatement();
          for (int i = 0; i < 5; i++) {
            String stmtString = "insert into " + tableName + " values(" + i + ",'test" + i + "')";
            stmt.addBatch(stmtString);
          }
          stmt.executeBatch();
        } catch (Exception e) {
          exception[0] = e;
          e.printStackTrace();
        }
      }
    });
    t.start();
    Thread.sleep(1000);

    server1.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Connection conn2 = TestUtil.getConnection();
              Statement stmt2 = conn2.createStatement();
              ResultSet rs = stmt2.executeQuery("select * from " + tableName);
              assert (!rs.next());
            } catch (Exception e) {
              exception[0] = e;
              e.printStackTrace();
            }
          }
        });
    server2.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Connection conn2 = TestUtil.getConnection();
              Statement stmt2 = conn2.createStatement();
              ResultSet rs = stmt2.executeQuery("select * from " + tableName);
              assert (!rs.next());
            } catch (Exception e) {
              exception[0] = e;
              e.printStackTrace();
            }
          }
        });

    server1.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Collection<TXStateProxy> proxies = Misc.getGemFireCache().getCacheTransactionManager().getHostedTransactionsInProgress();
              for (TXStateProxy tx : proxies) {
                if (tx.isSnapshot()) {
                  final TransactionObserver observer = tx.getObserver();
                  observer.duringIndividualCommit(tx, "test");
                }
              }
            } catch (Exception e) {
              exception[0] = e;
            }
          }
        });

    server2.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Collection<TXStateProxy> proxies = Misc.getGemFireCache().getCacheTransactionManager().getHostedTransactionsInProgress();
              for (TXStateProxy tx : proxies) {
                if (tx.isSnapshot()) {
                  final TransactionObserver observer = tx.getObserver();
                  observer.duringIndividualCommit(tx, "test");
                }
              }
            } catch (Exception e) {
              exception[0] = e;
            }
          }
        });

    t.join();

    try {
      Statement stmt2 = conn.createStatement();
      ResultSet rs = stmt2.executeQuery("select * from " + tableName);
      int num = 0;
      while (rs.next()) {
        num++;
      }
      assertTrue("Expected 5 but was " + num, num == 5);

    } catch (Exception e) {
      exception[0] = e;
      e.printStackTrace();
    }
    if (exception[0] != null) {
      throw exception[0];
    }
  }

  // test for default jdbc snapshot insert with conflict
  public void testDefaultJDBCSnapshotInsertWithConflict() throws Exception {
    Exception[] exception = new Exception[1];
    startVMs(1, 2);
    Properties props = new Properties();
    final Connection conn = TestUtil.getConnection(props);
    clientSQLExecute(1, "create table " + tableName + " (intcol int not null, text varchar" +
        "(100) not null) partition by column(intcol)  buckets 7 redundancy 1 persistent enable concurrency checks");

    Statement stmt = conn.createStatement();
    for (int i = 0; i < 100; i++) {
      String stmtString = "insert into " + tableName + " values(" + i + ",'test" + i + "')";
      stmt.addBatch(stmtString);
    }
    stmt.executeBatch();

    VM server1 = this.serverVMs.get(0);
    VM server2 = this.serverVMs.get(1);
    server1.invoke(new SerializableRunnable() {
      @Override
      public void run() {
        TXManagerImpl txMgr = GemFireCacheImpl.getExisting()
            .getCacheTransactionManager();
        txMgr.setObserver(new TransactionObserverAdapter() {
          Object lock1 = new Object();
          Object lock2 = new Object();
          boolean alreadyWaiting = false;
          @Override
          public void duringIndividualCommit(TXStateProxy tx,
              Object callbackArg) {

            if (callbackArg == "test") {
              synchronized (lock1) {
                lock1.notify();
              }
              return;
            }
            if(!alreadyWaiting) {
              alreadyWaiting = true;
              try {
                synchronized (lock1) {
                  lock1.wait();
                }
              } catch (InterruptedException ie) {
                // ignore
              }
            }
          }

          public void notifyCommit() {
            synchronized (lock1) {
              lock1.notify();
            }
          }
        });
      }
    });

    server2.invoke(new SerializableRunnable() {
      @Override
      public void run() {
        TXManagerImpl txMgr = GemFireCacheImpl.getExisting()
            .getCacheTransactionManager();
        txMgr.setObserver(new TransactionObserverAdapter() {
          Object lock1 = new Object();
          Object lock2 = new Object();
          boolean alreadyWaiting = false;
          @Override
          public void duringIndividualCommit(TXStateProxy tx,
              Object callbackArg) {

            if (callbackArg == "test") {
              synchronized (lock1) {
                lock1.notify();
              }
              return;
            }
            if(!alreadyWaiting) {
              alreadyWaiting = true;
              try {
                synchronized (lock1) {
                  lock1.wait();
                }
              } catch (InterruptedException ie) {
                // ignore
              }
            }
          }

          public void notifyCommit() {
            synchronized (lock1) {
              lock1.notify();
            }
          }
        });
      }
    });

    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          final Connection conn = TestUtil.getConnection();
          Statement stmt = conn.createStatement();
          stmt.executeUpdate("update " + tableName + " set text= 'suranjan' where intcol > 50");
        } catch (Exception e) {
          exception[0] = e;
          e.printStackTrace();
        }
      }
    });
    t.start();
    Thread.sleep(1000);

    try {
      stmt = conn.createStatement();
      stmt.executeUpdate("update " + tableName + " set text= 'kumar' where intcol > 30");
      fail("Expected conflict exception");
    } catch (Exception e) {
      if (!(e instanceof SQLTransactionRollbackException)) {
        exception[0] = e;
        e.printStackTrace();
      }
    }
    if (exception[0] != null) {
      throw exception[0];
    }
    server2.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Connection conn2 = TestUtil.getConnection();
              Statement stmt2 = conn2.createStatement();
              ResultSet rs = stmt2.executeQuery("select * from " + tableName + " where text='suranjan'");
              assert (!rs.next());
            } catch (Exception e) {
              exception[0] = e;
              e.printStackTrace();
            }
          }
        });

    server1.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Collection<TXStateProxy> proxies = Misc.getGemFireCache().getCacheTransactionManager().getHostedTransactionsInProgress();
              for (TXStateProxy tx : proxies) {
                if (tx.isSnapshot()) {
                  final TransactionObserver observer = tx.getObserver();
                  observer.duringIndividualCommit(tx, "test");
                }
              }
            } catch (Exception e) {
              exception[0] = e;
            }
          }
        });

    server2.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Collection<TXStateProxy> proxies = Misc.getGemFireCache().getCacheTransactionManager().getHostedTransactionsInProgress();
              for (TXStateProxy tx : proxies) {
                if (tx.isSnapshot()) {
                  final TransactionObserver observer = tx.getObserver();
                  observer.duringIndividualCommit(tx, "test");
                }
              }
            } catch (Exception e) {
              exception[0] = e;
            }
          }
        });

    t.join();

    try {
      Statement stmt2 = conn.createStatement();
      ResultSet rs = stmt2.executeQuery("select * from " + tableName + " where text='suranjan'");
      int num = 0;
      while (rs.next()) {
        num++;
      }
      assertTrue("Expected 49 but was " + num, num == 49);

    } catch (Exception e) {
      exception[0] = e;
      e.printStackTrace();
    }
    if (exception[0] != null) {
      throw exception[0];
    }
  }

  // test rollback due to conflict of update/delete
  // test for default jdbc snapshot insert with conflict
  public void testDefaultJDBCSnapshotUpdateDeleteConflict() throws Exception {
    Exception[] exception = new Exception[1];
    startVMs(1, 2);
    Properties props = new Properties();
    final Connection conn = TestUtil.getConnection(props);
    clientSQLExecute(1, "create table " + tableName + " (intcol int not null, text varchar" +
        "(100) not null) partition by column(intcol)  buckets 7 redundancy 1 persistent enable concurrency checks");

    Statement stmt = conn.createStatement();
    for (int i = 0; i < 100; i++) {
      String stmtString = "insert into " + tableName + " values(" + i + ",'test" + i + "')";
      stmt.addBatch(stmtString);
    }
    stmt.executeBatch();

    VM server1 = this.serverVMs.get(0);
    VM server2 = this.serverVMs.get(1);
    server1.invoke(new SerializableRunnable() {
      @Override
      public void run() {
        TXManagerImpl txMgr = GemFireCacheImpl.getExisting()
            .getCacheTransactionManager();
        txMgr.setObserver(new TransactionObserverAdapter() {
          Object lock1 = new Object();
          Object lock2 = new Object();
          boolean alreadyWaiting = false;
          @Override
          public void duringIndividualCommit(TXStateProxy tx,
              Object callbackArg) {

            if (callbackArg == "test") {
              synchronized (lock1) {
                lock1.notify();
              }
              return;
            }
            if(!alreadyWaiting) {
              alreadyWaiting = true;
              try {
                synchronized (lock1) {
                  lock1.wait();
                }
              } catch (InterruptedException ie) {
                // ignore
              }
            }
          }

          public void notifyCommit() {
            synchronized (lock1) {
              lock1.notify();
            }
          }
        });
      }
    });

    server2.invoke(new SerializableRunnable() {
      @Override
      public void run() {
        TXManagerImpl txMgr = GemFireCacheImpl.getExisting()
            .getCacheTransactionManager();
        txMgr.setObserver(new TransactionObserverAdapter() {
          Object lock1 = new Object();
          Object lock2 = new Object();
          boolean alreadyWaiting = false;
          @Override
          public void duringIndividualCommit(TXStateProxy tx,
              Object callbackArg) {

            if (callbackArg == "test") {
              synchronized (lock1) {
                lock1.notify();
              }
              return;
            }
            if(!alreadyWaiting) {
              alreadyWaiting = true;
              try {
                synchronized (lock1) {
                  lock1.wait();
                }
              } catch (InterruptedException ie) {
                // ignore
              }
            }
          }

          public void notifyCommit() {
            synchronized (lock1) {
              lock1.notify();
            }
          }
        });
      }
    });

    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          final Connection conn = TestUtil.getConnection();
          Statement stmt = conn.createStatement();
          stmt.executeUpdate("update " + tableName + " set text= 'suranjan' where intcol > 50");
        } catch (Exception e) {
          exception[0] = e;
          e.printStackTrace();
        }
      }
    });
    t.start();
    Thread.sleep(5000);
    getLogWriter().info("Did update which must be blocked ");

    try {
      stmt = conn.createStatement();
      stmt.executeUpdate("delete from " + tableName + " where intcol > 30");
      fail("Expected conflict exception");
    } catch (Exception e) {
      if (!(e instanceof SQLTransactionRollbackException)) {
        exception[0] = e;
        e.printStackTrace();
      }
    }
    if (exception[0] != null) {
      throw exception[0];
    }

    getLogWriter().info("Did delete ops.. ");
    server2.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Connection conn2 = TestUtil.getConnection();
              Statement stmt2 = conn2.createStatement();
              ResultSet rs = stmt2.executeQuery("select * from " + tableName + " where text='suranjan'");
              assert (!rs.next());
            } catch (Exception e) {
              exception[0] = e;
              e.printStackTrace();
            }
          }
        });
    getLogWriter().info("SKSK Did select in both vm ");
    server1.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Collection<TXStateProxy> proxies = Misc.getGemFireCache().getCacheTransactionManager().getHostedTransactionsInProgress();
              for (TXStateProxy tx : proxies) {
                if (tx.isSnapshot()) {
                  final TransactionObserver observer = tx.getObserver();
                  observer.duringIndividualCommit(tx, "test");
                }
              }
            } catch (Exception e) {
              exception[0] = e;
            }
          }
        });

    server2.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Collection<TXStateProxy> proxies = Misc.getGemFireCache().getCacheTransactionManager().getHostedTransactionsInProgress();
              for (TXStateProxy tx : proxies) {
                if (tx.isSnapshot()) {
                  final TransactionObserver observer = tx.getObserver();
                  observer.duringIndividualCommit(tx, "test");
                }
              }
            } catch (Exception e) {
              exception[0] = e;
            }
          }
        });
    getLogWriter().info("SKSK Did notify in both the vm. ");

    t.join();

    getLogWriter().info("SKSK update completed. ");

    try {
      Statement stmt2 = conn.createStatement();
      ResultSet rs = stmt2.executeQuery("select * from " + tableName + " where text='suranjan'");
      int num = 0;
      while (rs.next()) {
        num++;
      }
      assertTrue("Expected 49 but was " + num, num == 49);

    } catch (Exception e) {
      exception[0] = e;
      e.printStackTrace();
    }
    if (exception[0] != null) {
      throw exception[0];
    }
    getLogWriter().info("SKSK Test completed successfully.");
  }

//test rollback due to conflict

  public void testRollbackDueToConflict() throws Exception {
    Exception[] exception = new Exception[2];
    startVMs(1, 2);
    Properties props = new Properties();
    final Connection conn = TestUtil.getConnection(props);

    clientSQLExecute(1, "create table " + tableName + " (intcol int not null, text varchar" +
        "(100) not null, primary key (intcol))  partition by column(intcol)  buckets 7 redundancy 1 persistent enable concurrency checks");

    VM server1 = this.serverVMs.get(0);
    VM server2 = this.serverVMs.get(1);
    server1.invoke(new SerializableRunnable() {
      @Override
      public void run() {
        TXManagerImpl txMgr = GemFireCacheImpl.getExisting()
            .getCacheTransactionManager();
        txMgr.setObserver(new TransactionObserverAdapter() {
          Object lock1 = new Object();
          Object lock2 = new Object();
          boolean alreadyWaiting = false;
          @Override
          public void duringIndividualCommit(TXStateProxy tx,
              Object callbackArg) {

            if (callbackArg == "test") {
              synchronized (lock1) {
                lock1.notify();
              }
              return;
            }
            if(!alreadyWaiting) {
              alreadyWaiting = true;
              try {
                synchronized (lock1) {
                  lock1.wait();
                }
              } catch (InterruptedException ie) {
                // ignore
              }
            }
          }

          public void notifyCommit() {
            synchronized (lock1) {
              lock1.notify();
            }
          }
        });
      }
    });

    server2.invoke(new SerializableRunnable() {
      @Override
      public void run() {
        TXManagerImpl txMgr = GemFireCacheImpl.getExisting()
            .getCacheTransactionManager();
        txMgr.setObserver(new TransactionObserverAdapter() {
          Object lock1 = new Object();
          Object lock2 = new Object();
          boolean alreadyWaiting = false;
          @Override
          public void duringIndividualCommit(TXStateProxy tx,
              Object callbackArg) {

            if (callbackArg == "test") {
              synchronized (lock1) {
                lock1.notify();
              }
              return;
            }
            if(!alreadyWaiting) {
              alreadyWaiting = true;
              try {
                synchronized (lock1) {
                  lock1.wait();
                }
              } catch (InterruptedException ie) {
                // ignore
              }
            }
          }

          public void notifyCommit() {
            synchronized (lock1) {
              lock1.notify();
            }
          }
        });
      }
    });

    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          final Connection conn = TestUtil.getConnection();
          Statement stmt = conn.createStatement();
          for (int i = 0; i < 50; i++) {
            String stmtString = "insert into " + tableName + " values(" + i + ",'test" + i + "')";
            stmt.addBatch(stmtString);
          }
          stmt.executeBatch();
        } catch (Exception e) {
          if(!(e instanceof BatchUpdateException))
            exception[0] = e;
          e.printStackTrace();
        }
      }
    });
    t.start();
    Thread.sleep(1000);

    server1.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Connection conn2 = TestUtil.getConnection();
              Statement stmt2 = conn2.createStatement();
              ResultSet rs = stmt2.executeQuery("select * from " + tableName);
              assert (!rs.next());
            } catch (Exception e) {
              exception[0] = e;
              e.printStackTrace();
            }
          }
        });
    server2.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Connection conn2 = TestUtil.getConnection();
              Statement stmt2 = conn2.createStatement();
              ResultSet rs = stmt2.executeQuery("select * from " + tableName);
              assert (!rs.next());
            } catch (Exception e) {
              exception[0] = e;
              e.printStackTrace();
            }
          }
        });

    try {
      Statement stmt = conn.createStatement();
      for (int i = 40; i < 100; i++) {
        String stmtString = "insert into " + tableName + " values(" + i + ",'test" + i + "')";
        stmt.addBatch(stmtString);
      }
      stmt.executeBatch();
    } catch (Exception e) {
    }

    server1.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Collection<TXStateProxy> proxies = Misc.getGemFireCache().getCacheTransactionManager().getHostedTransactionsInProgress();
              for (TXStateProxy tx : proxies) {
                if (tx.isSnapshot()) {
                  final TransactionObserver observer = tx.getObserver();
                  observer.duringIndividualCommit(tx, "test");
                }
              }
            } catch (Exception e) {
              exception[0] = e;
            }
          }
        });

    server2.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Collection<TXStateProxy> proxies = Misc.getGemFireCache().getCacheTransactionManager().getHostedTransactionsInProgress();
              for (TXStateProxy tx : proxies) {
                if (tx.isSnapshot()) {
                  final TransactionObserver observer = tx.getObserver();
                  observer.duringIndividualCommit(tx, "test");
                }
              }
            } catch (Exception e) {
              exception[0] = e;
            }
          }
        });

    t.join();

    try {
      Connection conn2 = TestUtil.getConnection();
      Statement stmt2 = conn.createStatement();
      ResultSet rs = stmt2.executeQuery("select * from " + tableName);
      int num = 0;
      while (rs.next()) {
        num++;
      }
      assertTrue("Expected 100 but was " + num, num == 100);

    } catch (Exception e) {
      exception[0] = e;
      e.printStackTrace();
    }
    if (exception[0] != null) {
      throw exception[0];
    }
  }

  // test for rollback (persistent table with rollback) restart after LULL period should see only committed data
  public void testRollbackDueToConflictRestart() throws Exception {
    Exception[] exception = new Exception[2];
    startVMs(1, 2);
    Properties props = new Properties();
    final Connection conn = TestUtil.getConnection(props);

    clientSQLExecute(1, "create table " + tableName + " (intcol int not null, text varchar" +
        "(100) not null, primary key (intcol))  partition by column(intcol)  buckets 7 redundancy 1 persistent enable concurrency checks");

    VM server1 = this.serverVMs.get(0);
    VM server2 = this.serverVMs.get(1);
    server1.invoke(new SerializableRunnable() {
      @Override
      public void run() {
        TXManagerImpl txMgr = GemFireCacheImpl.getExisting()
            .getCacheTransactionManager();
        txMgr.setObserver(new TransactionObserverAdapter() {
          Object lock1 = new Object();
          Object lock2 = new Object();
          boolean alreadyWaiting = false;

          @Override
          public void duringIndividualCommit(TXStateProxy tx,
              Object callbackArg) {

            if (callbackArg == "test") {
              synchronized (lock1) {
                lock1.notify();
              }
              return;
            }
            if (!alreadyWaiting) {
              alreadyWaiting = true;
              try {
                synchronized (lock1) {
                  lock1.wait();
                }
              } catch (InterruptedException ie) {
                // ignore
              }
            }
          }

          public void notifyCommit() {
            synchronized (lock1) {
              lock1.notify();
            }
          }
        });
      }
    });

    server2.invoke(new SerializableRunnable() {
      @Override
      public void run() {
        TXManagerImpl txMgr = GemFireCacheImpl.getExisting()
            .getCacheTransactionManager();
        txMgr.setObserver(new TransactionObserverAdapter() {
          Object lock1 = new Object();
          Object lock2 = new Object();
          boolean alreadyWaiting = false;

          @Override
          public void duringIndividualCommit(TXStateProxy tx,
              Object callbackArg) {

            if (callbackArg == "test") {
              synchronized (lock1) {
                lock1.notify();
              }
              return;
            }
            if (!alreadyWaiting) {
              alreadyWaiting = true;
              try {
                synchronized (lock1) {
                  lock1.wait();
                }
              } catch (InterruptedException ie) {
                // ignore
              }
            }
          }

          public void notifyCommit() {
            synchronized (lock1) {
              lock1.notify();
            }
          }
        });
      }
    });

    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          final Connection conn = TestUtil.getConnection();
          Statement stmt = conn.createStatement();
          for (int i = 0; i < 50; i++) {
            String stmtString = "insert into " + tableName + " values(" + i + ",'test" + i + "')";
            stmt.addBatch(stmtString);
          }
          stmt.executeBatch();
        } catch (Exception e) {
          if(!(e instanceof BatchUpdateException))
            exception[0] = e;
          e.printStackTrace();
        }
      }
    });
    t.start();
    Thread.sleep(2000);

    server1.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Connection conn2 = TestUtil.getConnection();
              Statement stmt2 = conn2.createStatement();
              ResultSet rs = stmt2.executeQuery("select * from " + tableName);
              assert (!rs.next());
            } catch (Exception e) {
              exception[0] = e;
              e.printStackTrace();
            }
          }
        });
    server2.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Connection conn2 = TestUtil.getConnection();
              Statement stmt2 = conn2.createStatement();
              ResultSet rs = stmt2.executeQuery("select * from " + tableName);
              assert (!rs.next());
            } catch (Exception e) {
              exception[0] = e;
              e.printStackTrace();
            }
          }
        });

    try {
      Statement stmt = conn.createStatement();
      for (int i = 40; i < 100; i++) {
        String stmtString = "insert into " + tableName + " values(" + i + ",'test" + i + "')";
        stmt.addBatch(stmtString);
      }
      stmt.executeBatch();
    } catch (Exception e) {
      if (!(e instanceof BatchUpdateException))
        exception[0] = e;
      e.printStackTrace();
    }

    server1.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Collection<TXStateProxy> proxies = Misc.getGemFireCache().getCacheTransactionManager().getHostedTransactionsInProgress();
              for (TXStateProxy tx : proxies) {
                if (tx.isSnapshot()) {
                  final TransactionObserver observer = tx.getObserver();
                  observer.duringIndividualCommit(tx, "test");
                }
              }
            } catch (Exception e) {
              exception[0] = e;
            }
          }
        });

    server2.invoke(
        new SerializableRunnable() {
          @Override
          public void run() {
            try {
              Collection<TXStateProxy> proxies = Misc.getGemFireCache().getCacheTransactionManager().getHostedTransactionsInProgress();
              for (TXStateProxy tx : proxies) {
                if (tx.isSnapshot()) {
                  final TransactionObserver observer = tx.getObserver();
                  observer.duringIndividualCommit(tx, "test");
                }
              }
            } catch (Exception e) {
              exception[0] = e;
            }
          }
        });

    t.join();

    try {
      Statement stmt2 = conn.createStatement();
      ResultSet rs = stmt2.executeQuery("select * from " + tableName);
      int num = 0;
      while (rs.next()) {
        num++;
      }
      assertTrue("Expected 100 but was " + num, num == 100);

    } catch (Exception e) {
      exception[0] = e;
      e.printStackTrace();
    }
    if (exception[0] != null) {
      throw exception[0];
    }

    startServerVMs(1, 0, null);

    try {
      Statement stmt2 = conn.createStatement();
      ResultSet rs = stmt2.executeQuery("select * from " + tableName);
      int num = 0;
      while (rs.next()) {
        num++;
      }
      assertTrue("Expected 100 but was " + num, num == 100);

    } catch (Exception e) {
      exception[0] = e;
      e.printStackTrace();
    }
    if (exception[0] != null) {
      throw exception[0];
    }

    stopVMNum(-1);
    Statement stmt = conn.createStatement();
    stmt.execute("call sys.rebalance_all_buckets()");
    stopVMNum(-2);
    stmt.execute("call sys.rebalance_all_buckets()");
    stmt.close();

    try {
      Statement stmt2 = conn.createStatement();
      ResultSet rs = stmt2.executeQuery("select * from " + tableName);
      int num = 0;
      while (rs.next()) {
        num++;
      }
      assertTrue("Expected 100 but was " + num, num == 100);

    } catch (Exception e) {
      exception[0] = e;
      e.printStackTrace();
    }
    if (exception[0] != null) {
      throw exception[0];
    }
  }

}


text:
'use strict';

/**
 * Local dependencies
 */

var compilers = require('./lib/compilers');
var parsers = require('./lib/parsers');

/**
 * Module dependencies
 */

var debug = require('debug')('expand-brackets');
var extend = require('extend-shallow');
var Snapdragon = require('snapdragon');
var toRegex = require('to-regex');

/**
 * Parses the given POSIX character class `pattern` and returns a
 * string that can be used for creating regular expressions for matching.
 *
 * @param {String} `pattern`
 * @param {Object} `options`
 * @return {Object}
 * @api public
 */

function brackets(pattern, options) {
  debug('initializing from <%s>', __filename);
  var res = brackets.create(pattern, options);
  return res.output;
}

/**
 * Takes an array of strings and a POSIX character class pattern, and returns a new
 * array with only the strings that matched the pattern.
 *
 * ```js
 * var brackets = require('expand-brackets');
 * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]'));
 * //=> ['a']
 *
 * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]+'));
 * //=> ['a', 'ab']
 * ```
 * @param {Array} `arr` Array of strings to match
 * @param {String} `pattern` POSIX character class pattern(s)
 * @param {Object} `options`
 * @return {Array}
 * @api public
 */

brackets.match = function(arr, pattern, options) {
  arr = [].concat(arr);
  var opts = extend({}, options);
  var isMatch = brackets.matcher(pattern, opts);
  var len = arr.length;
  var idx = -1;
  var res = [];

  while (++idx < len) {
    var ele = arr[idx];
    if (isMatch(ele)) {
      res.push(ele);
    }
  }

  if (res.length === 0) {
    if (opts.failglob === true) {
      throw new Error('no matches found for "' + pattern + '"');
    }

    if (opts.nonull === true || opts.nullglob === true) {
      return [pattern.split('\\').join('')];
    }
  }
  return res;
};

/**
 * Returns true if the specified `string` matches the given
 * brackets `pattern`.
 *
 * ```js
 * var brackets = require('expand-brackets');
 *
 * console.log(brackets.isMatch('a.a', '[[:alpha:]].[[:alpha:]]'));
 * //=> true
 * console.log(brackets.isMatch('1.2', '[[:alpha:]].[[:alpha:]]'));
 * //=> false
 * ```
 * @param {String} `string` String to match
 * @param {String} `pattern` Poxis pattern
 * @param {String} `options`
 * @return {Boolean}
 * @api public
 */

brackets.isMatch = function(str, pattern, options) {
  return brackets.matcher(pattern, options)(str);
};

/**
 * Takes a POSIX character class pattern and returns a matcher function. The returned
 * function takes the string to match as its only argument.
 *
 * ```js
 * var brackets = require('expand-brackets');
 * var isMatch = brackets.matcher('[[:lower:]].[[:upper:]]');
 *
 * console.log(isMatch('a.a'));
 * //=> false
 * console.log(isMatch('a.A'));
 * //=> true
 * ```
 * @param {String} `pattern` Poxis pattern
 * @param {String} `options`
 * @return {Boolean}
 * @api public
 */

brackets.matcher = function(pattern, options) {
  var re = brackets.makeRe(pattern, options);
  return function(str) {
    return re.test(str);
  };
};

/**
 * Create a regular expression from the given `pattern`.
 *
 * ```js
 * var brackets = require('expand-brackets');
 * var re = brackets.makeRe('[[:alpha:]]');
 * console.log(re);
 * //=> /^(?:[a-zA-Z])$/
 * ```
 * @param {String} `pattern` The pattern to convert to regex.
 * @param {Object} `options`
 * @return {RegExp}
 * @api public
 */

brackets.makeRe = function(pattern, options) {
  var res = brackets.create(pattern, options);
  var opts = extend({strictErrors: false}, options);
  return toRegex(res.output, opts);
};

/**
 * Parses the given POSIX character class `pattern` and returns an object
 * with the compiled `output` and optional source `map`.
 *
 * ```js
 * var brackets = require('expand-brackets');
 * console.log(brackets('[[:alpha:]]'));
 * // { options: { source: 'string' },
 * //   input: '[[:alpha:]]',
 * //   state: {},
 * //   compilers:
 * //    { eos: [Function],
 * //      noop: [Function],
 * //      bos: [Function],
 * //      not: [Function],
 * //      escape: [Function],
 * //      text: [Function],
 * //      posix: [Function],
 * //      bracket: [Function],
 * //      'bracket.open': [Function],
 * //      'bracket.inner': [Function],
 * //      'bracket.literal': [Function],
 * //      'bracket.close': [Function] },
 * //   output: '[a-zA-Z]',
 * //   ast:
 * //    { type: 'root',
 * //      errors: [],
 * //      nodes: [ [Object], [Object], [Object] ] },
 * //   parsingErrors: [] }
 * ```
 * @param {String} `pattern`
 * @param {Object} `options`
 * @return {Object}
 * @api public
 */

brackets.create = function(pattern, options) {
  var snapdragon = (options && options.snapdragon) || new Snapdragon(options);
  compilers(snapdragon);
  parsers(snapdragon);

  var ast = snapdragon.parse(pattern, options);
  ast.input = pattern;
  var res = snapdragon.compile(ast, options);
  res.input = pattern;
  return res;
};

/**
 * Expose `brackets` constructor, parsers and compilers
 */

brackets.compilers = compilers;
brackets.parsers = parsers;

/**
 * Expose `brackets`
 * @type {Function}
 */

module.exports = brackets;

redpajama_set_name: RedPajamaGithub


text:
.class Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection$6;
.super Ljava/lang/Object;
.source "ChooseLockDirection.java"

# interfaces
.implements Landroid/animation/Animator$AnimatorListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;->initializeAnimations()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;

# direct methods
.method constructor <init>(Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;)V
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection$6;->this$0:Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onAnimationCancel(Landroid/animation/Animator;)V
    .locals 3

    iget-object v0, p0, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection$6;->this$0:Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;

    invoke-static {v0}, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;->-get25(Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;)Landroid/widget/ImageView;

    move-result-object v0

    iget-object v1, p0, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection$6;->this$0:Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;

    invoke-static {v1}, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;->-get12(Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;)Landroid/graphics/drawable/Drawable;

    move-result-object v1

    invoke-virtual {v0, v1}, Landroid/widget/ImageView;->setBackground(Landroid/graphics/drawable/Drawable;)V

    iget-object v0, p0, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection$6;->this$0:Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;

    invoke-static {v0}, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;->-get25(Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;)Landroid/widget/ImageView;

    move-result-object v0

    sget-object v1, Landroid/graphics/PorterDuff$Mode;->SRC_ATOP:Landroid/graphics/PorterDuff$Mode;

    const v2, -0x3b3b3c

    invoke-virtual {v0, v2, v1}, Landroid/widget/ImageView;->setColorFilter(ILandroid/graphics/PorterDuff$Mode;)V

    iget-object v0, p0, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection$6;->this$0:Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;

    invoke-static {v0}, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;->-get25(Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;)Landroid/widget/ImageView;

    move-result-object v0

    invoke-virtual {v0}, Landroid/widget/ImageView;->invalidate()V

    return-void
.end method

.method public onAnimationEnd(Landroid/animation/Animator;)V
    .locals 3

    iget-object v0, p0, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection$6;->this$0:Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;

    invoke-static {v0}, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;->-get25(Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;)Landroid/widget/ImageView;

    move-result-object v0

    iget-object v1, p0, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection$6;->this$0:Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;

    invoke-static {v1}, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;->-get12(Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;)Landroid/graphics/drawable/Drawable;

    move-result-object v1

    invoke-virtual {v0, v1}, Landroid/widget/ImageView;->setBackground(Landroid/graphics/drawable/Drawable;)V

    iget-object v0, p0, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection$6;->this$0:Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;

    invoke-static {v0}, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;->-get25(Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;)Landroid/widget/ImageView;

    move-result-object v0

    sget-object v1, Landroid/graphics/PorterDuff$Mode;->SRC_ATOP:Landroid/graphics/PorterDuff$Mode;

    const v2, -0x3b3b3c

    invoke-virtual {v0, v2, v1}, Landroid/widget/ImageView;->setColorFilter(ILandroid/graphics/PorterDuff$Mode;)V

    iget-object v0, p0, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection$6;->this$0:Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;

    invoke-static {v0}, Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;->-get25(Lcom/samsung/android/settings/accessibility/directionlock/ChooseLockDirection;)Landroid/widget/ImageView;

    move-result-object v0

    invoke-virtual {v0}, Landroid/widget/ImageView;->invalidate()V

    return-void
.end method

.method public onAnimationRepeat(Landroid/animation/Animator;)V
    .locals 0

    return-void
.end method

.method public onAnimationStart(Landroid/animation/Animator;)V
    .locals 0

    return-void
.end method


text:
<?php

namespace Nice\Extension;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class DoctrineOrmConfiguration implements ConfigurationInterface
{
    /**
     * Generates the configuration tree builder.
     *
     * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('doctrine_orm');

        $rootNode
            ->children()
                ->arrayNode('mapping')
                    ->isRequired()
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->children()
                            ->enumNode('driver')
                                ->values(array('yml', 'xml', 'annotation', 'php'))
                                ->defaultValue('annotation')
                            ->end()
                            ->scalarNode('namespace')->isRequired()->end()
                            ->arrayNode('paths')
                                ->isRequired()
                                ->requiresAtLeastOneElement()
                                ->prototype('scalar')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('database')
                    ->isRequired()
                    ->requiresAtLeastOneElement()
                    ->prototype('scalar')->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}


text:
package com.gp.solutions.service;

import com.gp.solutions.entity.dbo.Skill;
import com.gp.solutions.repository.SkillRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SkillServiceImpl implements SkillService {

    @Autowired
    private SkillRepository skillRepository;

    /**
     * @param levelName level name for search
     * @return skills in accordance with the introduced level name
     */
    @Override
    public List<Skill> getSkillByLevel(final String levelName) {
        return skillRepository.findByLevel(levelName);
    }
}


text:
package com.lzy.imagepicker.adapter;

import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class ImageViewHolder extends RecyclerView.ViewHolder {
    public ImageViewHolder(View itemView) {
        super(itemView);
    }

    public <T extends View> T v(@IdRes int resId) {
        return (T) itemView.findViewById(resId);
    }
}


text:
package app.database;

import org.apache.commons.dbcp2.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;

/**
 * Created by james on 11/25/16.
 */
public class DatabaseConnection {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseConnection.class);
    private final int N_CONNECTIONS = 6;

    private BasicDataSource connectionPool;

    public DatabaseConnection(String Uri) {
        initializeConnection(Uri);
    }

    private void initializeConnection(String Uri) {
        if (connectionPool != null) {
            return;
        }

        try {
            URI dbUri = new URI(Uri);
            String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
            connectionPool = new BasicDataSource();

            if (dbUri.getUserInfo() != null) {
                connectionPool.setUsername(dbUri.getUserInfo().split(":")[0]);
                connectionPool.setPassword(dbUri.getUserInfo().split(":")[1]);
            }

            connectionPool.setDriverClassName("org.postgresql.Driver");
            connectionPool.setUrl(dbUrl);
            connectionPool.setInitialSize(N_CONNECTIONS);

            // Ensure tables exist
            assert_users();

        } catch (URISyntaxException e) {
            logger.warn("Unable to parse DB URI '{}'", Uri);
        }
    }

    private void assert_users() {
        try {
            Connection connection = connectionPool.getConnection();
            Statement stmt = connection.createStatement();
            stmt.executeUpdate(DatabaseContract.Users.CREATE_TABLE);
        } catch (SQLException e) {
            logger.warn("SQL exception with 'users' table: '{}'", e.getMessage());
        }
    }

}


text:
<!--
  Any copyright is dedicated to the Public Domain.
  http://creativecommons.org/publicdomain/zero/1.0/
-->
<html>
<head>
  <title>Test for DOM Worker Threads</title>
  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<pre id="test">
<script class="testbody" type="text/javascript">

  try {
    var worker = new ChromeWorker("simpleThread_worker.js");
    ok(false, "ChromeWorker constructor should be blocked!");
  }
  catch (e) {
    ok(true, "ChromeWorker constructor wasn't blocked!");
  }

</script>
</pre>
</body>
</html>


text:
from __future__ import unicode_literals

from django.test import TestCase
from httmock import all_requests, HTTMock

from django_seo_js.tests.utils import override_settings
from django_seo_js.backends import PrerenderIO

MOCK_RESPONSE = b"
Hello, World!
"
MOCK_RESPONSE_HEADERS = {"foo": "bar"}
MOCK_RECACHE_RESPONSE = "OK"
MOCK_RECACHE_HEADERS = {"ibbity": "ack"}

@all_requests
def mock_prerender_recache_response(url, request):
    return {
        'status_code': 200,
        'content': MOCK_RECACHE_RESPONSE,
        'headers': MOCK_RECACHE_HEADERS,
    }

@all_requests
def mock_prerender_response(url, request):
    return {
        'status_code': 200,
        'content': MOCK_RESPONSE,
        'headers': MOCK_RESPONSE_HEADERS,
    }

class PrerenderIOTestToken(TestCase):

    @override_settings(PRERENDER_TOKEN=None)
    def test_get_token_throws_exception_if_missing(self):
        self.assertRaises(ValueError, PrerenderIO)

    @override_settings(PRERENDER_TOKEN="123124341adfsaf")
    def test_get_token(self):
        self.backend = PrerenderIO()
        # Test function
        self.assertEqual(self.backend._get_token(), "123124341adfsaf")
        # Test __init__
        self.assertEqual(self.backend.token, "123124341adfsaf")

class PrerenderIOTestMethods(TestCase):

    def setUp(self):
        self.backend = PrerenderIO()

    def test_get_response_for_url_missing_url(self):
        self.assertRaises(TypeError, self.backend.get_response_for_url)
        self.assertRaises(ValueError, self.backend.get_response_for_url, None)

    def test_get_response_for_url_valid(self):
        with HTTMock(mock_prerender_response):
            resp = self.backend.get_response_for_url("http://www.example.com")
            self.assertEqual(MOCK_RESPONSE, resp.content)
            for k, v in MOCK_RESPONSE_HEADERS.items():
                self.assertEqual(resp[k], v)

    def test_update_url_with_url_only(self):
        with HTTMock(mock_prerender_recache_response):
            resp = self.backend.update_url(url="http://www.example.com")
            self.assertEqual(resp, True)

    def test_update_url_with_regex_only(self):
        with HTTMock(mock_prerender_recache_response):
            resp = self.backend.update_url(regex="http://www.example.com/*")
            self.assertEqual(resp, True)

    def test_update_url_missing_url_and_regex(self):
        with HTTMock(mock_prerender_recache_response):
            self.assertRaises(ValueError, self.backend.update_url)


text:
package com.lifeonwalden.codeGenerator.dll.impl;

import com.lifeonwalden.codeGenerator.bean.Constraint;
import com.lifeonwalden.codeGenerator.bean.IndexColumn;
import com.lifeonwalden.codeGenerator.bean.config.Config;
import com.lifeonwalden.codeGenerator.dll.ConstraintGenerator;

public class MSSQLConstraintGeneratorImpl implements ConstraintGenerator {

    @Override
    public String generate(Constraint constraint, Config config) {
        StringBuilder sb = new StringBuilder();
        sb.append("CONSTRAINT ").append(constraint.getName()).append(" ").append(constraint.getType().toUpperCase()).append(" (");

        for (IndexColumn column : constraint.getColumns()) {
            sb.append(column.getName()).append(", ");
        }

        sb.replace(sb.length() - 2, sb.length(), ")");

        return sb.toString();
    }
}


text:
#include "stromx/runtime/Compare.h"
#include "stromx/runtime/DataProvider.h"
#include "stromx/runtime/EnumParameter.h"
#include "stromx/runtime/Id2DataComposite.h"
#include "stromx/runtime/Id2DataPair.h"
#include "stromx/runtime/Locale.h"
#include "stromx/runtime/NumericParameter.h"
#include "stromx/runtime/OperatorException.h"
#include "stromx/runtime/ReadAccess.h"
#include "stromx/runtime/Variant.h"
#include "stromx/runtime/VariantComposite.h"

#include <cmath>

namespace stromx
{
    namespace runtime
    {
        const std::string Compare::TYPE("Compare");
        const std::string Compare::PACKAGE(STROMX_RUNTIME_PACKAGE_NAME);
        const Version Compare::VERSION(STROMX_RUNTIME_VERSION_MAJOR, STROMX_RUNTIME_VERSION_MINOR, STROMX_RUNTIME_VERSION_PATCH);

        Compare::Compare()
        : OperatorKernel(TYPE, PACKAGE, VERSION, setupInitParameters())
        , m_compareToInput(false)
        , m_comparisonType(LESS)
        , m_value(0.0)
        , m_epsilon(1e-6)
        {
        }

        void Compare::setParameter(unsigned int id, const Data& value)
        {
            try
            {
                switch(id)
                {
                case COMPARE_TO_INPUT:
                    m_compareToInput = data_cast<Bool>(value);
                    break;
                case COMPARISON_TYPE:
                    m_comparisonType = data_cast<Enum>(value);
                    break;
                case PARAMETER_VALUE:
                    m_value = data_cast<Float64>(value);
                    break;
                case EPSILON:
                    m_epsilon = data_cast<Float64>(value);
                    break;
                default:
                    throw WrongParameterId(id, *this);
                }
            }
            catch(runtime::BadCast&)
            {
                throw WrongParameterType(parameter(id), *this);
            }
        }

        const DataRef Compare::getParameter(const unsigned int id) const
        {
            switch(id)
            {
            case COMPARE_TO_INPUT:
                return m_compareToInput;
            case COMPARISON_TYPE:
                return m_comparisonType;
            case PARAMETER_VALUE:
                return m_value;
            case EPSILON:
                return m_epsilon;
            default:
                throw WrongParameterId(id, *this);
            }
        }

        void Compare::initialize()
        {
            OperatorKernel::initialize(setupInputs(), setupOutputs(), setupParameters());
        }

        void Compare::execute(DataProvider& provider)
        {
            double value1 = 0.0;
            double value2 = 0.0;
            Id2DataPair number1Mapper(NUMBER_1);
            Id2DataPair number2Mapper(NUMBER_2);

            if (m_compareToInput)
            {
                provider.receiveInputData(number1Mapper && number2Mapper);
                ReadAccess access1(number1Mapper.data());
                ReadAccess access2(number2Mapper.data());

                value1 = toDouble(access1.get());
                value2 = toDouble(access2.get());
            }
            else
            {
                provider.receiveInputData(number1Mapper);
                ReadAccess access(number1Mapper.data());

                value1 = toDouble(access.get());
                value2 = m_value;
            }

            bool result = false;
            switch(m_comparisonType)
            {
            case LESS:
                result = value1 < value2;
                break;
            case GREATER:
                result = value1 > value2;
                break;
            case LESS_OR_EQUAL:
                result = value1 < value2 + m_epsilon;
                break;
            case GREATER_OR_EQUAL:
                result = value1 + m_epsilon > value2;
                break;
            case EQUAL:
                result = std::abs(value1 - value2) < m_epsilon;
                break;
            case NOT_EQUAL:
                result = std::abs(value1 - value2) >= m_epsilon;
                break;
            default:
                throw InternalError("Unsupported comparison type.");
            }

            DataContainer resultContainer(new Bool(result));
            provider.sendOutputData(Id2DataPair(RESULT, resultContainer));
        }

        const std::vector<const Input*> Compare::setupInputs()
        {
            std::vector<const Input*> inputs;

            if (m_compareToInput)
            {
                Input* number1 = new Input(NUMBER_1, Variant::INT || Variant::FLOAT);
                number1->setTitle(L_("Input 1"));
                inputs.push_back(number1);

                Input* number2 = new Input(NUMBER_2, Variant::INT || Variant::FLOAT);
                number2->setTitle(L_("Number 2"));
                inputs.push_back(number2);
            }
            else
            {
                Input* number = new Input(NUMBER_1, Variant::INT || Variant::FLOAT);
                number->setTitle(L_("Number"));
                inputs.push_back(number);
            }

            return inputs;
        }

        const std::vector<const Output*> Compare::setupOutputs()
        {
            std::vector<const Output*> outputs;

            Output* result = new Output(RESULT, Variant::BOOL);
            result->setTitle(L_("Result"));
            outputs.push_back(result);

            return outputs;
        }

        const std::vector<const Parameter*> Compare::setupInitParameters()
        {
            std::vector<const Parameter*> parameters;

            Parameter* compareToInput = new Parameter(COMPARE_TO_INPUT, Variant::BOOL);
            compareToInput->setAccessMode(Parameter::NONE_WRITE);
            compareToInput->setTitle(L_("Compare to second input"));
            parameters.push_back(compareToInput);

            return parameters;
        }

        const std::vector<const Parameter*> Compare::setupParameters()
        {
            std::vector<const Parameter*> parameters;

            EnumParameter* comparisonType = new EnumParameter(COMPARISON_TYPE);
            comparisonType->setAccessMode(Parameter::ACTIVATED_WRITE);
            comparisonType->setTitle(L_("Comparison type"));
            comparisonType->add(EnumDescription(runtime::Enum(LESS), L_("Less")));
            comparisonType->add(EnumDescription(runtime::Enum(LESS_OR_EQUAL), L_("Less or equal")));
            comparisonType->add(EnumDescription(runtime::Enum(GREATER), L_("Greater")));
            comparisonType->add(EnumDescription(runtime::Enum(GREATER_OR_EQUAL), L_("Greater or equal")));
            comparisonType->add(EnumDescription(runtime::Enum(EQUAL), L_("Equal")));
            comparisonType->add(EnumDescription(runtime::Enum(NOT_EQUAL), L_("Not equal")));
            parameters.push_back(comparisonType);

            if (! m_compareToInput)
            {
                NumericParameter<Float64>* parameterValue = new NumericParameter<Float64>(PARAMETER_VALUE);
                parameterValue->setAccessMode(Parameter::ACTIVATED_WRITE);
                parameterValue->setTitle(L_("Value"));
                parameters.push_back(parameterValue);
            }

            NumericParameter<Float64>* epsilon = new NumericParameter<Float64>(EPSILON);
            epsilon->setAccessMode(Parameter::ACTIVATED_WRITE);
            epsilon->setTitle(L_("Epsilon"));
            epsilon->setMin(Float64(0.0));
            parameters.push_back(epsilon);

            return parameters;
        }
    }
}


text:
package org.apache.kafka.streams.processor.internals;

import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.StreamingConfig;
import org.apache.kafka.streams.StreamingMetrics;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.processor.StateStore;
import org.apache.kafka.streams.processor.StateRestoreCallback;
import org.apache.kafka.streams.processor.TaskId;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

public class ProcessorContextImpl implements ProcessorContext, RecordCollector.Supplier {

    private static final Logger log = LoggerFactory.getLogger(ProcessorContextImpl.class);

    private final TaskId id;
    private final StreamTask task;
    private final StreamingMetrics metrics;
    private final RecordCollector collector;
    private final ProcessorStateManager stateMgr;

    private final Serializer<?> keySerializer;
    private final Serializer<?> valSerializer;
    private final Deserializer<?> keyDeserializer;
    private final Deserializer<?> valDeserializer;

    private boolean initialized;

    @SuppressWarnings("unchecked")
    public ProcessorContextImpl(TaskId id,
                                StreamTask task,
                                StreamingConfig config,
                                RecordCollector collector,
                                ProcessorStateManager stateMgr,
                                StreamingMetrics metrics) {
        this.id = id;
        this.task = task;
        this.metrics = metrics;
        this.collector = collector;
        this.stateMgr = stateMgr;

        this.keySerializer = config.keySerializer();
        this.valSerializer = config.valueSerializer();
        this.keyDeserializer = config.keyDeserializer();
        this.valDeserializer = config.valueDeserializer();

        this.initialized = false;
    }

    public void initialized() {
        this.initialized = true;
    }

    public TaskId id() {
        return id;
    }

    public ProcessorStateManager getStateMgr() {
        return stateMgr;
    }

    @Override
    public RecordCollector recordCollector() {
        return this.collector;
    }

    @Override
    public Serializer<?> keySerializer() {
        return this.keySerializer;
    }

    @Override
    public Serializer<?> valueSerializer() {
        return this.valSerializer;
    }

    @Override
    public Deserializer<?> keyDeserializer() {
        return this.keyDeserializer;
    }

    @Override
    public Deserializer<?> valueDeserializer() {
        return this.valDeserializer;
    }

    @Override
    public File stateDir() {
        return stateMgr.baseDir();
    }

    @Override
    public StreamingMetrics metrics() {
        return metrics;
    }

    @Override
    public void register(StateStore store, StateRestoreCallback stateRestoreCallback) {
        if (initialized)
            throw new KafkaException("Can only create state stores during initialization.");

        stateMgr.register(store, stateRestoreCallback);
    }

    @Override
    public StateStore getStateStore(String name) {
        ProcessorNode node = task.node();

        if (node == null)
            throw new KafkaException("accessing from an unknown node");

        if (!node.stateStores.contains(name))
            throw new KafkaException("Processor " + node.name() + " has no access to StateStore " + name);

        return stateMgr.getStore(name);
    }

    @Override
    public String topic() {
        if (task.record() == null)
            throw new IllegalStateException("this should not happen as topic() should only be called while a record is processed");

        return task.record().topic();
    }

    @Override
    public int partition() {
        if (task.record() == null)
            throw new IllegalStateException("this should not happen as partition() should only be called while a record is processed");

        return task.record().partition();
    }

    @Override
    public long offset() {
        if (this.task.record() == null)
            throw new IllegalStateException("this should not happen as offset() should only be called while a record is processed");

        return this.task.record().offset();
    }

    @Override
    public long timestamp() {
        if (task.record() == null)
            throw new IllegalStateException("this should not happen as timestamp() should only be called while a record is processed");

        return task.record().timestamp;
    }

    @Override
    public <K, V> void forward(K key, V value) {
        task.forward(key, value);
    }

    @Override
    public <K, V> void forward(K key, V value, int childIndex) {
        task.forward(key, value, childIndex);
    }

    @Override
    public void commit() {
        task.needCommit();
    }

    @Override
    public void schedule(long interval) {
        task.schedule(interval);
    }
}


text:
package com.google.idea.common.experiments;

import javax.annotation.Nullable;

/** String-valued experiment. */
public class StringExperiment extends Experiment {

  public StringExperiment(String key) {
    super(key);
  }

  @Nullable
  public String getValue() {
    return ExperimentService.getInstance().getExperimentString(this, null);
  }

  @Override
  public String getLogValue() {
    return String.valueOf(getValue());
  }
}


text:
<?php

namespace TimeMachine\ICal\Dumper\Formatter;

/**
 * @author Jean-François Simon <contact@jfsimon.fr>
 */
interface FormatterInterface
{
    /**
     * @param string $name
     *
     * @return string
     */
    function begin($name);

    /**
     * @param string $name
     *
     * @return string
     */
    function end($name);

    /**
     * @param string $name
     * @param string $value
     * @param array  $parameters
     *
     * @return string
     */
    function property($name, $value, array $parameters = array());

    /**
     * @param string $name
     * @param string $value
     *
     * @return string
     */
    function parameter($name, $value);

    /**
     * @param string $value
     * @param int    $level
     *
     * @return string
     */
    function indent($value, $level = 1);

    /**
     * @return string
     */
    function feed();
}


text:
package org.jetbrains.plugins.scala.extensions.implementation.iterator

import com.intellij.psi.PsiElement

/**
 * Pavel.Fatin, 11.05.2010
 */

class ParentsIterator(element: PsiElement) extends Iterator[PsiElement] {
  private var current = element.getParent

  def hasNext = current != null

  def next() = {
    val result = current
    current = current.getParent
    result
  }
}


text:
<%namespace file="utils.html" import="error_field, success_field"/>
<%namespace name="utils" file="utils.html"/>

%if thing.done:

your password has been reset and you've been logged in.  Go use the site!

%else:
${error_field("EXPIRED", 'p')}

<form id="chpass" method="post" action="/api/resetpassword"
      onsubmit="return post_form(this,'resetpassword')">

choose a new password for /u/${thing.username}

  <input type="hidden" name="key" value="${thing.key}"/>

    <%utils:round_field title="${_('new password')}">
      <input type="password" name="passwd" />
      ${error_field("BAD_PASSWORD", "passwd")}
    </%utils:round_field>

    <%utils:round_field title="${_('verify password')}">
      <input type="password" name="passwd2" />
      ${error_field("BAD_PASSWORD_MATCH", "passwd2")}
    </%utils:round_field>

<button class="btn" type="submit">submit</button>

</form>
%endif