text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.search.documents.indexes;

import com.azure.core.exception.HttpResponseException;
import com.azure.core.http.policy.HttpPipelinePolicy;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.core.util.CoreUtils;
import com.azure.search.documents.SearchTestBase;
import com.azure.search.documents.indexes.models.FieldMapping;
import com.azure.search.documents.indexes.models.IndexerExecutionResult;
import com.azure.search.documents.indexes.models.IndexerExecutionStatus;
import com.azure.search.documents.indexes.models.IndexerStatus;
import com.azure.search.documents.indexes.models.IndexingParameters;
import com.azure.search.documents.indexes.models.IndexingSchedule;
import com.azure.search.documents.indexes.models.InputFieldMappingEntry;
import com.azure.search.documents.indexes.models.OcrSkill;
import com.azure.search.documents.indexes.models.OutputFieldMappingEntry;
import com.azure.search.documents.indexes.models.SearchField;
import com.azure.search.documents.indexes.models.SearchFieldDataType;
import com.azure.search.documents.indexes.models.SearchIndex;
import com.azure.search.documents.indexes.models.SearchIndexer;
import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection;
import com.azure.search.documents.indexes.models.SearchIndexerLimits;
import com.azure.search.documents.indexes.models.SearchIndexerSkill;
import com.azure.search.documents.indexes.models.SearchIndexerSkillset;
import com.azure.search.documents.indexes.models.SearchIndexerStatus;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.jupiter.api.Test;

import java.net.HttpURLConnection;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import static com.azure.search.documents.TestHelpers.assertHttpResponseException;
import static com.azure.search.documents.TestHelpers.assertObjectEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;

public class IndexersManagementSyncTests extends SearchTestBase {
    private static final String TARGET_INDEX_NAME = "indexforindexers";
    private static final HttpPipelinePolicy MOCK_STATUS_PIPELINE_POLICY = (context, next) -> {
        String url = context.getHttpRequest().getUrl().toString();
        String separator = url.contains("?") ? "&" : "?";
        context.getHttpRequest()
            .setUrl(url + separator + "mock_status=inProgress");
        return next.process();
    };

    private final List<String> dataSourcesToDelete = new ArrayList<>();
    private final List<String> indexersToDelete = new ArrayList<>();
    private final List<String> indexesToDelete = new ArrayList<>();
    private final List<String> skillsetsToDelete = new ArrayList<>();

    private SearchIndexerClient searchIndexerClient;
    private SearchIndexClient searchIndexClient;

    private String createDataSource() {
        SearchIndexerDataSourceConnection dataSource = createBlobDataSource();
        searchIndexerClient.createOrUpdateDataSourceConnection(dataSource);

        dataSourcesToDelete.add(dataSource.getName());

        return dataSource.getName();
    }

    private String createIndex() {
        SearchIndex index = createTestIndexForLiveDatasource();
        searchIndexClient.createIndex(index);
        indexesToDelete.add(index.getName());

        return index.getName();
    }

    private SearchIndexer createTestDataSourceAndIndexer() {
        // Create the indexer object
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());
        searchIndexerClient.createIndexer(indexer);
        indexersToDelete.add(indexer.getName());

