text:
+function ($) {
  'use strict'

  // AsyncForm PUBLIC CLASS DEFINITION
  // ===============================

  var formAsyncSelector = 'form[data-async]'
  var AsyncForm = function (element, options) {
    this.$element = $(element)
    this.options = options
    this.$element.on('submit', $.proxy(function (e) {
      e.preventDefault()
      return this.send()
    }, this))
  }

  AsyncForm.VERSION = '3.3.6'

  AsyncForm.prototype.send = function (e) {
    if (e) e.preventDefault()
    var method = this.$element.attr('method')
    var url = this.$element.attr('action')
    var enctype = this.$element.attr('enctype')
    var contentType
    var data
    var that = this

    if (enctype && ~enctype.indexOf('form-data')) {
      // 'data-form' include in enctype
      data = new FormData(this.$element[0])
      contentType = false
    } else {
      data = this.$element.serialize()
    }

    this.$element.trigger(e = $.Event('beforeSubmit.bs.asyncForm'))
    $.ajax(url, {
      method: method,
      data: data,
      contentType: contentType,
      processData: false,
      success: function (data) {
        that.$element.trigger(e = $.Event('success.bs.asyncForm'), [data])
      },
      error: function (jqXHR, testStatus, errorThrown) {
        that.$element.trigger(e = $.Event('error.bs.asyncForm'), [jqXHR, testStatus, errorThrown])
      }
    })
  }

  // AsyncForm PLUGIN DEFINITION
  // =========================

  function Plugin(option)   {
    return this.each(function () {
      var $this = $(this)
      var data = $this.data('bs.asyncForm')
      var options = $.extend({}, $this.data(), typeof option == 'object' && option)
      if (!data) $this.data('bs.asyncForm', (data = new AsyncForm(this, options)))
    })
  }

  var old = $.fn.asyncForm

  $.fn.asyncForm = Plugin
  $.fn.asyncForm.Constructor = AsyncForm

  // AsyncForm NO CONFLICT
  // ===================

  $.fn.asyncForm.noConflict = function () {
    $.fn.asyncForm = old
    return this
  }

  // AsyncForm DATA-API
  // ================

  $(window).on('load', function () {
    $(formAsyncSelector).each(function () {
      var $this = $(this)
      Plugin.call($this)
    })
  })
}(jQuery);


text:
window.fireGlobalEvent = (eventName, params) => {
	window.dispatchEvent(new CustomEvent(eventName, {detail: params}));

	if (Sequoia.settings.get('Iframe_Integration_send_enable') === true) {
		parent.postMessage({
			eventName: eventName,
			data: params
		}, Sequoia.settings.get('Iframe_Integration_send_target_origin'));
	}
};

redpajama_set_name: RedPajamaGithub


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

namespace LibrarySystem.ViewModels
{
    public class BookNode
    {
        public string Name { get; set; }
        public string Url { get; set; }
    }
}


text:
package com.taskadapter.redmineapi.internal;

import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class URIConfiguratorTest {

    private static final RequestParam param1 = new RequestParam("name1", "value1");
    private static final RequestParam param2 = new RequestParam("name3", "value3");
    private static final RequestParam param2WithDifferentValue = new RequestParam("name3", "anotherValue3");
    private static final RequestParam nullParam = null;

    @Test
    public void testDistinctWithNullParam() {
        List<RequestParam> params = Arrays.asList(param1, nullParam, param2);
        assertThat(URIConfigurator.distinct(params)).containsOnly(param1, param2);
    }

    @Test
    public void testDistinctWithDuplicateParams() {
        List<RequestParam> params = Arrays.asList(param1, param2, param2);
        assertThat(URIConfigurator.distinct(params)).containsOnly(param1, param2);
    }

    @Test
    public void testDistinctWithSimilarNames() {
        List<RequestParam> params = Arrays.asList(param2, param2WithDifferentValue);
        assertThat(URIConfigurator.distinct(params)).containsOnly(param2);
    }

    @Test
    public void distinctWithDifferentNamesSameValuesShouldKeepAllItems() {
        assertThat(URIConfigurator.distinct(
                params("one", "value",
                        "two", "value")
        )).containsOnlyElementsOf(
                params("one", "value",
                        "two", "value"));
    }

    @Test
    public void toNameValueConvertsCollection() {
        assertThat(URIConfigurator.toNameValue(Arrays.asList(param1, param2))).containsOnly(
                new BasicNameValuePair(param1.getName(), param1.getValue()),
                new BasicNameValuePair(param2.getName(), param2.getValue()));
    }

    @Test
    public void toNameValueSkipsNullItems() {
        assertThat(URIConfigurator.toNameValue(Arrays.asList(param1, null, param2))).containsOnly(
                new BasicNameValuePair(param1.getName(), param1.getValue()),
                new BasicNameValuePair(param2.getName(), param2.getValue()));
    }

    private static Collection<RequestParam> params(String name, String value) {
        return Arrays.asList(new RequestParam(name, value));
    }

    private static Collection<RequestParam> params(String name1, String value1,
                                             String name2, String value2) {
        return Arrays.asList(new RequestParam(name1, value1),
                new RequestParam(name2, value2));
    }
}


text:
    VSMC_RUNTIME_ASSERT(                                                      \
        (flag), "**DiscreteDistribution** WEIGHTS ARE NOT NON-NEGATIVE")

namespace vsmc
{

/// \brief Draw a single sample given weights
/// \ingroup Distribution
template <typename IntType>
class DiscreteDistribution
{
    public:
    using result_type = IntType;
    using distribution_type = DiscreteDistribution<IntType>;

    class param_type
    {
        public:
        using result_type = IntType;
        using distribution_type = DiscreteDistribution<IntType>;

        param_type() {}

        template <typename InputIter>
        param_type(InputIter first, InputIter last) : probability_(first, last)
        {
            invariant();
        }

        param_type(std::initializer_list<double> weights)
            : probability_(weights.begin(), weights.end())
        {
            invariant();
        }

        template <typename UnaryOperation>
        param_type(std::size_t count, double xmin, double xmax,
            UnaryOperation unary_op)
        {
            probability_.reserve(count);
            double delta = (xmax - xmin) / static_cast<double>(count);
            xmin += 0.5 * delta;
            for (std::size_t i = 0; i != count; ++i)
                probability_.push_back(
                    unary_op(xmin + static_cast<double>(i) * delta));
            invariant();
        }

        Vector<double> probability() const { return probability_; }

        friend bool operator==(
            const param_type &param1, const param_type &param2)
        {
            if (param1.probability_.size() != param2.probability_.size())
                return false;

            for (std::size_t i = 0; i != param1.probability_.size(); ++i)
                if (!internal::is_equal(
                        param1.probability_[i], param2.probability_[i]))
                    return false;

            return true;
        }

        friend bool operator!=(
            const param_type &param1, const param_type &param2)
        {
            return !(param1 == param2);
        }

        template <typename CharT, typename Traits>
        friend std::basic_ostream<CharT, Traits> &operator<<(
            std::basic_ostream<CharT, Traits> &os, const param_type &param)
        {
            if (!os.good())
                return os;

            os << param.probability_.size() << ' ';
            for (std::size_t i = 0; i != param.probability_.size(); ++i)
                os << param.probability_[i] << ' ';

            return os;
        }

        template <typename CharT, typename Traits>
        friend std::basic_istream<CharT, Traits> &operator>>(
            std::basic_istream<CharT, Traits> &is, param_type &param)
        {
            if (!is.good())
                return is;

            std::size_t n = 0;
            is >> std::ws >> n;
            if (!is.good())
                return is;

            Vector<double> probability(n);
            for (std::size_t i = 0; i != n; ++i)
                is >> std::ws >> probability[i];

            if (is.good()) {
                double sum = 0;
                if (is_positive(probability, sum)) {
                    mul(probability.size(), 1 / sum, probability.data(),
                        probability.data());
                    param.probability_ = std::move(probability);
                } else {
                    is.setstate(std::ios_base::failbit);
                }
            }

            return is;
        }

        private:
        Vector<double> probability_;

        friend distribution_type;

        void invariant()
        {
            if (probability_.size() == 0)
                return;

            double sum = 0;
#ifndef NDEBUG
            bool flag = is_positive(probability_, sum);
            VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(flag);
#else
            is_positive(probability_, sum);
#endif
            mul(probability_.size(), 1 / sum, probability_.data(),
                probability_.data());
        }

        void reset() {}

        static bool is_positive(const Vector<double> &probability, double &sum)
        {
            sum = 0;
            bool flag = true;
            for (std::size_t i = 0; i != probability.size(); ++i) {
                sum += probability[i];
                if (probability[i] < 0)
                    flag = false;
            }

            return flag && sum > 0;
        }
    }; // class param_type

    DiscreteDistribution() {}

    template <typename InputIter>
    DiscreteDistribution(InputIter first, InputIter last) : param_(first, last)
    {
    }

    DiscreteDistribution(std::initializer_list<double> weights)
        : param_(weights)
    {
    }

    template <typename UnaryOperation>
    DiscreteDistribution(
        std::size_t count, double xmin, double xmax, UnaryOperation &&unary_op)
        : param_type(count, xmin, xmax, std::forward<UnaryOperation>(unary_op))
    {
    }

    explicit DiscreteDistribution(const param_type &param) : param_(param) {}

    explicit DiscreteDistribution(param_type &&param)
        : param_(std::move(param))
    {
    }

    result_type min() const { return 0; }

    result_type max() const
    {
        return param_.size() == 0 ? 0 : param_.size() - 1;
    }

