text:
package org.wso2.developerstudio.eclipse.gmf.esb.provider;

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

import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
import org.wso2.developerstudio.eclipse.gmf.esb.ArtifactType;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbServer;

/**
 * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.EsbServer} object.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public class EsbServerItemProvider
	extends EsbNodeItemProvider
	implements
		IEditingDomainItemProvider,
		IStructuredItemContentProvider,
		ITreeItemContentProvider,
		IItemLabelProvider,
		IItemPropertySource {
	/**
	 * This constructs an instance from a factory and a notifier.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public EsbServerItemProvider(AdapterFactory adapterFactory) {
		super(adapterFactory);
	}

	/**
	 * This returns the property descriptors for the adapted class.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */

	@Override
	public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
		if (itemPropertyDescriptors == null) {
			super.getPropertyDescriptors(object);

			addTypePropertyDescriptor(object);
		}
		return itemPropertyDescriptors;
	}

	/**
	 * This adds a property descriptor for the Type feature.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected void addTypePropertyDescriptor(Object object) {
		itemPropertyDescriptors.add
			(createItemPropertyDescriptor
				(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
				 getResourceLocator(),
				 getString("_UI_EsbServer_type_feature"),
				 getString("_UI_PropertyDescriptor_description", "_UI_EsbServer_type_feature", "_UI_EsbServer_type"),
				 EsbPackage.Literals.ESB_SERVER__TYPE,
				 true,
				 false,
				 false,
				 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
				 null,
				 null));
	}

	/**
	 * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
	 * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
	 * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */

	@Override
	public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
		if (childrenFeatures == null) {
			super.getChildrenFeatures(object);
			childrenFeatures.add(EsbPackage.Literals.ESB_SERVER__CHILDREN);
			childrenFeatures.add(EsbPackage.Literals.ESB_SERVER__MESSAGE_MEDIATOR);
		}
		return childrenFeatures;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */

	@Override
	protected EStructuralFeature getChildFeature(Object object, Object child) {
		// Check the type of the specified child object and return the proper feature to use for
		// adding (see {@link AddCommand}) it as a child.

		return super.getChildFeature(object, child);
	}

	/**
	 * This returns EsbServer.gif.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */

	@Override
	public Object getImage(Object object) {
		return overlayImage(object, getResourceLocator().getImage("full/obj16/EsbServer"));
	}

	/**
	 * This returns the label text for the adapted class.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */

	@Override
	public String getText(Object object) {
		ArtifactType labelValue = ((EsbServer)object).getType();
		String label = labelValue == null ? null : labelValue.toString();
		return label == null || label.length() == 0 ?
			getString("_UI_EsbServer_type") :
			getString("_UI_EsbServer_type") + " " + label;
	}

	/**
	 * This handles model notifications by calling {@link #updateChildren} to update any cached
	 * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */

	@Override
	public void notifyChanged(Notification notification) {
		updateChildren(notification);

		switch (notification.getFeatureID(EsbServer.class)) {
			case EsbPackage.ESB_SERVER__TYPE:
				fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
				return;
			case EsbPackage.ESB_SERVER__CHILDREN:
			case EsbPackage.ESB_SERVER__MESSAGE_MEDIATOR:
				fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
				return;
		}
		super.notifyChanged(notification);
	}

	/**
	 * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
	 * that can be created under this object.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */

	@Override
	protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
		super.collectNewChildDescriptors(newChildDescriptors, object);

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createCallMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createProxyService()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createMessageMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createDefaultEndPoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createAddressEndPoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createTemplateEndpoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createHTTPEndpoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createDropMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createFilterMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createMergeNode()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createLogMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createBAMMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createBeanMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createEJBMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createPropertyMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createEnrichMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createXSLTMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createSwitchMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createSequence()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createEventMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createEntitlementMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createEnqueueMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createClassMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createSpringMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createScriptMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createFaultMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createAggregateMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createRouterMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createCloneMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createIterateMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createCacheMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createXQueryMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createCalloutMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createRMSequenceMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createTransactionMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createOAuthMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createAutoscaleInMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createAutoscaleOutMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createHeaderMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createThrottleMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createCommandMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createDBLookupMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createDBReportMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createRuleMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createCallTemplateMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createLoopBackMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createRespondMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createSmooksMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createStoreMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createBuilderMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createPayloadFactoryMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createConditionalRouterMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createSendMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createParentEndPoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createFailoverEndPoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createWSDLEndPoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createLoadBalanceEndPoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createLocalEntry()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createSequences()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createURLRewriteMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createValidateMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createEndpointDiagram()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createNamedEndpoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createTemplate()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createTask()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createSynapseAPI()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createAPIResourceEndpoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createComplexEndpoints()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createAddressingEndpoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createRecipientListEndPoint()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createMessageStore()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createMessageProcessor()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createCloudConnector()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createCloudConnectorOperation()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createDataMapperMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__CHILDREN,
				 EsbFactory.eINSTANCE.createFastXSLTMediator()));

		newChildDescriptors.add
			(createChildParameter
				(EsbPackage.Literals.ESB_SERVER__MESSAGE_MEDIATOR,
				 EsbFactory.eINSTANCE.createMessageMediator()));
	}

	/**
	 * This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */

	@Override
	public String getCreateChildText(Object owner, Object feature, Object child, Collection<?> selection) {
		Object childFeature = feature;
		Object childObject = child;

		boolean qualify =
			childFeature == EsbPackage.Literals.ESB_SERVER__CHILDREN ||
			childFeature == EsbPackage.Literals.ESB_SERVER__MESSAGE_MEDIATOR;

		if (qualify) {
			return getString
				("_UI_CreateChild_text2",
				 new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) });
		}
		return super.getCreateChildText(owner, feature, child, selection);
	}

}


text:
package com.example.crudtester.provider;

import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.test.runner.AndroidJUnit4;

import com.example.crudtester.utils.CursorUtilities;
import com.example.crudtester.utils.DataUtilities;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;

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