        return indexer;
    }

    /**
     * Creates the index and indexer in the search service and then retrieves the indexer and validates it
     *
     * @param indexer the indexer to be created
     */
    private void createAndValidateIndexer(SearchIndexer indexer) {
        // create this indexer in the service
        SearchIndexer indexerResponse = searchIndexerClient.createIndexer(indexer);
        indexersToDelete.add(indexerResponse.getName());

        // verify the returned updated indexer is as expected
        setSameStartTime(indexer, indexerResponse);
        assertObjectEquals(indexer, indexerResponse, true, "etag");
    }

    @Override
    protected void beforeTest() {
        super.beforeTest();
        searchIndexerClient = getSearchIndexerClientBuilder().buildClient();
        searchIndexClient = getSearchIndexClientBuilder().buildClient();
    }

    @Override
    protected void afterTest() {
        super.afterTest();

        for (String skillset : skillsetsToDelete) {
            searchIndexerClient.deleteSkillset(skillset);
        }

        for (String dataSource : dataSourcesToDelete) {
            searchIndexerClient.deleteDataSourceConnection(dataSource);
        }

        for (String indexer : indexersToDelete) {
            searchIndexerClient.deleteIndexer(indexer);
        }

        for (String index : indexesToDelete) {
            searchIndexClient.deleteIndex(index);
        }
    }

    @Test
    public void createIndexerReturnsCorrectDefinition() {
        SearchIndexer expectedIndexer = createBaseTestIndexerObject(createIndex(), createDataSource())
            .setIsDisabled(true)
            .setParameters(new IndexingParameters()
                .setBatchSize(50)
                .setMaxFailedItems(10)
                .setMaxFailedItemsPerBatch(10));

        SearchIndexer actualIndexer = searchIndexerClient.createIndexer(expectedIndexer);
        indexersToDelete.add(actualIndexer.getName());

        setSameStartTime(expectedIndexer, actualIndexer);
        assertObjectEquals(expectedIndexer, actualIndexer, true, "etag");
    }

    @Test
    public void canCreateAndListIndexers() {
        String indexName = createIndex();
        String dataSourceName = createDataSource();

        // Create two indexers
        SearchIndexer indexer1 = createBaseTestIndexerObject("a" + testResourceNamer.randomName("indexer", 32),
            indexName, dataSourceName);
        SearchIndexer indexer2 = createBaseTestIndexerObject("b" + testResourceNamer.randomName("indexer", 32),
            indexName, dataSourceName);

        searchIndexerClient.createIndexer(indexer1);
        indexersToDelete.add(indexer1.getName());
        searchIndexerClient.createIndexer(indexer2);
        indexersToDelete.add(indexer2.getName());

        Iterator<SearchIndexer> indexers = searchIndexerClient.listIndexers().iterator();

        SearchIndexer returnedIndexer = indexers.next();
        assertObjectEquals(indexer1, returnedIndexer, true, "etag");
        returnedIndexer = indexers.next();
        assertObjectEquals(indexer2, returnedIndexer, true, "etag");
        assertFalse(indexers.hasNext());
    }

    @Test
    public void canCreateAndListIndexerNames() {
        String indexName = createIndex();
        String dataSourceName = createDataSource();

        SearchIndexer indexer1 = createBaseTestIndexerObject("a" + testResourceNamer.randomName("indexer", 32),
            indexName, dataSourceName);
        SearchIndexer indexer2 = createBaseTestIndexerObject("b" + testResourceNamer.randomName("indexer", 32),
            indexName, dataSourceName);
        searchIndexerClient.createIndexer(indexer1);
        indexersToDelete.add(indexer1.getName());
        searchIndexerClient.createIndexer(indexer2);
        indexersToDelete.add(indexer2.getName());

        Iterator<String> indexersRes = searchIndexerClient.listIndexerNames(Context.NONE)
            .iterator();

        String actualIndexer = indexersRes.next();
        assertNotNull(actualIndexer);
        assertEquals(indexer1.getName(), actualIndexer);

        actualIndexer = indexersRes.next();
        assertNotNull(actualIndexer);
        assertEquals(indexer2.getName(), actualIndexer);

        assertFalse(indexersRes.hasNext());
    }

    @Test
    public void createIndexerFailsWithUsefulMessageOnUserError() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), "thisdatasourcedoesnotexist");

        assertHttpResponseException(
            () -> searchIndexerClient.createIndexer(indexer),
            HttpURLConnection.HTTP_BAD_REQUEST,
            "This indexer refers to a data source 'thisdatasourcedoesnotexist' that doesn't exist");
    }

    @Test
    public void canResetIndexerAndGetIndexerStatus() {
        SearchIndexer indexer = createTestDataSourceAndIndexer();

        searchIndexerClient.resetIndexer(indexer.getName());
        SearchIndexerStatus indexerStatus = searchIndexerClient.getIndexerStatus(indexer.getName());
        assertEquals(IndexerStatus.RUNNING, indexerStatus.getStatus());
        assertEquals(IndexerExecutionStatus.RESET, indexerStatus.getLastResult().getStatus());
    }

    @Test
    public void canResetIndexerAndGetIndexerStatusWithResponse() {
        SearchIndexer indexer = createTestDataSourceAndIndexer();

        searchIndexerClient.resetIndexerWithResponse(indexer.getName(), Context.NONE);
        SearchIndexerStatus indexerStatusResponse = searchIndexerClient.getIndexerStatusWithResponse(indexer.getName(),
            Context.NONE).getValue();
        assertEquals(IndexerStatus.RUNNING, indexerStatusResponse.getStatus());
        assertEquals(IndexerExecutionStatus.RESET, indexerStatusResponse.getLastResult().getStatus());
    }

    @Test
    public void canRunIndexer() {
        SearchIndexer indexer = createTestDataSourceAndIndexer();
        searchIndexerClient.runIndexer(indexer.getName());

        SearchIndexerStatus indexerExecutionInfo = searchIndexerClient.getIndexerStatus(indexer.getName());
        assertEquals(IndexerStatus.RUNNING, indexerExecutionInfo.getStatus());
    }

    @Test
    public void canRunIndexerWithResponse() {
        SearchIndexer indexer = createTestDataSourceAndIndexer();
        Response<Void> response = searchIndexerClient.runIndexerWithResponse(indexer.getName(), Context.NONE);
        SearchIndexerStatus indexerExecutionInfo = searchIndexerClient.getIndexerStatus(indexer.getName());

        assertEquals(HttpURLConnection.HTTP_ACCEPTED, response.getStatusCode());
        assertEquals(IndexerStatus.RUNNING, indexerExecutionInfo.getStatus());
    }

    @Test
    public void canRunIndexerAndGetIndexerStatus() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());

        // When an indexer is created, the execution info may not be available immediately. Hence, a
        // pipeline policy that injects a "mock_status" query string is added to the client, which results in service
        // returning a well-known mock response
        SearchIndexerClient mockStatusClient = getSearchIndexerClientBuilder(MOCK_STATUS_PIPELINE_POLICY).buildClient();

        mockStatusClient.createIndexer(indexer);
        indexersToDelete.add(indexer.getName());

        SearchIndexerStatus indexerExecutionInfo = mockStatusClient.getIndexerStatus(indexer.getName());
        assertEquals(IndexerStatus.RUNNING, indexerExecutionInfo.getStatus());

        Response<Void> indexerRunResponse = mockStatusClient.runIndexerWithResponse(indexer.getName(),
            Context.NONE);
        assertEquals(HttpResponseStatus.ACCEPTED.code(), indexerRunResponse.getStatusCode());

        indexerExecutionInfo = mockStatusClient.getIndexerStatus(indexer.getName());

        assertValidSearchIndexerStatus(indexerExecutionInfo);
    }

    @Test
    public void canUpdateIndexer() {
        String indexName = createIndex();
        String dataSourceName = createDataSource();

        SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true);
        searchIndexerClient.createIndexer(initial);
        indexersToDelete.add(initial.getName());

        SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName)
            .setDescription("somethingdifferent");
        SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated);

        // verify the returned updated indexer is as expected
        setSameStartTime(updated, indexerResponse);
        assertObjectEquals(updated, indexerResponse, true, "etag");
    }

    @Test
    public void canUpdateIndexerFieldMapping() {
        String indexName = createIndex();
        String dataSourceName = createDataSource();

        SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true);
        searchIndexerClient.createIndexer(initial);
        indexersToDelete.add(initial.getName());

        SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName)
            .setFieldMappings(Collections.singletonList(new FieldMapping("state_alpha").setTargetFieldName("state")));
        SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated);

        // verify the returned updated indexer is as expected
        setSameStartTime(updated, indexerResponse);
        assertObjectEquals(updated, indexerResponse, true, "etag");
    }

    @Test
    public void canCreateIndexerWithFieldMapping() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource())
            .setFieldMappings(Collections.singletonList(new FieldMapping("state_alpha").setTargetFieldName("state")));

        createAndValidateIndexer(indexer);
    }

    @Test
    public void canUpdateIndexerDisabled() {
        String indexName = createIndex();
        String dataSourceName = createDataSource();

        SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true);
        searchIndexerClient.createIndexer(initial);
        indexersToDelete.add(initial.getName());

        SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName)
            .setIsDisabled(false);
        SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated);

        setSameStartTime(updated, indexerResponse);
        assertObjectEquals(updated, indexerResponse, true, "etag");
    }

    @Test
    public void canUpdateIndexerSchedule() {
        String indexName = createIndex();
        String dataSourceName = createDataSource();

        SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true);
        searchIndexerClient.createIndexer(initial);
        indexersToDelete.add(initial.getName());

        SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName)
            .setSchedule(new IndexingSchedule(Duration.ofMinutes(10)));
        SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated);

        setSameStartTime(updated, indexerResponse);
        assertObjectEquals(updated, indexerResponse, true, "etag");
    }

    @Test
    public void canCreateIndexerWithSchedule() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource())
            .setSchedule(new IndexingSchedule(Duration.ofMinutes(10)));

        createAndValidateIndexer(indexer);
    }

    @Test
    public void canUpdateIndexerBatchSizeMaxFailedItems() {
        String indexName = createIndex();
        String dataSourceName = createDataSource();

        SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true);
        searchIndexerClient.createIndexer(initial);
        indexersToDelete.add(initial.getName());

        SearchIndexer updated = createIndexerWithDifferentIndexingParameters(initial);
        SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated);

        setSameStartTime(updated, indexerResponse);
        assertObjectEquals(updated, indexerResponse, true, "etag");
    }

    @Test
    public void canCreateIndexerWithBatchSizeMaxFailedItems() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());
        SearchIndexer updatedExpected = createIndexerWithDifferentIndexingParameters(indexer);

        createAndValidateIndexer(updatedExpected);
    }

    // This test currently does not pass on our Dogfood account, as the
    // Storage resource provider is not returning an answer.
    @Test
    public void canUpdateIndexerBlobParams() {
        String indexName = createIndex();
        String dataSourceName = searchIndexerClient.createDataSourceConnection(createBlobDataSource()).getName();
        dataSourcesToDelete.add(dataSourceName);

        SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true);
        searchIndexerClient.createIndexer(initial);
        indexersToDelete.add(initial.getName());

        SearchIndexer updated = createIndexerWithStorageConfig(initial.getName(), indexName, dataSourceName);
        SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated);

        setSameStartTime(updated, indexerResponse);
        assertObjectEquals(updated, indexerResponse, true, "etag");
    }

    // This test currently does not pass on our Dogfood account, as the
    // Storage resource provider is not returning an answer.
    @Test
    public void canCreateIndexerWithBlobParams() {
        // Create the needed Azure blob resources and data source object
        SearchIndexerDataSourceConnection blobDataSource = createBlobDataSource();

        // Create the data source within the search service
        SearchIndexerDataSourceConnection dataSource = searchIndexerClient.createOrUpdateDataSourceConnection(blobDataSource);

        dataSourcesToDelete.add(dataSource.getName());

        // modify the indexer's blob params
        SearchIndexer indexer = createIndexerWithStorageConfig(createIndex(), dataSource.getName());

        createAndValidateIndexer(indexer);
    }

    @Test
    public void canCreateAndDeleteIndexer() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());
        searchIndexerClient.createIndexer(indexer);

        searchIndexerClient.deleteIndexer(indexer.getName());
        assertThrows(HttpResponseException.class, () -> searchIndexerClient.getIndexer(indexer.getName()));
    }

    @Test
    public void canCreateAndDeleteIndexerWithResponse() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());
        searchIndexerClient.createIndexerWithResponse(indexer, Context.NONE);

        searchIndexerClient.deleteIndexerWithResponse(indexer, false, Context.NONE);
        assertThrows(HttpResponseException.class, () -> searchIndexerClient.getIndexer(indexer.getName()));
    }

    @Test
    public void deleteIndexerIsIdempotent() {
        // Create the indexer object
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());

        // Try deleting before the indexer even exists.
        Response<Void> result = searchIndexerClient.deleteIndexerWithResponse(indexer, false,
            Context.NONE);
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, result.getStatusCode());

        // Actually create the indexer
        searchIndexerClient.createIndexer(indexer);

        // Now delete twice.
        result = searchIndexerClient.deleteIndexerWithResponse(indexer, false, Context.NONE);
        assertEquals(HttpURLConnection.HTTP_NO_CONTENT, result.getStatusCode());

        result = searchIndexerClient.deleteIndexerWithResponse(indexer, false, Context.NONE);
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, result.getStatusCode());
    }

    @Test
    public void canCreateAndGetIndexer() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());
        searchIndexerClient.createIndexer(indexer);
        indexersToDelete.add(indexer.getName());

        SearchIndexer indexerResult = searchIndexerClient.getIndexer(indexer.getName());
        assertObjectEquals(indexer, indexerResult, true, "etag");

        indexerResult = searchIndexerClient.getIndexerWithResponse(indexer.getName(), Context.NONE)
            .getValue();
        assertObjectEquals(indexer, indexerResult, true, "etag");
    }

    @Test
    public void getIndexerThrowsOnNotFound() {
        assertHttpResponseException(
            () -> searchIndexerClient.getIndexer("thisindexerdoesnotexist"),
            HttpURLConnection.HTTP_NOT_FOUND,
            "Indexer 'thisindexerdoesnotexist' was not found");
    }

    @Test
    public void createOrUpdateIndexerIfNotExistsSucceedsOnNoResource() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());
        SearchIndexer created = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, true, Context.NONE)
            .getValue();
        indexersToDelete.add(created.getName());

        assertFalse(CoreUtils.isNullOrEmpty(created.getETag()));
    }

    @Test
    public void deleteIndexerIfExistsWorksOnlyWhenResourceExists() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());
        SearchIndexer created = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE)
            .getValue();

        searchIndexerClient.deleteIndexerWithResponse(created, true, Context.NONE);

        // Try to delete again and expect to fail
        try {
            searchIndexerClient.deleteIndexerWithResponse(created, true, Context.NONE);
            fail("deleteFunc should have failed due to non existent resource.");
        } catch (HttpResponseException ex) {
            assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode());
        }
    }

    @Test
    public void deleteIndexerIfNotChangedWorksOnlyOnCurrentResource() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());
        SearchIndexer stale = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, true, Context.NONE)
            .getValue();

        SearchIndexer updated = searchIndexerClient.createOrUpdateIndexerWithResponse(stale, false, Context.NONE)
            .getValue();

        try {
            searchIndexerClient.deleteIndexerWithResponse(stale, true, Context.NONE);
            fail("deleteFunc should have failed due to precondition.");
        } catch (HttpResponseException ex) {
            assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode());
        }

        searchIndexerClient.deleteIndexerWithResponse(updated, true, Context.NONE);
    }

    @Test
    public void updateIndexerIfExistsSucceedsOnExistingResource() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());
        SearchIndexer original = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE)
            .getValue();
        String originalETag = original.getETag();
        indexersToDelete.add(original.getName());

        SearchIndexer updated = searchIndexerClient.createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"),
                false, Context.NONE)
            .getValue();
        String updatedETag = updated.getETag();

        // Verify the eTag is not empty and was changed
        assertFalse(CoreUtils.isNullOrEmpty(updatedETag));
        assertNotEquals(originalETag, updatedETag);
    }

    @Test
    public void updateIndexerIfNotChangedFailsWhenResourceChanged() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());
        SearchIndexer original = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE)
            .getValue();
        String originalETag = original.getETag();
        indexersToDelete.add(original.getName());

        SearchIndexer updated = searchIndexerClient.createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"),
                true, Context.NONE)
            .getValue();
        String updatedETag = updated.getETag();

        // Update and check the eTags were changed
        try {
            searchIndexerClient.createOrUpdateIndexerWithResponse(original, true, Context.NONE);
            fail("createOrUpdateDefinition should have failed due to precondition.");
        } catch (HttpResponseException ex) {
            assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode());
        }

        // Check eTags
        assertFalse(CoreUtils.isNullOrEmpty(originalETag));
        assertFalse(CoreUtils.isNullOrEmpty(updatedETag));
        assertNotEquals(originalETag, updatedETag);
    }

    @Test
    public void updateIndexerIfNotChangedSucceedsWhenResourceUnchanged() {
        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource());
        SearchIndexer original = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE)
            .getValue();
        String originalETag = original.getETag();
        indexersToDelete.add(original.getName());

        SearchIndexer updated = searchIndexerClient.createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"),
                true, Context.NONE)
            .getValue();
        String updatedETag = updated.getETag();

        // Check eTags as expected
        assertFalse(CoreUtils.isNullOrEmpty(originalETag));
        assertFalse(CoreUtils.isNullOrEmpty(updatedETag));
        assertNotEquals(originalETag, updatedETag);
    }

    @Test
    public void canUpdateIndexerSkillset() {
        String indexName = createIndex();
        String dataSourceName = createDataSource();

        SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true);
        searchIndexerClient.createIndexer(initial);
        indexersToDelete.add(initial.getName());

        SearchIndexerSkillset skillset = createSkillsetObject();
        searchIndexerClient.createSkillset(skillset);
        skillsetsToDelete.add(skillset.getName());
        SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName)
            .setSkillsetName(skillset.getName());
        SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated);

        setSameStartTime(updated, indexerResponse);
        assertObjectEquals(updated, indexerResponse, true, "etag");
    }

    @Test
    public void canCreateIndexerWithSkillset() {
        SearchIndexerSkillset skillset = searchIndexerClient.createSkillset(createSkillsetObject());
        skillsetsToDelete.add(skillset.getName());

        SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource())
            .setSkillsetName(skillset.getName());

        createAndValidateIndexer(indexer);
    }

    /**
     * Create a new valid skillset object
     *
     * @return the newly created skillset object
     */
    SearchIndexerSkillset createSkillsetObject() {
        List<InputFieldMappingEntry> inputs = Arrays.asList(
            new InputFieldMappingEntry("url")
                .setSource("/document/url"),
            new InputFieldMappingEntry("queryString")
                .setSource("/document/queryString")
        );

        List<OutputFieldMappingEntry> outputs = Collections.singletonList(
            new OutputFieldMappingEntry("text")
                .setTargetName("mytext")
        );

        List<SearchIndexerSkill> skills = Collections.singletonList(
            new OcrSkill(inputs, outputs)
                .setShouldDetectOrientation(true)
                .setName("myocr")
                .setDescription("Tested OCR skill")
                .setContext("/document")
        );
        return new SearchIndexerSkillset(testResourceNamer.randomName("ocr-skillset", 32))
            .setDescription("Skillset for testing default configuration")
            .setSkills(skills);
    }

    SearchIndexer createBaseTestIndexerObject(String targetIndexName, String dataSourceName) {
        return createBaseTestIndexerObject(testResourceNamer.randomName("indexer", 32), targetIndexName,
            dataSourceName);
    }

    SearchIndexer createBaseTestIndexerObject(String name, String targetIndexName, String dataSourceName) {
        if (name == null) {
            name = testResourceNamer.randomName("indexer", 32);
        }

        return new SearchIndexer(name, dataSourceName, targetIndexName)
            .setSchedule(new IndexingSchedule(Duration.ofDays(1)));
    }

    /**
     * This index contains fields that are declared on the live data source we use to test the indexers
     *
     * @return the newly created Index object
     */
    SearchIndex createTestIndexForLiveDatasource() {
        return new SearchIndex(testResourceNamer.randomName(IndexersManagementSyncTests.TARGET_INDEX_NAME, 32))
            .setFields(Arrays.asList(
                new SearchField("county_name", SearchFieldDataType.STRING)
                    .setSearchable(Boolean.FALSE)
                    .setFilterable(Boolean.TRUE),
                new SearchField("state", SearchFieldDataType.STRING)
                    .setSearchable(Boolean.TRUE)
                    .setFilterable(Boolean.TRUE),
                new SearchField("feature_id", SearchFieldDataType.STRING)
                    .setKey(Boolean.TRUE)
                    .setSearchable(Boolean.TRUE)
                    .setFilterable(Boolean.FALSE)));
    }

    /**
     * Create a new indexer and change its indexing parameters
     *
     * @return the created indexer
     */
    SearchIndexer createIndexerWithDifferentIndexingParameters(SearchIndexer indexer) {
        // create a new indexer object
        IndexingParameters ip = new IndexingParameters()
            .setMaxFailedItems(121)
            .setMaxFailedItemsPerBatch(11)
            .setBatchSize(20);

        // modify the indexer
        indexer.setParameters(ip);

        return indexer;
    }

    SearchIndexer createIndexerWithStorageConfig(String targetIndexName, String dataSourceName) {
        return createIndexerWithStorageConfig(null, targetIndexName, dataSourceName);
    }

    SearchIndexer createIndexerWithStorageConfig(String name, String targetIndexName, String dataSourceName) {
        // create an indexer object
        SearchIndexer updatedExpected = createBaseTestIndexerObject(name, targetIndexName, dataSourceName);

        // just adding some(valid) config values for blobs
        HashMap<String, Object> config = new HashMap<>();
        config.put("indexedFileNameExtensions", ".pdf,.docx");
        config.put("excludedFileNameExtensions", ".xlsx");
        config.put("dataToExtract", "storageMetadata");
        config.put("failOnUnsupportedContentType", false);

        IndexingParameters ip = new IndexingParameters()
            .setConfiguration(config);

        // modify it
        updatedExpected.setParameters(ip);

        return updatedExpected;
    }

    void setSameStartTime(SearchIndexer expected, SearchIndexer actual) {
        // There ought to be a start time in the response; We just can't know what it is because it would
        // make the test timing-dependent.
        expected.getSchedule().setStartTime(actual.getSchedule().getStartTime());
    }

    void assertStartAndEndTimeValid(IndexerExecutionResult result) {
        assertNotNull(result.getStartTime());
        assertNotEquals(OffsetDateTime.now(), result.getStartTime());
        assertNotNull(result.getEndTime());
        assertNotEquals(OffsetDateTime.now(), result.getEndTime());
    }

    void assertValidSearchIndexerStatus(SearchIndexerStatus indexerExecutionInfo) {
        assertEquals(IndexerExecutionStatus.IN_PROGRESS, indexerExecutionInfo.getLastResult().getStatus());
        assertEquals(3, indexerExecutionInfo.getExecutionHistory().size());

        SearchIndexerLimits limits = indexerExecutionInfo.getLimits();
        assertNotNull(limits);
        assertEquals(100000, limits.getMaxDocumentContentCharactersToExtract(), 0);
        assertEquals(1000, limits.getMaxDocumentExtractionSize(), 0);

        IndexerExecutionResult newestResult = indexerExecutionInfo.getExecutionHistory().get(0);
        IndexerExecutionResult middleResult = indexerExecutionInfo.getExecutionHistory().get(1);
        IndexerExecutionResult oldestResult = indexerExecutionInfo.getExecutionHistory().get(2);

        assertEquals(IndexerExecutionStatus.TRANSIENT_FAILURE, newestResult.getStatus());
        assertEquals("The indexer could not connect to the data source",
            newestResult.getErrorMessage());
        assertStartAndEndTimeValid(newestResult);

        assertEquals(IndexerExecutionStatus.RESET, middleResult.getStatus());
        assertStartAndEndTimeValid(middleResult);

        assertEquals(IndexerExecutionStatus.SUCCESS, oldestResult.getStatus());
        assertEquals(124876, oldestResult.getItemCount());
        assertEquals(2, oldestResult.getFailedItemCount());
        assertEquals("100", oldestResult.getInitialTrackingState());
        assertEquals("200", oldestResult.getFinalTrackingState());
        assertStartAndEndTimeValid(oldestResult);

        assertEquals(2, oldestResult.getErrors().size());
        assertEquals("1", oldestResult.getErrors().get(0).getKey());
        assertEquals("Key field contains unsafe characters",
            oldestResult.getErrors().get(0).getErrorMessage());
        assertEquals("DocumentExtraction.AzureBlob.MyDataSource",
            oldestResult.getErrors().get(0).getName());
        assertEquals("The file could not be parsed.", oldestResult.getErrors().get(0).getDetails());
        assertEquals("https://go.microsoft.com/fwlink/?linkid=2049388",
            oldestResult.getErrors().get(0).getDocumentationLink());

        assertEquals("121713", oldestResult.getErrors().get(1).getKey());
        assertEquals("Item is too large", oldestResult.getErrors().get(1).getErrorMessage());
        assertEquals("DocumentExtraction.AzureBlob.DataReader",
            oldestResult.getErrors().get(1).getName());
        assertEquals("Blob size cannot exceed 256 MB.", oldestResult.getErrors().get(1).getDetails());
        assertEquals("https://go.microsoft.com/fwlink/?linkid=2049388",
            oldestResult.getErrors().get(1).getDocumentationLink());

        assertEquals(1, oldestResult.getWarnings().size());
        assertEquals("2", oldestResult.getWarnings().get(0).getKey());
        assertEquals("Document was truncated to 50000 characters.",
            oldestResult.getWarnings().get(0).getMessage());
        assertEquals("Enrichment.LanguageDetectionSkill.#4",
            oldestResult.getWarnings().get(0).getName());
        assertEquals("Try to split the input into smaller chunks using Split skill.",
            oldestResult.getWarnings().get(0).getDetails());
        assertEquals("https://go.microsoft.com/fwlink/?linkid=2099692",
            oldestResult.getWarnings().get(0).getDocumentationLink());
    }
}