    Vector<double> probability() const { return param_.probability_; }

    template <typename RNGType>
    result_type operator()(RNGType &rng) const
    {
        return operator()(
            rng, param_.probability_.begin(), param_.probability_.end(), true);
    }

    /// \brief Draw sample with external probabilities
    ///
    /// \param rng A uniform random number generator
    /// \param first The first iterator of the weights sequence.
    /// \param last The one past the end iterator of the weights sequence.
    /// \param normalized If the weights are already normalized
    ///
    /// \details
    /// Given weights \f$(W_1,\dots,W_N)\f$, it is possible to draw the index
    /// \f$i\f$ using the `std::discrete_distribuiton` template. However, there
    /// are two drawbacks with this approach. First, if the weights are already
    /// normalized, this template does uncessary extra work to normalized the
    /// weights. Second, whenever the weights change, a new distribution need
    /// to be constructed (the `param_type` of the distribution is
    /// implementation defined and cannot be used to write portable code),
    /// which will lead to uncessary dynamic memory allocation. This function
    /// does not use dynamic memory and improve performance for normalized
    /// weights.
    template <typename RNGType, typename InputIter>
    result_type operator()(RNGType &rng, InputIter first, InputIter last,
        bool normalized = false) const
    {
        using value_type =
            typename std::iterator_traits<InputIter>::value_type;

        U01Distribution<value_type> u01;
        value_type u = u01(rng);

        if (!normalized) {
            value_type mulw =
                1 / std::accumulate(first, last, static_cast<value_type>(0));
            value_type accw = 0;
            result_type index = 0;
            while (first != last) {
                accw += *first * mulw;
                if (u <= accw)
                    return index;
                ++first;
                ++index;
            }

            return index - 1;
        }

        value_type accw = 0;
        result_type index = 0;
        while (first != last) {
            accw += *first;
            if (u <= accw)
                return index;
            ++first;
            ++index;
        }

        return index - 1;
    }

    friend bool operator==(
        const distribution_type &dist1, const distribution_type &dist2)
    {
        return dist1.param_ == dist2.param_;
    }

    friend bool operator!=(
        const distribution_type &dist1, const distribution_type &dist2)
    {
        return !(dist1 == dist2);
    }

    template <typename CharT, typename Traits>
    friend std::basic_ostream<CharT, Traits> &operator<<(
        std::basic_ostream<CharT, Traits> &os, const distribution_type &dist)
    {
        os << dist.param_;

        return os;
    }

    template <typename CharT, typename Traits>
    friend std::basic_istream<CharT, Traits> &operator>>(
        std::basic_istream<CharT, Traits> &is, distribution_type &dist)
    {
        is >> std::ws >> dist.param_;
        if (is.good())
            dist.reset();

        return is;
    }

    private:
    param_type param_;
}; // class DiscreteDistribution

} // namespace vsmc

#endif // VSMC_RNG_DISCRETE_DISTRIBUTION_HPP


text:
module Clients
  module Slack
    class Message
      attr_reader :title, :tags, :author, :post_url, :permalink,
                  :image_url, :subreddit, :posted_at

      def initialize(params = {})
        @title = params["title"]
        @tags = params["tags"]
        @author = params["author"]
        @post_url = params["post_url"]
        @permalink = params["permalink"]
        @image_url = params["image_url"]
        @subreddit = params["subreddit"]
        @posted_at = params["posted_at"]
      end

      def as_attachment
        {
          "fallback"    => "#{pretext}: #{title} - #{post_url}",
          "color"       => "#36a64f",
          "pretext"     => pretext,
          "author_name" => subreddit,
          "author_link" => "https://www.reddit.com#{permalink}",
          "author_icon" => "https://www.redditstatic.com/spreddit5.gif",
          "image_url"   => image_url,
          "title"       => title,
          "title_link"  => post_url,
          "ts"          => posted_at
        }
      end

      private

      def pretext
        "New post on Reddit by #{author}"
      end
    end
  end
end


text:
/* eslint-disable @typescript-eslint/no-explicit-any */
declare module 'node-persist' {
  export interface InitOptions {
    dir?: string; // default 'persist'
    stringify?: typeof JSON.stringify; // default JSON.stringify
    parse?: typeof JSON.parse; // default JSON.parse
    encoding?: string; // default 'utf8'
    logging?: boolean;
    continuous?: boolean; // default true (instantly persists to disk)
    interval?: false | number; // milliseconds
    ttl?: false | true | number; // can be true for 24h default or a number in MILLISECONDS
  }

  export class LocalStorage {
    constructor(options?: InitOptions);

    initSync(options?: InitOptions): void;
    getItem(key: string): any;
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    setItemSync(key: string, value: any): void;
    removeItemSync(key: string): void;
    persistSync(): void;
  }

  export function initSync(options?: InitOptions): void;
  export function create(options?: InitOptions): LocalStorage;
  export function getItem(key: string): any;
  export function setItemSync(key: string, data: any): void;
  export function persistSync(): void;
  export function removeItemSync(key: string): void;
}


text:
package org.apache.phoenix.end2end;

import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.phoenix.exception.SQLExceptionCode;
import org.apache.phoenix.jdbc.PhoenixStatement;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.schema.SequenceAlreadyExistsException;
import org.apache.phoenix.schema.SequenceNotFoundException;
import org.apache.phoenix.util.PhoenixRuntime;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.QueryUtil;
import org.apache.phoenix.util.ReadOnlyProps;
import org.apache.phoenix.util.SequenceUtil;
import org.junit.After;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.google.common.collect.Lists;

public class SequenceIT extends BaseClientManagedTimeIT {
    private static final String NEXT_VAL_SQL = "SELECT NEXT VALUE FOR foo.bar FROM SYSTEM.\"SEQUENCE\"";
    private static final String SELECT_NEXT_VALUE_SQL = "SELECT NEXT VALUE FOR %s FROM SYSTEM.\"SEQUENCE\"";
    private static final long BATCH_SIZE = 3;

    private Connection conn;

    @BeforeClass
    @Shadower(classBeingShadowed = BaseClientManagedTimeIT.class)
    public static void doSetup() throws Exception {
        Map<String,String> props = getDefaultProps();
        // Must update config before starting server
        props.put(QueryServices.SEQUENCE_CACHE_SIZE_ATTRIB, Long.toString(BATCH_SIZE));
        setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
    }

    @After
    public void tearDown() throws Exception {
        // close any open connection between tests, so that connections are not leaked
    	if (conn != null) {
    		conn.close();
    	}
    }

	@Test
	public void testSystemTable() throws Exception {
		nextConnection();
		String query = "SELECT sequence_schema, sequence_name, current_value, increment_by FROM SYSTEM.\"SEQUENCE\"";
		ResultSet rs = conn.prepareStatement(query).executeQuery();
		assertFalse(rs.next());
	}

	@Test
	public void testDuplicateSequences() throws Exception {
        nextConnection();
		conn.createStatement().execute("CREATE SEQUENCE alpha.beta START WITH 2 INCREMENT BY 4\n");

		try {
	        nextConnection();
			conn.createStatement().execute("CREATE SEQUENCE alpha.beta START WITH 2 INCREMENT BY 4\n");
			Assert.fail("Duplicate sequences");
		} catch (SequenceAlreadyExistsException e){

		}
	}

	@Test
	public void testSequenceNotFound() throws Exception {
        nextConnection();
		String query = "SELECT NEXT value FOR qwert.asdf FROM SYSTEM.\"SEQUENCE\"";
		try {
			conn.prepareStatement(query).executeQuery();
			fail("Sequence not found");
		}catch(SequenceNotFoundException e){

		}
	}

