text:
#ifndef __XN_DATA_PACKER_H__
#define __XN_DATA_PACKER_H__

//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <XnIOStream.h>
#include <XnGeneralBuffer.h>
#include <XnStreamData.h>
#include <XnFormats/XnCodec.h>
#include <XnCore/XnBuffer.h>
#include <XnPropertySet.h>

//---------------------------------------------------------------------------
// Types
//---------------------------------------------------------------------------
typedef XnUInt32 XnPackedDataType;

typedef enum
{
	XN_PACKED_PROPERTY_SET = 1,
	XN_PACKED_NEW_STREAM = 2,
	XN_PACKED_INT_PROPERTY = 3,
	XN_PACKED_REAL_PROPERTY = 4,
	XN_PACKED_STRING_PROPERTY = 5,
	XN_PACKED_GENERAL_PROPERTY = 6,
	XN_PACKED_STREAM_REMOVED = 7,
	XN_PACKED_STREAM_DATA = 8,
	XN_PACKED_END = 9,
	XN_PACKED_CUSTOM_MESSAGE = 2000,
} XnPredefinedPackedDataType;

struct XnPackedDataHeader; // Forward declaration

/**
* A helper class for packing and unpacking PS data from IO streams.
*/
class XN_DDK_CPP_API XnDataPacker
{
public:
	/**
	* Creates a DataPacker object.
	*
	* @param	pStream				[in]	The stream to read/write data from/to.
	* @param	nInternalBufferSize	[in]	The internal buffer size. This should be the maximum written/read object size.
	*/
	XnDataPacker(XnIOStream* pStream, XnUInt32 nInternalBufferSize);

	/**
	* Destroys a DataPacker object.
	*/
	~XnDataPacker();

	/**
	* Initialized the DataPacker object.
	*/
	XnStatus Init();

	/**
	* Frees the DataPacker object.
	*/
	XnStatus Free();

	/**
	* Writes a new stream into the stream.
	*
	* @param	strType			[in]	The type of the stream.
	* @param	strName			[in]	The name of the stream.
	* @param	pPropertySet	[in]	The property set to write.
	*/
	XnStatus WriteNewStream(const XnChar* strType, const XnChar* strName, const XnPropertySet* pPropertySet);

	/**
	* Writes stream removal into the stream.
	*
	* @param	csStreamName	[in]	The name of the stream.
	*/
	XnStatus WriteStreamRemoved(const XnChar* csStreamName);

	/**
	* Writes a property set into the stream.
	*
	* @param	pPropertySet	[in]	The property set to write.
	*/
	XnStatus WritePropertySet(const XnPropertySet* pPropertySet);

	/**
	* Writes an int property into the stream.
	*
	* @param	csModuleName	[in]	The name of the module.
	* @param	csProp			[in]	The name of the property.
	* @param	nValue			[in]	The value of the property.
	*/
	XnStatus WriteProperty(const XnChar* csModule, const XnChar* csProp, XnUInt64 nValue);
	/**
	* Writes a real property into the stream.
	*
	* @param	csModuleName	[in]	The name of the module.
	* @param	csProp			[in]	The name of the property.
	* @param	dValue			[in]	The value of the property.
	*/
	XnStatus WriteProperty(const XnChar* csModule, const XnChar* csProp, XnDouble dValue);
	/**
	* Writes a string property into the stream.
	*
	* @param	csModuleName	[in]	The name of the module.
	* @param	csProp			[in]	The name of the property.
	* @param	csValue			[in]	The value of the property.
	*/
	XnStatus WriteProperty(const XnChar* csModule, const XnChar* csProp, const XnChar* csValue);
	/**
	* Writes a general property into the stream.
	*
	* @param	csModuleName	[in]	The name of the module.
	* @param	csProp			[in]	The name of the property.
	* @param	gbValue			[in]	The value of the property.
	*/
	XnStatus WriteProperty(const XnChar* csModule, const XnChar* csProp, XnGeneralBuffer gbValue);
	/**
	* Writes a stream data object into the stream, compressing the data using the given codec.
	*
	* @param	pStreamOutput	[in]	The stream output object to write.
	* @param	pCodec			[in]	The codec that should be used to compress the data.
	*/
	XnStatus WriteStreamData(const XnStreamData* pStreamOutput, XnCodec* pCodec);

	/**
	* Writes a custom data object into the stream.
	*
	* @param	nObjectType		[in]	The type of the object being written.
	* @param	pData			[in]	A pointer to the data to be written.
	* @param	nDataSize		[in]	The size of the written data.
	*/
	XnStatus WriteCustomData(XnUInt32 nObjectType, const void* pData, XnUInt32 nDataSize);

	/**
	* Writes a marker telling this is the end of the stream.
	*/
	XnStatus WriteEnd();

	/**
	* Reads a single object from the IO stream into the internal buffer, and returns the type
	* of that object.
	*
	* @param	pType	[out]	The type of the object that was read from the stream.
	*/
	XnStatus ReadNextObject(XnPackedDataType* pType);

	/**
	* Reads a new stream name event from the internal buffer.
	*
	* @param	csType	[in/out]	A string to be filled with the stream type.
	* @param	csName	[in/out]	A string to be filled with the stream name.
	*/
	XnStatus ReadNewStreamName(XnChar* csType, XnChar* csName);

	/**
	* Reads a new module event from the internal buffer.
	*
	* @param	csModuleName	[in/out]	A string to be filled with the module name.
	* @param	pPropertySet	[in/out]	A property set to be filled with the stream properties.
	*/
	XnStatus ReadNewStream(XnChar* csType, XnChar* csName, XnPropertySet* pPropertySet);

	/**
	* Reads a stream removal event from the internal buffer.
	*
	* @param	csStreamName	[in/out]	A string to be filled with the stream name.
	*/
	XnStatus ReadStreamRemoved(XnChar* csStreamName);

	/**
	* Reads a property set from the internal buffer.
	*
	* @param	pPropertySet	[in/out]	A property set to be filled with the stream properties.
	*/
	XnStatus ReadPropertySet(XnPropertySet* pPropertySet);

	/**
	* Reads an int property from the internal buffer.
	*
	* @param	pcsModule		[in/out]	A string to be filled with the module name.
	* @param	pcsProp			[in/out]	A string to be filled with the property name.
	* @param	pnValue			[out]		The value of the property.
	*/
	XnStatus ReadProperty(XnChar* pcsModule, XnChar* pcsProp, XnUInt64* pnValue);
	/**
	* Reads a real property from the internal buffer.
	*
	* @param	pcsModule		[in/out]	A string to be filled with the module name.
	* @param	pcsProp			[in/out]	A string to be filled with the property name.
	* @param	pdValue			[out]		The value of the property.
	*/
	XnStatus ReadProperty(XnChar* pcsModule, XnChar* pcsProp, XnDouble* pdValue);
	/**
	* Reads a string property from the internal buffer.
	*
	* @param	pcsModule		[in/out]	A string to be filled with the module name.
	* @param	pcsProp			[in/out]	A string to be filled with the property name.
	* @param	pcsValue		[in/out]	A string to be filled with the property value.
	*/
	XnStatus ReadProperty(XnChar* pcsModule, XnChar* pcsProp, XnChar* pcsValue);

	/**
	* Reads a general property from the internal buffer.
	*
	* @param	pcsModule		[in/out]	A string to be filled with the module name.
	* @param	pcsProp			[in/out]	A string to be filled with the property name.
	* @param	pgbValue		[out]		A pointer to a general buffer, that, upon return will point to the data. The user should copy this data.
	*/
	XnStatus ReadProperty(XnChar* pcsModule, XnChar* pcsProp, XnGeneralBuffer* pgbValue);

	/**
	* Reads properties of a stream data.
	*
	* @param	pStreamOutput		[in/out]	A stream data object. All its fields will be populated, except for the actual data.
	* @param	pnCompression		[out]		Compression format.
	* @param	pnCompressedSize	[out]		Compressed Data Size.
	*/
	XnStatus ReadStreamDataProps(XnStreamData* pStreamOutput, XnCompressionFormats* pnCompression, XnUInt32* pnCompressedSize);

	/**
	* Reads a stream data object from the internal buffer, decompressing the data using the given codec.
	*
	* @param	pStreamOutput		[in/out]	A stream output object to be filled from the stream.
	* @param	pCodec				[in]		The codec that should be used to decompress the data.
	*/
	XnStatus ReadStreamData(XnStreamData* pStreamOutput, XnCodec* pCodec);

	/**
	* Reads a custom data from the internal buffer.
	*
	* @param	nObjectType		[in]		The expected object type.
	* @param	pData			[in]		A pointer to a buffer to be filled with data.
	* @param	nDataSize		[in/out]	in: Max allowed size, out: Received size
	*/
	XnStatus ReadCustomData(XnUInt32 nObjectType, void* pData, XnUInt32* pnDataSize);

private:
	/** Starts an internal object. */
	void StartWritingIntenalObject(XnUInt32 nType);
	/** Ends an internal object. */
	void EndWritingInternalObject();
	/** End an entire object and write it to stream. */
	XnStatus FlushInternalBuffer();