text:
The class methods in this class provides basic access to the free geo-ip lookup service provided by:

 http://ipinfodb.com/ip_location_api.php

See their site for more info.

It does not implement their services that allow you to look up more than one location at a time or look up a location using a domain name.

redpajama_set_name: RedPajamaGithub


text:
A tiny, convenient wrapper around Noble to easily scan BLE peripherals

[![npm version](https://img.shields.io/npm/v/lebon.svg)](https://www.npmjs.com/package/lebon)
[![Build Status](https://travis-ci.org/astagi/lebon.svg?branch=master)](https://travis-ci.org/astagi/lebon) [![codecov.io](https://codecov.io/github/astagi/lebon/coverage.svg?branch=master)](https://codecov.io/github/astagi/lebon?branch=master)

## Lebon peripheral discovered

    peripheral = {
      name: "Name",
      uuid: "UUID",
      address: "BT address",
      noblePeripheral: <Noble Peripheral Object>
    };

## Start scanning devices

    lebon.startScan(timeout);

Example:

    var lebon = require('lebon');

    lebon.on('discover', function(device) {
      console.log('New device discovered! ' + device.name);
    });

    lebon.startScan(20000);

## Stop scanning devices

    lebon.stopScan();

Example:

    var lebon = require('lebon');

    var start = function(device) {
      console.log(device.uuid)
    }

    lebon.on('discover', function(device) {
      if (device.name === 'BB-191') {
        lebon.stopScan();
        start(device);
      }
    });

    lebon.startScan(20000);

## Get latest devices scanned

    peripherals = lebon.getDiscoveredPeripherals()

## License

MIT © 2016 Andrea Stagi


text:
var $ = require("funcunit/browser/jquery");
var FuncUnit = require("funcunit/browser/core");

/**
 * @add FuncUnit
 */
//list of jQuery functions we want, number is argument index
//for wait instead of getting value
FuncUnit.funcs = {
  // methods
  /**
   * @function FuncUnit.prototype.size .size()
   * @parent dimensions
   * @signature `size([size] [,timeout] [,success] [,message])`
   * Gets the number of elements matched by the selector or
   * waits until the the selector is size.  You can also
   * provide a function that continues to the next action when
   * it returns true.
	 *
   * @codestart
   *F(".recipe").size() //gets the number of recipes
   *
   *F(".recipe").size(2) //waits until there are 2 recipes
   *
   * //waits until size is count
   *F(".recipe").size(function(size){
   *   return size == count;
   * })
   * @codeend
   * @param {Number|Function} [size] number or a checking function.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {Number} if the size parameter is not provided, size returns the number
   * of elements matched.
   */
  'size' : 0,
  /**
   * @function FuncUnit.prototype.attr .attr()
   * @parent manipulation
   * @signature `attr(data, value [,timeout] [,success] [,message])`
   * Gets the value of an attribute from an element or waits until the attribute
   * equals the attr param.
	 *
   * @codestart
   * //waits until the abc attribute == some
   *F("#something").attr("abc","some")
   * @codeend
   * @param {String} data The attribute to get, or wait for.
   * @param {String|Function} value If provided uses this as a check before continuing to the next action
     *
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {Object} if the attr parameter is not provided, returns
   * the attribute.
   */
  'attr' : 1,
  /**
   * @function FuncUnit.prototype.hasClass .hasClass()
   * @parent css
   * @signature `hasClass(className [,value] [,timeout] [,success] [,message])`
	 *
   * @codestart
   * //returns if the element has the class in its className
   *F("#something").hasClass("selected");
   *
   * //waits until #something has selected in its className
   *F("#something").hasClass("selected",true);
   *
   * //waits until #something does not have selected in its className
   *F("#something").hasClass("selected",false);
   * @codeend
   * @param {String} className The part of the className to search for.
   * @param {Boolean|Function} [value] If provided uses this as a check before continuing to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {Boolean|funcUnit} if the value parameter is not provided, returns
   * if the className is found in the element's className.  If a value paramters is provided, returns funcUnit for chaining.
   */
  'hasClass' : 1, //makes wait
  /**
     * @function FuncUnit.prototype.html .html()
     * @parent manipulation
     * @signature `html([html] [,timeout] [,success] [,message])`
   * Gets the [http://api.jquery.com/html/ html] from an element or waits until the html is a certain value.
	 *
   * @codestart
   * //checks foo's html has "JupiterJS"
   * ok( /JupiterJS/.test(F('#foo').html() ) )
   *
   * //waits until foo's html has JupiterJS
   *F('#foo').html(/JupiterJS/)
   *
   * //waits until foo's html is JupiterJS
   *F('#foo').html("JupiterJS")
   * @codeend
   *
   * @param {String|Function} [html] If provided uses this as a check before continuing to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if the html parameter is provided,
   * returns the funcUnit selector for chaining, otherwise returns the html of the selector.
   */
  'html' : 0,
  /**
     * @function FuncUnit.prototype.text .text()
     * @parent manipulation
     * @signature `text([text] [,timeout] [,success] [,message])`
   * Gets the [http://api.jquery.com/text/ text] from an element or waits until the text is a certain value.
	 *
   * @codestart
   * //checks foo's text has "JupiterJS"
   * ok( /JupiterJS/.test(F('#foo').text() ) )
   *
   * //waits until bar's text has JupiterJS
   *F('#foo').text(/JupiterJS/)
   *
   * //waits until bar's text is JupiterJS
   *F('#foo').text("JupiterJS")
   * @codeend
   *
   * @param {String|Function} [text] If provided uses this as a check before continuing to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if the text parameter is provided,
   * returns the funcUnit selector for chaining, otherwise returns the html of the selector.
   */
  'text' : 0,
  /**
     * @function FuncUnit.prototype.val .val()
     * @parent manipulation
     * @signature `val([val] [,timeout] [,success] [,message])`
   * Gets the [http://api.jquery.com/val/ val] from an element or waits until the val is a certain value.
	 *
   * @codestart
   * //checks foo's val has "JupiterJS"
   * ok( /JupiterJS/.test(F('input#foo').val() ) )
   *
   * //waits until bar's val has JupiterJS
   *F('input#foo').val(/JupiterJS/)
   *
   * //waits until bar's val is JupiterJS
   *F('input#foo').val("JupiterJS")
   * @codeend
   *
   * @param {String|Function} [val] If provided uses this as a check before continuing to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if the val parameter is provided,
   * returns the funcUnit selector for chaining, otherwise returns the html of the selector.
   */
  'val' : 0,
  /**
     * @function FuncUnit.prototype.css .css()
     * @parent css
     * @signature `css(prop [,val] [,timeout] [,success] [,message])`
   * Gets a [http://api.jquery.com/css/ css] property from an element or waits until the property is
   * a specified value.
	 *
   * @codestart
   * // gets the color
   *F("#foo").css("color")
   *
   * // waits until the color is red
   *F("#foo").css("color","red")
   * @codeend
   *
   * @param {String} prop A css property to get or wait until it is a specified value.
   * @param {String|Function} [val] If provided uses this as a check before continuing to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if the val parameter is provided,
   * returns the funcUnit selector for chaining, otherwise returns the css of the selector.
   */
  'css': 1,
  'prop': 1,
  /**
     * @function FuncUnit.prototype.offset .offset()
     * @parent dimensions
     * @signature `offset([offset] [,timeout] [,success] [,message])`
   * Gets an element's [http://api.jquery.com/offset/ offset] or waits until
   * the offset is a specified value.
	 *
   * @codestart
   * // gets the offset
   *F("#foo").offset();
   *
   * // waits until the offset is 100, 200
   *F("#foo").offset({top: 100, left: 200})
   * @codeend
   *
   * @param {Object|Function} [offset] If provided uses this as a check before continuing to the next action.  Or you can
   * provide a function that returns true to continue to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if the offset parameter is provided,
   * returns the funcUnit selector for chaining, otherwise returns the css of the selector.
   */
  'offset' : 0,
  /**
     * @function FuncUnit.prototype.position .position()
     * @parent dimensions
     * @signature `position([position] [,timeout] [,success] [,message])`
   * Gets an element's [http://api.jquery.com/position/ position] or waits until
   * the position is a specified value.
	 *
   * @codestart
   * // gets the position
   *F("#foo").position();
   *
   * // waits until the position is 100, 200
   *F("#foo").position({top: 100, left: 200})
   * @codeend
   *
   * @param {Object|Function} [position] If provided uses this as a check before continuing to the next action.  Or you can
   * provide a function that returns true to continue to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if the position parameter is provided,
   * returns the funcUnit selector for chaining, otherwise returns the offset of the selector.
   */
  'position' : 0,
  /**
     * @function FuncUnit.prototype.scrollTop .scrollTop()
     * @parent dimensions
     * @signature `scrollTop([scrollTop] [,timeout] [,success] [,message])`
   * Gets an element's [http://api.jquery.com/scrollTop/ scrollTop] or waits until
   * it equals a specified value.
	 *
   * @codestart
   * // gets the scrollTop
   *F("#foo").scrollTop();
   *
   * // waits until the scrollTop is 100
   *F("#foo").scrollTop(100)
   * @codeend
   *
   * @param {Number|Function} [scrollTop] If provided uses this as a check before continuing to the next action.  Or you can
   * provide a function that returns true to continue to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if scrollTop is provided,
   * returns the funcUnit selector for chaining, otherwise returns the scrollTop of the selector.
   */
  'scrollTop' : 0,
  /**
     * @function FuncUnit.prototype.scrollLeft .scrollLeft()
     * @parent dimensions
     * @signature `scrollLeft([scrollLeft] [,timeout] [,success] [,message])`
   * Gets an element's [http://api.jquery.com/scrollLeft/ scrollLeft] or waits until
   * it equals a specified value.
	 *
   * @codestart
   * // gets the scrollLeft
   *F("#foo").scrollLeft();
   *
   * // waits until the scrollLeft is 100
   *F("#foo").scrollLeft(100)
   * @codeend
   *
   * @param {Number|Function} [scrollLeft] If provided uses this as a check before continuing to the next action.  Or you can
   * provide a function that returns true to continue to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if scrollLeft is provided,
   * returns the funcUnit selector for chaining, otherwise returns the scrollLeft of the selector.
   */
  'scrollLeft' : 0,
  /**
     * @function FuncUnit.prototype.height .height()
     * @parent dimensions
     * @signature `height([height] [,timeout] [,success] [,message])`
   * Gets an element's [http://api.jquery.com/height/ height] or waits until
   * it equals a specified value.
	 *
   * @codestart
   * // gets the height
   *F("#foo").height();
   *
   * // waits until the height is 100
   *F("#foo").height(100)
   * @codeend
   *
   * @param {Number|Function} [height] If provided uses this as a check before continuing to the next action.  Or you can
   * provide a function that returns true to continue to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if height is provided,
   * returns the funcUnit selector for chaining, otherwise returns the height of the selector.
   */
  'height' : 0,
  /**
     * @function FuncUnit.prototype.width .width()
     * @parent dimensions
     * @signature `width([width] [,timeout] [,success] [,message])`
   * Gets an element's [http://api.jquery.com/width/ width] or waits until
   * it equals a specified value.
	 *
   * @codestart
   * // gets the width
   *F("#foo").width();
   *
   * // waits until the width is 100
   *F("#foo").width(100)
   * @codeend
   *
   * @param {Number|Function} [width] If provided uses this as a check before continuing to the next action.  Or you can
   * provide a function that returns true to continue to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if width is provided,
   * returns the funcUnit selector for chaining, otherwise returns the width of the selector.
   */
  'width' : 0,
  /**
     * @function FuncUnit.prototype.innerHeight .innerHeight()
     * @parent dimensions
     * @signature `innerHeight([innerHeight] [,timeout] [,success] [,message])`
   * Gets an element's [http://api.jquery.com/innerHeight/ innerHeight] or waits until
   * it equals a specified value.
	 *
   * @codestart
   * // gets the innerHeight
   *F("#foo").innerHeight();
   *
   * // waits until the innerHeight is 100
   *F("#foo").innerHeight(100)
   * @codeend
   *
   * @param {Number|Function} [innerHeight] If provided uses this as a check before continuing to the next action.  Or you can
   * provide a function that returns true to continue to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if innerHeight is provided,
   * returns the funcUnit selector for chaining, otherwise returns the innerHeight of the selector.
   */
  'innerHeight' : 0,
  /**
     * @function FuncUnit.prototype.innerWidth .innerWidth()
     * @parent dimensions
     * @signature `innerWidth([innerWidth] [,timeout] [,success] [,message])`
   * Gets an element's [http://api.jquery.com/innerWidth/ innerWidth] or waits until
   * it equals a specified value.
	 *
   * @codestart
   * // gets the innerWidth
   *F("#foo").innerWidth();
   *
   * // waits until the innerWidth is 100
   *F("#foo").innerWidth(100)
   * @codeend
   *
   * @param {Number|Function} [innerWidth] If provided uses this as a check before continuing to the next action.  Or you can
   * provide a function that returns true to continue to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if innerWidth is provided,
   * returns the funcUnit selector for chaining, otherwise returns the innerWidth of the selector.
   */
  'innerWidth' : 0,
  /**
     * @function FuncUnit.prototype.outerHeight .outerHeight()
     * @parent dimensions
     * @signature `outerHeight([outerHeight] [,timeout] [,success] [,message])`
   * Gets an element's [http://api.jquery.com/outerHeight/ outerHeight] or waits until
   * it equals a specified value.
	 *
   * @codestart
   * // gets the outerHeight
   *F("#foo").outerHeight();
   *
   * // waits until the outerHeight is 100
   *F("#foo").outerHeight(100)
   * @codeend
   *
   * @param {Number|Function} [outerHeight] If provided uses this as a check before continuing to the next action.  Or you can
   * provide a function that returns true to continue to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if outerHeight is provided,
   * returns the funcUnit selector for chaining, otherwise returns the outerHeight of the selector.
   */
  'outerHeight' : 0,
  /**
     * @function FuncUnit.prototype.outerWidth .outerWidth()
     * @parent dimensions
     * @signature `outerWidth([outerWidth] [,timeout] [,success] [,message])`
   * Gets an element's [http://api.jquery.com/outerWidth/ outerWidth] or waits until
   * it equals a specified value.
	 *
   * @codestart
   * // gets the outerWidth
   *F("#foo").outerWidth();
   *
   * // waits until the outerWidth is 100
   *F("#foo").outerWidth(100)
   * @codeend
   *
   * @param {Number|Function} [outerWidth] If provided uses this as a check before continuing to the next action.  Or you can
   * provide a function that returns true to continue to the next action.
   * @param {Number} [timeout] overrides FuncUnit.timeout.  If provided, the wait will fail if not completed before this timeout.
   * @param {Function} [success] a callback that will run after this action completes.
   * @param {String} [message] if provided, an assertion will be passed when this wait condition completes successfully
   * @return {String|funcUnit} if outerWidth is provided,
   * returns the funcUnit selector for chaining, otherwise returns the outerWidth of the selector.
   */
  'outerWidth' : 0
};

//makes a jQuery like command.
FuncUnit.makeFunc = function(fname, argIndex){
  var orig = FuncUnit.fn[fname];
  //makes a read / wait function
  FuncUnit.prototype[fname] = function(){
    //assume last arg is success
    var args = FuncUnit.makeArray(arguments),
      isWait = args.length > argIndex,
      success,
      self = this;

    args.unshift(this.selector,this.frame,fname)
    if(isWait){
      //get the args greater and equal to argIndex
      var tester = args[argIndex+3],
        timeout = args[argIndex+4],
        success = args[argIndex+5],
        message = args[argIndex+6],
        testVal = tester,
        errorMessage = "waiting for "+fname +" on " + this.selector,
        frame = this.frame,
        logMessage = "Checking "+fname+" on '"+this.selector+"'",
        ret;

      // can pass in an object or list of arguments
      if(typeof tester == 'object' && !(tester instanceof RegExp)){
        timeout = tester.timeout;
        success = tester.success;
        message = tester.message;
        if(tester.errorMessage){
          errorMessage = tester.errorMessage
        }
        if(typeof tester.logMessage !== "undefined"){
          logMessage = tester.logMessage
        }
        tester = tester.condition;
      }
      if(typeof timeout == 'function'){
        message = success;
        success = timeout;
        timeout = undefined;
      }
      if(typeof timeout == 'string'){
        message = timeout;
        timeout = undefined;
        success = undefined;
      }
      if(typeof message !== 'string'){
        message = undefined;
      }
      args.splice(argIndex+3, args.length- argIndex - 3);

      if(typeof tester != 'function'){
        errorMessage += " !== "+testVal
        tester = function(val){
          return FuncUnit.unit.equiv(val, testVal) ||
            (testVal instanceof RegExp && testVal.test(val) );
        }
      }
      if(message){
        errorMessage = message;
      }
      FuncUnit.repeat({
        method : function(print){
          // keep getting new collection because the page might be updating, we need to keep re-checking
          if(this.bind.prevObject && this.bind.prevTraverser){
            var prev = this.bind;
            this.bind = this.bind.prevObject[this.bind.prevTraverser](this.bind.prevTraverserSelector)
            this.bind.prevTraverser = prev.prevTraverser;
            this.bind.prevTraverserSelector = prev.prevTraverserSelector;
          } else {
            // pass false so it will only do one synchronous request
            this.bind =F(this.selector, {
              frame: frame,
              forceSync: true
            })
          }
          if(logMessage){
            print(logMessage)
          }
          var methodArgs = [];
          // might need an argument
          if(argIndex > 0){
            methodArgs.push(args[3]);
          }
          // lazy flag to ignore the getter error below
          FuncUnit._ignoreGetterError = true;
          ret = this.bind[fname].apply(this.bind, methodArgs)
          FuncUnit._ignoreGetterError = false;

          var passed = tester.call(this.bind, ret);

          // unless this is a "size" command, require size to be non-zero (don't pass through if there's no elements)
          if(this.bind.length === 0 && fname !== "size"){
            passed = false;
          }

          if(passed){
            // if document is still loading
            if(!FuncUnit.documentLoaded()){
              passed = false;
            } else {
              // after every successful wait, check for a new document (if someone clicked a link),
              // and overwrite alert/confirm/prompt
              // TODO this creates a potential race if a new document is loaded but its steal isn't ready...should poll
              FuncUnit.checkForNewDocument();
            }
          }
          return passed;
        },
        success : function(){
          if(message){
            FuncUnit.unit.assertOK(true, message)
          }
          success && success.apply(this, arguments);
        },
        error : function(){
          var msg = errorMessage;
          if(ret){
            msg += ", actual value: "+ret;
          }
          FuncUnit.unit.assertOK(false, msg);
        },
        timeout : timeout,
        bind: this,
        type: "wait"
      })
      return this;
    }else{
      // throw a warning if user tries to use a getter after the start of the test (if there are other async methods)
      if(!FuncUnit._ignoreGetterError && !FuncUnit._incallback && FuncUnit._haveAsyncQueries()){
        console && console.error("You can't run getters after actions and waits. Please put your getters in a callback or at the beginning of the test.")
      }
      // just call the original jQ method
      var methodArgs = [];
      if(argIndex > 0){
        methodArgs.push(args[3]);
      }
      return orig.apply(this, methodArgs);
    }
  }
}

for (var prop in FuncUnit.funcs) {
  FuncUnit.makeFunc(prop, FuncUnit.funcs[prop]);
}

module.exports = FuncUnit;


text:
import { isDirectory, exists } from "@azure-tools/async-io";
import { fetchPackageMetadata } from "@azure-tools/extension";
import { isUri } from "@azure-tools/uri";
import { omit } from "lodash";
import { AutorestNormalizedConfiguration } from "./autorest-normalized-configuration";

const desugarUseField = async (use: string[] | string) => {
  // Create an empty extension manager to be able to call findPackages.
  const useArray = typeof use === "string" ? [use] : use;
  const extensions: Record<string, string> = {};
  for (const useEntry of useArray) {
    if (typeof useEntry === "string") {
      // potential formats:
      // <pkg>
      // <pkg>@<version>
      // @<org>/<pkg>
      // @<org>/<pkg>@<version>
      // <path>
      // <path/uri to .tgz package file>
      // if the entry starts with an @ it's definitely a package reference
      if (useEntry.endsWith(".tgz") || (await isDirectory(useEntry)) || useEntry.startsWith("file:/")) {
        const pkg = await fetchPackageMetadata(useEntry);
        extensions[pkg.name] = useEntry;
      } else {
        const [, identity, version] = /^https?:\/\//g.exec(useEntry)
          ? [undefined, useEntry, undefined]
          : <RegExpExecArray>/(^@.*?\/[^@]*|[^@]*)@?(.*)/.exec(useEntry);

        if (identity) {
          // parsed correctly
          if (version) {
            extensions[identity] = version;
          } else {
            // it's either a location or just the name
            if (isUri(identity) || (await exists(identity))) {
              // seems like it's a location to something. we don't know the actual name at this point.
              const pkg = await fetchPackageMetadata(identity);
              extensions[pkg.name] = identity;
            } else {
              extensions[identity] = "*";
            }
          }
        }
      }
    }
  }
  return extensions;
};

/**
 * Resolve some sugar properties.
 * @param rawConfig Config to clean.
 */
export const desugarRawConfig = async (
  rawConfig: AutorestNormalizedConfiguration,
): Promise<AutorestNormalizedConfiguration> => {
  return {
    ...omit(rawConfig, "licence-header"),
    "license-header": rawConfig["license-header"] ?? rawConfig["licence-header"],
    "use-extension": {
      ...rawConfig["use-extension"],
      ...(rawConfig.use && (await desugarUseField(rawConfig.use))),
    },
  };
};


text:
import React, { Component } from 'react';
import create from '../redux/create';
import ConnectedAll from './ConnectedAll';
import { reduxToReact } from 'redux-as-component';
import { init } from '../actions/init';
import { rotate } from '../actions/rotate';
import { getBlob } from '../actions/handlers';

export default (reduxToReact(
	{
		onCropperReduxUpdate: ({
			image,
			cropBox,
			myState,
			canvas
		})=>({
			image,
			cropBox,
			myState,
			canvas
		})
	},
	{
		rotate : rotate,
		'@default' : init
	},
	{
		getBlob,
	},
	create,
	{isDebug: true},
	ConnectedAll
))


text:
require 'test_helper'

class AssignsControllerTest < ActionController::TestCase
  def test_assigns
    process :test_assigns
    # assigns can be accessed using assigns(key)
    # or assigns[key], where key is a string or
    # a symbol
    assert_equal "foo", assigns(:foo)
    assert_equal "foo", assigns("foo")
    assert_equal "foo", assigns[:foo]
    assert_equal "foo", assigns["foo"]

    # but the assigned variable should not have its own keys stringified
    expected_hash = { foo: :bar }
    assert_equal expected_hash, assigns(:foo_hash)
  end

  def test_view_assigns
    @controller = ViewAssignsController.new
    process :test_assigns
    assert_nil assigns(:foo)
    assert_nil assigns[:foo]
    assert_equal "bar", assigns(:bar)
    assert_equal "bar", assigns[:bar]
  end
end


text:
'use strict'

var _ = require('lodash')

var internals = {
  name: 'mem-store'
}

module.exports = function (options) {
  var seneca = this

  // merge default options with any provided by the caller
  options = seneca.util.deepextend({
    prefix: '/mem-store',
    web: {
      dump: false
    }
  }, options)

  // The calling Seneca instance will provide
  // a description for us on init(), it will
  // be used in the logs
  var desc

  // Our super awesome in mem database. Please bear in mind
  // that this store is meant for fast prototyping, using
  // it for production is not advised!
  var entmap = {}

  // Define the store using a description object.
  // This is a convenience provided by seneca.store.init function.
  var store = {

    // The name of the plugin, this is what is the name you would
    // use in seneca.use(), eg seneca.use('mem-store').
    name: internals.name,

    save: function (msg, done) {

      // Take a reference to Seneca
      // and the entity to save
      var seneca = this
      var ent = msg.ent

      // create our cannon and take a copy of
      // the zone, base and name, we will use
      // this info further down.
      var canon = ent.canon$({object: true})
      var zone = canon.zone
      var base = canon.base
      var name = canon.name

      // check if we are in create mode,
      // if we are do a create, otherwise
      // we will do a save instead
      var create = ent.id == null
      if (create) {
        create_new()
      }
      else {
        do_save()
      }

      // The actual save logic for saving or
      // creating and then saving the entity.
      function do_save (id, isnew) {
        var mement = ent.data$(true, 'string')

        if (undefined !== id) {
          mement.id = id
        }

        mement.entity$ = ent.entity$

        entmap[base] = entmap[base] || {}
        entmap[base][name] = entmap[base][name] || {}

        var prev = entmap[base][name][mement.id]
        if (isnew && prev) {
          return done(new Error('Entity of type ' + ent.entity$ + ' with id = ' + id + ' already exists.'))
        }

        var shouldMerge = true
        if (options.merge !== false && ent.merge$ === false) {
          shouldMerge = false
        }
        if (options.merge === false && ent.merge$ !== true) {
          shouldMerge = false
        }

        mement = _.cloneDeep(mement)
        if (shouldMerge) {
          mement = _.assign(prev || {}, mement)
        }
        prev = entmap[base][name][mement.id] = mement

        seneca.log.debug(function () {
          return ['save/' + (create ? 'insert' : 'update'), ent.canon$({string: 1}), mement, desc]
        })

        done(null, ent.make$(prev))
      }

      // We will still use do_save to save the entity but
      // we need a place to handle new entites and id concerns.
      function create_new () {

        // Check if we already have an id or if
        // we need to generate a new one.
        if (undefined !== ent.id$) {

          // Take a copy of the existing id and
          // delete it from the ent object. Do
          // save will handle the id for us.
          var id = ent.id$
          delete ent.id$

          // Save with the existing id
          return do_save(id, true)
        }

        // We need an id so we will call out
        // to Seneca for one.
        var gen_id = {
          role: 'basic',
          cmd: 'generate_id',
          name: name,
          base: base,
          zone: zone
        }

        // When we get a respones we will use the id param
        // as our entity id, if this fails we just fail and
        // call done() as we have no way to save without an id
        seneca.act(gen_id, function (err, id) {
          if (err) {
            done(err)
          }
          else {
            do_save(id, true)
          }
        })
      }
    },

    load: function (msg, done) {
      var qent = msg.qent
      var q = msg.q

      listents(this, entmap, qent, q, function (err, list) {
        var ent = list[0] || null

        this.log.debug(function () {
          return [ 'load', q, qent.canon$({string: 1}), ent, desc ]
        })

        done(err, ent)
      })
    },

    list: function (msg, done) {

      var qent = msg.qent
      var q = msg.q

      listents(this, entmap, qent, q, function (err, list) {

        this.log.debug(function () {
          return ['list', q, qent.canon$({string: 1}), list.length, list[0], desc]
        })

        done(err, list)
      })
    },

    remove: function (msg, done) {
      var seneca = this
      var qent = msg.qent
      var q = msg.q
      var all = q.all$

      // default false
      var load = q.load$ === true

      listents(seneca, entmap, qent, q, function (err, list) {
        if (err) {
          return done(err)
        }

        list = list || []
        list = all ? list : list.slice(0, 1)

        list.forEach(function (ent) {
          var canon = qent.canon$({
            object: true
          })

          delete entmap[canon.base][canon.name][ent.id]

          seneca.log.debug(function () {
            return ['remove/' + (all ? 'all' : 'one'), q, qent.canon$({string: 1}), ent, desc]
          })
        })

        var ent = !all && load && list[0] || null

        done(null, ent)
      })
    },

    close: function (msg, done) {
      this.log.debug('close', desc)
      done()
    },

    // .native() is used to handle calls to the underlying driver. Since
    // there is no underlying driver for mem-store we simply return the
    // default entityMap object.
    native: function (msg, done) {
      done(null, entmap)
    }
  }

  // Init the store using the seneca instance, merged
  // options and the store description object above.
  var meta = seneca.store.init(seneca, options, store)

  // int() returns some metadata for us, one of these is the
  // description, we'll take a copy of that here.
  desc = meta.desc

  options.idlen = options.idlen || 6

  seneca.add({role: store.name, cmd: 'dump'}, function (msg, done) {
    done(null, entmap)
  })

  seneca.add({role: store.name, cmd: 'export'}, function (msg, done) {
    var entjson = JSON.stringify(entmap)

    done(null, {json: entjson})
  })

  seneca.add({role: store.name, cmd: 'import'}, function (msg, done) {
    try {
      entmap = JSON.parse(msg.json)
      done()
    }
    catch (e) {
      done(e)
    }
  })

  // Seneca will call init:plugin-name for us. This makes
  // this action a great place to do any setup.
  seneca.add('init:mem-store', function (msg, done) {
    if (options.web.dump) {
      seneca.act('role:web', {
        use: {
          prefix: options.prefix,
          pin: {role: 'mem-store', cmd: '*'},
          map: {dump: true}
        }
      })
    }

    return done()
  })

  // We don't return the store itself, it will self load into Seneca via the
  // init() function. Instead we return a simple object with the stores name
  // and generated meta tag.
  return {
    name: store.name,
    tag: meta.tag,
    exportmap: {
      native: entmap
    }
  }
}

module.exports.preload = function () {
  var seneca = this

  var meta = {
    name: internals.name,
    exportmap: {
      native: function () {
        seneca.export(internals.name + '/native').apply(this, arguments)
      }
    }
  }

  return meta
}

// Seneca supports a reasonable set of features
// in terms of listing. This function can handle
// sorting, skiping, limiting and general retrieval.
function listents (seneca, entmap, qent, q, done) {
  var list = []

  var canon = qent.canon$({object: true})
  var base = canon.base
  var name = canon.name

  var entset = entmap[base] ? entmap[base][name] : null

  if (entset) {
    if (_.isString(q)) {
      var ent = entset[q]
      if (ent) {
        list.push(ent)
      }
    }
    if (_.isArray(q)) {
      _.each(q, function (id) {
        var ent = entset[id]
        if (ent) {
          ent = qent.make$(ent)
          list.push(ent)
        }
      })
    }
    if (_.isObject(q)) {
      _.keys(entset).forEach(function (id) {
        var ent = entset[id]
        for (var p in q) {
          if (!~p.indexOf('$') && q[p] !== ent[p]) {
            return
          }
        }
        ent = qent.make$(ent)
        list.push(ent)
      })
    }
  }

  // Always sort first, this is the 'expected' behaviour.
  if (q.sort$) {
    for (var sf in q.sort$) {
      break
    }

    var sd = q.sort$[sf] < 0 ? -1 : 1
    list = list.sort(function (a, b) {
      return sd * (a[sf] < b[sf] ? -1 : a[sf] === b[sf] ? 0 : 1)
    })
  }

  // Skip before limiting.
  if (q.skip$ && q.skip$ > 0) {
    list = list.slice(q.skip$)
  }

  // Limited the possibly sorted and skipped list.
  if (q.limit$ && q.limit$ >= 0) {
    list = list.slice(0, q.limit$)
  }

  // Return the resulting list to the caller.
  done.call(seneca, null, list)
}


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

<title>Uses of Class org.apache.cassandra.repair.messages.RepairMessage (apache-cassandra API)</title>
<meta name="date" content="2014-09-07">
<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

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.cassandra.repair.messages.RepairMessage

Packages that use RepairMessage

Package
Description

org.apache.cassandra.repair

org.apache.cassandra.repair.messages

org.apache.cassandra.service

Uses of RepairMessage in org.apache.cassandra.repair

Method parameters in org.apache.cassandra.repair with type arguments of type RepairMessage

Modifier and Type
Method and Description

void
RepairMessageVerbHandler.doVerb(MessageIn<RepairMessage> message,
      int id)

Uses of RepairMessage in org.apache.cassandra.repair.messages

Classes in org.apache.cassandra.repair.messages with type parameters of type RepairMessage

Modifier and Type
Interface and Description

static interface
RepairMessage.MessageSerializer<T extends RepairMessage>

Subclasses of RepairMessage in org.apache.cassandra.repair.messages

Modifier and Type
Class and Description

class
AnticompactionRequest

class
PrepareMessage

class
SnapshotMessage

class
SyncComplete

class
SyncRequest

Body part of SYNC_REQUEST repair message.

class
ValidationComplete

ValidationComplete message is sent when validation compaction completed successfully.

class
ValidationRequest

ValidationRequest

Fields in org.apache.cassandra.repair.messages with type parameters of type RepairMessage

Modifier and Type
Field and Description

static IVersionedSerializer<RepairMessage>
RepairMessage.serializer

Methods in org.apache.cassandra.repair.messages that return RepairMessage

Modifier and Type
Method and Description

RepairMessage
RepairMessage.RepairMessageSerializer.deserialize(java.io.DataInput in,
           int version)

Methods in org.apache.cassandra.repair.messages that return types with arguments of type RepairMessage

Modifier and Type
Method and Description

MessageOut<RepairMessage>
RepairMessage.createMessage()

Methods in org.apache.cassandra.repair.messages with parameters of type RepairMessage

Modifier and Type
Method and Description

void
RepairMessage.RepairMessageSerializer.serialize(RepairMessage message,
         DataOutputPlus out,
         int version)

long
RepairMessage.RepairMessageSerializer.serializedSize(RepairMessage message,
              int version)

Uses of RepairMessage in org.apache.cassandra.service

Methods in org.apache.cassandra.service with parameters of type RepairMessage

Modifier and Type
Method and Description

void
ActiveRepairService.handleMessage(java.net.InetAddress endpoint,
             RepairMessage message)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 The Apache Software Foundation


text:
package com.asksunny.jbdstudio.rest;

import java.util.Collections;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

public class InteractiveRestClient {

	public final static String PROMPT = "restclient>";

	public void invoke()
	{
		ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder();

		//clientBuilder.defaultProxy(hostname, port, scheme)
		//clientBuilder.disableTrustManager()
		//clientBuilder.keyStore(keyStore, password)
		//clientBuilder.trustStore(truststore)

		ResteasyClient client = clientBuilder.build();
		ResteasyWebTarget target = client.target("http://localhost:12345/jbdstudio/ping");
		Response response = target.request().get(); //.accept(MediaType.WILDCARD).post(arg0)

		MultivaluedHashMap<String, String> params = new MultivaluedHashMap<String, String>();
		params.put("name", Collections.singletonList("value"));
		//target.request().accept(MediaType.WILDCARD).post(Entity.form(new Form(params)));
		//target.request().accept(MediaType.WILDCARD).put(Entity.form(new Form(params)));

		String ret = response.readEntity(String.class);
		System.out.println(ret);
		response.close();
		client.close();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{

	}

}


text:
=begin
#The Plaid API

#The Plaid REST API. Please see https://plaid.com/docs/api for more details.

The version of the OpenAPI document: 2020-09-14_1.205.3

Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.1

=end

require 'date'
require 'time'

module Plaid
  class PaymentInitiationConsentStatus
    UNAUTHORISED = "UNAUTHORISED".freeze
    AUTHORISED = "AUTHORISED".freeze
    REVOKED = "REVOKED".freeze
    REJECTED = "REJECTED".freeze
    EXPIRED = "EXPIRED".freeze

    # Builds the enum from string
    # @param [String] The enum value in the form of the string
    # @return [String] The enum value
    def self.build_from_hash(value)
      new.build_from_hash(value)
    end

    # Builds the enum from string
    # @param [String] The enum value in the form of the string
    # @return [String] The enum value
    def build_from_hash(value)
      # We do not validate that the value is one of the enums set in the OpenAPI
      # file because we want to be able to add to our list of enums without
      # breaking this client library.
      value
    end
  end

end


text:
define([

], function () {
  function SelectOnClose () { }

  SelectOnClose.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    container.on('close', function () {
      self._handleSelectOnClose();
    });
  };

  SelectOnClose.prototype._handleSelectOnClose = function () {
    var $highlightedResults = this.getHighlightedResults();

    // Only select highlighted results
    if ($highlightedResults.length < 1) {
      return;
    }

    var data = $highlightedResults.data('data');

    // Don't re-select already selected resulte
    if (
      (data.element != null && data.element.selected) ||
      (data.element == null && data.selected)
    ) {
      return;
    }

    this.trigger('select', {
        data: data
    });
  };

  return SelectOnClose;
});


text:
<?php
namespace Modules\Stations\Controllers;

use \Entity\Station;
use \Entity\StationManager;

class VoteController extends BaseController
{
    protected $vote_hash;
    protected $vote_name;

    public function preDispatch()
    {
        parent::preDispatch();

        $user = $this->auth->getLoggedInUser();

        $this->vote_hash = $this->station->id.'_'.md5(strtolower($user->email));
        $this->vote_name = $this->station->name.' ('.$user->name.')';
    }

    public function indexAction()
    {
        $pending_raw = $this->em->createQuery('SELECT s FROM Entity\Station s WHERE s.is_active = 0 ORDER BY s.id DESC')->getArrayResult();

        $pending_stations = array();
        foreach($pending_raw as $station)
        {
            $votes_raw = (array)$station['intake_votes'];

            if (isset($votes_raw[$this->vote_hash]))
                $station['my_vote'] = $votes_raw[$this->vote_hash];

            $pending_stations[$station['id']] = $station;
        }

        $this->view->pending_stations = $pending_stations;
    }

    public function viewAction()
    {
        $id = $this->getParam('id');
        $station = Station::find($id);

        if ($station->is_active)
            throw new \DF\Exception\DisplayOnly('This station has already been reviewed and is active.');

        $station_form = new \DF\Form($this->module_config['frontend']->forms->submit_station);
        $station_form->populate($station->toArray());

        $form = new \DF\Form($this->current_module_config->forms->vote);

        if($_POST && $form->isValid($_POST))
        {
            $data = $form->getValues();
            $data['name'] = $this->vote_name;

            $intake_votes = (array)$station->intake_votes;
            if ($data['decision'] == 'Abstain')
                unset($intake_votes[$this->vote_hash]);
            else
                $intake_votes[$this->vote_hash] = $data;

            $station->intake_votes = $intake_votes;
            $station->save();

            $this->alert('Your vote has been submitted. Thank you for your feedback.', 'green');
            $this->redirectFromHere(array('action' => 'index', 'id' => NULL));
            return;
        }

        $this->view->station_form = $station_form;
        $this->view->form = $form;
    }
}


text:
class FixesToReturnOnlyOneGoalWhenHaveMultiplesWithSameValue < ActiveRecord::Migration
  def up
    execute %Q{
CREATE OR REPLACE VIEW "1"."projects" AS
 SELECT p.id AS project_id,
    p.category_id,
    p.name AS project_name,
    p.headline,
    p.permalink,
    p.mode,
    (p.state)::text AS state,
    so.so AS state_order,
    od.od AS online_date,
    p.recommended,
    thumbnail_image(p.*, 'large'::text) AS project_img,
    remaining_time_json(p.*) AS remaining_time,
    p.expires_at,
    COALESCE(( SELECT
                CASE
                    WHEN (p.mode = 'sub'::text) THEN ( SELECT sum(s_1.amount) AS sum
                       FROM subscriptions s_1
                      WHERE ((s_1.project_id = p.id) AND ((s_1.status)::text = 'active'::text)))
                    ELSE ( SELECT
                            CASE
                                WHEN ((p.state)::text = 'failed'::text) THEN pt.pledged
                                ELSE pt.paid_pledged
                            END AS paid_pledged
                       FROM "1".project_totals pt
                      WHERE (pt.project_id = p.id))
                END AS paid_pledged), (0)::numeric) AS pledged,
    COALESCE(( SELECT
                CASE
                    WHEN (p.mode = 'sub'::text) THEN ((( SELECT sum(s_1.amount) AS sum
                       FROM subscriptions s_1
                      WHERE ((s_1.project_id = p.id) AND ((s_1.status)::text = 'active'::text))) / COALESCE(( SELECT g.value
                       FROM goals g
                      WHERE ((g.project_id = p.id) AND (g.value >= ( SELECT sum(s_1.amount) AS sum
                               FROM subscriptions s_1
                              WHERE ((s_1.project_id = p.id) AND ((s_1.status)::text = 'active'::text))))) limit 1), ( SELECT max(goals.value) AS max
                       FROM goals
                      WHERE (goals.project_id = p.id)))) * (100)::numeric)
                    ELSE ( SELECT pt.progress
                       FROM "1".project_totals pt
                      WHERE (pt.project_id = p.id))
                END AS progress), (0)::numeric) AS progress,
    s.acronym AS state_acronym,
    u.name AS owner_name,
    c.name AS city_name,
    p.full_text_index,
    is_current_and_online(p.expires_at, (p.state)::text) AS open_for_contributions,
    elapsed_time_json(p.*) AS elapsed_time,
    score(p.*) AS score,
    (EXISTS ( SELECT true AS bool
           FROM (contributions c_1
             JOIN user_follows uf ON ((uf.follow_id = c_1.user_id)))
          WHERE ((is_confirmed(c_1.*) AND (uf.user_id = current_user_id())) AND (c_1.project_id = p.id)))) AS contributed_by_friends,
    p.user_id AS project_user_id,
    p.video_embed_url,
    p.updated_at,
    u.public_name AS owner_public_name,
    zone_timestamp(p.expires_at) AS zone_expires_at
   FROM (((((projects p
     JOIN users u ON ((p.user_id = u.id)))
     LEFT JOIN cities c ON ((c.id = p.city_id)))
     LEFT JOIN states s ON ((s.id = c.state_id)))
     JOIN LATERAL zone_timestamp(online_at(p.*)) od(od) ON (true))
     JOIN LATERAL state_order(p.*) so(so) ON (true));
}
  end

  def down
    execute %Q{
CREATE OR REPLACE VIEW "1"."projects" AS
 SELECT p.id AS project_id,
    p.category_id,
    p.name AS project_name,
    p.headline,
    p.permalink,
    p.mode,
    (p.state)::text AS state,
    so.so AS state_order,
    od.od AS online_date,
    p.recommended,
    thumbnail_image(p.*, 'large'::text) AS project_img,
    remaining_time_json(p.*) AS remaining_time,
    p.expires_at,
    COALESCE(( SELECT
                CASE
                    WHEN (p.mode = 'sub'::text) THEN ( SELECT sum(s_1.amount) AS sum
                       FROM subscriptions s_1
                      WHERE ((s_1.project_id = p.id) AND ((s_1.status)::text = 'active'::text)))
                    ELSE ( SELECT
                            CASE
                                WHEN ((p.state)::text = 'failed'::text) THEN pt.pledged
                                ELSE pt.paid_pledged
                            END AS paid_pledged
                       FROM "1".project_totals pt
                      WHERE (pt.project_id = p.id))
                END AS paid_pledged), (0)::numeric) AS pledged,
    COALESCE(( SELECT
                CASE
                    WHEN (p.mode = 'sub'::text) THEN ((( SELECT sum(s_1.amount) AS sum
                       FROM subscriptions s_1
                      WHERE ((s_1.project_id = p.id) AND ((s_1.status)::text = 'active'::text))) / COALESCE(( SELECT g.value
                       FROM goals g
                      WHERE ((g.project_id = p.id) AND (g.value >= ( SELECT sum(s_1.amount) AS sum
                               FROM subscriptions s_1
                              WHERE ((s_1.project_id = p.id) AND ((s_1.status)::text = 'active'::text)))))), ( SELECT max(goals.value) AS max
                       FROM goals
                      WHERE (goals.project_id = p.id)))) * (100)::numeric)
                    ELSE ( SELECT pt.progress
                       FROM "1".project_totals pt
                      WHERE (pt.project_id = p.id))
                END AS progress), (0)::numeric) AS progress,
    s.acronym AS state_acronym,
    u.name AS owner_name,
    c.name AS city_name,
    p.full_text_index,
    is_current_and_online(p.expires_at, (p.state)::text) AS open_for_contributions,
    elapsed_time_json(p.*) AS elapsed_time,
    score(p.*) AS score,
    (EXISTS ( SELECT true AS bool
           FROM (contributions c_1
             JOIN user_follows uf ON ((uf.follow_id = c_1.user_id)))
          WHERE ((is_confirmed(c_1.*) AND (uf.user_id = current_user_id())) AND (c_1.project_id = p.id)))) AS contributed_by_friends,
    p.user_id AS project_user_id,
    p.video_embed_url,
    p.updated_at,
    u.public_name AS owner_public_name,
    zone_timestamp(p.expires_at) AS zone_expires_at
   FROM (((((projects p
     JOIN users u ON ((p.user_id = u.id)))
     LEFT JOIN cities c ON ((c.id = p.city_id)))
     LEFT JOIN states s ON ((s.id = c.state_id)))
     JOIN LATERAL zone_timestamp(online_at(p.*)) od(od) ON (true))
     JOIN LATERAL state_order(p.*) so(so) ON (true));
}
  end
end


text:
package org.bouncycastle.pqc.jcajce.provider.xmss;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.PublicKey;

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.pqc.crypto.util.PublicKeyFactory;
import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory;
import org.bouncycastle.pqc.crypto.xmss.XMSSPublicKeyParameters;
import org.bouncycastle.pqc.jcajce.interfaces.XMSSKey;
import org.bouncycastle.util.Arrays;

public class BCXMSSPublicKey
    implements PublicKey, XMSSKey
{
    private static final long serialVersionUID = -5617456225328969766L;

    private transient XMSSPublicKeyParameters keyParams;
    private transient ASN1ObjectIdentifier treeDigest;

    public BCXMSSPublicKey(
        ASN1ObjectIdentifier treeDigest,
        XMSSPublicKeyParameters keyParams)
    {
        this.treeDigest = treeDigest;
        this.keyParams = keyParams;
    }

    public BCXMSSPublicKey(SubjectPublicKeyInfo keyInfo)
        throws IOException
    {
        init(keyInfo);
    }

    private void init(SubjectPublicKeyInfo keyInfo)
        throws IOException
    {
        this.keyParams = (XMSSPublicKeyParameters)PublicKeyFactory.createKey(keyInfo);
        this.treeDigest = DigestUtil.getDigestOID(keyParams.getTreeDigest());
    }

    /**
     * @return name of the algorithm - "XMSS"
     */
    public final String getAlgorithm()
    {
        return "XMSS";
    }

    public byte[] getEncoded()
    {
        try
        {
            SubjectPublicKeyInfo pki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(keyParams);
            return pki.getEncoded();
        }
        catch (IOException e)
        {
            return null;
        }
    }

    public String getFormat()
    {
        return "X.509";
    }

    CipherParameters getKeyParams()
    {
        return keyParams;
    }

    public boolean equals(Object o)
    {
        if (o == this)
        {
            return true;
        }

        if (o instanceof BCXMSSPublicKey)
        {
            BCXMSSPublicKey otherKey = (BCXMSSPublicKey)o;

            try
            {
                return treeDigest.equals(otherKey.treeDigest) && Arrays.areEqual(keyParams.getEncoded(), otherKey.keyParams.getEncoded());
            }
            catch (IOException e)
            {
                return false;
            }
        }

        return false;
    }

    public int hashCode()
    {
        try
        {
            return treeDigest.hashCode() + 37 * Arrays.hashCode(keyParams.getEncoded());
        }
        catch (IOException e)
        {
            // should never happen, but...
            return treeDigest.hashCode();
        }
    }

    public int getHeight()
    {
        return keyParams.getParameters().getHeight();
    }

    public String getTreeDigest()
    {
        return DigestUtil.getXMSSDigestName(treeDigest);
    }

    private void readObject(
        ObjectInputStream in)
        throws IOException, ClassNotFoundException
    {
        in.defaultReadObject();

        byte[] enc = (byte[])in.readObject();

        init(SubjectPublicKeyInfo.getInstance(enc));
    }

    private void writeObject(
        ObjectOutputStream out)
        throws IOException
    {
        out.defaultWriteObject();

        out.writeObject(this.getEncoded());
    }
}


text:
<?php

/**
 * @file
 * Definition of Drupal\rest\test\DeleteTest.
 */

namespace Drupal\rest\Tests;

use Drupal\Core\Url;

/**
 * Tests the deletion of resources.
 *
 * @group rest
 */
class DeleteTest extends RESTTestBase {

  /**
   * Modules to install.
   *
   * @var array
   */
  public static $modules = array('hal', 'rest', 'entity_test');

  /**
   * Tests several valid and invalid delete requests on all entity types.
   */
  public function testDelete() {
    // Define the entity types we want to test.
    // @todo expand this test to at least users once their access
    // controllers are implemented.
    $entity_types = array('entity_test', 'node');
    foreach ($entity_types as $entity_type) {
      $this->enableService('entity:' . $entity_type, 'DELETE');
      // Create a user account that has the required permissions to delete
      // resources via the REST API.
      $permissions = $this->entityPermissions($entity_type, 'delete');
      $permissions[] = 'restful delete entity:' . $entity_type;
      $account = $this->drupalCreateUser($permissions);
      $this->drupalLogin($account);

      // Create an entity programmatically.
      $entity = $this->entityCreate($entity_type);
      $entity->save();
      // Delete it over the REST API.
      $response = $this->httpRequest($entity->urlInfo(), 'DELETE');
      // Clear the static cache with entity_load(), otherwise we won't see the
      // update.
      $entity = entity_load($entity_type, $entity->id(), TRUE);
      $this->assertFalse($entity, $entity_type . ' entity is not in the DB anymore.');
      $this->assertResponse('204', 'HTTP response code is correct.');
      $this->assertEqual($response, '', 'Response body is empty.');

      // Try to delete an entity that does not exist.
      $response = $this->httpRequest(Url::fromRoute('entity.' . $entity_type . '.canonical', [$entity_type => 9999]), 'DELETE');
      $this->assertResponse(404);
      $this->assertText('The requested page could not be found.');

      // Try to delete an entity without proper permissions.
      $this->drupalLogout();
      // Re-save entity to the database.
      $entity = $this->entityCreate($entity_type);
      $entity->save();
      $this->httpRequest($entity->urlInfo(), 'DELETE');
      $this->assertResponse(403);
      $this->assertNotIdentical(FALSE, entity_load($entity_type, $entity->id(), TRUE), 'The ' . $entity_type . ' entity is still in the database.');
    }
    // Try to delete a resource which is not REST API enabled.
    $this->enableService(FALSE);
    $account = $this->drupalCreateUser();
    $this->drupalLogin($account);
    $this->httpRequest($account->urlInfo(), 'DELETE');
    $user_storage = $this->container->get('entity.manager')->getStorage('user');
    $user_storage->resetCache(array($account->id()));
    $user = $user_storage->load($account->id());
    $this->assertEqual($account->id(), $user->id(), 'User still exists in the database.');
    $this->assertResponse(405);
  }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.0"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>EmbASP-Python v7.1.0: parsers.asp.dlvhex.DLVHEXParser.DLVHEXParser.OutputContext Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

EmbASP-Python v7.1.0

parsers

asp

dlvhex

DLVHEXParser

DLVHEXParser

OutputContext

Public Member Functions |
Public Attributes |
List of all members

parsers.asp.dlvhex.DLVHEXParser.DLVHEXParser.OutputContext Class Reference

Inheritance diagram for parsers.asp.dlvhex.DLVHEXParser.DLVHEXParser.OutputContext:

Public Member Functions

def 	__init__ (self, parser, parent=None, invokingState=-1)

def 	answer_set (self, i=None)

def 	getRuleIndex (self)

def 	accept (self, visitor)

Public Attributes

 	parser

Constructor & Destructor Documentation

◆ __init__()

          def parsers.asp.dlvhex.DLVHEXParser.DLVHEXParser.OutputContext.__init__
          (

          self,

          parser,

          parent = None,

          invokingState = -1

          )

Member Function Documentation

◆ accept()

          def parsers.asp.dlvhex.DLVHEXParser.DLVHEXParser.OutputContext.accept
          (

          self,

          visitor

          )

◆ answer_set()

          def parsers.asp.dlvhex.DLVHEXParser.DLVHEXParser.OutputContext.answer_set
          (

          self,

          i = None

          )

◆ getRuleIndex()

          def parsers.asp.dlvhex.DLVHEXParser.DLVHEXParser.OutputContext.getRuleIndex
          (

          self	)

Member Data Documentation

◆ parser

          parsers.asp.dlvhex.DLVHEXParser.DLVHEXParser.OutputContext.parser

The documentation for this class was generated from the following file:

embasp-python/parsers/asp/dlvhex/DLVHEXParser.py

<address class="footer">
Generated by  1.9.0
</address>