	@Test
    public void testCreateSequence() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE alpha.omega START WITH 2 INCREMENT BY 4");
        nextConnection();
        String query = "SELECT sequence_schema, sequence_name, current_value, increment_by FROM SYSTEM.\"SEQUENCE\" WHERE sequence_name='OMEGA'";
        ResultSet rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals("ALPHA", rs.getString("sequence_schema"));
        assertEquals("OMEGA", rs.getString("sequence_name"));
        assertEquals(2, rs.getInt("current_value"));
        assertEquals(4, rs.getInt("increment_by"));
        assertFalse(rs.next());
	}

    @Test
    public void testCurrentValueFor() throws Exception {
        ResultSet rs;
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE used.nowhere START WITH 2 INCREMENT BY 4");
        nextConnection();
        try {
            rs = conn.createStatement().executeQuery("SELECT CURRENT VALUE FOR used.nowhere FROM SYSTEM.\"SEQUENCE\"");
            rs.next();
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.CANNOT_CALL_CURRENT_BEFORE_NEXT_VALUE.getErrorCode(), e.getErrorCode());
            assertTrue(e.getNextException()==null);
        }

        rs = conn.createStatement().executeQuery("SELECT NEXT VALUE FOR used.nowhere FROM SYSTEM.\"SEQUENCE\"");
        assertTrue(rs.next());
        assertEquals(2, rs.getInt(1));
        rs = conn.createStatement().executeQuery("SELECT CURRENT VALUE FOR used.nowhere FROM SYSTEM.\"SEQUENCE\"");
        assertTrue(rs.next());
        assertEquals(2, rs.getInt(1));
	}

    @Test
    public void testDropSequence() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE alpha.omega START WITH 2 INCREMENT BY 4");
        nextConnection();
        String query = "SELECT sequence_schema, sequence_name, current_value, increment_by FROM SYSTEM.\"SEQUENCE\" WHERE sequence_name='OMEGA'";
        ResultSet rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals("ALPHA", rs.getString("sequence_schema"));
        assertEquals("OMEGA", rs.getString("sequence_name"));
        assertEquals(2, rs.getInt("current_value"));
        assertEquals(4, rs.getInt("increment_by"));
        assertFalse(rs.next());

        conn.createStatement().execute("DROP SEQUENCE alpha.omega");
        nextConnection();
        query = "SELECT sequence_schema, sequence_name, current_value, increment_by FROM SYSTEM.\"SEQUENCE\" WHERE sequence_name='OMEGA'";
        rs = conn.prepareStatement(query).executeQuery();
        assertFalse(rs.next());

        try {
            conn.createStatement().execute("DROP SEQUENCE alpha.omega");
            fail();
        } catch (SequenceNotFoundException ignore) {
        }
    }

	@Test
	public void testSelectNextValueFor() throws Exception {
        nextConnection();
		conn.createStatement().execute("CREATE SEQUENCE foo.bar START WITH 3 INCREMENT BY 2");
        nextConnection();
        assertSequenceValuesForSingleRow(3, 5, 7);
	}

	@Test
	public void testInsertNextValueFor() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE alpha.tau START WITH 2 INCREMENT BY 1");
		conn.createStatement().execute("CREATE TABLE test.sequence_number ( id INTEGER NOT NULL PRIMARY KEY)");
        nextConnection();
		conn.createStatement().execute("UPSERT INTO test.sequence_number (id) VALUES (NEXT VALUE FOR alpha.tau)");
        conn.createStatement().execute("UPSERT INTO test.sequence_number (id) VALUES (NEXT VALUE FOR alpha.tau)");
		conn.commit();
        nextConnection();
		String query = "SELECT id FROM test.sequence_number";
		ResultSet rs = conn.prepareStatement(query).executeQuery();
		assertTrue(rs.next());
		assertEquals(2, rs.getInt(1));
        assertTrue(rs.next());
        assertEquals(3, rs.getInt(1));
	}

    @Test
    public void testSequenceCreation() throws Exception {
        nextConnection();
        conn.createStatement()
                .execute(
                    "CREATE SEQUENCE alpha.gamma START WITH 2 INCREMENT BY 3 MINVALUE 0 MAXVALUE 10 CYCLE CACHE 5");
        nextConnection();
        ResultSet rs =
                conn.createStatement()
                        .executeQuery(
                            "SELECT start_with, current_value, increment_by, cache_size, min_value, max_value, cycle_flag, sequence_schema, sequence_name FROM SYSTEM.\"SEQUENCE\"");
        assertTrue(rs.next());
        assertEquals(2, rs.getLong("start_with"));
        assertEquals(2, rs.getInt("current_value"));
        assertEquals(3, rs.getLong("increment_by"));
        assertEquals(5, rs.getLong("cache_size"));
        assertEquals(0, rs.getLong("min_value"));
        assertEquals(10, rs.getLong("max_value"));
        assertEquals(true, rs.getBoolean("cycle_flag"));
        assertEquals("ALPHA", rs.getString("sequence_schema"));
        assertEquals("GAMMA", rs.getString("sequence_name"));
        assertFalse(rs.next());
        rs =
                conn.createStatement()
                        .executeQuery(
                            "SELECT NEXT VALUE FOR alpha.gamma, CURRENT VALUE FOR alpha.gamma FROM SYSTEM.\"SEQUENCE\"");
        assertTrue(rs.next());
        assertEquals(2, rs.getLong(1));
        assertEquals(2, rs.getLong(2));
        assertFalse(rs.next());
        rs =
                conn.createStatement()
                        .executeQuery(
                            "SELECT CURRENT VALUE FOR alpha.gamma, NEXT VALUE FOR alpha.gamma FROM SYSTEM.\"SEQUENCE\"");
        assertTrue(rs.next());
        assertEquals(5, rs.getLong(1));
        assertEquals(5, rs.getLong(2));
        assertFalse(rs.next());
    }

    @Test
    public void testSameMultipleSequenceValues() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE alpha.zeta START WITH 4 INCREMENT BY 7");
        nextConnection();
        String query = "SELECT NEXT VALUE FOR alpha.zeta, NEXT VALUE FOR alpha.zeta FROM SYSTEM.\"SEQUENCE\"";
        ResultSet rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals(4, rs.getInt(1));
        assertEquals(4, rs.getInt(2));
        assertFalse(rs.next());
        conn.close();
    }

    @Test
    public void testMultipleSequenceValues() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE alpha.zeta START WITH 4 INCREMENT BY 7");
        conn.createStatement().execute("CREATE SEQUENCE alpha.kappa START WITH 9 INCREMENT BY 2");
        nextConnection();
        String query = "SELECT NEXT VALUE FOR alpha.zeta, NEXT VALUE FOR alpha.kappa FROM SYSTEM.\"SEQUENCE\"";
        ResultSet rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals(4, rs.getInt(1));
        assertEquals(9, rs.getInt(2));
        assertTrue(rs.next());
        assertEquals(4+7, rs.getInt(1));
        assertEquals(9+2, rs.getInt(2));
        assertFalse(rs.next());
        conn.close();
        // Test that sequences don't have gaps (if no other client request the same sequence before we close it)
        nextConnection();
        rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals(4+7*2, rs.getInt(1));
        assertEquals(9+2*2, rs.getInt(2));
        assertTrue(rs.next());
        assertEquals(4+7*3, rs.getInt(1));
        assertEquals(9+2*3, rs.getInt(2));
        assertFalse(rs.next());
        conn.close();
    }

    @Test
    public void testMultipleSequencesNoCycle() throws Exception {
        nextConnection();
        conn.createStatement().execute(
            "CREATE SEQUENCE alpha.zeta START WITH 4 INCREMENT BY 7 MAXVALUE 24");
        conn.createStatement().execute(
            "CREATE SEQUENCE alpha.kappa START WITH 9 INCREMENT BY -2 MINVALUE 5");
        nextConnection();
        String query =
                "SELECT NEXT VALUE FOR alpha.zeta, NEXT VALUE FOR alpha.kappa FROM SYSTEM.\"SEQUENCE\"";
        ResultSet rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals(4, rs.getInt(1));
        assertEquals(9, rs.getInt(2));
        assertTrue(rs.next());
        assertEquals(4 + 7, rs.getInt(1));
        assertEquals(9 - 2, rs.getInt(2));
        assertFalse(rs.next());
        conn.close();

        nextConnection();
        rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals(4 + 7 * 2, rs.getInt(1));
        assertEquals(9 - 2 * 2, rs.getInt(2));
        try {
            rs.next();
            fail();
        } catch (SQLException e) {
            SQLException sqlEx1 =
                    SequenceUtil.getException("ALPHA", "ZETA",
                        SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE);
            SQLException sqlEx2 =
                    SequenceUtil.getException("ALPHA", "KAPPA",
                        SQLExceptionCode.SEQUENCE_VAL_REACHED_MIN_VALUE);
            verifyExceptions(e, Lists.newArrayList(sqlEx1.getMessage(), sqlEx2.getMessage()));
        }
        conn.close();
    }

    @Test
    public void testMultipleSequencesCycle() throws Exception {
        nextConnection();
        conn.createStatement().execute(
            "CREATE SEQUENCE alpha.zeta START WITH 4 INCREMENT BY 7 MINVALUE 4 MAXVALUE 19 CYCLE");
        conn.createStatement().execute(
            "CREATE SEQUENCE alpha.kappa START WITH 9 INCREMENT BY -2 MINVALUE 5 MAXVALUE 9 CYCLE");
        nextConnection();
        String query =
                "SELECT NEXT VALUE FOR alpha.zeta, NEXT VALUE FOR alpha.kappa FROM SYSTEM.\"SEQUENCE\"";
        ResultSet rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals(4, rs.getInt(1));
        assertEquals(9, rs.getInt(2));
        assertTrue(rs.next());
        assertEquals(4 + 7, rs.getInt(1));
        assertEquals(9 - 2, rs.getInt(2));
        assertFalse(rs.next());
        conn.close();

        nextConnection();
        rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals(4 + 7 * 2, rs.getInt(1));
        assertEquals(9 - 2 * 2, rs.getInt(2));
        assertTrue(rs.next());
        assertEquals(4, rs.getInt(1));
        assertEquals(9, rs.getInt(2));
        conn.close();
    }

	@Test
	public void testCompilerOptimization() throws Exception {
		nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE seq.perf START WITH 3 INCREMENT BY 2");
		conn.createStatement().execute("CREATE TABLE t (k INTEGER NOT NULL PRIMARY KEY, v1 VARCHAR, v2 VARCHAR) IMMUTABLE_ROWS=true");
        nextConnection();
        conn.createStatement().execute("CREATE INDEX idx ON t(v1) INCLUDE (v2)");
        nextConnection();
        PhoenixStatement stmt = conn.createStatement().unwrap(PhoenixStatement.class);
        stmt.optimizeQuery("SELECT k, NEXT VALUE FOR seq.perf FROM t WHERE v1 = 'bar'");
	}

	@Test
	public void testSelectRowAndSequence() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE alpha.epsilon START WITH 1 INCREMENT BY 4");
		conn.createStatement().execute("CREATE TABLE test.foo ( id INTEGER NOT NULL PRIMARY KEY)");
        nextConnection();
		conn.createStatement().execute("UPSERT INTO test.foo (id) VALUES (NEXT VALUE FOR alpha.epsilon)");
		conn.commit();
        nextConnection();
		String query = "SELECT NEXT VALUE FOR alpha.epsilon, id FROM test.foo";
		ResultSet rs = conn.prepareStatement(query).executeQuery();
		assertTrue(rs.next());
		assertEquals(5, rs.getInt(1));
		assertEquals(1, rs.getInt(2));
        assertFalse(rs.next());
	}

    @Test
    public void testSelectNextValueForOverMultipleBatches() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar");
        conn.createStatement().execute("CREATE TABLE foo (k BIGINT NOT NULL PRIMARY KEY)");

        nextConnection();
        PreparedStatement stmt = conn.prepareStatement("UPSERT INTO foo VALUES(NEXT VALUE FOR foo.bar)");
        for (int i = 0; i < BATCH_SIZE  * 2 + 1; i++) {
            stmt.execute();
        }
        conn.commit();
        nextConnection();
        ResultSet rs = conn.createStatement().executeQuery("SELECT count(*),max(k) FROM foo");
        assertTrue(rs.next());
        assertEquals(BATCH_SIZE * 2 + 1, rs.getInt(1));
        assertEquals(BATCH_SIZE * 2 + 1, rs.getInt(2));
    }

    @Test
    public void testSelectNextValueForGroupBy() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar");
        conn.createStatement().execute("CREATE TABLE foo (k BIGINT NOT NULL PRIMARY KEY, v VARCHAR)");
        conn.createStatement().execute("CREATE TABLE bar (k BIGINT NOT NULL PRIMARY KEY, v VARCHAR)");

        nextConnection();
        PreparedStatement stmt = conn.prepareStatement("UPSERT INTO foo VALUES(NEXT VALUE FOR foo.bar, ?)");
        stmt.setString(1, "a");
        stmt.execute();
        stmt.setString(1, "a");
        stmt.execute();
        stmt.setString(1, "b");
        stmt.execute();
        stmt.setString(1, "b");
        stmt.execute();
        stmt.setString(1, "c");
        stmt.execute();
        conn.commit();

        nextConnection();
        ResultSet rs = conn.createStatement().executeQuery("SELECT k from foo");
        assertTrue(rs.next());
        assertEquals(1, rs.getInt(1));
        assertTrue(rs.next());
        assertEquals(2, rs.getInt(1));
        assertTrue(rs.next());
        assertEquals(3, rs.getInt(1));
        assertTrue(rs.next());
        assertEquals(4, rs.getInt(1));
        assertTrue(rs.next());
        assertEquals(5, rs.getInt(1));
        assertFalse(rs.next());

        nextConnection();
        conn.setAutoCommit(true);;
        conn.createStatement().execute("UPSERT INTO bar SELECT NEXT VALUE FOR foo.bar,v FROM foo GROUP BY v");
        nextConnection();
        rs = conn.createStatement().executeQuery("SELECT * from bar");
        assertTrue(rs.next());
        assertEquals(6, rs.getInt(1));
        assertEquals("a", rs.getString(2));
        assertTrue(rs.next());
        assertEquals(7, rs.getInt(1));
        assertEquals("b", rs.getString(2));
        assertTrue(rs.next());
        assertEquals(8, rs.getInt(1));
        assertEquals("c", rs.getString(2));
        assertFalse(rs.next());
    }

    @Test
    public void testSelectNextValueForMultipleConn() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar");
        conn.createStatement().execute("CREATE TABLE foo (k BIGINT NOT NULL PRIMARY KEY)");

        nextConnection();
        Connection conn1 = conn;
        conn = null; // So that call to nextConnection doesn't close it

        PreparedStatement stmt1 = conn1.prepareStatement("UPSERT INTO foo VALUES(NEXT VALUE FOR foo.bar)");
        for (int i = 0; i < BATCH_SIZE+ 1; i++) {
            stmt1.execute();
        }
        conn1.commit();

        nextConnection();
        Connection conn2 = conn;
        PreparedStatement stmt2 = conn2.prepareStatement("UPSERT INTO foo VALUES(NEXT VALUE FOR foo.bar)");
        stmt2.execute();
        stmt1.close(); // Should still continue with next value, even on separate connection
        for (int i = 0; i < BATCH_SIZE; i++) {
            stmt2.execute();
        }
        conn2.commit();
        conn2.close();
        conn1.close();

        nextConnection();
        // No gaps exist even when sequences were generated from different connections
        ResultSet rs = conn.createStatement().executeQuery("SELECT k FROM foo");
        for (int i = 0; i < (BATCH_SIZE+ 1)*2; i++) {
            assertTrue(rs.next());
            assertEquals(i+1, rs.getInt(1));
        }
        assertFalse(rs.next());
    }

    @Test
    public void testSelectNextValueForMultipleConnWithStmtClose() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar");
        conn.createStatement().execute("CREATE TABLE foo (k BIGINT NOT NULL PRIMARY KEY)");

        nextConnection();
        Connection conn1 = conn;
        conn = null; // So that call to nextConnection doesn't close it

        PreparedStatement stmt1 = conn1.prepareStatement("UPSERT INTO foo VALUES(NEXT VALUE FOR foo.bar)");
        for (int i = 0; i < BATCH_SIZE+ 1; i++) {
            stmt1.execute();
        }
        conn1.commit();
        stmt1.close();

        nextConnection();
        Connection conn2 = conn;
        conn = null; // So that call to nextConnection doesn't close it

        PreparedStatement stmt2 = conn2.prepareStatement("UPSERT INTO foo VALUES(NEXT VALUE FOR foo.bar)");
        for (int i = 0; i < BATCH_SIZE + 1; i++) {
            stmt2.execute();
        }
        conn2.commit();
        conn2.close();
        conn1.close();

        nextConnection();
        ResultSet rs = conn.createStatement().executeQuery("SELECT k FROM foo");
        for (int i = 0; i < 2*(BATCH_SIZE + 1); i++) {
            assertTrue(rs.next());
            assertEquals(i+1, rs.getInt(1));
        }
        assertFalse(rs.next());
    }

    @Test
    public void testSelectNextValueForMultipleConnWithConnClose() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar");
        conn.createStatement().execute("CREATE TABLE foo (k BIGINT NOT NULL PRIMARY KEY)");

        nextConnection();
        Connection conn1 = conn;
        conn = null; // So that call to nextConnection doesn't close it

        PreparedStatement stmt1 = conn1.prepareStatement("UPSERT INTO foo VALUES(NEXT VALUE FOR foo.bar)");
        for (int i = 0; i < BATCH_SIZE+ 1; i++) {
            stmt1.execute();
        }
        conn1.commit();
        conn1.close();

        nextConnection();
        Connection conn2 = conn;
        conn = null; // So that call to nextConnection doesn't close it

        PreparedStatement stmt2 = conn2.prepareStatement("UPSERT INTO foo VALUES(NEXT VALUE FOR foo.bar)");
        for (int i = 0; i < BATCH_SIZE + 1; i++) {
            stmt2.execute();
        }
        conn2.commit();
        conn2.close();

        nextConnection();
        ResultSet rs = conn.createStatement().executeQuery("SELECT k FROM foo");
        for (int i = 0; i < 2*(BATCH_SIZE + 1); i++) {
            assertTrue(rs.next());
            assertEquals(i+1, rs.getInt(1));
        }
        assertFalse(rs.next());
    }

    @Test
    public void testDropCachedSeq1() throws Exception {
        testDropCachedSeq(false);
    }

    @Test
    public void testDropCachedSeq2() throws Exception {
        testDropCachedSeq(true);
    }

    private void testDropCachedSeq(boolean detectDeleteSeqInEval) throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar");
        conn.createStatement().execute("CREATE SEQUENCE bar.bas START WITH 101");
        conn.createStatement().execute("CREATE TABLE foo (k BIGINT NOT NULL PRIMARY KEY)");

        nextConnection();
        Connection conn1 = conn;
        conn = null; // So that call to nextConnection doesn't close it

        String stmtStr1a = "UPSERT INTO foo VALUES(NEXT VALUE FOR foo.bar)";
        PreparedStatement stmt1a = conn1.prepareStatement(stmtStr1a);
        stmt1a.execute();
        stmt1a.execute();
        String stmtStr1b = "UPSERT INTO foo VALUES(NEXT VALUE FOR bar.bas)";
        PreparedStatement stmt1b = conn1.prepareStatement(stmtStr1b);
        stmt1b.execute();
        stmt1b.execute();
        stmt1b.execute();
        conn1.commit();

        nextConnection();
        Connection conn2 = conn;
        conn = null; // So that call to nextConnection doesn't close it

        PreparedStatement stmt2 = conn2.prepareStatement("UPSERT INTO foo VALUES(NEXT VALUE FOR bar.bas)");
        stmt2.execute();
        conn2.commit();

        nextConnection();
        ResultSet rs = conn.createStatement().executeQuery("SELECT k FROM foo");
        assertTrue(rs.next());
        assertEquals(1, rs.getInt(1));
        assertTrue(rs.next());
        assertEquals(2, rs.getInt(1));
        assertTrue(rs.next());
        assertEquals(101, rs.getInt(1));
        assertTrue(rs.next());
        assertEquals(102, rs.getInt(1));
        assertTrue(rs.next());
        assertEquals(103, rs.getInt(1));
        assertTrue(rs.next());
        assertEquals(104, rs.getInt(1));
        assertFalse(rs.next());

        nextConnection();
        conn.createStatement().execute("DROP SEQUENCE bar.bas");

        nextConnection();
        stmt1a = conn.prepareStatement(stmtStr1a);
        stmt1a.execute();
        if (!detectDeleteSeqInEval) {
            stmt1a.execute(); // Will allocate new batch for foo.bar and get error for bar.bas, but ignore it
        }

        stmt1b = conn.prepareStatement(stmtStr1b);
        try {
            stmt1b.execute(); // Will try to get new batch, but fail b/c sequence has been dropped
            fail();
        } catch (SequenceNotFoundException e) {
        }
        conn1.close();
        conn2.close();
    }

    @Test
    public void testExplainPlanValidatesSequences() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE bar");
        conn.createStatement().execute("CREATE TABLE foo (k BIGINT NOT NULL PRIMARY KEY)");

        nextConnection();
        Connection conn2 = conn;
        conn = null; // So that call to nextConnection doesn't close it
        ResultSet rs = conn2.createStatement().executeQuery("EXPLAIN SELECT NEXT VALUE FOR bar FROM foo");
        assertEquals("CLIENT PARALLEL 1-WAY FULL SCAN OVER FOO\n" +
                "    SERVER FILTER BY FIRST KEY ONLY\n" +
        		"CLIENT RESERVE VALUES FROM 1 SEQUENCE", QueryUtil.getExplainPlan(rs));

        nextConnection();
        rs = conn.createStatement().executeQuery("SELECT sequence_name, current_value FROM SYSTEM.\"SEQUENCE\" WHERE sequence_name='BAR'");
        assertTrue(rs.next());
        assertEquals("BAR", rs.getString(1));
        assertEquals(1, rs.getInt(2));
        conn.close();
        conn2.close();

        nextConnection();
        try {
            conn.createStatement().executeQuery("EXPLAIN SELECT NEXT VALUE FOR zzz FROM foo");
            fail();
        } catch (SequenceNotFoundException e) {
            // expected
        }
        conn.close();
    }

    @Test
    public void testSelectNextValueAsInput() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar START WITH 3 INCREMENT BY 2");
        nextConnection();
        String query = "SELECT LPAD(ENCODE(NEXT VALUE FOR foo.bar,'base62'),5,'0') FROM SYSTEM.\"SEQUENCE\"";
        ResultSet rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals("00003", rs.getString(1));
    }

    @Test
    public void testSelectNextValueInArithmetic() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar START WITH 3 INCREMENT BY 2");
        nextConnection();
        String query = "SELECT NEXT VALUE FOR foo.bar+1 FROM SYSTEM.\"SEQUENCE\"";
        ResultSet rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals(4, rs.getInt(1));
    }

    // if nextConnection() is not used to get to get a connection, make sure you call .close() so that connections are not leaked
    private void nextConnection() throws Exception {
        if (conn != null) conn.close();
        long ts = nextTimestamp();
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts));
        conn = DriverManager.getConnection(getUrl(), props);
    }

    @Test
    public void testSequenceDefault() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar");
        nextConnection();
        assertSequenceValuesForSingleRow(1, 2, 3);
        conn.createStatement().execute("DROP SEQUENCE foo.bar");

        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar INCREMENT BY -1");
        nextConnection();
        assertSequenceValuesForSingleRow(1, 0, -1);
        conn.createStatement().execute("DROP SEQUENCE foo.bar");

        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar MINVALUE 10");
        nextConnection();
        assertSequenceValuesForSingleRow(10, 11, 12);
        conn.createStatement().execute("DROP SEQUENCE foo.bar");

        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar INCREMENT BY -1 MINVALUE 10 ");
        nextConnection();
        assertSequenceValuesForSingleRow(Long.MAX_VALUE, Long.MAX_VALUE - 1, Long.MAX_VALUE - 2);
        conn.createStatement().execute("DROP SEQUENCE foo.bar");

        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar MAXVALUE 0");
        nextConnection();
        assertSequenceValuesForSingleRow(Long.MIN_VALUE, Long.MIN_VALUE + 1, Long.MIN_VALUE + 2);
        conn.createStatement().execute("DROP SEQUENCE foo.bar");

        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar INCREMENT BY -1 MAXVALUE 0");
        nextConnection();
        assertSequenceValuesForSingleRow(0, -1, -2);
    }

    @Test
    public void testSequenceValidateStartValue() throws Exception {
        nextConnection();
        try {
            conn.createStatement().execute(
                "CREATE SEQUENCE foo.bar1 START WITH 1 INCREMENT BY 1 MINVALUE 2 MAXVALUE 3");
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.STARTS_WITH_MUST_BE_BETWEEN_MIN_MAX_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }

        try {
            conn.createStatement().execute(
                "CREATE SEQUENCE foo.bar2 START WITH 4 INCREMENT BY 1 MINVALUE 2 MAXVALUE 3");
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.STARTS_WITH_MUST_BE_BETWEEN_MIN_MAX_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceValidateMinValue() throws Exception {
        nextConnection();
        try {
            conn.createStatement().execute("CREATE SEQUENCE foo.bar MINVALUE abc");
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.MINVALUE_MUST_BE_CONSTANT.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceValidateMaxValue() throws Exception {
        nextConnection();
        try {
            conn.createStatement().execute("CREATE SEQUENCE foo.bar MAXVALUE null");
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.MAXVALUE_MUST_BE_CONSTANT.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceValidateMinValueLessThanOrEqualToMaxValue() throws Exception {
        nextConnection();
        try {
            conn.createStatement().execute("CREATE SEQUENCE foo.bar MINVALUE 2 MAXVALUE 1");
            fail();
        } catch (SQLException e) {
            assertEquals(
                SQLExceptionCode.MINVALUE_MUST_BE_LESS_THAN_OR_EQUAL_TO_MAXVALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceValidateIncrementConstant() throws Exception {
        nextConnection();
        try {
            conn.createStatement().execute("CREATE SEQUENCE foo.bar INCREMENT null");
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.INCREMENT_BY_MUST_BE_CONSTANT.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceValidateIncrementNotEqualToZero() throws Exception {
        nextConnection();
        try {
            conn.createStatement().execute("CREATE SEQUENCE foo.bar INCREMENT 0");
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.INCREMENT_BY_MUST_NOT_BE_ZERO.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceStartWithMinMaxSameValueIncreasingCycle() throws Exception {
        nextConnection();
        conn.createStatement()
                .execute(
                    "CREATE SEQUENCE foo.bar START WITH 3 INCREMENT BY 1 MINVALUE 3 MAXVALUE 3 CYCLE CACHE 1");
        nextConnection();
        assertSequenceValuesForSingleRow(3, 3, 3);
    }

    @Test
    public void testSequenceStartWithMinMaxSameValueDecreasingCycle() throws Exception {
        nextConnection();
        conn.createStatement()
                .execute(
                    "CREATE SEQUENCE foo.bar START WITH 3 INCREMENT BY -1 MINVALUE 3 MAXVALUE 3 CYCLE CACHE 2");
        nextConnection();
        assertSequenceValuesForSingleRow(3, 3, 3);
    }

    @Test
    public void testSequenceStartWithMinMaxSameValueIncreasingNoCycle() throws Exception {
        nextConnection();
        conn.createStatement()
                .execute(
                    "CREATE SEQUENCE foo.bar START WITH 3 INCREMENT BY 1 MINVALUE 3 MAXVALUE 3 CACHE 1");
        nextConnection();
        assertSequenceValuesForSingleRow(3);
        try {
            ResultSet rs = conn.createStatement().executeQuery(NEXT_VAL_SQL);
            rs.next();
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceStartWithMinMaxSameValueDecreasingNoCycle() throws Exception {
        nextConnection();
        conn.createStatement()
                .execute(
                    "CREATE SEQUENCE foo.bar START WITH 3 INCREMENT BY -1 MINVALUE 3 MAXVALUE 3 CACHE 2");
        nextConnection();
        assertSequenceValuesForSingleRow(3);
        try {
            ResultSet rs = conn.createStatement().executeQuery(NEXT_VAL_SQL);
            rs.next();
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MIN_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceIncreasingCycle() throws Exception {
        nextConnection();
        conn.createStatement()
                .execute(
                    "CREATE SEQUENCE foo.bar START WITH 2 INCREMENT BY 3 MINVALUE 1 MAXVALUE 10 CYCLE CACHE 2");
        nextConnection();
        assertSequenceValuesForSingleRow(2, 5, 8, 1, 4, 7, 10, 1, 4);
    }

    @Test
    public void testSequenceDecreasingCycle() throws Exception {
        nextConnection();
        conn.createStatement()
                .execute(
                    "CREATE SEQUENCE foo.bar START WITH 3 INCREMENT BY -2 MINVALUE 1 MAXVALUE 10 CYCLE CACHE 2");
        nextConnection();
        assertSequenceValuesForSingleRow(3, 1, 10, 8, 6, 4, 2, 10, 8);
    }

    @Test
    public void testSequenceIncreasingNoCycle() throws Exception {
        nextConnection();
        // client throws exception
        conn.createStatement().execute(
            "CREATE SEQUENCE foo.bar START WITH 2 INCREMENT BY 3 MINVALUE 1 MAXVALUE 10 CACHE 100");
        nextConnection();
        assertSequenceValuesForSingleRow(2, 5, 8);
        try {
            ResultSet rs = conn.createStatement().executeQuery(NEXT_VAL_SQL);
            rs.next();
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceIncreasingUsingMaxValueNoCycle() throws Exception {
        nextConnection();
        // server throws exception
        conn.createStatement().execute(
            "CREATE SEQUENCE foo.bar START WITH 8 INCREMENT BY 2 MINVALUE 1 MAXVALUE 10 CACHE 2");
        nextConnection();
        assertSequenceValuesForSingleRow(8, 10);
        try {
            ResultSet rs = conn.createStatement().executeQuery(NEXT_VAL_SQL);
            rs.next();
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceDecreasingNoCycle() throws Exception {
        nextConnection();
        // client will throw exception
        conn.createStatement()
                .execute(
                    "CREATE SEQUENCE foo.bar START WITH 4 INCREMENT BY -2 MINVALUE 1 MAXVALUE 10 CACHE 100");
        nextConnection();
        assertSequenceValuesForSingleRow(4, 2);
        try {
            ResultSet rs = conn.createStatement().executeQuery(NEXT_VAL_SQL);
            rs.next();
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MIN_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceDecreasingUsingMinValueNoCycle() throws Exception {
        nextConnection();
        // server will throw exception
        conn.createStatement().execute(
            "CREATE SEQUENCE foo.bar START WITH 3 INCREMENT BY -2 MINVALUE 1 MAXVALUE 10 CACHE 2");
        nextConnection();
        assertSequenceValuesForSingleRow(3, 1);
        try {
            ResultSet rs = conn.createStatement().executeQuery(NEXT_VAL_SQL);
            rs.next();
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MIN_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceIncreasingOverflowNoCycle() throws Exception {
        nextConnection();
        // start with Long.MAX_VALUE
        conn.createStatement().execute(
            "CREATE SEQUENCE foo.bar START WITH 9223372036854775807 INCREMENT BY 1 CACHE 10");
        nextConnection();
        assertSequenceValuesForSingleRow(Long.MAX_VALUE);
        try {
            ResultSet rs = conn.createStatement().executeQuery(NEXT_VAL_SQL);
            rs.next();
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceIncreasingOverflowCycle() throws Exception {
        nextConnection();
        // start with Long.MAX_VALUE
        conn.createStatement()
                .execute(
                    "CREATE SEQUENCE foo.bar START WITH 9223372036854775807 INCREMENT BY 9223372036854775807 CYCLE CACHE 10");
        nextConnection();
        assertSequenceValuesForSingleRow(Long.MAX_VALUE, Long.MIN_VALUE, -1, Long.MAX_VALUE - 1,
            Long.MIN_VALUE, -1);
    }

    @Test
    public void testSequenceDecreasingOverflowNoCycle() throws Exception {
        nextConnection();
        // start with Long.MIN_VALUE + 1
        conn.createStatement().execute(
            "CREATE SEQUENCE foo.bar START WITH -9223372036854775807 INCREMENT BY -1 CACHE 10");
        nextConnection();
        assertSequenceValuesForSingleRow(Long.MIN_VALUE + 1, Long.MIN_VALUE);
        try {
            ResultSet rs = conn.createStatement().executeQuery(NEXT_VAL_SQL);
            rs.next();
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MIN_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testSequenceDecreasingOverflowCycle() throws Exception {
        nextConnection();
        // start with Long.MIN_VALUE + 1
        conn.createStatement()
                .execute(
                    "CREATE SEQUENCE foo.bar START WITH -9223372036854775807 INCREMENT BY -9223372036854775807 CYCLE CACHE 10");
        nextConnection();
        assertSequenceValuesForSingleRow(Long.MIN_VALUE + 1, Long.MAX_VALUE, 0, Long.MIN_VALUE + 1,
            Long.MAX_VALUE, 0);
    }

    @Test
    public void testMultipleSequenceValuesNoCycle() throws Exception {
        nextConnection();
        conn.createStatement().execute(
            "CREATE SEQUENCE foo.bar START WITH 1 INCREMENT BY 2 MINVALUE 1 MAXVALUE 10 CACHE 2");
        conn.createStatement().execute("CREATE SEQUENCE foo.bar2");
        nextConnection();
        assertSequenceValuesMultipleSeq(1, 3);
        assertSequenceValuesMultipleSeq(5, 7);

        ResultSet rs = conn.prepareStatement(NEXT_VAL_SQL).executeQuery();
        assertTrue(rs.next());
        assertEquals(9, rs.getInt(1));
        try {
            assertTrue(rs.next());
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }

        try {
            rs = conn.prepareStatement(NEXT_VAL_SQL).executeQuery();
            rs.next();
            fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    @Test
    public void testMultipleSequenceValuesCycle() throws Exception {
        nextConnection();
        conn.createStatement()
                .execute(
                    "CREATE SEQUENCE foo.bar START WITH 1 INCREMENT BY 2 MINVALUE 1 MAXVALUE 10 CYCLE CACHE 2");
        conn.createStatement().execute("CREATE SEQUENCE foo.bar2");
        nextConnection();
        assertSequenceValuesMultipleSeq(1, 3);
        assertSequenceValuesMultipleSeq(5, 7);
        assertSequenceValuesMultipleSeq(9, 1);
        assertSequenceValuesMultipleSeq(3, 5);
        assertSequenceValuesMultipleSeq(7, 9);
        assertSequenceValuesMultipleSeq(1, 3);
        assertSequenceValuesMultipleSeq(5, 7);
    }

    @Test
    public void testUpsertSelectGroupByWithSequence() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE foo.bar");
        nextConnection();

        conn.createStatement()
                .execute(
                    "CREATE TABLE EVENTS (event_id BIGINT NOT NULL PRIMARY KEY, user_id char(15), val BIGINT )");
        conn.createStatement()
                .execute(
                    "CREATE TABLE METRICS (metric_id char(15) NOT NULL PRIMARY KEY, agg_id char(15), metric_val INTEGER )");

        nextConnection();
        // 2 rows for user1, 3 rows for user2 and 1 row for user3
        insertEvent(1, "user1", 1);
        insertEvent(2, "user2", 1);
        insertEvent(3, "user1", 1);
        insertEvent(4, "user2", 1);
        insertEvent(5, "user2", 1);
        insertEvent(6, "user3", 1);
        conn.commit();
        nextConnection();

        conn.createStatement()
                .execute(
                    "UPSERT INTO METRICS SELECT 'METRIC_'||(LPAD(ENCODE(NEXT VALUE FOR foo.bar,'base62'),5,'0')), user_id, sum(val) FROM events GROUP BY user_id ORDER BY user_id");
        conn.commit();
        nextConnection();

        PreparedStatement stmt =
                conn.prepareStatement("SELECT metric_id, agg_id, metric_val FROM METRICS");
        ResultSet rs = stmt.executeQuery();
        assertTrue(rs.next());
        assertEquals("METRIC_00001", rs.getString("metric_id"));
        assertEquals("user1", rs.getString("agg_id"));
        assertEquals(2, rs.getLong("metric_val"));
        assertTrue(rs.next());
        assertEquals("METRIC_00002", rs.getString("metric_id"));
        assertEquals("user2", rs.getString("agg_id"));
        assertEquals(3, rs.getLong("metric_val"));
        assertTrue(rs.next());
        assertEquals("METRIC_00003", rs.getString("metric_id"));
        assertEquals("user3", rs.getString("agg_id"));
        assertEquals(1, rs.getLong("metric_val"));
        assertFalse(rs.next());
    }

    @Test
    /**
     * Test to validate that the bug discovered in PHOENIX-2149 has been fixed. There was an issue
     * whereby, when closing connections and returning sequences we were not setting the limit
     * reached flag correctly and this was causing the max value to be ignored as the LIMIT_REACHED_FLAG
     * value was being unset from true to false.
     */
    public void testNextValuesForSequenceClosingConnections() throws Exception {

        // Create Sequence
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE seqtest.closeconn START WITH 4990 MINVALUE 4990 MAXVALUE 5000 CACHE 10");
        nextConnection();

        // Call NEXT VALUE FOR 1 time more than available values in the Sequence. We expected the final time
        // to throw an error as we will have reached the max value
        try {
            long val = 0L;
            for (int i = 0; i <= 11; i++) {
                ResultSet rs = conn.createStatement().executeQuery(String.format(SELECT_NEXT_VALUE_SQL, "seqtest.closeconn"));
                rs.next();
                val = rs.getLong(1);
                nextConnection();
            }
            fail("Expect to fail as we have arrived at the max sequence value " + val);
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE.getErrorCode(),
                e.getErrorCode());
            assertTrue(e.getNextException() == null);
        }
    }

    private void insertEvent(long id, String userId, long val) throws SQLException {
        PreparedStatement stmt = conn.prepareStatement("UPSERT INTO events VALUES(?,?,?)");
        stmt.setLong(1, id);
        stmt.setString(2, userId);
        stmt.setLong(3, val);
        stmt.execute();
    }

    /**
     * Helper to verify the sequence values returned in multiple ResultSets each containing one row
     * @param seqVals expected sequence values (one per ResultSet)
     */
    private void assertSequenceValuesForSingleRow(long... seqVals)
            throws SQLException {
        PreparedStatement stmt = conn.prepareStatement(NEXT_VAL_SQL);
        for (long seqVal : seqVals) {
            ResultSet rs = stmt.executeQuery();
            assertTrue(rs.next());
            assertEquals(seqVal, rs.getLong(1));
            assertFalse(rs.next());
            rs.close();
        }
        stmt.close();
    }

    /**
     * Helper to verify the sequence values returned in a single ResultSet containing multiple row
     * @param seqVals expected sequence values (from one ResultSet)
     */
    private void assertSequenceValuesMultipleSeq(long... seqVals) throws SQLException {
        PreparedStatement stmt = conn.prepareStatement(NEXT_VAL_SQL);
        ResultSet rs = stmt.executeQuery();
        for (long seqVal : seqVals) {
            assertTrue(rs.next());
            assertEquals(seqVal, rs.getLong(1));
        }
        assertFalse(rs.next());
        rs.close();
        stmt.close();
    }

    private void verifyExceptions(SQLException sqlE, List<String> expectedExceptions) {
        List<String> missingExceptions = Lists.newArrayList(expectedExceptions);
        List<String> unexpectedExceptions = Lists.newArrayList();
        do {
            if (!expectedExceptions.contains(sqlE.getMessage())) {
                unexpectedExceptions.add(sqlE.getMessage());
            }
            missingExceptions.remove(sqlE.getMessage());
        } while ((sqlE = sqlE.getNextException()) != null);
        if (unexpectedExceptions.size() != 0 && missingExceptions.size() != 0) {
            fail("Actual exceptions does not match expected exceptions. Unexpected exceptions : "
                    + unexpectedExceptions + " missing exceptions : " + missingExceptions);
        }
    }

    @Test
    public void testValidateBeforeReserve() throws Exception {
        nextConnection();
        conn.createStatement().execute(
                "CREATE TABLE foo (k VARCHAR PRIMARY KEY, l BIGINT)");
        conn.createStatement().execute(
            "CREATE SEQUENCE foo.bar");

        nextConnection();
        ResultSet rs = conn.createStatement().executeQuery("EXPLAIN SELECT NEXT VALUE FOR foo.bar FROM foo");
        assertTrue(rs.next());
        conn.createStatement().execute(
                "UPSERT INTO foo VALUES ('a', NEXT VALUE FOR foo.bar)");
        conn.createStatement().execute(
                "UPSERT INTO foo VALUES ('b', NEXT VALUE FOR foo.bar)");
        conn.commit();

        nextConnection();
        rs = conn.createStatement().executeQuery("SELECT * FROM foo");
        assertTrue(rs.next());
        assertEquals("a",rs.getString(1));
        assertEquals(1,rs.getLong(2));
        assertTrue(rs.next());
        assertEquals("b",rs.getString(1));
        assertEquals(2,rs.getLong(2));
        assertFalse(rs.next());

        nextConnection();
        PreparedStatement stmt = conn.prepareStatement("SELECT NEXT VALUE FOR foo.bar FROM foo");
        ParameterMetaData md = stmt.getParameterMetaData();
        assertEquals(0,md.getParameterCount());
        rs = stmt.executeQuery();
        assertTrue(rs.next());
        assertEquals(3, rs.getLong(1));
        assertTrue(rs.next());
        assertEquals(4, rs.getLong(1));
        assertFalse(rs.next());
    }

    @Test
    public void testNoFromClause() throws Exception {
        ResultSet rs;
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE myseq START WITH 1 INCREMENT BY 1");
        conn.createStatement().execute("CREATE SEQUENCE anotherseq START WITH 2 INCREMENT BY 3");
        nextConnection();
        rs = conn.createStatement().executeQuery("EXPLAIN SELECT NEXT VALUE FOR myseq");
        assertEquals("CLIENT RESERVE VALUES FROM 1 SEQUENCE", QueryUtil.getExplainPlan(rs));
        rs = conn.createStatement().executeQuery("SELECT NEXT VALUE FOR myseq");
        assertTrue(rs.next());
        assertEquals(1, rs.getInt(1));
        rs = conn.createStatement().executeQuery("EXPLAIN SELECT CURRENT VALUE FOR myseq");
        assertEquals("CLIENT RESERVE VALUES FROM 1 SEQUENCE", QueryUtil.getExplainPlan(rs));
        rs = conn.createStatement().executeQuery("SELECT CURRENT VALUE FOR myseq");
        assertTrue(rs.next());
        assertEquals(1, rs.getInt(1));
        rs = conn.createStatement().executeQuery("SELECT NEXT VALUE FOR myseq, NEXT VALUE FOR anotherseq");
        assertTrue(rs.next());
        assertEquals(2, rs.getInt(1));
        assertEquals(2, rs.getInt(2));
        rs = conn.createStatement().executeQuery("SELECT CURRENT VALUE FOR myseq, NEXT VALUE FOR anotherseq");
        assertTrue(rs.next());
        assertEquals(2, rs.getInt(1));
        assertEquals(5, rs.getInt(2));
    }

    @Test
    public void testReturnAllSequencesNotCalledForNoOpenConnections() throws Exception {
        nextConnection();
        conn.createStatement().execute("CREATE SEQUENCE alpha.zeta START WITH 3 INCREMENT BY 2 CACHE 5");
        nextConnection();
        String query = "SELECT NEXT VALUE FOR alpha.zeta FROM SYSTEM.\"SEQUENCE\"";
        ResultSet rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals(3, rs.getInt(1));
        assertFalse(rs.next());
        rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals(5, rs.getInt(1));
        assertFalse(rs.next());
        conn.close();

        // verify that calling close() does not return sequence values back to the server
        query = "SELECT CURRENT_VALUE FROM SYSTEM.\"SEQUENCE\" WHERE SEQUENCE_SCHEMA='ALPHA' AND SEQUENCE_NAME='ZETA'";
        rs = conn.prepareStatement(query).executeQuery();
        assertTrue(rs.next());
        assertEquals(13, rs.getInt(1));
        assertFalse(rs.next());
    }

}


text:
import pkgutil
import inspect
from components import featureBroker

__all__ = []

for loader, name, is_pkg in pkgutil.walk_packages(__path__):
    module = loader.find_module(name).load_module(name)

    for name, value in inspect.getmembers(module):
        if name.startswith('__'):
            continue

        globals()[name] = value
        __all__.append(name)

class Commander(featureBroker.Component):
    commands = featureBroker.RequiredFeatures('command', featureBroker.HasMethods('runCommand'))

    def runCommand(self, command):
        """ Run a given command. """
        for c in self.commands:
            c.runCommand(command)

featureBroker.features.Provide('commander', Commander)


text:
package com.facebook.share.model;

import android.os.Parcel;

import com.facebook.internal.NativeProtocol;

/**
 * Describes an Open Graph Object to be created.
 *

 * Use {@link ShareOpenGraphObject.Builder} to create instances
 *

 * See the documentation for
 * Open Graph Objects.
 */
public final class ShareOpenGraphObject extends
        ShareOpenGraphValueContainer<ShareOpenGraphObject, ShareOpenGraphObject.Builder> {

    private ShareOpenGraphObject(final Builder builder) {
        super(builder);
    }

    ShareOpenGraphObject(final Parcel in) {
        super(in);
    }

    @SuppressWarnings("unused")
    public static final Creator<ShareOpenGraphObject> CREATOR =
            new Creator<ShareOpenGraphObject>() {
        public ShareOpenGraphObject createFromParcel(final Parcel in) {
            return new ShareOpenGraphObject(in);
        }

        public ShareOpenGraphObject[] newArray(final int size) {
            return new ShareOpenGraphObject[size];
        }
    };

    /**
     * Builder for the {@link com.facebook.share.model.ShareOpenGraphObject} interface.
     */
    public static final class Builder
            extends ShareOpenGraphValueContainer.Builder<ShareOpenGraphObject, Builder> {
        public Builder() {
            super();
            this.putBoolean(NativeProtocol.OPEN_GRAPH_CREATE_OBJECT_KEY, true);
        }

        @Override
        public ShareOpenGraphObject build() {
            return new ShareOpenGraphObject(this);
        }

        @Override
        public Builder readFrom(final Parcel parcel) {
            return this.readFrom(
                    (ShareOpenGraphObject)parcel.readParcelable(
                            ShareOpenGraphObject.class.getClassLoader()));
        }
    }
}


text:
"""Module for building models using ISAMBARD."""

import enum
import itertools
import sys

import isambard
import isambard.add_ons.knobs_into_holes as kihs

REGISTER_ADJUST = {
    'a': 0,
    'b': 102.8,
    'c': 205.6,
    'd': 308.4,
    'e': 51.4,
    'f': 154.2,
    'g': 257
}

def build_coiled_coil(parameters, debug=False):
    """Builds a model of a coiled coil using the input parameters.

    Parameters
    ----------
    parameter : [ dict[str, int/float/str] ]
        List of parameter dictionaries required for building a coiled coil
        i.e. oligomer state, radius, pitch, phiCA, sequence.

    Returns
    -------
    model_data : dict
        A dictionary containing information about the model that has
        been produced.
    """
    if debug:
        print(parameters, file=sys.stderr)
    coiled_coil = isambard.specifications.CoiledCoil(
        len(parameters), auto_build=False)
    coiled_coil.aas = [len(p['Sequence']) for p in parameters]
    coiled_coil.major_radii = [p['Radius'] for p in parameters]
    coiled_coil.major_pitches = [p['Pitch'] for p in parameters]
    raw_phi = [p['Interface Angle'] for p in parameters]
    registers = [p['Register'] for p in parameters]
    coiled_coil.phi_c_alphas = [ia + REGISTER_ADJUST[r]
                                for ia, r in zip(raw_phi, registers)]
    sequences = [p['Sequence'] for p in parameters]
    coiled_coil.z_shifts = [p['Z-Shift'] for p in parameters]
    lshr_adjust = [(p['Z-Shift'] / p['Pitch']) * 360 if p['Linked SHR'] else 0
                   for p in parameters]
    coiled_coil.rotational_offsets = [d + p['Super-Helical Rotation'] - a
                                      for d, p, a in zip(
                                          coiled_coil.rotational_offsets,
                                          parameters,
                                          lshr_adjust)]
    coiled_coil.orientations = [-1 if p['Orientation']
                                else 1 for p in parameters]
    coiled_coil.build()
    coiled_coil.pack_new_sequences(sequences)
    mean_rpt_value = calculate_average_rpt(coiled_coil)
    score = coiled_coil.buff_interaction_energy.total_energy
    knobs = [k.knob_residue for k in kihs.find_kihs(coiled_coil)]
    knob_ids = [[k.ampal_parent.id, k.id] for k in knobs]
    return coiled_coil.pdb, score, mean_rpt_value, knob_ids

def build_collagen(parameters, debug=False):
    """Builds a model of a collagen triple-helix using the input parameters.

    Parameters
    ----------
    parameter : [ dict[str, int/float/str] ]
        List of parameter dictionaries required for building a coiled coil
        i.e. radius, pitch, phiCA, sequence.

    Returns
    -------
    model_data : dict
        A dictionary containing information about the model that has
        been produced.
    """
    if debug:
        print(parameters, file=sys.stderr)
    collagen = isambard.specifications.CoiledCoil.tropocollagen(
        auto_build=False)
    collagen.aas = [len(p['Sequence']) for p in parameters]
    collagen.major_radii = [p['Radius'] for p in parameters]
    collagen.major_pitches = [p['Pitch'] for p in parameters]
    collagen.phi_c_alphas = [p['Interface Angle'] for p in parameters]
    original_sequences = [p['Sequence'] for p in parameters]
    proline_sequences = [seq.replace('O', 'P') for seq in original_sequences]
    collagen.z_shifts = [
        d + p['Z-Shift'] for d, p in zip(
            collagen.z_shifts, parameters)]
    lshr_adjust = [(z / p['Pitch']) * 360 if p['Linked SHR'] else 0
                   for z, p in zip(collagen.z_shifts, parameters)]
    collagen.rotational_offsets = [d + p['Super-Helical Rotation'] + a
                                   for d, p, a in zip(
                                       collagen.rotational_offsets,
                                       parameters,
                                       lshr_adjust)]
    collagen.orientations = [-1 if p['Orientation']
                             else 1 for p in parameters]
    collagen.build()
    collagen.pack_new_sequences(proline_sequences)
    score = collagen.buff_interaction_energy.total_energy
    mean_rpt_value = calculate_average_rpt(collagen)
    for res, ml in zip(collagen.get_monomers(), ''.join(original_sequences)):
        if ml == 'O':
            isambard.ampal.non_canonical.convert_pro_to_hyp(res)
    knob_ids = []  # Collagen can't have KIHs
    return collagen.pdb, score, mean_rpt_value, knob_ids

def optimise_coiled_coil(parameters, debug=False):
    """Optimises the parameters for a given structure.

    Parameters
    ----------
    parameter : [ dict[str, int/float/str] ]
        List of parameter dictionaries required for building a coiled coil i.e.
        oligomer state, radius, pitch, phiCA, sequence.

    Returns
    -------
    model_data : dict
        A dictionary containing information about the model that has
        been produced.
    """
    if debug:
        print(parameters, file=sys.stderr)
    oligomer_state = len(parameters)
    radius_centre = parameters[0]['Radius']
    phi_centre = parameters[0]['Interface Angle'] + \
        REGISTER_ADJUST[parameters[0]['Register']]
    opt = isambard.optimisation.optimizer.GA_Opt_Internal(
        isambard.specifications.CoiledCoil.from_parameters)
    opt.parameters(
        [parameters[0]['Sequence']] * oligomer_state,
        [radius_centre, 300, phi_centre],
        [2, 150, 20],
        [oligomer_state, len(parameters[0]['Sequence']),
         'var0', 'var1', 'var2']
    )
    opt.run_opt(20, 5, 2)
    top_model = opt.best_model
    knobs = [k.knob_residue for k in kihs.find_kihs(top_model)]
    knob_ids = [[k.ampal_parent.id, k.id] for k in knobs]
    optimised_parameters = {
        'radius': top_model.major_radii[0],
        'pitch': top_model.major_pitches[0],
        'phiCA': top_model.phi_c_alphas[0] - \
            REGISTER_ADJUST[parameters[0]['Register']],
        'sequence': top_model[0].sequence,
        'register': parameters[0]['Register']
    }
    model_and_info = {
        'pdb': top_model.pdb,
        'mean_rpt_value': calculate_average_rpt(top_model),
        'score': top_model.buff_interaction_energy.total_energy,
        'knob_ids': knob_ids
    }
    return optimised_parameters, model_and_info

def optimise_collagen(parameters, debug=False):
    """Optimises the parameters for a collagen structure.

    Parameters
    ----------
    parameter : [ dict[str, int/float/str] ]
        List of parameter dictionaries required for building a coiled coil i.e.
        oligomer state, radius, pitch, phiCA, sequence.

    Returns
    -------
    model_data : dict
        A dictionary containing information about the model that has
        been produced.
    """
    if debug:
        print(parameters, file=sys.stderr)
    radius_centre = parameters[0]['Radius']
    phi_centre = parameters[0]['Interface Angle']
    opt = isambard.optimisation.optimizer.GA_Opt_Internal(OptCollagen)
    opt.parameters(
        [parameters[0]['Sequence']] * 3,
        [radius_centre, 150, phi_centre],
        [2, 100, 20],
        [len(parameters[0]['Sequence']), 'var0', 'var1', 'var2']
    )
    opt.run_opt(20, 5, 2)
    top_model = opt.best_model
    knob_ids = []
    optimised_parameters = {
        'radius': top_model.major_radii[0],
        'pitch': top_model.major_pitches[0],
        'phiCA': top_model.phi_c_alphas[0],
        'sequence': top_model[0].sequence,
        'register': parameters[0]['Register']
    }
    model_and_info = {
        'pdb': top_model.pdb,
        'mean_rpt_value': calculate_average_rpt(top_model),
        'score': top_model.buff_interaction_energy.total_energy,
        'knob_ids': knob_ids
    }
    return optimised_parameters, model_and_info

def calculate_average_rpt(ampal):
    """Returns the mean residues per turn value for an AMPAL object."""
    rpt_lists = [isambard.analyse_protein.residues_per_turn(ch)[
        :-1] for ch in ampal]
    rpt_values = list(itertools.chain(*rpt_lists))
    average_rpt = sum(rpt_values) / len(rpt_values)
    return average_rpt

class OptCollagen(isambard.specifications.CoiledCoil):
    """A wrapper class for building collagens with simple parameters."""
    def __init__(self, aas, major_radius, major_pitch, interface_angle):
        n = 3
        super().__init__(n, auto_build=False)
        self.aas = [aas] * n
        self.phi_c_alphas = [interface_angle] * n
        self.minor_helix_types = ['PPII'] * n
        self.major_pitches = [major_pitch] * n
        self.major_radii = [major_radius] * n
        self.major_handedness = ['r'] * n
        self.minor_repeats = [None] * n
        rpr_ppii = 3.1
        self.z_shifts = [-rpr_ppii * 2, 0.0, -rpr_ppii]
        rot_adj = [(z / p) * 360 for z,
                   p in zip(self.z_shifts, self.major_pitches)]
        self.rotational_offsets = [r + ra for r, ra in zip(
            self.rotational_offsets, rot_adj)]
        self.build()

class HelixType(enum.Enum):
    """Possible helix types that can be encountered."""
    ALPHA = 1
    COLLAGEN = 2


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Acta Horti Petropolit. 19: 21 (1901)

#### Original name
Parmelia molliuscula f. desertorum Elenkin

### Remarks
null


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Test Suite</title>
  <link rel="stylesheet" href="../node_modules/qunit/qunit/qunit.css" media="screen">


text:
package com.ms.coco.registry.poxy;

import com.ms.coco.policy.proxy.RpcProxy;
import com.ms.coco.registry.common.Listener;

/**
 * @author wanglin/netboy
 * @version 创建时间:2016年7月6日 下午8:01:41
 * @func
 */
public interface ProxyZk extends Listener, RpcProxy {
}


text:
'use strict';

var assign = require('object-assign');
var Dispatcher = require('./dispatcher');
var Dispatch = assign({}, Dispatcher.prototype,{});
var React = require('react');
var ReactDom = require('react-dom');
var $ = require('jquery');
require('jquery-ui');
var MenuBar=React.createClass({
  getInitialState: function() {
    return {
    };
  },

  componentDidMount: function() {
  },

  menuClicked: function() {
    $('#menubar-menu').effect('highlight',{}, 500, null);
  },

  render: function() {
    var menuImg = './pics/menu.png';
    var titleImg = './pics/dutyfreejoy.png';

  return (

);
  },
});

/*ReactDom.render(
<MenuBar/>,
  document.getElementById('menubar')
);*/

module.exports=MenuBar;


text:
<title>Berkeley DB Reference Guide: Release 4.5: Replication method naming</title>
<meta name="description" content="Berkeley DB: An embedded database programmatic toolkit.">
<meta name="keywords" content="embedded,database,programmatic,toolkit,btree,hash,hashing,transaction,transactions,locking,logging,access method,access methods,Java,C,C++">

Berkeley DB Reference Guide:
Upgrading Berkeley DB Applications

Release 4.5: Replication method naming

The method names DB_ENV->set_rep_limit, DB_ENV->get_rep_limit
and DB_ENV->set_rep_transport have been changed to
DB_ENV->rep_set_limit, DB_ENV->rep_get_limit and
DB_ENV->rep_set_transport in order to be consistent with the other
replication method names.   That is, the characters "set_rep" and
"get_rep" have been changed to "rep_set" and "rep_get".

Applications should modify the method names, no other change is
required.

Copyright (c) 1996,2008 Oracle.  All rights reserved.