	/* Reads the next object into the internal buffer (appending it) */
	XnStatus ReadNextObjectImpl();
	/* If read object is BC, make it look like a new one. */
	XnStatus FixReadBCObjects();

	void MoveToNextObject();

	XnStatus WritePropertySetImpl(const XnPropertySet* pPropertySet);
	XnStatus WritePropertySetProperties(const XnPropertySet* pPropertySet);
	XnStatus WritePropertyImpl(const XnChar* csModule, const XnChar* csProp, XnUInt64 nValue);
	XnStatus WritePropertyImpl(const XnChar* csModule, const XnChar* csProp, XnDouble dValue);
	XnStatus WritePropertyImpl(const XnChar* csModule, const XnChar* csProp, const XnChar* csValue);
	XnStatus WritePropertyImpl(const XnChar* csModule, const XnChar* csProp, XnGeneralBuffer gbValue);
	XnStatus WriteString(const XnChar* pcsString);

	XnStatus ReadPropertySetImpl(XnPropertySet* pSet);
	XnStatus ReadPropertyImpl(XnChar* pcsModule, XnChar* pcsProp, XnUInt64* pnValue);
	XnStatus ReadPropertyImpl(XnChar* pcsModule, XnChar* pcsProp, XnDouble* pdValue);
	XnStatus ReadPropertyImpl(XnChar* pcsModule, XnChar* pcsProp, XnChar* pcsValue);
	XnStatus ReadPropertyImpl(XnChar* pcsModule, XnChar* pcsProp, XnGeneralBuffer* pgbValue);
	XnStatus ReadString(XnChar* pcsString);

	XnStatus ReadInternalBuffer(XnUChar* pData, XnUInt32 nDataSize);
	XnStatus WriteStringToBuffer(const XnChar* csString);
	XnStatus ReadStringFromBuffer(XnChar* pcsString);

	void ResetReadBuffer();

	XnIOStream* m_pStream;
	XnUInt32 m_nBufferSize;
	XnBuffer m_InternalBuffer;
	XnPackedDataHeader* m_pCurrentHeader;
	XnUInt32 m_nInternalBufferReadIndex;
};

#endif //__XN_DATA_PACKER_H__


text:
require 'test_helper'

class HasOneTest < ActiveSupport::TestCase
  def setup
    @parent = User.new
    @model = Email.new

    @args = ActiveSupport::HashWithIndifferentAccess.new(
      model: @model,
      association_name: "email",
      attrs: {
        "address" => "petrakos@gmail.com"
      },
      parent: @parent
    )

    @populator = FormObject::Populator::HasOne.new(@args)
  end

  test "contains the according properties" do
    assert_equal @model, @populator.model
    assert_equal "email", @populator.association_name
    assert_equal @args[:attrs], @populator.pending_attributes
    assert_equal @parent, @populator.parent
  end

  test "populates the model" do
    @populator.call

    assert_equal "petrakos@gmail.com", @populator.model.address
    assert_equal @parent.email, @populator.model
  end
end

redpajama_set_name: RedPajamaGithub


text:
package io.realm;

import android.content.Context;
import android.widget.FrameLayout;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import androidx.test.annotation.UiThreadTest;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import io.realm.adapter.RecyclerViewTestAdapter;
import io.realm.entity.AllJavaTypes;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

@RunWith(AndroidJUnit4.class)
public class RealmRecyclerAdapterTests {

    private Context context;

    private static final int TEST_DATA_SIZE = 47;
    private static final boolean AUTOMATIC_UPDATE = true;

    private Realm realm;

    @Before
    @UiThreadTest
    public void setUp() {
        context = InstrumentationRegistry.getInstrumentation().getContext();
        RealmConfiguration realmConfig = new RealmConfiguration.Builder(context).modules(new RealmTestModule()).build();
        Realm.deleteRealm(realmConfig);
        realm = Realm.getInstance(realmConfig);

        realm.beginTransaction();
        for (int i = 0; i < TEST_DATA_SIZE; i++) {
            AllJavaTypes allTypes = realm.createObject(AllJavaTypes.class, i);
            allTypes.setFieldString("test data " + i);
        }
        realm.commitTransaction();
    }

    @After
    @UiThreadTest
    public void tearDown() {
        realm.close();
    }