/**
 * Test the content provider using the REPLACE conflict algorithm
 */
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ReplaceBasicCRUDProviderTest extends BaseBasicCRUDProviderTest {

    public ReplaceBasicCRUDProviderTest() {
        super();
    }

    @NonNull
    @Override
    protected String getTable() {
        return ReplaceContract.TABLE;
    }

    @NonNull
    @Override
    public Uri getUri() {
        return ReplaceContract.URI;
    }

    @NonNull
    @Override
    public String getUniqueColumn() {
        return ReplaceContract.Columns.DATA1;
    }

    @NonNull
    @Override
    public String getDistinctColumn() {
        return ReplaceContract.Columns.DATA2;
    }

    @Test
    @Override
    public void test01GetType() throws Exception {
        super.test01GetType();
    }

    @Test
    @Override
    public void test02BasicCrudOperations() {
        super.test02BasicCrudOperations();
    }

    @Test
    @Override
    public void test03BasicBulkCrudOperations() {
        super.test03BasicBulkCrudOperations();
    }

    @Test
    @Override
    public void test04QueryParameters() {
        super.test04QueryParameters();
    }

    /**
     * Verify insertion conflicts are replaced. Meaning if you insert the exact same data
     * the "id" will be different, but the contents identical.
     */
    @Test
    @Override
    public void test05InsertConflicts() {
        // Prep by inserting data
        ContentValues insertData = DataUtilities.insertUser1();
        Uri uri = providerTestRule.getResolver().insert(getUri(), insertData);
        assertThat(uri, is(notNullValue()));

        long id = ContentUris.parseId(uri);

        //noinspection ConstantConditions
        try (Cursor cursor = providerTestRule.getResolver().query(uri, null, null, null, null)) {
            assertThat(cursor, is(notNullValue()));
            CursorUtilities.validateCursor("Insert", cursor, insertData, id);
        }

        // Attempt to insert the data again, ignore very similar to rollback. Only
        // difference is whether or not an exception is thrown to indicate the conflict
        // for a single insert. In both cases null is returned for the uri.

        // Inserting same data again. Uri should be identical to original insert
        Uri conflictUri = providerTestRule.getResolver().insert(getUri(), insertData);
        assertThat(conflictUri, is(notNullValue()));
        assertThat(conflictUri, is(not(uri)));

        long conflictId = ContentUris.parseId(conflictUri);
        assertThat(conflictId, is(not(id)));

        // Verify the data is "unchanged" in the database except for the id. Must use new
        // URI since original insert no longer exists.
        //noinspection ConstantConditions
        try (Cursor cursor = providerTestRule.getResolver().query(conflictUri, null, null, null, null)) {
            assertThat(cursor, is(notNullValue()));
            CursorUtilities.validateCursor("Verify after ignore", cursor, insertData, conflictId);
        }
    }

    /**
     * Verify bulk insertion conflicts do not change the database and 0 is returned as the
     * number of rows altered which indicates the insert failed and was rolled back.
     *

     * This variation tests bulk inserting identical data.  100% conflicts
     */
    @Test
    @Override
    public void test06BulkInsertConflicts() {
        // Prep by inserting data
        ContentValues[] insertData = DataUtilities.insertBulkUsers();
        int rows = providerTestRule.getResolver().bulkInsert(getUri(), insertData);
        assertThat(rows, is(insertData.length));

        try (Cursor cursor = providerTestRule.getResolver().query(getUri(), null, null, null, getUniqueColumn())) {
            assertThat(cursor, is(notNullValue()));
            CursorUtilities.validateCursor("Bulk Insert", getUniqueColumn(), cursor, insertData);

            // Attempt to insert the data again.

            // Inserting same data again. Rows will be 2 to indicate 100% successful
            rows = providerTestRule.getResolver().bulkInsert(getUri(), insertData);
            assertThat(rows, is(insertData.length));

            // Verify the data is "unchanged" in the database
            try (Cursor conflictCursor = providerTestRule.getResolver().query(getUri(), null, null, null, getUniqueColumn())) {
                assertThat(conflictCursor, is(notNullValue()));
                //noinspection ConstantConditions
                CursorUtilities.ensureCursorsMatchExcludingId("Cursors match", cursor, conflictCursor);
            }
        }
    }

    /**
     * Verify bulk insertion conflicts change the database and 1is returned as the
     * number of rows altered which indicates the insert partially was ignored.
     *

     * This variation tests bulk inserting identical data, however only part of the data is
     * conflicted. All rows should be inserted and the original row should be replaced.
     */
    @Test
    @Override
    public void test07BulkInsertPartialConflicts() {
        // Prep by inserting data. This data wil conflict on 2nd row of bulk update
        ContentValues insertData = DataUtilities.insertUser2();
        Uri uri = providerTestRule.getResolver().insert(getUri(), insertData);
        assertThat(uri, is(notNullValue()));

        long id = ContentUris.parseId(uri);

        //noinspection ConstantConditions
        try (Cursor cursor = providerTestRule.getResolver().query(uri, null, null, null, null)) {
            assertThat(cursor, is(notNullValue()));
            CursorUtilities.validateCursor("Insert", cursor, insertData, id);
        }

        // Attempt to bulk insert data where the 2nd row conflicts

        // Rows will be match rows provided as all data inserted or replaced
        ContentValues[] bulkInsertData = DataUtilities.insertBulkUsers();
        int rows = providerTestRule.getResolver().bulkInsert(getUri(), bulkInsertData);
        assertThat(rows, is(bulkInsertData.length));

        // Verify the data is "changed". Ie all expected rows now exist in the db.
        try (Cursor cursor = providerTestRule.getResolver().query(getUri(), null, null, null, null)) {
            assertThat(cursor, is(notNullValue()));
            CursorUtilities.validateCursor("Verify after conflict", getUniqueColumn(), cursor, bulkInsertData);
        }

        // Also verify original row no longer exists, using the original id
        try (Cursor cursor = providerTestRule.getResolver().query(uri, null, null, null, null)) {
            assertThat(cursor, is(notNullValue()));
            //noinspection ConstantConditions
            assertThat(cursor.getCount(), is(0));
        }
    }

    /**
     * Verify update conflicts do not change the database and 2 is returned as the
     * number of rows altered which indicates the update was successful. However, because
     * the conflicted row was deleted, only one row remains in the database.
     *

     * To generate update conflict, attempt to update a "unique" column with data that
     * already exists.
     */
    @Test
    @Override
    public void test08UpdateConflicts() {
        // Prep by inserting data
        ContentValues[] insertData = DataUtilities.insertBulkUsers();
        int rows = providerTestRule.getResolver().bulkInsert(getUri(), insertData);
        assertThat(rows, is(insertData.length));

        try (Cursor cursor = providerTestRule.getResolver().query(getUri(), null, null, null, null)) {
            assertThat(cursor, is(notNullValue()));
            CursorUtilities.validateCursor("Bulk Insert", getUniqueColumn(), cursor, insertData);
        }

        // Attempt to update data to have same data on all rows.

        // Rows will be 2 to indicate all rows updated or replaced
        ContentValues updateData = DataUtilities.updateDataPossibleConflict();
        rows = providerTestRule.getResolver().update(getUri(), updateData, null, null);
        assertThat(rows, is(2));

        // Verify only the user1 now exists in the database as the conflicting row was replaced (ie
        // deleted to allow update).
        try (Cursor cursor = providerTestRule.getResolver().query(getUri(), null, null, null, null)) {
            assertThat(cursor, is(notNullValue()));
            //noinspection ConstantConditions
            assertThat(cursor.getCount(), is(1));
            CursorUtilities.validateCursor("Verify after conflict", getUniqueColumn(), cursor, new ContentValues[]{updateData});
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace BekoDesign\versioAPI\Contracts;

interface IWebhosting
{

}


text:
#ifndef WebIDBDatabaseCallbacks_h
#define WebIDBDatabaseCallbacks_h

#include "platform/WebCommon.h"
#include "platform/WebString.h"

namespace WebKit {

class WebIDBDatabaseCallbacks {
public:
    virtual ~WebIDBDatabaseCallbacks() { }

    virtual void onForcedClose() { WEBKIT_ASSERT_NOT_REACHED(); }
    virtual void onVersionChange(long long oldVersion, long long newVersion) { WEBKIT_ASSERT_NOT_REACHED(); }
    virtual void onVersionChange(const WebString& requestedVersion) { WEBKIT_ASSERT_NOT_REACHED(); }
};

} // namespace WebKit

#endif // WebIDBDatabaseCallbacks_h


text:
package eu.dnetlib.iis.wf.importer.content;

import eu.dnetlib.iis.common.java.io.JsonUtils;
import eu.dnetlib.iis.common.schemas.Identifier;
import eu.dnetlib.iis.importer.auxiliary.schemas.DocumentContentUrl;
import org.apache.avro.mapred.AvroKey;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static eu.dnetlib.iis.wf.importer.ImportWorkflowRuntimeParameters.IMPORT_FACADE_FACTORY_CLASS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;

/**
 * @author mhorst
 *
 */
@ExtendWith(MockitoExtension.class)
@SuppressWarnings({"rawtypes", "unchecked"})
public class ObjectStoreDocumentContentUrlImporterMapperTest {

    private final static String EXPECTED_OUTPUT_ROOT_LOCATION = "eu/dnetlib/iis/wf/importer/content/output/";

    @Mock
    private Context context;

    @Captor
    private ArgumentCaptor<AvroKey<DocumentContentUrl>> contentUrlCaptor;

    private ObjectStoreDocumentContentUrlImporterMapper mapper = new ObjectStoreDocumentContentUrlImporterMapper();

    // ------------------------------------- TESTS -----------------------------------

    @Test
    public void testSetupWithoutISLookupFacade() {
        // given
        Configuration conf = new Configuration();
        doReturn(conf).when(context).getConfiguration();

        // execute
        assertThrows(RuntimeException.class, () -> mapper.setup(context));
    }

    @Test
    public void testMapThrowingException() throws Exception {
        // given
        Configuration conf = new Configuration();
        conf.set(IMPORT_FACADE_FACTORY_CLASS,
                "eu.dnetlib.iis.wf.importer.content.ExceptionThrowingObjectStoreFacadeFactory");
        doReturn(conf).when(context).getConfiguration();
        mapper.setup(context);

        AvroKey<Identifier> key = new AvroKey<>(buildIdentifier("objectStoreId"));

        // execute
        assertThrows(IOException.class, () -> mapper.map(key, null, context));
    }

    @Test
    public void testMap() throws Exception {
        // given
        Configuration conf = new Configuration();
        conf.set(IMPORT_FACADE_FACTORY_CLASS,
                "eu.dnetlib.iis.wf.importer.content.MockObjectStoreFacadeFactory");
        doReturn(conf).when(context).getConfiguration();
        mapper.setup(context);

        AvroKey<Identifier> key = new AvroKey<>(buildIdentifier("objectStoreId"));

        // execute
        mapper.map(key, null, context);

        // assert
        int expectedCount = 5;
        verify(context, times(expectedCount)).write(contentUrlCaptor.capture(), any());
        List<DocumentContentUrl> expectedList = loadExpected();
        for (int i=0; i < expectedCount; i++) {
            assertEquals(expectedList.get(i), contentUrlCaptor.getAllValues().get(i).datum());
        }
    }

    // ------------------------------------- PRIVATE -----------------------------------

    private Identifier buildIdentifier(String id) {
        return Identifier.newBuilder().setId(id).build();
    }

    private List<DocumentContentUrl> loadExpected() {
        List<DocumentContentUrl> results = new ArrayList<>();
        results.addAll(loadExpected("document_content_url_html.json"));
        results.addAll(loadExpected("document_content_url_pdf.json"));
        results.addAll(loadExpected("document_content_url_pdf2.json"));
        results.addAll(loadExpected("document_content_url_wos.json"));
        results.addAll(loadExpected("document_content_url_xml.json"));
        return results;
    }

    private List<DocumentContentUrl> loadExpected(String fileName) {
        return JsonUtils.convertToList(EXPECTED_OUTPUT_ROOT_LOCATION + fileName,
                DocumentContentUrl.SCHEMA$, DocumentContentUrl.class);
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="Student.cs" company="Telerik">
//     Telerik (c).
// </copyright>
//-----------------------------------------------------------------------
namespace Methods
{
    using Contracts;

    /// <summary>
    /// Represent template for a student
    /// </summary>
    public class Student : IStudent
    {
        /// <summary>
        /// Creates an instance of a student.
        /// </summary>
        public Student()
        {
            // Default constructor
        }

        /// <summary>
        /// Creates an instance of a student.
        /// </summary>
        /// <param name="firstName"> Represents the first name of a student. </param>
        /// <param name="lastName"> Represents the last name of a student. </param>
        /// <param name="age"> Represents the age of a student. </param>
        public Student(string firstName, string lastName, uint age)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Age = age;
        }

        /// <summary>
        /// Student's first name.
        /// </summary>
        public string FirstName { get; set; }

        /// <summary>
        /// Student's last name.
        /// </summary>
        public string LastName { get; set; }

        /// <summary>
        /// Student's age.
        /// </summary>
        public uint Age { get; set; }

        /// <summary>
        /// Student's other info.
        /// </summary>
        public string OtherInfo { get; set; }

        /// <summary>
        /// Finds if student is bigger than other student.
        /// </summary>
        /// <param name="other"> Represents a student. </param>
        /// <returns> Bolean representing if a student is bigger than other student. </returns>
        public bool IsOlderThan(IStudent other)
        {
            var isOlder = this.Age > other.Age;
            return isOlder;
        }
    }
}


text:
module Shoestrap
  module Rails
    class Engine < ::Rails::Engine
      initializer 'shoestrap-rails.assets.precompile' do |app|
        app.config.assets.paths << root.join('assets', 'stylesheets').to_s
      end
    end
  end
end


text:
function results = gab_task_fmri_segment(args)

defaults = spm('defaults','fmri');

if isfield(args,'gmFiles') && ~isempty(args.gmFiles)
    defaults.preproc.output.GM=args.gmFiles;
end
if isfield(args,'wmFiles') && ~isempty(args.wmFiles)
    defaults.preproc.output.WM=args.wmFiles;
end
if isfield(args,'csfFiles') && ~isempty(args.csfFiles)
    defaults.preproc.output.CSF=args.csfFiles;
end

if ~isfield(args,'mask') || isempty(args.mask)
    args.mask={''};
end

matlabbatch{1}.spm.spatial.preproc= struct(...
    'data',{{args.source}},...
    'output',defaults.preproc.output,...
    'opts',rmfield(defaults.preproc,'output'));

matlabbatch{1}.spm.spatial.preproc.opts.msk=args.mask;

jid=cfg_util('initjob',{matlabbatch});
cfg_util('run',jid);

results = 'done';


text:
var keystone = require('keystone');
var async    = require('async');
var _        = require('lodash');
var moment   = require('moment');
var NewsPost = keystone.list('NewsPost');
var Movie    = keystone.list('Movie');

exports = module.exports = function (req, res) {

	var view   = new keystone.View(req, res);
	var locals = res.locals;

	// Init locals
	locals.section = 'index';
	locals.movies  = [];
	locals.news    = [];

	function getMonthDateRange(year, month) {
    var startDate = moment([year, month]);
    var endDate = moment(startDate).endOf('month');
    // make sure to call toDate() for plain JavaScript date type
    return { start: startDate, end: endDate };
	}

	// Load the news and movies
	view.on('init', function (next) {
		var dateRange = getMonthDateRange(moment().year(), moment().month());
		var q = Movie.model.find()
			.where('state', 'published')
			// .where({
			// 	state: 'published',
			// 	inDate: {"$gte": dateRange.start, "$lt": dateRange.end}
			// })
			.sort('-inDate')
			.limit(360)
			.populate('author categories');

		q.exec(function (err, results) {
			locals.movies = _.chunk(results, 3);
			next(err);
		});
	});

	view.on('init', function (next) {
		var q = NewsPost.paginate({
			page    : req.query.page || 1,
			perPage : 6,
			maxPages: 10,
		})
		.where('state', 'published')
		.sort('-publishedDate')
		.populate('author');

		q.exec(function (err, results) {
			locals.news = results;
			next(err);
		});
	});
	view.render('index');
}


text:
using FluentBoilerplate.Providers;
using FluentBoilerplate.Providers.WCF;
using FluentBoilerplate.Runtime.Providers;
using System;
using System.ServiceModel;
using TechTalk.SpecFlow;
using FluentAssertions;

namespace FluentBoilerplate.Tests.PublicContract.Providers.WCF
{
    [Binding]
    public class CanConnectThroughWcfSteps
    {
        private readonly TestContext testContext;

        public CanConnectThroughWcfSteps(TestContext testContext)
        {
            this.testContext = testContext;
        }

        [Given(@"there is a hosted WCF service using named pipes")]
        public void GivenThereIsAHostedWCFServiceUsingNamedPipes()
        {
            var host =  new ServiceHost(typeof(TestWcfService));
            host.Open();
            this.testContext.HostedWcfService = host;
        }

        [Given(@"I have a type provider for the named pipe endpoint")]
        public void GivenIHaveATypeProviderForTheNamedPipeEndpoint()
        {
            var service = new WcfService<ITestWcfService>("PipeClient");
            var provider = new WcfConnectionProvider(new [] { service });
            this.testContext.Access = new TypeAccessProvider(PermissionsProvider.Default, new[] { provider });
        }

        [Given(@"there is a hosted WCF service using TCP")]
        public void GivenThereIsAHostedWCFServiceUsingTCP()
        {
            this.testContext.HostedWcfService = new ServiceHost(typeof(TestWcfService));
        }

        [Given(@"I have a type provider for the TCP endpoint")]
        public void GivenIHaveATypeProviderForTheTCPEndpoint()
        {
            var service = new WcfService<ITestWcfService>("TcpClient");
            var provider = new WcfConnectionProvider(new[] { service });
            this.testContext.Access = new TypeAccessProvider(PermissionsProvider.Default, new[] { provider });
        }

        [When(@"I ask for the WCF service contract type through the type provider")]
        public void WhenIAskForTheWCFServiceContractTypeThroughTheTypeProvider()
        {
            try
            {
                var response = this.testContext.Access.TryAccess<ITestWcfService, bool>(this.testContext.Identity, service => service.GetTrue());
                this.testContext.WcfCallWasSuccessful = response.IsSuccess;
            }
            catch (Exception ex)
            {
                this.testContext.WcfCallWasSuccessful = false;
                this.testContext.UnhandledException = ex;
            }
        }

        [Then(@"the WCF connection should be successful")]
        public void ThenTheWCFConnectionShouldBeSuccessful()
        {
            this.testContext.UnhandledException.Should().BeNull("because no exception should have been thrown");
            this.testContext.WcfCallWasSuccessful.Should().BeTrue("because the connection should have been successful");
        }
    }
}


text:
package us.grahn.trojanow.logic;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

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

import us.grahn.trojanow.data.Type;
import us.grahn.trojanow.presentation.home.HomeScreenActivity;

/**
 * A simplified API for reading sensor data.
 *
 * @us.grahn.class     SensorAPI
 * @us.grahn.component SensorAPI
 * @us.grahn.tier      Logic
 */
public class SensorAPI {

    private static SensorManager getManager() {
        return (SensorManager) HomeScreenActivity.getAppContext().getSystemService(Context.SENSOR_SERVICE);
    }

    /**
     * Get a list of the valid sensors.
     *
     * @return the valid sensors
     */
    public static List<Type> getSensors() {

        List<Type> sensors = new ArrayList<Type>();
        SensorManager manager = getManager();

        for(Type type : Type.values()) {
            Sensor sensor = manager.getDefaultSensor(type.getSensor());
            if(sensor != null) sensors.add(type);
        }

        return sensors;
    }

    /**
     * Reads the specified sensor.
     *
     * @param type the sensor to read
     */
    public static void read(Type type, final SensorEventListener listener) {

        Sensor sensor = getManager().getDefaultSensor(type.getSensor());

        getManager().registerListener(new SensorEventListener() {

            @Override
            public void onSensorChanged(final SensorEvent event) {
                listener.onSensorChanged(event);
                getManager().unregisterListener(this);
            }

            @Override
            public void onAccuracyChanged(final Sensor sensor, final int accuracy) {

            }

        }, sensor, SensorManager.SENSOR_DELAY_UI);
    }
}


text:
package org.alien4cloud.tosca.catalog.index;

import javax.inject.Inject;

import org.alien4cloud.tosca.model.Csar;
import org.springframework.stereotype.Component;

import alien4cloud.security.AuthorizationUtil;
import alien4cloud.security.model.Role;

@Component
public class CsarAuthorizationFilter implements ICsarAuthorizationFilter {
    @Inject
    private ITopologyCatalogService catalogService;
    @Inject
    private IToscaTypeSearchService searchService;

    @Override
    public void checkWriteAccess(Csar csar) {
        // if this csar has node types, check the COMPONENTS_MANAGER Role
        if (searchService.hasTypes(csar.getName(), csar.getVersion())) {
            AuthorizationUtil.checkHasOneRoleIn(Role.COMPONENTS_MANAGER);
        }
        // if the csar is bound to a topology, check the ARCHITECT Role
        if (catalogService.exists(csar.getId())) {
            AuthorizationUtil.checkHasOneRoleIn(Role.ARCHITECT);
        }
    }

    @Override
    public void checkReadAccess(Csar csar) {
        // Component browser has access to Csar
        AuthorizationUtil.checkHasOneRoleIn(Role.COMPONENTS_BROWSER);
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Diagram Struktur Organisasi</title>
<link href="<?=$this->config->item('base_url');?>assets/css/tree.css" rel="stylesheet" type="text/css" />

<?php
echo $data;
?>


text:
package com.example.yuyu.slideactivity.demo;

import android.graphics.Color;

import com.example.yuyu.slideactivity.base.BaseActivity;

/**
 * Created by yuyu on 2015/10/26.
 */
public class Activity2 extends BaseActivity {

    @Override
    protected int setBackgroundColor() {
        return Color.YELLOW;
    }

    @Override
    protected String setButtonText() {
        return "第二个Activity";
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>de.intarsys.security.smartcard.pcsc</title>
<meta name="date" content="2013-07-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package de.intarsys.security.smartcard.pcsc

This is the high level PC/SC wrapper.

See: Description

Interface Summary

Interface
Description

INativePCSCLib

The abstraction of an external library implementing the PC/SC API.

IPCSCCardReader

The iconified PC/SC card reader terminal.

IPCSCConnection

The iconified PC/SC connection.

IPCSCContext

The iconified PC/SC context.

IPCSCContextFactory

A factory for an IPCSCContext.

PCSCStatusMonitor.IStatusListener

Class Summary

Class
Description

CommonPCSCContext

A common implementation for IPCSCContext.

CommonPCSCLib

A common implementation for a native library, installed in the
 NativePCSCContextFactory.

Connect

EmptyContext

A dummy context.

ListReaders

MockPCSCCardReader

MockPCSCCardReaderState

MockPCSCContext

MockPCSCSystem

MonitorReaders

NativePCSCContextFactory

An IPCSCContextFactory wrapping native libraries.

NativePCSCLib

The default INativePCSCLib implementation.

PCSCAttribute

PC/SC attribute related constants.

PCSCCardReader

The default IPCSCCardReader implementation.

PCSCCardReaderState

The PC/SC model level card reader state.

PCSCConnection

The default IPCSCConnection implementation.

PCSCContext

The default IPCSCContext implementation.

PCSCContextFactory

A singleton access for the IPCSCContextFactory on this system.

PCSCMultiContext

A special context that can elegate to multiple libraries.

PCSCStatusMonitor

Monitor the state of an IPCSCCardReader.

PCSCTools

Some tools for handling PC/SC.

Exception Summary

Exception
Description

PCSCException

An exceptional condition in the PC/SC handling

PCSCReset

Signal a PCSC level card reset.

Package de.intarsys.security.smartcard.pcsc Description

This is the high level PC/SC wrapper.

 Based on intarsys native-c all relevant functions and structures for accessing PC/SC on Windows
 and pcsc-lite based platforms are provided.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
""" module to implement a python mode for the ped editor does colorizing of code """
from ped_core import editor_common
from ped_dialog.message_dialog import message
import re
from pygments.lexers import PythonLexer
from pygments.token import Token
from ped_core.mode import Tokens, render
from ped_core import keytab

def get_tabs(editor):
    """ return the tab stops for this type of file """
    return [4,8]

def detect_mode(editor):
    """ hook called to detect if this mode should be used for a file, returns True if it should be used, False otherwise """
    workfile = editor.getWorkfile()
    if re.search(r"(\.py$)|(\.py\:\(r.*\)$)",workfile.getFilename()):
        return True
    elif workfile.getLine(0).startswith("#!/usr/bin/python"):
        return True
    elif workfile.getLine(0).startswith("#!/usr/bin/env python"):
        return True
    else:
        return False

def handle(editor,ch):
    """ hook called for each keystroke, can be used for auto-indent or auto-complete """
    if ch == 10:
        old_left = editor.left
        old_line = editor.line
        editor.cr()
        wf = editor.getWorkfile()
        line = editor.line + editor.vpos
        above = wf.getLine(line-1)
        match = re.match(r"^\s*(if|for|while|else|elif|try|except|def|class|finally|with)\W",above)
        if match:
            stop = wf.get_tab_stop(match.start(1))
            editor.insert(stop*' ')
        else:
            match = re.match(r"^\s*(\S+)",above)
            if match:
                editor.insert(match.start(1)*' ')
        if editor.left != old_left or editor.line != old_line:
            editor.invalidate_screen()
        return 0

    return ch

def finish(editor):
    """ this editor is going away do anything required to clean up """
    wf = editor.getWorkfile()
    if wf:
        if hasattr(wf,"python_mode_tokens"):
            del wf.python_mode_tokens
            wf.python_mode_tokens = None
            delattr(wf,"python_mode_tokens")

def redraw(editor):
    """ redraw the colorization based on the current token set, regenerate it if needed """
    workfile = editor.getWorkfile()

    if hasattr(workfile,"python_mode_tokens"):
        tokens = workfile.python_mode_tokens
    else:
        tokens = Tokens()
        setattr(workfile,"python_mode_tokens",tokens)

    if not tokens:
        return False

    if not tokens.getTokens() or tokens.getModref() != workfile.getModref():
        tokens.refresh(editor,PythonLexer())
        return False

    render(editor, tokens,
    [Token.Operator.Word,Token.Name.Builtin.Pseudo,Token.Keyword,Token.Keyword.Namespace],
    [Token.Text,Token.String,Token.Literal.String,Token.Literal.String.Single,Token.Literal.String.Double,Token.Literal.String.Doc],
    [Token.Comment,Token.Comment.Hashbang,Token.Comment.Multiline,Token.Comment.Single])

    return True

def name():
    """ hook to return this mode's human readable name """
    return "python_mode"


text:
package org.elasticsearch.index.search;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.Term;
import org.apache.lucene.queries.ExtendedCommonTermsQuery;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.MultiPhraseQuery;
import org.apache.lucene.search.MultiTermQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.lucene.search.MultiPhrasePrefixQuery;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.support.QueryParsers;

import java.io.IOException;

public class MatchQuery {

    public static enum Type implements Writeable<Type> {
        /**
         * The text is analyzed and terms are added to a boolean query.
         */
        BOOLEAN(0),
        /**
         * The text is analyzed and used as a phrase query.
         */
        PHRASE(1),
        /**
         * The text is analyzed and used in a phrase query, with the last term acting as a prefix.
         */
        PHRASE_PREFIX(2);

        private final int ordinal;

        private static final Type PROTOTYPE = BOOLEAN;

        private Type(int ordinal) {
            this.ordinal = ordinal;
        }

        @Override
        public Type readFrom(StreamInput in) throws IOException {
            int ord = in.readVInt();
            for (Type type : Type.values()) {
                if (type.ordinal == ord) {
                    return type;
                }
            }
            throw new ElasticsearchException("unknown serialized type [" + ord + "]");
        }

        public static Type readTypeFrom(StreamInput in) throws IOException {
            return PROTOTYPE.readFrom(in);
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            out.writeVInt(this.ordinal);
        }
    }

    public static enum ZeroTermsQuery implements Writeable<ZeroTermsQuery> {
        NONE(0),
        ALL(1);

        private final int ordinal;

        private static final ZeroTermsQuery PROTOTYPE = NONE;

        private ZeroTermsQuery(int ordinal) {
            this.ordinal = ordinal;
        }

        @Override
        public ZeroTermsQuery readFrom(StreamInput in) throws IOException {
            int ord = in.readVInt();
            for (ZeroTermsQuery zeroTermsQuery : ZeroTermsQuery.values()) {
                if (zeroTermsQuery.ordinal == ord) {
                    return zeroTermsQuery;
                }
            }
            throw new ElasticsearchException("unknown serialized type [" + ord + "]");
        }

        public static ZeroTermsQuery readZeroTermsQueryFrom(StreamInput in) throws IOException {
            return PROTOTYPE.readFrom(in);
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            out.writeVInt(this.ordinal);
        }
    }

    /** the default phrase slop */
    public static final int DEFAULT_PHRASE_SLOP = 0;

    /** the default leniency setting */
    public static final boolean DEFAULT_LENIENCY = false;

    /** the default zero terms query */
    public static final ZeroTermsQuery DEFAULT_ZERO_TERMS_QUERY = ZeroTermsQuery.NONE;

    protected final QueryShardContext context;

    protected String analyzer;

    protected BooleanClause.Occur occur = BooleanClause.Occur.SHOULD;

    protected boolean enablePositionIncrements = true;

    protected int phraseSlop = DEFAULT_PHRASE_SLOP;

    protected Fuzziness fuzziness = null;

    protected int fuzzyPrefixLength = FuzzyQuery.defaultPrefixLength;

    protected int maxExpansions = FuzzyQuery.defaultMaxExpansions;

    protected boolean transpositions = FuzzyQuery.defaultTranspositions;

    protected MultiTermQuery.RewriteMethod fuzzyRewriteMethod;

    protected boolean lenient = DEFAULT_LENIENCY;

    protected ZeroTermsQuery zeroTermsQuery = DEFAULT_ZERO_TERMS_QUERY;

    protected Float commonTermsCutoff = null;

    public MatchQuery(QueryShardContext context) {
        this.context = context;
    }

    public void setAnalyzer(String analyzer) {
        this.analyzer = analyzer;
    }

    public void setOccur(BooleanClause.Occur occur) {
        this.occur = occur;
    }

    public void setCommonTermsCutoff(Float cutoff) {
        this.commonTermsCutoff = cutoff;
    }

    public void setEnablePositionIncrements(boolean enablePositionIncrements) {
        this.enablePositionIncrements = enablePositionIncrements;
    }

    public void setPhraseSlop(int phraseSlop) {
        this.phraseSlop = phraseSlop;
    }

    public void setFuzziness(Fuzziness fuzziness) {
        this.fuzziness = fuzziness;
    }

    public void setFuzzyPrefixLength(int fuzzyPrefixLength) {
        this.fuzzyPrefixLength = fuzzyPrefixLength;
    }

    public void setMaxExpansions(int maxExpansions) {
        this.maxExpansions = maxExpansions;
    }

    public void setTranspositions(boolean transpositions) {
        this.transpositions = transpositions;
    }

    public void setFuzzyRewriteMethod(MultiTermQuery.RewriteMethod fuzzyRewriteMethod) {
        this.fuzzyRewriteMethod = fuzzyRewriteMethod;
    }

    public void setLenient(boolean lenient) {
        this.lenient = lenient;
    }

    public void setZeroTermsQuery(ZeroTermsQuery zeroTermsQuery) {
        this.zeroTermsQuery = zeroTermsQuery;
    }

    protected Analyzer getAnalyzer(MappedFieldType fieldType) {
        if (this.analyzer == null) {
            if (fieldType != null) {
                return context.getSearchAnalyzer(fieldType);
            }
            return context.getMapperService().searchAnalyzer();
        } else {
            Analyzer analyzer = context.getMapperService().analysisService().analyzer(this.analyzer);
            if (analyzer == null) {
                throw new IllegalArgumentException("No analyzer found for [" + this.analyzer + "]");
            }
            return analyzer;
        }
    }

    public Query parse(Type type, String fieldName, Object value) throws IOException {
        final String field;
        MappedFieldType fieldType = context.fieldMapper(fieldName);
        if (fieldType != null) {
            field = fieldType.name();
        } else {
            field = fieldName;
        }

        /*
         * If the user forced an analyzer we really don't care if they are
         * searching a type that wants term queries to be used with query string
         * because the QueryBuilder will take care of it. If they haven't forced
         * an analyzer then types like NumberFieldType that want terms with
         * query string will blow up because their analyzer isn't capable of
         * passing through QueryBuilder.
         */
        boolean noForcedAnalyzer = this.analyzer == null;
        if (fieldType != null && fieldType.useTermQueryWithQueryString() && noForcedAnalyzer) {
            return termQuery(fieldType, value);
        }

        Analyzer analyzer = getAnalyzer(fieldType);
        assert analyzer != null;
        MatchQueryBuilder builder = new MatchQueryBuilder(analyzer, fieldType);
        builder.setEnablePositionIncrements(this.enablePositionIncrements);

        Query query = null;
        switch (type) {
            case BOOLEAN:
                if (commonTermsCutoff == null) {
                    query = builder.createBooleanQuery(field, value.toString(), occur);
                } else {
                    query = builder.createCommonTermsQuery(field, value.toString(), occur, occur, commonTermsCutoff, fieldType);
                }
                break;
            case PHRASE:
                query = builder.createPhraseQuery(field, value.toString(), phraseSlop);
                break;
            case PHRASE_PREFIX:
                query = builder.createPhrasePrefixQuery(field, value.toString(), phraseSlop, maxExpansions);
                break;
            default:
                throw new IllegalStateException("No type found for [" + type + "]");
        }

        if (query == null) {
            return zeroTermsQuery();
        } else {
            return query;
        }
    }

    /**
     * Creates a TermQuery-like-query for MappedFieldTypes that don't support
     * QueryBuilder which is very string-ish. Just delegates to the
     * MappedFieldType for MatchQuery but gets more complex for blended queries.
     */
    protected Query termQuery(MappedFieldType fieldType, Object value) {
        return termQuery(fieldType, value, lenient);
    }

    protected final Query termQuery(MappedFieldType fieldType, Object value, boolean lenient) {
        try {
            return fieldType.termQuery(value, context);
        } catch (RuntimeException e) {
            if (lenient) {
                return null;
            }
            throw e;
        }
    }

    protected Query zeroTermsQuery() {
        return zeroTermsQuery == DEFAULT_ZERO_TERMS_QUERY ? Queries.newMatchNoDocsQuery() : Queries.newMatchAllQuery();
    }

    private class MatchQueryBuilder extends QueryBuilder {

        private final MappedFieldType mapper;

        /**
         * Creates a new QueryBuilder using the given analyzer.
         */
        public MatchQueryBuilder(Analyzer analyzer, @Nullable MappedFieldType mapper) {
            super(analyzer);
            this.mapper = mapper;
        }

        @Override
        protected Query newTermQuery(Term term) {
            return blendTermQuery(term, mapper);
        }

        public Query createPhrasePrefixQuery(String field, String queryText, int phraseSlop, int maxExpansions) {
            final Query query = createFieldQuery(getAnalyzer(), Occur.MUST, field, queryText, true, phraseSlop);
            final MultiPhrasePrefixQuery prefixQuery = new MultiPhrasePrefixQuery();
            prefixQuery.setMaxExpansions(maxExpansions);
            prefixQuery.setSlop(phraseSlop);
            if (query instanceof PhraseQuery) {
                PhraseQuery pq = (PhraseQuery)query;
                Term[] terms = pq.getTerms();
                int[] positions = pq.getPositions();
                for (int i = 0; i < terms.length; i++) {
                    prefixQuery.add(new Term[] {terms[i]}, positions[i]);
                }
                return prefixQuery;
            } else if (query instanceof MultiPhraseQuery) {
                MultiPhraseQuery pq = (MultiPhraseQuery)query;
                Term[][] terms = pq.getTermArrays();
                int[] positions = pq.getPositions();
                for (int i = 0; i < terms.length; i++) {
                    prefixQuery.add(terms[i], positions[i]);
                }
                return prefixQuery;
            } else if (query instanceof TermQuery) {
                prefixQuery.add(((TermQuery) query).getTerm());
                return prefixQuery;
            }
            return query;
        }

        public Query createCommonTermsQuery(String field, String queryText, Occur highFreqOccur, Occur lowFreqOccur, float maxTermFrequency, MappedFieldType fieldType) {
            Query booleanQuery = createBooleanQuery(field, queryText, lowFreqOccur);
            if (booleanQuery != null && booleanQuery instanceof BooleanQuery) {
                BooleanQuery bq = (BooleanQuery) booleanQuery;
                ExtendedCommonTermsQuery query = new ExtendedCommonTermsQuery(highFreqOccur, lowFreqOccur, maxTermFrequency, ((BooleanQuery)booleanQuery).isCoordDisabled(), fieldType);
                for (BooleanClause clause : bq.clauses()) {
                    if (!(clause.getQuery() instanceof TermQuery)) {
                        return booleanQuery;
                    }
                    query.add(((TermQuery) clause.getQuery()).getTerm());
                }
                return query;
            }
            return booleanQuery;

        }
    }

    protected Query blendTermQuery(Term term, MappedFieldType fieldType) {
        if (fuzziness != null) {
            if (fieldType != null) {
                try {
                    Query query = fieldType.fuzzyQuery(term.text(), fuzziness, fuzzyPrefixLength, maxExpansions, transpositions);
                    if (query instanceof FuzzyQuery) {
                        QueryParsers.setRewriteMethod((FuzzyQuery) query, fuzzyRewriteMethod);
                    }
                    return query;
                } catch (RuntimeException e) {
                    return new TermQuery(term);
                    // See long comment below about why we're lenient here.
                }
            }
            int edits = fuzziness.asDistance(term.text());
            FuzzyQuery query = new FuzzyQuery(term, edits, fuzzyPrefixLength, maxExpansions, transpositions);
            QueryParsers.setRewriteMethod(query, fuzzyRewriteMethod);
            return query;
        }
        if (fieldType != null) {
            /*
             * Its a bit weird to default to lenient here but its the backwards
             * compatible. It makes some sense when you think about what we are
             * doing here: at this point the user has forced an analyzer and
             * passed some string to the match query. We cut it up using the
             * analyzer and then tried to cram whatever we get into the field.
             * lenient=true here means that we try the terms in the query and on
             * the off chance that they are actually valid terms then we
             * actually try them. lenient=false would mean that we blow up the
             * query if they aren't valid terms. "valid" in this context means
             * "parses properly to something of the type being queried." So "1"
             * is a valid number, etc.
             *
             * We use the text form here because we we've received the term from
             * an analyzer that cut some string into text.
             */
            Query query = termQuery(fieldType, term.bytes(), true);
            if (query != null) {
                return query;
            }
        }
        return new TermQuery(term);
    }

}


text:
/*
 *  Fragile error test for (some) API error messages
 */

/*===
*** test_1a (duk_safe_call)
==> rc=1, result='RangeError: invalid stack index -3'
*** test_1b (duk_safe_call)
==> rc=1, result='RangeError: invalid stack index -3'
*** test_1c (duk_safe_call)
==> rc=1, result='RangeError: invalid stack index -1'
*** test_2a (duk_safe_call)
TypeError: null required, found none (stack index -3)
top: 1
test__undefined ok
TypeError: null required, found undefined (stack index -3)
TypeError: boolean required, found undefined (stack index -3)
TypeError: number required, found undefined (stack index -3)
TypeError: string required, found undefined (stack index -3)
TypeError: buffer required, found undefined (stack index -3)
TypeError: pointer required, found undefined (stack index -3)
TypeError: nativefunction required, found undefined (stack index -3)
top: 1
TypeError: undefined required, found null (stack index -3)
test__null ok
TypeError: boolean required, found null (stack index -3)
TypeError: number required, found null (stack index -3)
TypeError: string required, found null (stack index -3)
TypeError: buffer required, found null (stack index -3)
TypeError: pointer required, found null (stack index -3)
TypeError: nativefunction required, found null (stack index -3)
top: 1
TypeError: undefined required, found true (stack index -3)
TypeError: null required, found true (stack index -3)
test__boolean ok
TypeError: number required, found true (stack index -3)
TypeError: string required, found true (stack index -3)
TypeError: buffer required, found true (stack index -3)
TypeError: pointer required, found true (stack index -3)
TypeError: nativefunction required, found true (stack index -3)
top: 1
TypeError: undefined required, found false (stack index -3)
TypeError: null required, found false (stack index -3)
test__boolean ok
TypeError: number required, found false (stack index -3)
TypeError: string required, found false (stack index -3)
TypeError: buffer required, found false (stack index -3)
TypeError: pointer required, found false (stack index -3)
TypeError: nativefunction required, found false (stack index -3)
top: 1
TypeError: undefined required, found 123 (stack index -3)
TypeError: null required, found 123 (stack index -3)
TypeError: boolean required, found 123 (stack index -3)
test__number ok
TypeError: string required, found 123 (stack index -3)
TypeError: buffer required, found 123 (stack index -3)
TypeError: pointer required, found 123 (stack index -3)
TypeError: nativefunction required, found 123 (stack index -3)
top: 1
TypeError: undefined required, found 'foo' (stack index -3)
TypeError: null required, found 'foo' (stack index -3)
TypeError: boolean required, found 'foo' (stack index -3)
TypeError: number required, found 'foo' (stack index -3)
test__string ok
TypeError: buffer required, found 'foo' (stack index -3)
TypeError: pointer required, found 'foo' (stack index -3)
TypeError: nativefunction required, found 'foo' (stack index -3)
top: 1
TypeError: undefined required, found [buffer:16] (stack index -3)
TypeError: null required, found [buffer:16] (stack index -3)
TypeError: boolean required, found [buffer:16] (stack index -3)
TypeError: number required, found [buffer:16] (stack index -3)
TypeError: string required, found [buffer:16] (stack index -3)
test__buffer ok
TypeError: pointer required, found [buffer:16] (stack index -3)
TypeError: nativefunction required, found [buffer:16] (stack index -3)
top: 1
TypeError: undefined required, found (null) (stack index -3)
TypeError: null required, found (null) (stack index -3)
TypeError: boolean required, found (null) (stack index -3)
TypeError: number required, found (null) (stack index -3)
TypeError: string required, found (null) (stack index -3)
TypeError: buffer required, found (null) (stack index -3)
test__pointer ok
TypeError: nativefunction required, found (null) (stack index -3)
top: 1
TypeError: undefined required, found (PTR) (stack index -3)
TypeError: null required, found (PTR) (stack index -3)
TypeError: boolean required, found (PTR) (stack index -3)
TypeError: number required, found (PTR) (stack index -3)
TypeError: string required, found (PTR) (stack index -3)
TypeError: buffer required, found (PTR) (stack index -3)
test__pointer ok
TypeError: nativefunction required, found (PTR) (stack index -3)
top: 1
TypeError: undefined required, found [object Object] (stack index -3)
TypeError: null required, found [object Object] (stack index -3)
TypeError: boolean required, found [object Object] (stack index -3)
TypeError: number required, found [object Object] (stack index -3)
TypeError: string required, found [object Object] (stack index -3)
TypeError: buffer required, found [object Object] (stack index -3)
TypeError: pointer required, found [object Object] (stack index -3)
TypeError: nativefunction required, found [object Object] (stack index -3)
top: 1
TypeError: undefined required, found [object Array] (stack index -3)
TypeError: null required, found [object Array] (stack index -3)
TypeError: boolean required, found [object Array] (stack index -3)
TypeError: number required, found [object Array] (stack index -3)
TypeError: string required, found [object Array] (stack index -3)
TypeError: buffer required, found [object Array] (stack index -3)
TypeError: pointer required, found [object Array] (stack index -3)
TypeError: nativefunction required, found [object Array] (stack index -3)
top: 1
TypeError: undefined required, found [object Function] (stack index -3)
TypeError: null required, found [object Function] (stack index -3)
TypeError: boolean required, found [object Function] (stack index -3)
TypeError: number required, found [object Function] (stack index -3)
TypeError: string required, found [object Function] (stack index -3)
TypeError: buffer required, found [object Function] (stack index -3)
TypeError: pointer required, found [object Function] (stack index -3)
test__c_function ok
top: 1
TypeError: undefined required, found function LFUNC() { [lightfunc code] } (stack index -3)
TypeError: null required, found function LFUNC() { [lightfunc code] } (stack index -3)
TypeError: boolean required, found function LFUNC() { [lightfunc code] } (stack index -3)
TypeError: number required, found function LFUNC() { [lightfunc code] } (stack index -3)
TypeError: string required, found function LFUNC() { [lightfunc code] } (stack index -3)
TypeError: buffer required, found function LFUNC() { [lightfunc code] } (stack index -3)
TypeError: pointer required, found function LFUNC() { [lightfunc code] } (stack index -3)
TypeError: nativefunction required, found function LFUNC() { [lightfunc code] } (stack index -3)
top: 1
TypeError: undefined required, found [object Function] (stack index -3)
TypeError: null required, found [object Function] (stack index -3)
TypeError: boolean required, found [object Function] (stack index -3)
TypeError: number required, found [object Function] (stack index -3)
TypeError: string required, found [object Function] (stack index -3)
TypeError: buffer required, found [object Function] (stack index -3)
TypeError: pointer required, found [object Function] (stack index -3)
TypeError: nativefunction required, found [object Function] (stack index -3)
top: 1
TypeError: undefined required, found [object Thread] (stack index -3)
TypeError: null required, found [object Thread] (stack index -3)
TypeError: boolean required, found [object Thread] (stack index -3)
TypeError: number required, found [object Thread] (stack index -3)
TypeError: string required, found [object Thread] (stack index -3)
TypeError: buffer required, found [object Thread] (stack index -3)
TypeError: pointer required, found [object Thread] (stack index -3)
TypeError: nativefunction required, found [object Thread] (stack index -3)
done
==> rc=0, result='undefined'
===*/

static duk_ret_t test_1a(duk_context *ctx, void *udata) {
	(void) udata;

	duk_require_normalize_index(ctx, -3);
	return 0;
}

static duk_ret_t test_1b(duk_context *ctx, void *udata) {
	(void) udata;

	duk_require_valid_index(ctx, -3);
	return 0;
}

static duk_ret_t test_1c(duk_context *ctx, void *udata) {
	(void) udata;

	duk_require_top_index(ctx);
	return 0;
}

static duk_ret_t dummy_func(duk_context *ctx) {
	(void) ctx;

	return 0;
}

static duk_ret_t test__undefined(duk_context *ctx, void *udata) {
	(void) udata;

	duk_require_undefined(ctx, -3);
	return 0;
}
static duk_ret_t test__null(duk_context *ctx, void *udata) {
	(void) udata;

	duk_require_null(ctx, -3);
	return 0;
}
static duk_ret_t test__boolean(duk_context *ctx, void *udata) {
	(void) udata;

	(void) duk_require_boolean(ctx, -3);
	return 0;
}
static duk_ret_t test__number(duk_context *ctx, void *udata) {
	(void) udata;

	(void) duk_require_number(ctx, -3);
	return 0;
}
static duk_ret_t test__string(duk_context *ctx, void *udata) {
	(void) udata;

	(void) duk_require_string(ctx, -3);
	return 0;
}
static duk_ret_t test__buffer(duk_context *ctx, void *udata) {
	duk_size_t sz;

	(void) udata;

	(void) duk_require_buffer(ctx, -3, &sz);
	return 0;
}
static duk_ret_t test__pointer(duk_context *ctx, void *udata) {
	(void) udata;

	(void) duk_require_pointer(ctx, -3);
	return 0;
}
static duk_ret_t test__c_function(duk_context *ctx, void *udata) {
	(void) udata;

	(void) duk_require_c_function(ctx, -3);
	return 0;
}

#define TEST_REQUIRE(fn) do { \
		duk_set_top(ctx, 1); \
		duk_dup(ctx, 0); \
		duk_push_null(ctx); \
		duk_push_null(ctx); \
		rc = duk_safe_call(ctx, (fn), NULL, 3, 3); \
		if (rc != 0) { \
			duk_eval_string(ctx, "(function (v) { print(String(v).replace(/\\(0x.*?\\)/g, '(PTR)')" \
			                     ".replace(/light_[0-9a-fA-F_]+/g, 'LFUNC')); })"); \
			duk_dup(ctx, -4); \
			duk_call(ctx, 1); \
		} else { \
			printf("%s ok\n", #fn); \
		} \
		duk_set_top(ctx, 1); \
	} while (0)

static void test__require_calls(duk_context *ctx) {
	duk_int_t rc;

	printf("top: %ld\n", (long) duk_get_top(ctx));

	TEST_REQUIRE(test__undefined);
	TEST_REQUIRE(test__null);
	TEST_REQUIRE(test__boolean);
	TEST_REQUIRE(test__number);
	TEST_REQUIRE(test__string);
	TEST_REQUIRE(test__buffer);
	TEST_REQUIRE(test__pointer);
	TEST_REQUIRE(test__c_function);
	/* No duk_require_object(), duk_require_array(), duk_require_c_lightfunc(), etc. */
}

static duk_ret_t test_2a(duk_context *ctx, void *udata) {
	(void) udata;

	/* Test first with nothing on stack index -3. */
	duk_safe_call(ctx, test__null, NULL, 0, 1); printf("%s\n", duk_safe_to_string(ctx, 0));
	duk_pop(ctx);

	duk_set_top(ctx, 0); duk_push_undefined(ctx); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_null(ctx); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_true(ctx); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_false(ctx); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_number(ctx, 123.0); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_string(ctx, "foo\x00" "bar"); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_fixed_buffer(ctx, 16); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_pointer(ctx, NULL); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_pointer(ctx, (void *) 0xdeadbeef); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_object(ctx); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_array(ctx); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_c_function(ctx, dummy_func, 0); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_c_lightfunc(ctx, dummy_func, 0, 0, 0); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_eval_string(ctx, "(function dummy(){})"); test__require_calls(ctx);
	duk_set_top(ctx, 0); duk_push_thread(ctx); test__require_calls(ctx);

	printf("done\n");
	return 0;
}

void test(duk_context *ctx) {
	TEST_SAFE_CALL(test_1a);
	TEST_SAFE_CALL(test_1b);
	TEST_SAFE_CALL(test_1c);
	TEST_SAFE_CALL(test_2a);
}


text:
const chai = require('chai');
const chaiHttp = require('chai-http');

chai.use(chaiHttp);
const expect = chai.expect;

// Set up env vars
require('dotenv').config();

const { TEST_JWT } = require('./auth_bootstrap');
const server = require('../index');

describe('Accounts', () => {
  let app;
  let db;
  let pins;
  let accounts;
  before(() => server.connect(5001).then((res) => {
    app = res.app;
    db = res.db;
    pins = db.collection('pins');
    accounts = db.collection('accounts');
    return db;
  }));

  // reset db
  afterEach(() => pins.deleteMany());
  afterEach(() => accounts.deleteMany());

  describe('GET Accounts', () => {
    it('should create a new user account if none exists', () =>
      chai.request(app)
        .get('/api/accounts/currentuser')
        .set('Authorization', `Bearer ${TEST_JWT}`)
        .then((res) => {
          expect(res).to.have.status(200);
          const account = res.body;
          expect(account.createDate).to.be.not.empty;
          expect(account.username).to.equal('TestUser');
          expect(account.numSeeds).to.equal(0);
          expect(account.numPins).to.equal(0);
        })
        .catch((err) => {
          throw err;
        }));
    it('should find an existing user account', () =>
      accounts.insertOne({
        username: 'TestUser',
        auth0Id: process.env.TEST_USER_SUB,
        createDate: new Date(),
        numSeeds: 10,
        numPins: 5,
      }).then(res => res.ops[0]).then(acct =>
        chai.request(app)
          .get('/api/accounts/currentuser')
          .set('Authorization', `Bearer ${TEST_JWT}`)
          .then((res) => {
            expect(res).to.have.status(200);
            const account = res.body;
            expect(new Date(account.createDate)).to.eql(acct.createDate);
            expect(account.username).to.equal(acct.username);
            expect(account.numSeeds).to.equal(acct.numSeeds);
            expect(account.numPins).to.equal(acct.numPins);
          })
      ).catch((err) => {
        throw err;
      }));
  });
});


text:
namespace imp {
namespace cu {

//------------------------------------------------------------------------------
VariationalStereo::VariationalStereo(Parameters::Ptr params)
{
  if (params)
  {
    params_ = params;
  }
  else
  {
    params_ = std::make_shared<Parameters>();
  }

  ctf_.reset(new StereoCtFWarping(params_));
}

//------------------------------------------------------------------------------
VariationalStereo::~VariationalStereo()
{ ; }

//------------------------------------------------------------------------------
void VariationalStereo::addImage(const ImageGpu32fC1::Ptr& image)
{
  ctf_->addImage(image);
}

//------------------------------------------------------------------------------
void VariationalStereo::solve()
{
  ctf_->solve();
}

//------------------------------------------------------------------------------
ImageGpu32fC1::Ptr VariationalStereo::computePrimalEnergy(size_t level)
{
  return ctf_->computePrimalEnergy(level);
}

//------------------------------------------------------------------------------
VariationalStereo::ImageGpu32fC1::Ptr VariationalStereo::getDisparities(size_t level)
{
  return ctf_->getDisparities(level);
}

//------------------------------------------------------------------------------
VariationalStereo::ImageGpu32fC1::Ptr VariationalStereo::getOcclusion(size_t level)
{
  return ctf_->getOcclusion(level);
}

} // namespace cu
} // namespace imp


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

namespace Assets.Scripts
{
    /// <summary>
    /// Detects if the game is sent to background
    /// </summary>
    public class BackgroundDetector : MonoBehaviour
    {
        public GameObject menuObject;
        public GameObject player;

        /// <inheritdoc>
        private void OnApplicationFocus(bool focus)
        {
            if (focus)
            {
                Debug.Log("Game brought back to foreground.");
            }
            else
            {
                Debug.Log("Game sent to background.");
                menuObject.SetActive(true);
                WalkingScript WalkingController = player.GetComponent<WalkingScript>();
                WalkingController.enabled = false;
                menuObject.transform.parent = null;
            }
        }
    }
}


text:
         Home
            Blog
            Events
            Event Request


text:
<?php

namespace Croogo\Taxonomy\Test\TestCase\View\Helper;

use Cake\Controller\Controller;
use Croogo\TestSuite\CroogoTestCase;
use Taxonomy\View\Helper\TaxonomiesHelper;

class TheTaxonomyTestController extends Controller
{

    public $uses = null;
}

class TaxonomiesHelperTest extends CroogoTestCase
{

/**
 * setUp
 */
    public function setUp()
    {
        parent::setUp();
        $this->ComponentRegistry = new ComponentRegistry();

        $request = $this->getMock('Request');
        $response = $this->getMock('Response');
        $this->View = new View(new TheTaxonomyTestController($request, $response));
        $this->Taxonomies = new TaxonomiesHelper($this->View);
    }

/**
 * tearDown
 */
    public function tearDown()
    {
        unset($this->View);
        unset($this->Taxonomies);
    }

/**
 * Test [vocabulary] shortcode
 */
    public function testVocabularyShortcode()
    {
        $content = '[vocabulary:categories type="blog"]';
        $this->View->viewVars['vocabulariesForLayout']['categories'] = [
            'Vocabulary' => [
                'id' => 1,
                'title' => 'Categories',
                'alias' => 'categories',
            ],
            'threaded' => [],
        ];
        Croogo::dispatchEvent('Helper.Layout.beforeFilter', $this->View, ['content' => &$content]);
        $this->assertContains('vocabulary-1', $content);
        $this->assertContains('class="vocabulary"', $content);
    }
}


text:
class ServerUpload < ActiveRecord::Base
  belongs_to :server
  belongs_to :file_upload

  validates_presence_of :server_id, :file_upload_id
  validates_uniqueness_of :file_upload_id, scope: :server_id

  after_commit -> { broadcast_replace_to file_upload, target: "file_upload_#{file_upload.id}_server_#{server_id}", partial: 'server_uploads/server_upload', locals: { server_upload: self } }, on: %i[create update]

  def status
    return 'Upload complete' if uploaded_at
    return 'Upload started' if started_at

    'Waiting to upload'
  end
end


text:
import sys, os

import pgq, pgq.producer
import skytools, skytools._pyquoting

from bootstrap import HBaseBootstrap
from HBaseConsumer import HBaseConsumer

ini = "hbrep.ini"

command_usage = """
%prog [options] inifile command [tablenames]

commands:
  play          Run event consumer to update specified tables with hbase.
  bootstrap     Bootstrap specified tables args into hbase.
  install       Setup the pgq queue, and install trigger on each table.
  uninstall     Remove the triggers from each specified table.
"""

#def main(*args, **kwargs):
#    script = HBaseConsumer(service_name, [ini] + self.table_names)
#    script.start

class HBaseReplic(skytools.DBScript):
  def __init__(self, service_name, args):
    try:
      self.run_script = 0

      # This will process any options eg -k -v -d
      skytools.DBScript.__init__(self, service_name, args)

      self.config_file = self.args[0]

      if len(self.args) < 2:
        self.print_usage()
        print "need command"
        sys.exit(0)
      cmd = self.args[1]

      if not cmd in ["play","bootstrap","install", "uninstall"]:
        self.print_usage()
        print "unknown command"
        sys.exit(0)

      if cmd == "play":
        self.run_script = HBaseConsumer(service_name, self.config_file)
      elif cmd == "bootstrap":
          self.run_script = HBaseBootstrap(service_name, [self.config_file] + args[2:])
      #elif cmd == "install":
      #  self.work = self.do_install
      #elif cmd == "uninstall":
      #  self.work = self.do_uninstall

    except Exception, e:
      sys.exit(e)

  def print_usage(self):
    print "Usage: " + command_usage

  def init_optparse(self, parser=None):
    p = skytools.DBScript.init_optparse(self, parser)
    p.set_usage(command_usage.strip())
    return p

  def start(self):
    if self.run_script:
      self.run_script.start()
    else:
      skytools.DBScript.start(self)

  def startup(self):
    # make sure the script loops only once.
    self.set_single_loop(1)

  def do_install(self):
    try:
      queue_name = self.cf.get("pgq_queue_name")
      consumer = self.job_name

      self.log.info('Creating queue: %s' % queue_name)
      self.exec_sql("select pgq.create_queue(%s)", [queue_name])

      self.log.info('Registering consumer %s on queue %s' % (consumer, queue_name))
      self.exec_sql("select pgq.register_consumer(%s, %s)", [queue_name, consumer])

      for table_name in self.table_names:
        self.log.info('Creating trigger hbase_replic on table %s' % (table_name))
        q = """
        CREATE TRIGGER hbase_replic
          AFTER INSERT OR UPDATE OR DELETE
          ON %s
          FOR EACH ROW
          EXECUTE PROCEDURE pgq.logutriga('%s')"""
        self.exec_sql(q % (table_name, queue_name), [])
    except Exception, e:
      sys.exit(e)

  def do_uninstall(self):
    try:
      queue_name = self.cf.get("pgq_queue_name")
      consumer = "HBaseReplic"

      #self.log.info('Unregistering consumer %s on queue %s' % (consumer, queue_name))
      #self.exec_sql("select pgq.unregister_consumer(%s, %s)", [queue_name, consumer])

      for table_name in self.table_names:
        self.log.info('Dropping trigger hbase_replic on table %s' % (table_name))
        q = "DROP TRIGGER hbase_replic ON %s" % table_name
        self.exec_sql(q, [])

    except Exception, e:
      sys.exit(e)

  def exec_sql(self, q, args):
    self.log.debug(q)
    db = self.get_database('postgresql_db')
    curs = db.cursor()
    curs.execute(q, args)
    db.commit()

if __name__ == '__main__':
  script = HBaseReplic("HBaseReplic",sys.argv[1:])
  script.start()


text:
<?php

return array(
    'service_manager' => array(
        'shared' => array(
            'speckcatalog_option_form'          => false,
            'speckcatalog_choice_form'          => false,
            'speckcatalog_product_form'         => false,
            'speckcatalog_uom_form'             => false,
            'speckcatalog_image_form'           => false,
            'speckcatalog_spec_form'            => false,
            'speckcatalog_availability_form'    => false,
            'speckcatalog_product_uom_form'     => false,
            'speckcatalog_builder_product_form' => false,
            'speckcatalog_image_mapper'         => false,
        ),
        'invokables' => array(
            'speckcatalog_product_service'          => 'SpeckCatalog\Service\Product',
            'speckcatalog_company_service'          => 'SpeckCatalog\Service\Company',
            'speckcatalog_option_service'           => 'SpeckCatalog\Service\Option',
            'speckcatalog_choice_service'           => 'SpeckCatalog\Service\Choice',
            'speckcatalog_product_uom_service'      => 'SpeckCatalog\Service\ProductUom',
            'speckcatalog_uom_service'              => 'SpeckCatalog\Service\Uom',
            'speckcatalog_document_service'         => 'SpeckCatalog\Service\Document',
            'speckcatalog_builder_product_service'  => 'SpeckCatalog\Service\Builder',
            'speckcatalog_availability_service'     => 'SpeckCatalog\Service\Availability',
            'speckcatalog_spec_service'             => 'SpeckCatalog\Service\Spec',
            'speckcatalog_sites_service'            => 'SpeckCatalog\Service\Sites',
            'speckcatalog_form_service'             => 'SpeckCatalog\Service\FormService',
            'speckcatalog_configure_buy_service'    => 'SpeckCatalog\Service\ConfigureBuy',

            'speckcatalog_option_form'              => 'SpeckCatalog\Form\Option',
            'speckcatalog_choice_form'              => 'SpeckCatalog\Form\Choice',
            'speckcatalog_uom_form'                 => 'SpeckCatalog\Form\Uom',
            'speckcatalog_company_form'             => 'SpeckCatalog\Form\Company',
            'speckcatalog_category_form'            => 'SpeckCatalog\Form\Category',
            'speckcatalog_spec_form'                => 'SpeckCatalog\Form\Spec',
            'speckcatalog_image_form'               => 'SpeckCatalog\Form\Image',
            'speckcatalog_document_form'            => 'SpeckCatalog\Form\Document',
            'speckcatalog_builder_product_form'     => 'SpeckCatalog\Form\Builder',

            'speckcatalog_spec_form_filter'            => 'SpeckCatalog\Filter\Spec',
            'speckcatalog_document_form_filter'        => 'SpeckCatalog\Filter\Document',
            'speckcatalog_product_form_filter'         => 'SpeckCatalog\Filter\Product',
            'speckcatalog_product_uom_form_filter'     => 'SpeckCatalog\Filter\ProductUom',
            'speckcatalog_option_form_filter'          => 'SpeckCatalog\Filter\Option',
            'speckcatalog_choice_form_filter'          => 'SpeckCatalog\Filter\Choice',
            'speckcatalog_category_form_filter'        => 'SpeckCatalog\Filter\Category',
            'speckcatalog_availability_form_filter'    => 'SpeckCatalog\Filter\Availability',
            'speckcatalog_builder_product_form_filter' => 'SpeckCatalog\Filter\Builder',

            'speckcatalog_product_mapper'           => 'SpeckCatalog\Mapper\Product',
            'speckcatalog_builder_product_mapper'   => 'SpeckCatalog\Mapper\Builder',
            'speckcatalog_category_mapper'          => 'SpeckCatalog\Mapper\Category',
            'speckcatalog_option_mapper'            => 'SpeckCatalog\Mapper\Option',
            'speckcatalog_choice_mapper'            => 'SpeckCatalog\Mapper\Choice',
            'speckcatalog_product_uom_mapper'       => 'SpeckCatalog\Mapper\ProductUom',
            'speckcatalog_image_mapper'             => 'SpeckCatalog\Mapper\Image',
            'speckcatalog_document_mapper'          => 'SpeckCatalog\Mapper\Document',
            'speckcatalog_uom_mapper'               => 'SpeckCatalog\Mapper\Uom',
            'speckcatalog_availability_mapper'      => 'SpeckCatalog\Mapper\Availability',
            'speckcatalog_spec_mapper'              => 'SpeckCatalog\Mapper\Spec',
            'speckcatalog_sites_mapper'             => 'SpeckCatalog\Mapper\Sites',
            'speckcatalog_feature_mapper'           => 'SpeckCatalog\Mapper\Feature',
            'speckcatalog_company_mapper'           => 'SpeckCatalog\Mapper\Company',
        ),
    ),
);


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<license-lookup
    xmlns="https://source.jasig.org/schemas/maven-notice-plugin/license-lookup"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://source.jasig.org/schemas/maven-notice-plugin/license-lookup https://source.jasig.org/schemas/maven-notice-plugin/license-lookup/license-lookup-v1.0.xsd">

    <artifact>
        <groupId>jaxen</groupId>
        <artifactId>jaxen</artifactId>
        <license>The BSD 3-Clause License</license>
    </artifact>
</license-lookup>


text:
package org.kj.pxe.protocol.impl;

import java.io.DataOutputStream;
import java.io.IOException;

import org.kj.pxe.protocol.VendorSuboption;

/**
 * Represents the End suboption in Dhcp option 43. Contains only a single
 * constant value.
 *
 * @author Kinjal
 *
 */
class PxeEndSuboption implements VendorSuboption {

	/**
	 * Writes this suboption as bytes to a stream. The only value that is
	 * written is the tag, which is a single byte.
	 *
	 * @param stream
	 *            the stream to write to
	 * @throws IOException
	 *             if there is an error writing to stream
	 */
	@Override
	public void writeToStream(DataOutputStream stream) throws IOException {
		stream.writeByte(VendorSuboptionTag.END.getValue());
	}

	/**
	 * Returns the length, which is always 0 since this suboption has no data.
	 *
	 * @return the length, which is 0
	 */
	@Override
	public short getLen() {
		return 0;
	}

	/**
	 * Returns the tag for this suboption.
	 *
	 * @return the tag
	 */
	@Override
	public short getTag() {
		return (short) VendorSuboptionTag.END.getValue();
	}
}


text:
<?php

namespace Incenteev\TranslationCheckerBundle\Tests\DependencyInjection;

use Incenteev\TranslationCheckerBundle\DependencyInjection\IncenteevTranslationCheckerExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class IncenteevTranslationCheckerExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ContainerBuilder
     */
    private $containerBuilder;

    protected function setUp()
    {
        $this->containerBuilder = new ContainerBuilder();
        $this->containerBuilder->setParameter('kernel.bundles', array(
            'IncenteevTranslationCheckerBundle' => 'Incenteev\TranslationCheckerBundle\IncenteevTranslationCheckerBundle',
            'FrameworkBundle' => 'Symfony\Bundle\FrameworkBundle\FrameworkBundle',
        ));
    }

    public function testDefaultPaths()
    {
        $extension = new IncenteevTranslationCheckerExtension();

        $extension->load(array(), $this->containerBuilder);

        $this->assertParameter(array('%kernel.root_dir%/Resources/views'), 'incenteev_translation_checker.extractor.symfony.paths');
    }

    public function testBundlePaths()
    {
        $extension = new IncenteevTranslationCheckerExtension();

        $config = array('extraction' => array('bundles' => array('IncenteevTranslationCheckerBundle')));

        $extension->load(array($config), $this->containerBuilder);

        $expectedPaths = array(
            dirname(dirname(__DIR__)).'/Resources/views',
            '%kernel.root_dir%/Resources/IncenteevTranslationCheckerBundle/views',
            '%kernel.root_dir%/Resources/views',
        );

        $this->assertParameter($expectedPaths, 'incenteev_translation_checker.extractor.symfony.paths');
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The bundle TwigBundle is not registered in the kernel.
     */
    public function testNotRegisteredBundle()
    {
        $extension = new IncenteevTranslationCheckerExtension();

        $config = array('extraction' => array('bundles' => array('TwigBundle')));

        $extension->load(array($config), $this->containerBuilder);
    }

    /**
     * @param mixed  $value
     * @param string $key
     */
    private function assertParameter($value, $key)
    {
        $this->assertEquals($value, $this->containerBuilder->getParameter($key), sprintf('%s parameter is correct', $key));
    }
}


text:
class CreateJodelPosts < ActiveRecord::Migration
  def change
    create_table :jodel_posts do |t|
      t.string :post_id
      t.datetime :created_at
      t.datetime :updated_at
      t.string :message
      t.integer :vote_count
      t.string :color
      t.string :image_url
      t.string :thumbnail_url

      t.timestamps null: false
      t.references :jodel_city, index: true, foreign_key: true

    end

    add_index :jodel_posts, :post_id, unique: true
    add_index :jodel_posts, [:jodel_city_id, :vote_count]

  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/bg_for_touch" android:state_pressed="true" />
    <item android:drawable="@color/bg_for_touch" android:state_focused="true" />
    <item android:drawable="@color/white" />
</selector>