    @Test
    @UiThreadTest
    public void constructor_testRecyclerAdapterUnmanagedParameterExceptions() {
        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).findAll();
        RealmList<AllJavaTypes> unmanagedRealmList = new RealmList<>(resultList.toArray(new AllJavaTypes[0]));
        try {
            new RecyclerViewTestAdapter(context, unmanagedRealmList, true);
            fail("Should throw exception if list is un-managed");
        } catch (IllegalStateException ignore) {
        }
    }

    @Test
    @UiThreadTest
    public void clear() {
        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).findAll();
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, resultList, AUTOMATIC_UPDATE);
        realm.beginTransaction();
        resultList.deleteAllFromRealm();
        realm.commitTransaction();

        assertEquals(0, realmAdapter.getItemCount());
        assertEquals(0, resultList.size());
    }

    @Test
    @UiThreadTest
    public void updateData_realmResultInAdapter() {
        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).findAll();
        resultList.sort(AllJavaTypes.FIELD_STRING);
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, resultList, false);
        //noinspection ConstantConditions
        assertEquals(resultList.first().getFieldString(), realmAdapter.getData().first().getFieldString());
        assertEquals(resultList.size(), realmAdapter.getData().size());

        realm.beginTransaction();
        AllJavaTypes allTypes = realm.createObject(AllJavaTypes.class, TEST_DATA_SIZE);
        allTypes.setFieldString("test data " + TEST_DATA_SIZE);
        realm.commitTransaction();
        assertEquals(resultList.last().getFieldString(), realmAdapter.getData().last().getFieldString());
        assertEquals(resultList.size(), realmAdapter.getData().size());

        RealmResults<AllJavaTypes> emptyResultList = realm.where(AllJavaTypes.class).equalTo(AllJavaTypes.FIELD_STRING, "Not there").findAll();
        realmAdapter.updateData(emptyResultList);
        assertEquals(emptyResultList.size(), realmAdapter.getData().size());
    }

    @Test
    @UiThreadTest
    public void updateData_replaceInvalidData() {
        // test for https://github.com/realm/realm-android-adapters/issues/58
        final RealmConfiguration configuration = realm.getConfiguration();

        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).sort(AllJavaTypes.FIELD_STRING).findAll();
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, resultList, true);
        realm.close(); // to make resultList invalid

        // check precondition
        assertFalse(resultList.isValid());

        realm = Realm.getInstance(configuration);

        // create another valid RealmResults and check if updateData does not throw an exception.
        resultList = realm.where(AllJavaTypes.class).findAll();
        realmAdapter.updateData(resultList);
    }

    @Test
    @UiThreadTest
    public void updateData_realmUnsupportedCollectionInAdapter() {
        try {
            RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, null, AUTOMATIC_UPDATE);
            RealmResults<AllJavaTypes> results =
                    realm.where(AllJavaTypes.class).sort(AllJavaTypes.FIELD_STRING).findAll();
            realmAdapter.updateData(results.createSnapshot());
            fail("Should throw exception if there is unsupported collection");
        } catch (IllegalArgumentException ignore) {
        }
    }

    @Test
    @UiThreadTest
    public void getItemCount_emptyRealmResult() {
        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).equalTo(AllJavaTypes.FIELD_STRING, "Not there").findAll();
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, resultList, AUTOMATIC_UPDATE);
        assertEquals(0, resultList.size());
        //noinspection ConstantConditions
        assertEquals(0, realmAdapter.getData().size());
        assertEquals(0, realmAdapter.getItemCount());
    }

    @Test
    @UiThreadTest
    public void getItem_testGettingData() {
        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).findAll();
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, resultList, AUTOMATIC_UPDATE);

        //noinspection ConstantConditions
        assertEquals(resultList.first().getFieldString(), realmAdapter.getItem(0).getFieldString());
        //noinspection ConstantConditions
        assertEquals(resultList.size(), realmAdapter.getData().size());
        //noinspection ConstantConditions
        assertEquals(resultList.last().getFieldString(), realmAdapter.getData().last().getFieldString());
    }

    @Test
    @UiThreadTest
    public void getItem_testGettingNullData() {
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, null, AUTOMATIC_UPDATE);
        assertNull(realmAdapter.getItem(0));
    }

    @Test
    @UiThreadTest
    public void getItemId_testGetItemId() {
        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).findAll();
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, resultList, AUTOMATIC_UPDATE);
        for (int i = 0; i < resultList.size(); i++) {
            assertEquals(i, realmAdapter.getItemId(i));
        }
    }

    @Test
    @UiThreadTest
    public void getItemCount_testGetCount() {
        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).findAll();
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, resultList, AUTOMATIC_UPDATE);
        assertEquals(TEST_DATA_SIZE, realmAdapter.getItemCount());
    }

    @Test
    @UiThreadTest
    public void getItemCount_testNullResults() {
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, null, AUTOMATIC_UPDATE);
        assertEquals(0, realmAdapter.getItemCount());
    }

    @Test
    @UiThreadTest
    public void getItemCount_testNotValidResults() {
        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).findAll();
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, resultList, AUTOMATIC_UPDATE);

        realm.close();
        assertEquals(0, realmAdapter.getItemCount());
    }

    @Test
    @UiThreadTest
    public void getItemCount_testNonNullToNullResults() {
        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).findAll();
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, resultList, AUTOMATIC_UPDATE);
        realmAdapter.updateData(null);

        assertEquals(0, realmAdapter.getItemCount());
    }

    @Test
    @UiThreadTest
    public void getItemCount_testNullToNonNullResults() {
        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).findAll();
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, null, AUTOMATIC_UPDATE);
        assertEquals(0, realmAdapter.getItemCount());

        realmAdapter.updateData(resultList);
        assertEquals(TEST_DATA_SIZE, realmAdapter.getItemCount());
    }

    @Test
    @UiThreadTest
    public void viewHolderTestForSimpleView() {
        RealmResults<AllJavaTypes> resultList = realm.where(AllJavaTypes.class).findAll();
        RecyclerViewTestAdapter realmAdapter = new RecyclerViewTestAdapter(context, resultList, AUTOMATIC_UPDATE);

        RecyclerViewTestAdapter.ViewHolder holder = realmAdapter.onCreateViewHolder(new FrameLayout(context), 0);
        assertNotNull(holder.textView);

        realmAdapter.onBindViewHolder(holder, 0);
        assertEquals(resultList.first().getFieldString(), holder.textView.getText());
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ceskoslov. Lišejn. Celedi Verrucariaceae 21 (1954)

#### Original name
Amphoridium aljazevi Servít

### Remarks
null


text:
public class ClasseFilha extends ClasseMae {

	public String atributoB;

	public ClasseFilha(String atributoA, String atributoB) {
		super(atributoA);
		this.atributoB = atributoB;

		System.out.println("Construtor ClasseFilha. Atributo B: "+atributoB);
	}

	public void metodoClasseFilha() {
		System.out.println("método classe Filha");
	}
}


text:
package mil.nga.geopackage.extension.im.vector_tiles;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

/**
 * Describes the fields in a vector tiles set
 *
 * @author jyutzler
 * @since 4.0.0
 */
@DatabaseTable(tableName = "gpkgext_vt_fields", daoClass = VectorTilesFieldsDao.class)
public class VectorTilesFields {
    public static final String TABLE_NAME = "gpkgext_vt_fields";
    public static final String COLUMN_ID = "id";
    public static final String COLUMN_LAYER_ID = "layer_id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_TYPE = "type";

    @DatabaseField(columnName = COLUMN_ID, generatedId = true, canBeNull = false)
    private long id;

    @DatabaseField(columnName = COLUMN_LAYER_ID, canBeNull = false)
    private long layerId;

    @DatabaseField(columnName = COLUMN_NAME, canBeNull = false)
    private String name;

    @DatabaseField(columnName = COLUMN_TYPE, canBeNull = false)
    private String type;

    public VectorTilesFields() {
    }

    public VectorTilesFields(long id, long layerId, String name, String type) {
        this.id = id;
        this.layerId = layerId;
        this.name = name;
        this.type = type;
    }

    /**
     * Reset the id so the row can be inserted as new
     */
    public void resetId() {
        this.id = 0;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public long getLayerId() {
        return layerId;
    }

    public void setLayerId(long layerId) {
        this.layerId = layerId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}


text:
<?xml version="1.0"?>

<iati-activities version="xx">
  <iati-activity>
    <iati-identifier></iati-identifier>
    <reporting-org type="xx" ref="xx">
      <narrative>Organisation name</narrative>
    </reporting-org>
    <title>
      <narrative>Xxxxxxx</narrative>
    </title>
    <description>
      <narrative>Xxxxxxx</narrative>
    </description>
    <participating-org role="xx"></participating-org>
    <activity-status code="xx"/>
    <activity-date type="xx" iso-date="2013-11-27"/>
    <activity-date type="xx" iso-date="2013-11-27">
      <narrative>Some stuff ere</narrative>
    </activity-date>
    <result type="xx">
      <title>
        <narrative>Sample text</narrative>
      </title>
      <indicator measure="xx" ascending="0">
        <title>
          <narrative>Sample text</narrative>
        </title>
        <period>
          <period-start iso-date="2017-11-22"/>
          <period-end iso-date="2017-11-23"/>
          <actual value="xx">
            <document-link url="xx" format="xx">
              <title>
                <narrative>Sample text</narrative>
              </title>
              <category code="xx"/>
              <document-date iso-date="2000-01-01"/>
              <document-date iso-date="2000-01-02"/><!-- FAIL: Non-permitted, additional element added. -->
            </document-link>
          </actual>
        </period>
      </indicator>
    </result>
  </iati-activity>
</iati-activities>


text:
#include "stkmenuitem.h"

StkMenuItem::StkMenuItem(const QString &icon, const QString &title)
{
    mIcon = icon;
    mTitle = title;
}

QString StkMenuItem::icon() const
{
    return mIcon;
}

QString StkMenuItem::title() const
{
    return mTitle;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<!-- KSA Mysql环境 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://127.0.0.1/ksa_logistics?autoReconnect=true" />
		<property name="username" value="ksa" />
		<property name="password" value="ksab915" />

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize"><value>10</value></property>
        <property name="minIdle"><value>10</value></property>
        <property name="maxActive"><value>50</value></property>

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait"><value>60000</value></property>

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis"><value>60000</value></property>

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis"><value>300000</value></property>

        <property name="validationQuery"><value>SELECT 1</value></property>
        <property name="testWhileIdle"><value>true</value></property>
        <property name="testOnBorrow"><value>false</value></property>
        <property name="testOnReturn"><value>false</value></property>
	</bean>

	<!-- dao -->
	<import resource="classpath:spring/dao/dao-config.xml" />

	<!-- service -->
	<import resource="classpath*:spring/service/*-service-context.xml" />

</beans>


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var EducationComponent = (function () {
    function EducationComponent() {
    }
    EducationComponent = __decorate([
        core_1.Component({
            selector: 'education',
            templateUrl: 'app/education.component.html',
        }),
        __metadata('design:paramtypes', [])
    ], EducationComponent);
    return EducationComponent;
}());
exports.EducationComponent = EducationComponent;
//# sourceMappingURL=education.component.js.map


text:
title: Rachel Mogck
date: 2016-09-11 21:04:00 -05:00
position: 5
image: "/uploads/Photo-5-Rachel.png"
img-alt: Rachel Mogck
---

Media Mage // Rachel Mogck is an aspiring sound designer. One of her life goals is to meet Isaac Brock and tell him she loves him and that he changed her life. She is a Pisces who believes in magic and will probably ask you what your sign is faster than you are comfortable with.


text:
package cmd

import (
	boshdir "github.com/cloudfoundry/bosh-cli/director"
	boshui "github.com/cloudfoundry/bosh-cli/ui"
)

type DeleteDeploymentCmd struct {
	ui         boshui.UI
	deployment boshdir.Deployment
}

func NewDeleteDeploymentCmd(ui boshui.UI, deployment boshdir.Deployment) DeleteDeploymentCmd {
	return DeleteDeploymentCmd{ui: ui, deployment: deployment}
}

func (c DeleteDeploymentCmd) Run(opts DeleteDeploymentOpts) error {
	err := c.ui.AskForConfirmation()
	if err != nil {
		return err
	}

	return c.deployment.Delete(opts.Force)
}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

from pants.backend.jvm.scala.target_platform import TargetPlatform
from pants.backend.jvm.targets.exportable_jvm_library import ExportableJvmLibrary
from pants.base.address import SyntheticAddress
from pants.base.exceptions import TargetDefinitionException

class ScalaLibrary(ExportableJvmLibrary):
  """A collection of Scala code.

  Normally has conceptually-related sources; invoking the ``compile`` goal
  on this target compiles scala and generates classes. Invoking the ``bundle``
  goal on this target creates a ``.jar``; but that's an unusual thing to do.
  Instead, a ``jvm_binary`` might depend on this library; that binary is a
  more sensible thing to bundle.
  """

  def __init__(self, java_sources=None, **kwargs):
    """
    :param java_sources: Java libraries this library has a *circular*
      dependency on.
      If you don't have the particular problem of circular dependencies
      forced by splitting interdependent java and scala into multiple targets,
      don't use this at all.
      Prefer using ``dependencies`` to express non-circular dependencies.
    :type java_sources: target spec or list of target specs
    :param resources: An optional list of paths (DEPRECATED) or ``resources``
      targets containing resources that belong on this library's classpath.
    """
    self._java_sources_specs = self.assert_list(java_sources)
    super(ScalaLibrary, self).__init__(**kwargs)
    self.add_labels('scala')

  @property
  def traversable_dependency_specs(self):
    for spec in super(ScalaLibrary, self).traversable_dependency_specs:
      yield spec

    # TODO(John Sirois): Targets should have a config plumbed as part of the implicit
    # BuildFileParser injected context and that could be used to allow in general for targets with
    # knobs and in particular an explict config arg to the TargetPlatform constructor below.
    for library_spec in TargetPlatform().library_specs:
      yield library_spec

  @property
  def traversable_specs(self):
    for spec in super(ScalaLibrary, self).traversable_specs:
      yield spec
    for java_source_spec in self._java_sources_specs:
      yield java_source_spec

  def get_jar_dependencies(self):
    for jar in super(ScalaLibrary, self).get_jar_dependencies():
      yield jar
    for java_source_target in self.java_sources:
      for jar in java_source_target.jar_dependencies:
        yield jar

  @property
  def java_sources(self):
    for spec in self._java_sources_specs:
      address = SyntheticAddress.parse(spec, relative_to=self.address.spec_path)
      target = self._build_graph.get_target(address)
      if target is None:
        raise TargetDefinitionException(self, 'No such java target: %s' % spec)
      yield target


text:
		<title>PxJointLimit.h File Reference</title>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<LINK HREF="NVIDIA.css" REL="stylesheet" TYPE="text/css">

				Main Page
				Class Hierarchy
				Compound List
				Compound Members

Include

extensions

Classes

PxJointLimit.h File Reference

#include "foundation/PxMath.h"

#include "PxPhysXConfig.h"

#include "common/PxTolerancesScale.h"

#include "PxJoint.h"

This graph shows which files directly or indirectly include this file:

<map name="PxJointLimit_8hdep" id="PxJointLimit_8hdep">
</map>

Go to the source code of this file.

Classes

class  	PxJointLimitParameters

 	Describes the parameters for a joint limit.  More...

class  	PxJointLinearLimit

 	Describes a one-sided linear limit.  More...

class  	PxJointLinearLimitPair

 	Describes a two-sided limit.  More...

class  	PxJointAngularLimitPair

class  	PxJointLimitCone

 	Describes an elliptical conical joint limit. Note that very small or highly elliptical limit cones may result in jitter.  More...

Copyright © 2008-2015 NVIDIA Corporation, 2701 San Tomas Expressway, Santa Clara, CA 95050 U.S.A. All rights reserved. www.nvidia.com


text:
package com.medicapital.server.security;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.servlet.http.HttpSession;
import com.medicapital.common.entities.LoginData;

/**
 * Container for data related with user session
 *
 * @author mwronski
 *
 */
public class SessionData {

	public static final String SESSION_DATA = "SessionData";
	private HttpSession httpSession;
	private LoginData loginData;

	SessionData(HttpSession httpSession, final LoginData loginData) {
		this.httpSession = httpSession;
		this.loginData = loginData;
	}

	void invalidate() {
		if (httpSession != null) {
			httpSession.invalidate();
		}
		loginData = null;
		httpSession = null;
	}

	public Date getExpiryDate() {
		if (httpSession == null) {
			return null;
		}
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTimeInMillis(httpSession.getLastAccessedTime());
		calendar.add(Calendar.SECOND, httpSession.getMaxInactiveInterval());
		return calendar.getTime();
	}

	HttpSession getHttpSession() {
		return httpSession;
	}

	public String getSessionId() {
		return httpSession != null ? httpSession.getId() : null;
	}

	public int getMaxInactiveInterval() {
		return httpSession != null ? httpSession.getMaxInactiveInterval() : 0;
	}

	public Date getCreationTime() {
		return httpSession != null ? new Date(httpSession.getCreationTime()) : null;
	}

	public Date getLastAccessedTime() {
		return httpSession != null ? new Date(httpSession.getLastAccessedTime()) : null;
	}

	public LoginData getLoginData() {
		return loginData != null ? loginData.clone() : null;
	}

	@Override
	public String toString() {
		final StringBuilder string = new StringBuilder("[");
		string.append("SessionId: ").append(getSessionId()).append(", ");
		string.append("Create time: ").append(getCreationTime()).append(", ");
		string.append("Max inactive interval: ").append(getMaxInactiveInterval()).append(", ");
		string.append("Last access time: ").append(getLastAccessedTime()).append(", ");
		string.append("Expiry date: ").append(getExpiryDate()).append(", ");
		string.append("Login data: ").append(loginData);
		string.append("]");
		return string.toString();
	}

}


text:
package com.obidea.semantika.queryanswer.internal;

import com.obidea.semantika.queryanswer.exception.QueryAnswerException;

public class DatabaseSessionException extends QueryAnswerException
{
   private static final long serialVersionUID = 629451L;

   public DatabaseSessionException()
   {
      super();
   }

   public DatabaseSessionException(String message)
   {
      super(message);
   }

   public DatabaseSessionException(String message, Throwable cause)
   {
      super(message, cause);
   }

   public DatabaseSessionException(Throwable cause)
   {
      super(cause);
   }
}


text:
<?php

namespace Calam\Dbal\Driver\Pdo\MySql\Log\Analyzer;

class MissingIndexAnalyzeResult
{
    /**
     * @var array
     */
    private $missingIndexes;

    public function getMissingIndexes()
    {
        return $this->missingIndexes;
    }

    public function setMissingIndexes($missingIndexes)
    {
        $this->missingIndexes = $missingIndexes;

        return $this;
    }
}


text:
package com.commonsware.android.recyclerview.horizontalvideolist;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

public class MainActivity extends RecyclerViewActivity implements
    LoaderManager.LoaderCallbacks<Cursor> {
  private static final String STATE_IN_PERMISSION="inPermission";
  private static final int REQUEST_PERMS=137;
  private boolean isInPermission=false;

  @Override
  public void onCreate(Bundle state) {
    super.onCreate(state);

    setLayoutManager(new LinearLayoutManager(this,
                            LinearLayoutManager.HORIZONTAL, false));
    setAdapter(new VideoAdapter());

    if (state!=null) {
      isInPermission=
        state.getBoolean(STATE_IN_PERMISSION, false);
    }

    if (hasFilesPermission()) {
      loadVideos();
    }
    else if (!isInPermission) {
      isInPermission=true;

      ActivityCompat.requestPermissions(this,
        new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
        REQUEST_PERMS);
    }
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putBoolean(STATE_IN_PERMISSION, isInPermission);
  }

  @Override
  public void onRequestPermissionsResult(int requestCode,
                                         String[] permissions,
                                         int[] grantResults) {
    isInPermission=false;

    if (requestCode==REQUEST_PERMS) {
      if (hasFilesPermission()) {
        loadVideos();
      }
      else {
        finish(); // denied permission, so we're done
      }
    }
  }

  @Override
  public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
    return(new CursorLoader(this,
                            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                            null, null, null,
                            MediaStore.Video.Media.TITLE));
  }

  @Override
  public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
    ((VideoAdapter)getAdapter()).setVideos(c);
  }

  @Override
  public void onLoaderReset(Loader<Cursor> loader) {
    ((VideoAdapter)getAdapter()).setVideos(null);
  }

  private boolean hasFilesPermission() {
    return(ContextCompat.checkSelfPermission(this,
      Manifest.permission.READ_EXTERNAL_STORAGE)==
      PackageManager.PERMISSION_GRANTED);
  }

  private void loadVideos() {
    getSupportLoaderManager().initLoader(0, null, this);
  }

  class VideoAdapter extends RecyclerView.Adapter<RowController> {
    Cursor videos=null;

    @Override
    public RowController onCreateViewHolder(ViewGroup parent, int viewType) {
      return(new RowController(getLayoutInflater()
                                 .inflate(R.layout.row, parent, false)));
    }

    void setVideos(Cursor videos) {
      this.videos=videos;
      notifyDataSetChanged();
    }

    @Override
    public void onBindViewHolder(RowController holder, int position) {
      videos.moveToPosition(position);
      holder.bindModel(videos);
    }

    @Override
    public int getItemCount() {
      if (videos==null) {
        return(0);
      }

      return(videos.getCount());
    }
  }
}


text:
module ActivityStreams
  class Exception < StandardError
  end

  class InvalidAttribute < Exception
  end
end


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

import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.consumer.internals.PartitionAssignor;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.metrics.Metrics;
import org.apache.kafka.common.utils.MockTime;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStreamBuilder;
import org.apache.kafka.streams.processor.TaskId;
import org.apache.kafka.streams.processor.TopologyBuilder;
import org.apache.kafka.streams.state.Stores;
import org.apache.kafka.test.MockClientSupplier;
import org.apache.kafka.test.MockProcessorSupplier;
import org.apache.kafka.test.MockTimestampExtractor;
import org.apache.kafka.test.TestUtils;
import org.junit.Assert;
import org.junit.Test;

import java.io.File;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class StreamThreadTest {

    private final String clientId = "clientId";
    private final String applicationId = "stream-thread-test";
    private final UUID processId = UUID.randomUUID();

    private TopicPartition t1p1 = new TopicPartition("topic1", 1);
    private TopicPartition t1p2 = new TopicPartition("topic1", 2);
    private TopicPartition t2p1 = new TopicPartition("topic2", 1);
    private TopicPartition t2p2 = new TopicPartition("topic2", 2);
    private TopicPartition t3p1 = new TopicPartition("topic3", 1);
    private TopicPartition t3p2 = new TopicPartition("topic3", 2);

    private List<PartitionInfo> infos = Arrays.asList(
            new PartitionInfo("topic1", 0, Node.noNode(), new Node[0], new Node[0]),
            new PartitionInfo("topic1", 1, Node.noNode(), new Node[0], new Node[0]),
            new PartitionInfo("topic1", 2, Node.noNode(), new Node[0], new Node[0]),
            new PartitionInfo("topic2", 0, Node.noNode(), new Node[0], new Node[0]),
            new PartitionInfo("topic2", 1, Node.noNode(), new Node[0], new Node[0]),
            new PartitionInfo("topic2", 2, Node.noNode(), new Node[0], new Node[0]),
            new PartitionInfo("topic3", 0, Node.noNode(), new Node[0], new Node[0]),
            new PartitionInfo("topic3", 1, Node.noNode(), new Node[0], new Node[0]),
            new PartitionInfo("topic3", 2, Node.noNode(), new Node[0], new Node[0])
    );

    private Cluster metadata = new Cluster("cluster", Arrays.asList(Node.noNode()), infos, Collections.<String>emptySet(),
            Collections.<String>emptySet());

    private final PartitionAssignor.Subscription subscription =
            new PartitionAssignor.Subscription(Arrays.asList("topic1", "topic2", "topic3"), subscriptionUserData());

    private ByteBuffer subscriptionUserData() {
        UUID uuid = UUID.randomUUID();
        ByteBuffer buf = ByteBuffer.allocate(4 + 16 + 4 + 4);
        // version
        buf.putInt(1);
        // encode client processId
        buf.putLong(uuid.getMostSignificantBits());
        buf.putLong(uuid.getLeastSignificantBits());
        // previously running tasks
        buf.putInt(0);
        // cached tasks
        buf.putInt(0);
        buf.rewind();
        return buf;
    }

    // task0 is unused
    private final TaskId task1 = new TaskId(0, 1);
    private final TaskId task2 = new TaskId(0, 2);
    private final TaskId task3 = new TaskId(0, 3);
    private final TaskId task4 = new TaskId(1, 1);
    private final TaskId task5 = new TaskId(1, 2);

    private Properties configProps() {
        return new Properties() {
            {
                setProperty(StreamsConfig.APPLICATION_ID_CONFIG, applicationId);
                setProperty(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:2171");
                setProperty(StreamsConfig.BUFFERED_RECORDS_PER_PARTITION_CONFIG, "3");
                setProperty(StreamsConfig.TIMESTAMP_EXTRACTOR_CLASS_CONFIG, MockTimestampExtractor.class.getName());
                setProperty(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getAbsolutePath());
            }
        };
    }

    private static class TestStreamTask extends StreamTask {
        public boolean committed = false;
        private boolean closed;
        private boolean closedStateManager;

        public TestStreamTask(TaskId id,
                              String applicationId,
                              Collection<TopicPartition> partitions,
                              ProcessorTopology topology,
                              Consumer<byte[], byte[]> consumer,
                              Producer<byte[], byte[]> producer,
                              Consumer<byte[], byte[]> restoreConsumer,
                              StreamsConfig config,
                              StateDirectory stateDirectory) {
            super(id, applicationId, partitions, topology, consumer, producer, restoreConsumer, config, null, stateDirectory, null);
        }

        @Override
        public void commit() {
            super.commit();
            committed = true;
        }

        @Override
        public void commitOffsets() {
            super.commitOffsets();
            committed = true;
        }

        @Override
        protected void initializeOffsetLimits() {
            // do nothing
        }

        @Override
        public void close() {
            this.closed = true;
            super.close();
        }

        @Override
        void closeStateManager() {
            super.closeStateManager();
            this.closedStateManager = true;
        }
    }

    @SuppressWarnings("unchecked")
    @Test
    public void testPartitionAssignmentChange() throws Exception {
        StreamsConfig config = new StreamsConfig(configProps());
        StateListenerStub stateListener = new StateListenerStub();

        TopologyBuilder builder = new TopologyBuilder().setApplicationId("X");
        builder.addSource("source1", "topic1");
        builder.addSource("source2", "topic2");
        builder.addSource("source3", "topic3");
        builder.addProcessor("processor", new MockProcessorSupplier(), "source2", "source3");

        StreamThread thread = new StreamThread(builder, config, new MockClientSupplier(), applicationId, clientId, processId, new Metrics(), Time.SYSTEM, new StreamsMetadataState(builder)) {
            @Override
            protected StreamTask createStreamTask(TaskId id, Collection<TopicPartition> partitionsForTask) {
                ProcessorTopology topology = builder.build(id.topicGroupId);
                return new TestStreamTask(id, applicationId, partitionsForTask, topology, consumer, producer, restoreConsumer, config, stateDirectory);
            }
        };
        thread.setStateListener(stateListener);
        assertEquals(thread.state(), StreamThread.State.RUNNING);
        initPartitionGrouper(config, thread);

        ConsumerRebalanceListener rebalanceListener = thread.rebalanceListener;

        assertTrue(thread.tasks().isEmpty());

        List<TopicPartition> revokedPartitions;
        List<TopicPartition> assignedPartitions;
        Set<TopicPartition> expectedGroup1;
        Set<TopicPartition> expectedGroup2;

        revokedPartitions = Collections.emptyList();
        assignedPartitions = Collections.singletonList(t1p1);
        expectedGroup1 = new HashSet<>(Arrays.asList(t1p1));

        rebalanceListener.onPartitionsRevoked(revokedPartitions);
        assertEquals(thread.state(), StreamThread.State.PARTITIONS_REVOKED);
        Assert.assertEquals(stateListener.numChanges, 1);
        Assert.assertEquals(stateListener.oldState, StreamThread.State.RUNNING);
        Assert.assertEquals(stateListener.newState, StreamThread.State.PARTITIONS_REVOKED);
        rebalanceListener.onPartitionsAssigned(assignedPartitions);
        assertEquals(thread.state(), StreamThread.State.RUNNING);
        Assert.assertEquals(stateListener.numChanges, 3);
        Assert.assertEquals(stateListener.oldState, StreamThread.State.ASSIGNING_PARTITIONS);
        Assert.assertEquals(stateListener.newState, StreamThread.State.RUNNING);

        assertTrue(thread.tasks().containsKey(task1));
        assertEquals(expectedGroup1, thread.tasks().get(task1).partitions());
        assertEquals(1, thread.tasks().size());

        revokedPartitions = assignedPartitions;
        assignedPartitions = Collections.singletonList(t1p2);
        expectedGroup2 = new HashSet<>(Arrays.asList(t1p2));

        rebalanceListener.onPartitionsRevoked(revokedPartitions);
        assertFalse(thread.tasks().containsKey(task1));
        assertEquals(0, thread.tasks().size());
        rebalanceListener.onPartitionsAssigned(assignedPartitions);

        assertTrue(thread.tasks().containsKey(task2));
        assertEquals(expectedGroup2, thread.tasks().get(task2).partitions());
        assertEquals(1, thread.tasks().size());

        revokedPartitions = assignedPartitions;
        assignedPartitions = Arrays.asList(t1p1, t1p2);
        expectedGroup1 = new HashSet<>(Collections.singleton(t1p1));
        expectedGroup2 = new HashSet<>(Collections.singleton(t1p2));

        rebalanceListener.onPartitionsRevoked(revokedPartitions);
        rebalanceListener.onPartitionsAssigned(assignedPartitions);

        assertTrue(thread.tasks().containsKey(task1));
        assertTrue(thread.tasks().containsKey(task2));
        assertEquals(expectedGroup1, thread.tasks().get(task1).partitions());
        assertEquals(expectedGroup2, thread.tasks().get(task2).partitions());
        assertEquals(2, thread.tasks().size());

        revokedPartitions = assignedPartitions;
        assignedPartitions = Arrays.asList(t2p1, t2p2, t3p1, t3p2);
        expectedGroup1 = new HashSet<>(Arrays.asList(t2p1, t3p1));
        expectedGroup2 = new HashSet<>(Arrays.asList(t2p2, t3p2));

        rebalanceListener.onPartitionsRevoked(revokedPartitions);
        rebalanceListener.onPartitionsAssigned(assignedPartitions);

        assertTrue(thread.tasks().containsKey(task4));
        assertTrue(thread.tasks().containsKey(task5));
        assertEquals(expectedGroup1, thread.tasks().get(task4).partitions());
        assertEquals(expectedGroup2, thread.tasks().get(task5).partitions());
        assertEquals(2, thread.tasks().size());

        revokedPartitions = assignedPartitions;
        assignedPartitions = Arrays.asList(t1p1, t2p1, t3p1);
        expectedGroup1 = new HashSet<>(Arrays.asList(t1p1));
        expectedGroup2 = new HashSet<>(Arrays.asList(t2p1, t3p1));

        rebalanceListener.onPartitionsRevoked(revokedPartitions);
        rebalanceListener.onPartitionsAssigned(assignedPartitions);

        assertTrue(thread.tasks().containsKey(task1));
        assertTrue(thread.tasks().containsKey(task4));
        assertEquals(expectedGroup1, thread.tasks().get(task1).partitions());
        assertEquals(expectedGroup2, thread.tasks().get(task4).partitions());
        assertEquals(2, thread.tasks().size());

        revokedPartitions = assignedPartitions;
        assignedPartitions = Arrays.asList(t1p1, t2p1, t3p1);
        expectedGroup1 = new HashSet<>(Arrays.asList(t1p1));
        expectedGroup2 = new HashSet<>(Arrays.asList(t2p1, t3p1));

        rebalanceListener.onPartitionsRevoked(revokedPartitions);
        rebalanceListener.onPartitionsAssigned(assignedPartitions);

        assertTrue(thread.tasks().containsKey(task1));
        assertTrue(thread.tasks().containsKey(task4));
        assertEquals(expectedGroup1, thread.tasks().get(task1).partitions());
        assertEquals(expectedGroup2, thread.tasks().get(task4).partitions());
        assertEquals(2, thread.tasks().size());

        revokedPartitions = assignedPartitions;
        assignedPartitions = Collections.emptyList();

        rebalanceListener.onPartitionsRevoked(revokedPartitions);
        rebalanceListener.onPartitionsAssigned(assignedPartitions);

        assertTrue(thread.tasks().isEmpty());

        thread.close();
        assertTrue((thread.state() == StreamThread.State.PENDING_SHUTDOWN) ||
            (thread.state() == StreamThread.State.NOT_RUNNING));
    }

    final static String TOPIC = "topic";
    final Set<TopicPartition> task0Assignment = Collections.singleton(new TopicPartition(TOPIC, 0));
    final Set<TopicPartition> task1Assignment = Collections.singleton(new TopicPartition(TOPIC, 1));

    @Test
    public void testHandingOverTaskFromOneToAnotherThread() throws Exception {
        final TopologyBuilder builder = new TopologyBuilder();
        builder.addStateStore(
            Stores
                .create("store")
                .withByteArrayKeys()
                .withByteArrayValues()
                .persistent()
                .build()
        );
        final StreamsConfig config = new StreamsConfig(configProps());
        final MockClientSupplier mockClientSupplier = new MockClientSupplier();
        mockClientSupplier.consumer.assign(Arrays.asList(new TopicPartition(TOPIC, 0), new TopicPartition(TOPIC, 1)));

        final StreamThread thread1 = new StreamThread(builder, config, mockClientSupplier, applicationId, clientId + 1, processId, new Metrics(), Time.SYSTEM, new StreamsMetadataState(builder));
        final StreamThread thread2 = new StreamThread(builder, config, mockClientSupplier, applicationId, clientId + 2, processId, new Metrics(), Time.SYSTEM, new StreamsMetadataState(builder));

        final Map<TaskId, Set<TopicPartition>> task0 = Collections.singletonMap(new TaskId(0, 0), task0Assignment);
        final Map<TaskId, Set<TopicPartition>> task1 = Collections.singletonMap(new TaskId(0, 1), task1Assignment);

        final Map<TaskId, Set<TopicPartition>> thread1Assignment = new HashMap<>(task0);
        final Map<TaskId, Set<TopicPartition>> thread2Assignment = new HashMap<>(task1);

        thread1.partitionAssignor(new MockStreamsPartitionAssignor(thread1Assignment));
        thread2.partitionAssignor(new MockStreamsPartitionAssignor(thread2Assignment));

        // revoke (to get threads in correct state)
        thread1.rebalanceListener.onPartitionsRevoked(Collections.EMPTY_SET);
        thread2.rebalanceListener.onPartitionsRevoked(Collections.EMPTY_SET);

        // assign
        thread1.rebalanceListener.onPartitionsAssigned(task0Assignment);
        thread2.rebalanceListener.onPartitionsAssigned(task1Assignment);

        final Set<TaskId> originalTaskAssignmentThread1 = new HashSet<>();
        for (TaskId tid : thread1.tasks().keySet()) {
            originalTaskAssignmentThread1.add(tid);
        }
        final Set<TaskId> originalTaskAssignmentThread2 = new HashSet<>();
        for (TaskId tid : thread2.tasks().keySet()) {
            originalTaskAssignmentThread2.add(tid);
        }

        // revoke (task will be suspended)
        thread1.rebalanceListener.onPartitionsRevoked(task0Assignment);
        thread2.rebalanceListener.onPartitionsRevoked(task1Assignment);

        // assign reverted
        thread1Assignment.clear();
        thread1Assignment.putAll(task1);

        thread2Assignment.clear();
        thread2Assignment.putAll(task0);

        Thread runIt = new Thread(new Runnable() {
            @Override
            public void run() {
                thread1.rebalanceListener.onPartitionsAssigned(task1Assignment);
            }
        });
        runIt.start();

        thread2.rebalanceListener.onPartitionsAssigned(task0Assignment);

        runIt.join();

        assertThat(thread1.tasks().keySet(), equalTo(originalTaskAssignmentThread2));
        assertThat(thread2.tasks().keySet(), equalTo(originalTaskAssignmentThread1));
        assertThat(thread1.prevTasks(), equalTo(originalTaskAssignmentThread1));
        assertThat(thread2.prevTasks(), equalTo(originalTaskAssignmentThread2));
    }

    private class MockStreamsPartitionAssignor extends StreamPartitionAssignor {

        private final Map<TaskId, Set<TopicPartition>> activeTaskAssignment;

        public MockStreamsPartitionAssignor(final Map<TaskId, Set<TopicPartition>> activeTaskAssignment) {
            this.activeTaskAssignment = activeTaskAssignment;
        }

        @Override
        Map<TaskId, Set<TopicPartition>> activeTasks() {
            return activeTaskAssignment;
        }
    }

    @Test
    public void testMaybeClean() throws Exception {
        File baseDir = Files.createTempDirectory("test").toFile();
        try {
            final long cleanupDelay = 1000L;
            Properties props = configProps();
            props.setProperty(StreamsConfig.STATE_CLEANUP_DELAY_MS_CONFIG, Long.toString(cleanupDelay));
            props.setProperty(StreamsConfig.STATE_DIR_CONFIG, baseDir.getCanonicalPath());

            StreamsConfig config = new StreamsConfig(props);

            File applicationDir = new File(baseDir, applicationId);
            applicationDir.mkdir();
            File stateDir1 = new File(applicationDir, task1.toString());
            File stateDir2 = new File(applicationDir, task2.toString());
            File stateDir3 = new File(applicationDir, task3.toString());
            File extraDir = new File(applicationDir, "X");
            stateDir1.mkdir();
            stateDir2.mkdir();
            stateDir3.mkdir();
            extraDir.mkdir();

            MockTime mockTime = new MockTime();

            TopologyBuilder builder = new TopologyBuilder().setApplicationId("X");
            builder.addSource("source1", "topic1");

            StreamThread thread = new StreamThread(builder, config, new MockClientSupplier(), applicationId, clientId,  processId, new Metrics(), mockTime, new StreamsMetadataState(builder)) {
                @Override
                public void maybeClean() {
                    super.maybeClean();
                }

                @Override
                protected StreamTask createStreamTask(TaskId id, Collection<TopicPartition> partitionsForTask) {
                    ProcessorTopology topology = builder.build(id.topicGroupId);
                    return new TestStreamTask(id, applicationId, partitionsForTask, topology, consumer, producer, restoreConsumer, config, stateDirectory);
                }
            };

            initPartitionGrouper(config, thread);

            ConsumerRebalanceListener rebalanceListener = thread.rebalanceListener;

            assertTrue(thread.tasks().isEmpty());
            mockTime.sleep(cleanupDelay);

            // all directories exist since an assignment didn't happen
            assertTrue(stateDir1.exists());
            assertTrue(stateDir2.exists());
            assertTrue(stateDir3.exists());
            assertTrue(extraDir.exists());

            List<TopicPartition> revokedPartitions;
            List<TopicPartition> assignedPartitions;
            Map<TaskId, StreamTask> prevTasks;

            //
            // Assign t1p1 and t1p2. This should create task1 & task2
            //
            final Map<TaskId, Set<TopicPartition>> activeTasks = new HashMap<>();
            activeTasks.put(task1, Collections.singleton(t1p1));
            activeTasks.put(task2, Collections.singleton(t1p2));
            thread.partitionAssignor(new MockStreamsPartitionAssignor(activeTasks));

            revokedPartitions = Collections.emptyList();
            assignedPartitions = Arrays.asList(t1p1, t1p2);
            prevTasks = new HashMap<>(thread.tasks());

            rebalanceListener.onPartitionsRevoked(revokedPartitions);
            rebalanceListener.onPartitionsAssigned(assignedPartitions);

            // there shouldn't be any previous task
            assertTrue(prevTasks.isEmpty());

            // task 1 & 2 are created
            assertEquals(2, thread.tasks().size());

            // all directories should still exit before the cleanup delay time
            mockTime.sleep(cleanupDelay - 10L);
            thread.maybeClean();
            assertTrue(stateDir1.exists());
            assertTrue(stateDir2.exists());
            assertTrue(stateDir3.exists());
            assertTrue(extraDir.exists());

            // all state directories except for task task2 & task3 will be removed. the extra directory should still exists
            mockTime.sleep(11L);
            thread.maybeClean();
            assertTrue(stateDir1.exists());
            assertTrue(stateDir2.exists());
            assertFalse(stateDir3.exists());
            assertTrue(extraDir.exists());

            //
            // Revoke t1p1 and t1p2. This should remove task1 & task2
            //
            activeTasks.clear();

            revokedPartitions = assignedPartitions;
            assignedPartitions = Collections.emptyList();
            prevTasks = new HashMap<>(thread.tasks());

            rebalanceListener.onPartitionsRevoked(revokedPartitions);
            rebalanceListener.onPartitionsAssigned(assignedPartitions);

            // previous tasks should be committed
            assertEquals(2, prevTasks.size());
            for (StreamTask task : prevTasks.values()) {
                assertTrue(((TestStreamTask) task).committed);
                ((TestStreamTask) task).committed = false;
            }

            // no task
            assertTrue(thread.tasks().isEmpty());

            // all state directories for task task1 & task2 still exist before the cleanup delay time
            mockTime.sleep(cleanupDelay - 10L);
            thread.maybeClean();
            assertTrue(stateDir1.exists());
            assertTrue(stateDir2.exists());
            assertFalse(stateDir3.exists());
            assertTrue(extraDir.exists());

            // all state directories for task task1 & task2 are removed
            mockTime.sleep(11L);
            thread.maybeClean();
            assertFalse(stateDir1.exists());
            assertFalse(stateDir2.exists());
            assertFalse(stateDir3.exists());
            assertTrue(extraDir.exists());

        } finally {
            Utils.delete(baseDir);
        }
    }

    @Test
    public void testMaybeCommit() throws Exception {
        File baseDir = Files.createTempDirectory("test").toFile();
        try {
            final long commitInterval = 1000L;
            Properties props = configProps();
            props.setProperty(StreamsConfig.STATE_DIR_CONFIG, baseDir.getCanonicalPath());
            props.setProperty(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, Long.toString(commitInterval));

            StreamsConfig config = new StreamsConfig(props);

            MockTime mockTime = new MockTime();

            TopologyBuilder builder = new TopologyBuilder().setApplicationId("X");
            builder.addSource("source1", "topic1");

            StreamThread thread = new StreamThread(builder, config, new MockClientSupplier(), applicationId, clientId,  processId, new Metrics(), mockTime, new StreamsMetadataState(builder)) {
                @Override
                public void maybeCommit() {
                    super.maybeCommit();
                }

                @Override
                protected StreamTask createStreamTask(TaskId id, Collection<TopicPartition> partitionsForTask) {
                    ProcessorTopology topology = builder.build(id.topicGroupId);
                    return new TestStreamTask(id, applicationId, partitionsForTask, topology, consumer, producer, restoreConsumer, config, stateDirectory);
                }
            };

            initPartitionGrouper(config, thread);

            ConsumerRebalanceListener rebalanceListener = thread.rebalanceListener;

            List<TopicPartition> revokedPartitions;
            List<TopicPartition> assignedPartitions;

            //
            // Assign t1p1 and t1p2. This should create Task 1 & 2
            //
            revokedPartitions = Collections.emptyList();
            assignedPartitions = Arrays.asList(t1p1, t1p2);

            rebalanceListener.onPartitionsRevoked(revokedPartitions);
            rebalanceListener.onPartitionsAssigned(assignedPartitions);

            assertEquals(2, thread.tasks().size());

            // no task is committed before the commit interval
            mockTime.sleep(commitInterval - 10L);
            thread.maybeCommit();
            for (StreamTask task : thread.tasks().values()) {
                assertFalse(((TestStreamTask) task).committed);
            }

            // all tasks are committed after the commit interval
            mockTime.sleep(11L);
            thread.maybeCommit();
            for (StreamTask task : thread.tasks().values()) {
                assertTrue(((TestStreamTask) task).committed);
                ((TestStreamTask) task).committed = false;
            }

            // no task is committed before the commit interval, again
            mockTime.sleep(commitInterval - 10L);
            thread.maybeCommit();
            for (StreamTask task : thread.tasks().values()) {
                assertFalse(((TestStreamTask) task).committed);
            }

            // all tasks are committed after the commit interval, again
            mockTime.sleep(11L);
            thread.maybeCommit();
            for (StreamTask task : thread.tasks().values()) {
                assertTrue(((TestStreamTask) task).committed);
                ((TestStreamTask) task).committed = false;
            }

        } finally {
            Utils.delete(baseDir);
        }
    }

    @Test
    public void testInjectClients() {
        TopologyBuilder builder = new TopologyBuilder().setApplicationId("X");
        StreamsConfig config = new StreamsConfig(configProps());
        MockClientSupplier clientSupplier = new MockClientSupplier();
        StreamThread thread = new StreamThread(builder, config, clientSupplier, applicationId,
                                               clientId,  processId, new Metrics(), new MockTime(), new StreamsMetadataState(builder));
        assertSame(clientSupplier.producer, thread.producer);
        assertSame(clientSupplier.consumer, thread.consumer);
        assertSame(clientSupplier.restoreConsumer, thread.restoreConsumer);
    }

    @Test
    public void shouldNotNullPointerWhenStandbyTasksAssignedAndNoStateStoresForTopology() throws Exception {
        final TopologyBuilder builder = new TopologyBuilder();
        builder.setApplicationId("appId")
                .addSource("name", "topic")
                .addSink("out", "output");

        final StreamsConfig config = new StreamsConfig(configProps());
        final StreamThread thread = new StreamThread(builder, config, new MockClientSupplier(), applicationId,
                                                     clientId, processId, new Metrics(), new MockTime(), new StreamsMetadataState(builder));

        thread.partitionAssignor(new StreamPartitionAssignor() {
            @Override
            Map<TaskId, Set<TopicPartition>> standbyTasks() {
                return Collections.singletonMap(new TaskId(0, 0), Utils.mkSet(new TopicPartition("topic", 0)));
            }
        });

        thread.rebalanceListener.onPartitionsRevoked(Collections.<TopicPartition>emptyList());
        thread.rebalanceListener.onPartitionsAssigned(Collections.<TopicPartition>emptyList());
    }

    @Test
    public void shouldInitializeRestoreConsumerWithOffsetsFromStandbyTasks() throws Exception {
        final KStreamBuilder builder = new KStreamBuilder();
        builder.setApplicationId("appId");
        builder.stream("t1").groupByKey().count("count-one");
        builder.stream("t2").groupByKey().count("count-two");
        final StreamsConfig config = new StreamsConfig(configProps());
        final MockClientSupplier clientSupplier = new MockClientSupplier();

        final StreamThread thread = new StreamThread(builder, config, clientSupplier, applicationId,
                                                     clientId, processId, new Metrics(), new MockTime(), new StreamsMetadataState(builder));

        final MockConsumer<byte[], byte[]> restoreConsumer = clientSupplier.restoreConsumer;
        restoreConsumer.updatePartitions("stream-thread-test-count-one-changelog",
                                         Collections.singletonList(new PartitionInfo("stream-thread-test-count-one-changelog",
                                                                                0,
                                                                                null,
                                                                                new Node[0],
                                                                                new Node[0])));
        restoreConsumer.updatePartitions("stream-thread-test-count-two-changelog",
                                         Collections.singletonList(new PartitionInfo("stream-thread-test-count-two-changelog",
                                                                                0,
                                                                                null,
                                                                                new Node[0],
                                                                                new Node[0])));

        final Map<TaskId, Set<TopicPartition>> standbyTasks = new HashMap<>();
        final TopicPartition t1 = new TopicPartition("t1", 0);
        standbyTasks.put(new TaskId(0, 0), Utils.mkSet(t1));

        thread.partitionAssignor(new StreamPartitionAssignor() {
            @Override
            Map<TaskId, Set<TopicPartition>> standbyTasks() {
                return standbyTasks;
            }
        });

        thread.rebalanceListener.onPartitionsRevoked(Collections.<TopicPartition>emptyList());
        thread.rebalanceListener.onPartitionsAssigned(Collections.<TopicPartition>emptyList());

        assertThat(restoreConsumer.assignment(), equalTo(Utils.mkSet(new TopicPartition("stream-thread-test-count-one-changelog", 0))));

        // assign an existing standby plus a new one
        standbyTasks.put(new TaskId(1, 0), Utils.mkSet(new TopicPartition("t2", 0)));
        thread.rebalanceListener.onPartitionsRevoked(Collections.<TopicPartition>emptyList());
        thread.rebalanceListener.onPartitionsAssigned(Collections.<TopicPartition>emptyList());

        assertThat(restoreConsumer.assignment(), equalTo(Utils.mkSet(new TopicPartition("stream-thread-test-count-one-changelog", 0),
                                                                     new TopicPartition("stream-thread-test-count-two-changelog", 0))));
    }

    @Test
    public void shouldCloseSuspendedTasksThatAreNoLongerAssignedToThisStreamThreadBeforeCreatingNewTasks() throws Exception {
        final KStreamBuilder builder = new KStreamBuilder();
        builder.setApplicationId("appId");
        builder.stream("t1").groupByKey().count("count-one");
        builder.stream("t2").groupByKey().count("count-two");
        final StreamsConfig config = new StreamsConfig(configProps());
        final MockClientSupplier clientSupplier = new MockClientSupplier();

        final StreamThread thread = new StreamThread(builder, config, clientSupplier, applicationId,
                                                     clientId, processId, new Metrics(), new MockTime(), new StreamsMetadataState(builder));
        final MockConsumer<byte[], byte[]> restoreConsumer = clientSupplier.restoreConsumer;
        restoreConsumer.updatePartitions("stream-thread-test-count-one-changelog",
                                         Collections.singletonList(new PartitionInfo("stream-thread-test-count-one-changelog",
                                                                                0,
                                                                                null,
                                                                                new Node[0],
                                                                                new Node[0])));
        restoreConsumer.updatePartitions("stream-thread-test-count-two-changelog",
                                         Collections.singletonList(new PartitionInfo("stream-thread-test-count-two-changelog",
                                                                                0,
                                                                                null,
                                                                                new Node[0],
                                                                                new Node[0])));

        final HashMap<TopicPartition, Long> offsets = new HashMap<>();
        offsets.put(new TopicPartition("stream-thread-test-count-one-changelog", 0), 0L);
        offsets.put(new TopicPartition("stream-thread-test-count-two-changelog", 0), 0L);
        restoreConsumer.updateEndOffsets(offsets);
        restoreConsumer.updateBeginningOffsets(offsets);

        final Map<TaskId, Set<TopicPartition>> standbyTasks = new HashMap<>();
        final TopicPartition t1 = new TopicPartition("t1", 0);
        standbyTasks.put(new TaskId(0, 0), Utils.mkSet(t1));

        final Map<TaskId, Set<TopicPartition>> activeTasks = new HashMap<>();
        final TopicPartition t2 = new TopicPartition("t2", 0);
        activeTasks.put(new TaskId(1, 0), Utils.mkSet(t2));

        thread.partitionAssignor(new StreamPartitionAssignor() {
            @Override
            Map<TaskId, Set<TopicPartition>> standbyTasks() {
                return standbyTasks;
            }

            @Override
            Map<TaskId, Set<TopicPartition>> activeTasks() {
                return activeTasks;
            }
        });

        thread.rebalanceListener.onPartitionsRevoked(Collections.<TopicPartition>emptyList());
        thread.rebalanceListener.onPartitionsAssigned(Utils.mkSet(t2));

        // swap the assignment around and make sure we don't get any exceptions
        standbyTasks.clear();
        activeTasks.clear();
        standbyTasks.put(new TaskId(1, 0), Utils.mkSet(t2));
        activeTasks.put(new TaskId(0, 0), Utils.mkSet(t1));

        thread.rebalanceListener.onPartitionsRevoked(Collections.<TopicPartition>emptyList());
        thread.rebalanceListener.onPartitionsAssigned(Utils.mkSet(t1));
    }

    @Test
    public void shouldCloseActiveTasksThatAreAssignedToThisStreamThreadButAssignmentHasChangedBeforeCreatingNewTasks() throws Exception {
        final KStreamBuilder builder = new KStreamBuilder();
        builder.setApplicationId("appId");
        builder.stream(Pattern.compile("t.*")).to("out");
        final StreamsConfig config = new StreamsConfig(configProps());
        final MockClientSupplier clientSupplier = new MockClientSupplier();

        final Map<Collection<TopicPartition>, TestStreamTask> createdTasks = new HashMap<>();

        final StreamThread thread = new StreamThread(builder, config, clientSupplier, applicationId,
                                                     clientId, processId, new Metrics(), new MockTime(), new StreamsMetadataState(builder)) {
            @Override
            protected StreamTask createStreamTask(final TaskId id, final Collection<TopicPartition> partitions) {
                final ProcessorTopology topology = builder.build(id.topicGroupId);
                final TestStreamTask task = new TestStreamTask(id, "appId", partitions, topology, consumer, producer, restoreConsumer, config, stateDirectory);
                createdTasks.put(partitions, task);
                return task;
            }
        };

        final Map<TaskId, Set<TopicPartition>> activeTasks = new HashMap<>();
        final TopicPartition t1 = new TopicPartition("t1", 0);
        final Set<TopicPartition> task00Partitions = new HashSet<>();
        task00Partitions.add(t1);
        final TaskId taskId = new TaskId(0, 0);
        activeTasks.put(taskId, task00Partitions);

        thread.partitionAssignor(new StreamPartitionAssignor() {
            @Override
            Map<TaskId, Set<TopicPartition>> activeTasks() {
                return activeTasks;
            }
        });

        // should create task for id 0_0 with a single partition
        thread.rebalanceListener.onPartitionsRevoked(Collections.<TopicPartition>emptyList());
        thread.rebalanceListener.onPartitionsAssigned(task00Partitions);

        final TestStreamTask firstTask = createdTasks.get(task00Partitions);
        assertThat(firstTask.id(), is(taskId));

        // update assignment for the task 0_0 so it now has 2 partitions
        task00Partitions.add(new TopicPartition("t2", 0));
        thread.rebalanceListener.onPartitionsRevoked(Collections.<TopicPartition>emptyList());
        thread.rebalanceListener.onPartitionsAssigned(task00Partitions);

        // should close the first task as the assignment has changed
        assertTrue("task should have been closed as assignment has changed", firstTask.closed);
        assertTrue("tasks state manager should have been closed as assignment has changed", firstTask.closedStateManager);
        // should have created a new task for 00
        assertThat(createdTasks.get(task00Partitions).id(), is(taskId));
    }

    private void initPartitionGrouper(StreamsConfig config, StreamThread thread) {

        StreamPartitionAssignor partitionAssignor = new StreamPartitionAssignor();

        partitionAssignor.configure(config.getConsumerConfigs(thread, thread.applicationId, thread.clientId));

        Map<String, PartitionAssignor.Assignment> assignments =
                partitionAssignor.assign(metadata, Collections.singletonMap("client", subscription));

        partitionAssignor.onAssignment(assignments.get("client"));
    }

    public static class StateListenerStub implements StreamThread.StateListener {
        public int numChanges = 0;
        public StreamThread.State oldState = null;
        public StreamThread.State newState = null;

        @Override
        public void onChange(final StreamThread thread, final StreamThread.State newState, final StreamThread.State oldState) {
            this.numChanges++;
            if (this.newState != null) {
                if (this.newState != oldState) {
                    throw new RuntimeException("State mismatch " + oldState + " different from " + this.newState);
                }
            }
            this.oldState = oldState;
            this.newState = newState;
        }
    }
}


text:
module RailsTables::Sorting
  extend ActiveSupport::Concern

  included do
    class_attribute :initial_order
    extend ClassMethods
  end

  module ClassMethods
    # Gotta set these to fight against datatables' default ordering on first column
    def initial_ordering(orderings)
      self.initial_order = orderings
    end

  end

  # InstanceMethods
private
  # Check if table is sortable
  def sortable
    if params[:bUseDefaultSort] == 'true'
      true
    else
      self.columns.map(&:sortable)[params[:iSortCol_0].to_i]
    end
  end
  # Find column to search by and create a Squeel Order
  def sort
    if params[:bUseDefaultSort] == 'true' and self.initial_order.present?
      column = self.columns.select{|c|c.name == self.initial_order.keys.first.to_s}.first
      direction = self.initial_order.values.first.to_s == "asc" ? 1 : -1
    else
      column = self.columns[params[:iSortCol_0].to_i]
      direction = params[:sSortDir_0] == "asc" ? 1 : -1
    end
    if column.sortable
      Squeel::Nodes::KeyPath.new(column.column_source.to_s.split('.') << Squeel::Nodes::Order.new(Squeel::Nodes::Stub.new(column.method_name.to_s), direction))
    end
  end

end


text:
namespace core
{

struct context_t
{

};
typedef std::shared_ptr<context_t> context_pt;

}


text:
package jp.cafebabe.birthmarks.entities;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;

import jp.cafebabe.birthmarks.entities.Pair;
import org.junit.Test;

public class PairTest {
    private Pair<String> pair = new Pair<>("left", "right");

    @Test
    public void testBasic(){
        assertThat(pair.left(), is("left"));
        assertThat(pair.right(), is("right"));
        assertThat(pair, is(new Pair<>("left", "right")));

        assertThat(pair.toString(), is("<left, right>"));

        assertThat(pair, is(not("<left, right>")));
        assertThat(pair, is(not(new Pair<>("left2", "right"))));
        assertThat(pair, is(not(new Pair<>("left", "right2"))));
        assertThat(pair, is(not(nullValue())));

        assertThat(pair.hashCode(), is(new Pair<>("left", "right").hashCode()));
        assertThat(pair.hashCode(), is(not(new Pair<>("left2", "right2").hashCode())));
    }
}


text:
package com.alorma.github.ui.utils.uris;

import android.content.Context;
import android.net.Uri;

public class DefaultUriType extends UriType {
  @Override
  public String getPath(Context context, Uri uri) {
    return String.valueOf(uri);
  }
}