text:
int main()
{
    assert(std::regex_constants::match_default == 0);
    assert(std::regex_constants::match_not_bol != 0);
    assert(std::regex_constants::match_not_eol != 0);
    assert(std::regex_constants::match_not_bow != 0);
    assert(std::regex_constants::match_not_eow != 0);
    assert(std::regex_constants::match_any != 0);
    assert(std::regex_constants::match_not_null != 0);
    assert(std::regex_constants::match_continuous != 0);
    assert(std::regex_constants::match_prev_avail != 0);
    assert(std::regex_constants::format_default == 0);
    assert(std::regex_constants::format_sed != 0);
    assert(std::regex_constants::format_no_copy != 0);
    assert(std::regex_constants::format_first_only != 0);

    assert((std::regex_constants::match_not_bol & std::regex_constants::match_not_eol) == 0);
    assert((std::regex_constants::match_not_bol & std::regex_constants::match_not_bow) == 0);
    assert((std::regex_constants::match_not_bol & std::regex_constants::match_not_eow) == 0);
    assert((std::regex_constants::match_not_bol & std::regex_constants::match_any) == 0);
    assert((std::regex_constants::match_not_bol & std::regex_constants::match_not_null) == 0);
    assert((std::regex_constants::match_not_bol & std::regex_constants::match_continuous) == 0);
    assert((std::regex_constants::match_not_bol & std::regex_constants::match_prev_avail) == 0);
    assert((std::regex_constants::match_not_bol & std::regex_constants::format_sed) == 0);
    assert((std::regex_constants::match_not_bol & std::regex_constants::format_no_copy) == 0);
    assert((std::regex_constants::match_not_bol & std::regex_constants::format_first_only) == 0);

    assert((std::regex_constants::match_not_eol & std::regex_constants::match_not_bow) == 0);
    assert((std::regex_constants::match_not_eol & std::regex_constants::match_not_eow) == 0);
    assert((std::regex_constants::match_not_eol & std::regex_constants::match_any) == 0);
    assert((std::regex_constants::match_not_eol & std::regex_constants::match_not_null) == 0);
    assert((std::regex_constants::match_not_eol & std::regex_constants::match_continuous) == 0);
    assert((std::regex_constants::match_not_eol & std::regex_constants::match_prev_avail) == 0);
    assert((std::regex_constants::match_not_eol & std::regex_constants::format_sed) == 0);
    assert((std::regex_constants::match_not_eol & std::regex_constants::format_no_copy) == 0);
    assert((std::regex_constants::match_not_eol & std::regex_constants::format_first_only) == 0);

    assert((std::regex_constants::match_not_bow & std::regex_constants::match_not_eow) == 0);
    assert((std::regex_constants::match_not_bow & std::regex_constants::match_any) == 0);
    assert((std::regex_constants::match_not_bow & std::regex_constants::match_not_null) == 0);
    assert((std::regex_constants::match_not_bow & std::regex_constants::match_continuous) == 0);
    assert((std::regex_constants::match_not_bow & std::regex_constants::match_prev_avail) == 0);
    assert((std::regex_constants::match_not_bow & std::regex_constants::format_sed) == 0);
    assert((std::regex_constants::match_not_bow & std::regex_constants::format_no_copy) == 0);
    assert((std::regex_constants::match_not_bow & std::regex_constants::format_first_only) == 0);

    assert((std::regex_constants::match_not_eow & std::regex_constants::match_any) == 0);
    assert((std::regex_constants::match_not_eow & std::regex_constants::match_not_null) == 0);
    assert((std::regex_constants::match_not_eow & std::regex_constants::match_continuous) == 0);
    assert((std::regex_constants::match_not_eow & std::regex_constants::match_prev_avail) == 0);
    assert((std::regex_constants::match_not_eow & std::regex_constants::format_sed) == 0);
    assert((std::regex_constants::match_not_eow & std::regex_constants::format_no_copy) == 0);
    assert((std::regex_constants::match_not_eow & std::regex_constants::format_first_only) == 0);

    assert((std::regex_constants::match_any & std::regex_constants::match_not_null) == 0);
    assert((std::regex_constants::match_any & std::regex_constants::match_continuous) == 0);
    assert((std::regex_constants::match_any & std::regex_constants::match_prev_avail) == 0);
    assert((std::regex_constants::match_any & std::regex_constants::format_sed) == 0);
    assert((std::regex_constants::match_any & std::regex_constants::format_no_copy) == 0);
    assert((std::regex_constants::match_any & std::regex_constants::format_first_only) == 0);

    assert((std::regex_constants::match_not_null & std::regex_constants::match_continuous) == 0);
    assert((std::regex_constants::match_not_null & std::regex_constants::match_prev_avail) == 0);
    assert((std::regex_constants::match_not_null & std::regex_constants::format_sed) == 0);
    assert((std::regex_constants::match_not_null & std::regex_constants::format_no_copy) == 0);
    assert((std::regex_constants::match_not_null & std::regex_constants::format_first_only) == 0);

    assert((std::regex_constants::match_continuous & std::regex_constants::match_prev_avail) == 0);
    assert((std::regex_constants::match_continuous & std::regex_constants::format_sed) == 0);
    assert((std::regex_constants::match_continuous & std::regex_constants::format_no_copy) == 0);
    assert((std::regex_constants::match_continuous & std::regex_constants::format_first_only) == 0);

    assert((std::regex_constants::match_prev_avail & std::regex_constants::format_sed) == 0);
    assert((std::regex_constants::match_prev_avail & std::regex_constants::format_no_copy) == 0);
    assert((std::regex_constants::match_prev_avail & std::regex_constants::format_first_only) == 0);

    assert((std::regex_constants::format_sed & std::regex_constants::format_no_copy) == 0);
    assert((std::regex_constants::format_sed & std::regex_constants::format_first_only) == 0);

    assert((std::regex_constants::format_no_copy & std::regex_constants::format_first_only) == 0);

    std::regex_constants::match_flag_type e1 = std::regex_constants::match_not_bol;
    std::regex_constants::match_flag_type e2 = std::regex_constants::match_not_eol;
    e1 = ~e1;
    e1 = e1 & e2;
    e1 = e1 | e2;
    e1 = e1 ^ e2;
    e1 &= e2;
    e1 |= e2;
    e1 ^= e2;
}


text:
/*
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.ocs.dynamo.filter;

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

/**
 * Interface for objects that
 *
 * @author bas.rutten
 */
public interface Filter {

    /**
     * Evaluates an object against the filter
     *
     * @param that
     *            the object to evaluate
     * @return
     */
    boolean evaluate(Object that);

    /**
     * Applies the filter to a collection of objects, and retunrs the objects that match the filter
     *
     * @param collection
     * @return
     */
    <T> List<T> applyFilter(Collection<T> collection);

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

module.exports = function(grunt) {

  // Nodejs libs.
  var path = require('path');
  var url = require('url');

  // External lib.
  var phantomjs = require('grunt-lib-phantomjs').init(grunt);

  // Keep track of the last-started module, test and status.
  var options, currentModule, currentTest, status;
  // Keep track of the last-started test(s).
  var unfinished = {};

  // Get an asset file, local to the root of the project.
  var asset = path.join.bind(null, __dirname, '..');

  // Allow an error message to retain its color when split across multiple lines.
  var formatMessage = function(str) {
    return String(str).split('\n').map(function(s) { return s.magenta; }).join('\n');
  };

  // If options.force then log an error, otherwise exit with a warning
  var warnUnlessForced = function (message) {
    if (options && options.force) {
      grunt.log.error(message);
    } else {
      grunt.warn(message);
    }
  };

  // Keep track of failed assertions for pretty-printing.
  var failedAssertions = [];
  var logFailedAssertions = function() {
    var assertion;
    // Print each assertion error.
    while (assertion = failedAssertions.shift()) {
      grunt.verbose.or.error(assertion.testName);
      grunt.log.error('Message: ' + formatMessage(assertion.message));
      if (assertion.actual !== assertion.expected) {
        grunt.log.error('Actual: ' + formatMessage(assertion.actual));
        grunt.log.error('Expected: ' + formatMessage(assertion.expected));
      }
      if (assertion.source) {
        grunt.log.error(assertion.source.replace(/ {4}(at)/g, '  $1'));
      }
      grunt.log.writeln();
    }
  };

  // QUnit hooks.
  phantomjs.on('qunit.moduleStart', function(name) {
    unfinished[name] = true;
    currentModule = name;
  });

  phantomjs.on('qunit.moduleDone', function(name/*, failed, passed, total*/) {
    delete unfinished[name];
  });

  phantomjs.on('qunit.log', function(result, actual, expected, message, source) {
    if (!result) {
      failedAssertions.push({
        actual: actual, expected: expected, message: message, source: source,
        testName: currentTest
      });
    }
  });

  phantomjs.on('qunit.testStart', function(name) {
    currentTest = (currentModule ? currentModule + ' - ' : '') + name;
    grunt.verbose.write(currentTest + '...');
  });

  phantomjs.on('qunit.testDone', function(name, failed/*, passed, total*/) {
    // Log errors if necessary, otherwise success.
    if (failed > 0) {
      // list assertions
      if (grunt.option('verbose')) {
        grunt.log.error();
        logFailedAssertions();
      } else {
        grunt.log.write('F'.red);
      }
    } else {
      grunt.verbose.ok().or.write('.');
    }
  });

  phantomjs.on('qunit.done', function(failed, passed, total, duration) {
    phantomjs.halt();
    status.failed += failed;
    status.passed += passed;
    status.total += total;
    status.duration += duration;
    // Print assertion errors here, if verbose mode is disabled.
    if (!grunt.option('verbose')) {
      if (failed > 0) {
        grunt.log.writeln();
        logFailedAssertions();
      } else if (total === 0) {
        warnUnlessForced('0/0 assertions ran (' + duration + 'ms)');
      } else {
        grunt.log.ok();
      }
    }
  });

  // Re-broadcast qunit events on grunt.event.
  phantomjs.on('qunit.*', function() {
    var args = [this.event].concat(grunt.util.toArray(arguments));
    grunt.event.emit.apply(grunt.event, args);
  });

  // Built-in error handlers.
  phantomjs.on('fail.load', function(url) {
    phantomjs.halt();
    grunt.verbose.write('...');
    grunt.event.emit('qunit.fail.load', url);
    grunt.log.error('PhantomJS unable to load "' + url + '" URI.');
    status.failed += 1;
    status.total += 1;
  });

  phantomjs.on('fail.timeout', function() {
    phantomjs.halt();
    grunt.log.writeln();
    grunt.event.emit('qunit.fail.timeout');
    grunt.log.error('PhantomJS timed out, possibly due to a missing QUnit start() call.');
    status.failed += 1;
    status.total += 1;
  });

  phantomjs.on('error.onError', function (msg, stackTrace) {
    grunt.event.emit('qunit.error.onError', msg, stackTrace);
    grunt.log.warn('PhantomJS error:\n', msg, '\n', stackTrace);
  });

  grunt.registerMultiTask('qunit', 'Run QUnit unit tests in a headless PhantomJS instance.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    options = this.options({
      // Default PhantomJS timeout.
      timeout: 5000,
      // QUnit-PhantomJS bridge file to be injected.
      inject: asset('phantomjs/bridge.js'),
      // Explicit non-file URLs to test.
      urls: [],
      force: false,
      // Connect phantomjs console output to grunt output
      console: true,
      // Do not use an HTTP base by default
      httpBase: false
    });

    var urls;

    if (options.httpBase) {
      //If URLs are explicitly referenced, use them still
      urls = options.urls;
      // Then create URLs for the src files
      this.filesSrc.forEach(function(testFile) {
        urls.push(options.httpBase + '/' + testFile);
      });
    } else {
      // Combine any specified URLs with src files.
      urls = options.urls.concat(this.filesSrc);
    }

    if (options.noGlobals) {
      // Append a noglobal query string param to all urls
      var parsed;
      urls = urls.map(function(testUrl) {
        parsed = url.parse(testUrl, true);
        parsed.query.noglobals = "";
        delete parsed.search;
        return url.format(parsed);
      });
    }

    // This task is asynchronous.
    var done = this.async();

    // Reset status.
    status = {failed: 0, passed: 0, total: 0, duration: 0};

    // Pass-through console.log statements.
    if(options.console) {
      phantomjs.on('console', console.log.bind(console));
    }

    // Process each filepath in-order.
    grunt.util.async.forEachSeries(urls, function(url, next) {
      grunt.verbose.subhead('Testing ' + url + ' ').or.write('Testing ' + url + ' ');

      // Reset current module.
      currentModule = null;

      // Launch PhantomJS.
      grunt.event.emit('qunit.spawn', url);
      phantomjs.spawn(url, {
        // Additional PhantomJS options.
        options: options,
        // Do stuff when done.
        done: function(err) {
          if (err) {
            // If there was an error, abort the series.
            done();
          } else {
            // Otherwise, process next url.
            next();
          }
        },
      });
    },
    // All tests have been run.
    function() {
      // Log results.
      if (status.failed > 0) {
        warnUnlessForced(status.failed + '/' + status.total +
            ' assertions failed (' + status.duration + 'ms)');
      } else if (status.total === 0) {
        warnUnlessForced('0/0 assertions ran (' + status.duration + 'ms)');
      } else {
        grunt.verbose.writeln();
        grunt.log.ok(status.total + ' assertions passed (' + status.duration + 'ms)');
      }
      // All done!
      done(status.failed === 0);
    });
  });

};


text:
package com.ning.http.util;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.Security;

/**
 * This class is a copy of http://github.com/sonatype/wagon-ning/raw/master/src/main/java/org/apache/maven/wagon/providers/http/SslUtils.java
 */
public class SslUtils {

    public static SSLEngine getSSLEngine()
            throws GeneralSecurityException, IOException {
        SSLEngine engine = null;

        SSLContext context = getSSLContext();
        if (context != null) {
            engine = context.createSSLEngine();
            engine.setUseClientMode(true);
        }

        return engine;
    }

    public static SSLContext getSSLContext()
            throws GeneralSecurityException, IOException {
        SSLConfig config = new SSLConfig();
        if (config.keyStoreLocation == null || config.trustStoreLocation == null) {
            return getLooseSSLContext();
        } else {
            return getStrictSSLContext(config);
        }
    }

    static SSLContext getStrictSSLContext(SSLConfig config)
            throws GeneralSecurityException, IOException {
        KeyStore keyStore = KeyStore.getInstance(config.keyStoreType);
        InputStream keystoreInputStream = new FileInputStream(config.keyStoreLocation);
        try {
            keyStore.load(keystoreInputStream, (config.keyStorePassword == null) ? null
                    : config.keyStorePassword.toCharArray());
        } finally {
            keystoreInputStream.close();
        }

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(config.keyManagerAlgorithm);
        keyManagerFactory.init(keyStore, (config.keyManagerPassword == null) ? null
                : config.keyManagerPassword.toCharArray());
        KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

        KeyStore trustStore = KeyStore.getInstance(config.trustStoreType);
        InputStream truststoreInputStream = new FileInputStream(config.trustStoreLocation);
        try {
            trustStore.load(truststoreInputStream, (config.trustStorePassword == null) ? null
                    : config.trustStorePassword.toCharArray());
        } finally {
            truststoreInputStream.close();
        }

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(config.trustManagerAlgorithm);
        trustManagerFactory.init(trustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagers, trustManagers, null);

        return context;
    }

    static SSLContext getLooseSSLContext()
            throws GeneralSecurityException {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{LooseTrustManager.INSTANCE}, new SecureRandom());
        return sslContext;
    }

    static class LooseTrustManager
            implements X509TrustManager {

        public static final LooseTrustManager INSTANCE = new LooseTrustManager();

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[0];
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    }

    private final static class SSLConfig {

        public String keyStoreLocation;

        public String keyStoreType = "JKS";

        public String keyStorePassword = "changeit";

        public String keyManagerAlgorithm = "SunX509";

        public String keyManagerPassword = "changeit";

        public String trustStoreLocation;

        public String trustStoreType = "JKS";

        public String trustStorePassword = "changeit";

        public String trustManagerAlgorithm = "SunX509";

        public SSLConfig() {
            keyStoreLocation = System.getProperty("javax.net.ssl.keyStore");
            keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword", "changeit");
            keyStoreType = System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType());
            keyManagerAlgorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");

            if (keyManagerAlgorithm == null) {
                keyManagerAlgorithm = "SunX509";
            }

            keyManagerPassword = System.getProperty("javax.net.ssl.keyStorePassword", "changeit");

            trustStoreLocation = System.getProperty("javax.net.ssl.trustStore");
            if (trustStoreLocation == null) {
                trustStoreLocation = keyStoreLocation;
                trustStorePassword = keyStorePassword;
                trustStoreType = keyStoreType;
            } else {
                trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword", "changeit");
                trustStoreType = System.getProperty("javax.net.ssl.trustStoreType", KeyStore.getDefaultType());
            }
            trustManagerAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm");

            if (trustManagerAlgorithm == null) {
                trustManagerAlgorithm = "SunX509";
            }
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/padding_vertical"
        android:paddingBottom="@dimen/padding_vertical"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/message_received"
        android:gravity="center" />

    <TextView
        android:id="@+id/message_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/padding_vertical"
        android:paddingBottom="@dimen/padding_vertical"
        android:paddingLeft="@dimen/padding_horizontal"
        android:paddingRight="@dimen/padding_horizontal"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>


text:
//
//  ContactsWrapper.h
//  ContactsWrapper
//
//  Created by Abdullah Selek on 01/08/16.
//  Copyright © 2016 Abdullah Selek. All rights reserved.
//
//  The MIT License (MIT)
//
//  Copyright (c) 2016 Abdullah Selek
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.

#import <Foundation/Foundation.h>
#import <Contacts/Contacts.h>

#define BLOCK_EXEC(block, ...) if (block) { block(__VA_ARGS__); };

NS_ASSUME_NONNULL_BEGIN

@interface ContactsWrapper : NSObject

/**
  * Singleton for Contacts Wrapper
  *
  * @return Instance
 */
+ (instancetype)sharedInstance;

/**
  * Get All Contacts with their Family Name, Given Name, Phone Numbers, Image Data
  *
  * @param containerId Container id
  * @param completionBlock Nullable contacts and error
 */
- (void)getContactsWithContainerId:(nullable NSString *)containerId completionBlock:(void (^)(NSArray<CNContact *> * _Nullable contacts, NSError  * _Nullable error))completionBlock;

/**
  * Get All Contacts with given keys
  *
  * @param keys Keys for filling contact data
  * @param containerId Container id
  * @param completionBlock Nullable contacts and error
 */
- (void)getContactsWithKeys:(NSArray<id<CNKeyDescriptor>> *)keys
                containerId:(nullable NSString *)containerId
            completionBlock:(void (^)(NSArray<CNContact *> * _Nullable contacts, NSError  * _Nullable error))completionBlock;

/**
  * Save given contact
  *
  * @param contact Contact object to save
  * @param containerId Container id
  * @param completionBlock isSuccess and error
 */
- (void)saveContact:(CNMutableContact *)contact
        containerId:(nullable NSString *)containerId
    completionBlock:(void (^)(BOOL isSuccess, NSError *error))completionBlock;

/**
  * Get Contacts with given name
  *
  * @param givenName Given name
  * @param completionBlock Nullable contacts and error
 */
- (void)getContactsWithGivenName:(NSString *)givenName
                 completionBlock:(void (^)(NSArray<CNContact *> * _Nullable contacts, NSError * _Nullable error))completionBlock;

/**
 * Get Contacts with given name
 *
 * @param givenName Given name
 * @param familyName Family name
 * @param completionBlock Nullable contacts and error
 */
- (void)getContactsWithGivenName:(NSString *)givenName
                      familyName:(NSString *)familyName
                 completionBlock:(void (^)(NSArray<CNContact *> * _Nullable contacts, NSError * _Nullable error))completionBlock;

/**
  * Update given contact
  *
  * @param completionBlock isSuccess and error
 */
- (void)updateContact:(CNMutableContact *)contact
      completionBlock:(void (^)(BOOL isSuccess, NSError * _Nullable error))completionBlock;

/**
  * Get contacts with given email address
  *
  * @param emailAddress Email address
  * @param completionBlock Nullable contacts and error
 */
- (void)getContactsWithEmailAddress:(NSString *)emailAddress
                    completionBlock:(void (^)(NSArray<CNContact *> * _Nullable contacts, NSError * _Nullable error))completionBlock;

/**
  * Delete given contact
  *
  * @param completionBlock isSuccess and error
 */
- (void)deleteContact:(CNContact *)contact
      completionBlock:(void (^)(BOOL isSuccess, NSError * _Nullable error))completionBlock;

/**
  * Add given group to contacts list
  *
  * @param group Group to add
  * @param containerId Container id
  * @param completionBlock isSuccess and error
 */
- (void)addGroup:(CNMutableGroup *)group
     containerId:(nullable NSString *)containerId
 completionBlock:(void (^)(BOOL isSuccess, NSError * _Nullable error))completionBlock;

/**
  * Delete given group
  *
  * @param completionBlock isSuccess and error
 */
- (void)deleteGroup:(CNMutableGroup *)group
    completionBlock:(void (^)(BOOL isSuccess, NSError * _Nullable error))completionBlock;

/**
  * Update given group
  *
  * @param completionBlock isSuccess and error
 */
- (void)updateGroup:(CNMutableGroup *)group
    completionBlock:(void (^)(BOOL isSuccess, NSError * _Nullable error))completionBlock;

/**
  * Add given contact to given group
  *
  * @param contact Contact will be added to group
  * @param group Group which contact will be added in
  * @param completionBlock isSuccess and error
 */
- (void)addGroupMember:(CNContact *)contact
                 group:(CNGroup *)group
       completionBlock:(void (^)(BOOL isSuccess, NSError * _Nullable error))completionBlock;

/**
  * Add given contacts to given group
  *
  * @param contacts Contacts will be added to group
  * @param group Group which contact will be added in
  * @param completionBlock isSuccess and error
 */
- (void)addGroupMembers:(NSArray<CNMutableContact *> *)contacts
                  group:(CNGroup *)group
        completionBlock:(void (^)(BOOL isSuccess, NSError * _Nullable error))completionBlock;

/**
  * Get groups
  *
  * @param containerId Container id
  * @param completionBlock Nullable groups and error
 */
- (void)getGroupsWithContainerId:(nullable NSString *)containerId completionBlock:(void (^)(NSArray<CNGroup *> * _Nullable groups, NSError * _Nullable error))completionBlock;

/**
  * Get containers
  *
  * @param completionBlock Nullable container and error
 */
- (void)getContainers:(void (^)(NSArray<CNContainer *> * _Nullable containers, NSError * _Nullable error))completionBlock;

@end

NS_ASSUME_NONNULL_END


text:
Modifier ereplace
=================

Perform a regular expression search and replace.
[Read more](http://www.php.net/manual/en/reference.pcre.pattern.syntax.php) about regular expression.

```
{$string|replace:$pattern:$replacement}
```

Searches `$string` for matches to `$pattern` and replaces them with `$replacement`.

`$replacement` may contain references of the form `\n`, `$n` or `${n}`, with the latter form being the preferred one.
Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99,
and `\0` or `$0` refers to the text matched by the whole pattern.
Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern.
To use backslash in replacement, it must be doubled.

```smarty
{var $string = 'April 15, 2014'}

{$string|ereplace:'/(\w+) (\d+), (\d+)/i':'${1}1, $3'} {* April1, 2014 *}
```


text:
package solr

import (
	"fmt"
	"net/url"
	"os"
	"strings"
	"testing"
)

func TestMain(m *testing.M) {
	go mockStartServer()
	os.Exit(m.Run())
}

var solrUrl = "http://127.0.0.1:12345/solr"

func TestSolrDocument(t *testing.T) {
	d := Document{"id": "test_id", "title": "test title"}
	if d.Has("id") == false {
		t.Errorf("Has id expected to be true")
	}

	if d.Has("not_exist") == true {
		t.Errorf("Has not_exist expected to be false")
	}

	if d.Get("title").(string) != "test title" {
		t.Errorf("title expected to have value 'test title'")
	}

	d.Set("new_title", "new title")
	if d.Get("new_title").(string) != "new title" {
		t.Errorf("new_title expected to have value 'new title'")
	}

	if d.Get("not_exist") != nil {
		t.Errorf("Get not_exist key should return nil but got '%s'", d.Get("not_exist"))
	}
}

func TestSolrInvalidUrl(t *testing.T) {
	_, err := NewSolrInterface("sdff", "")
	if err == nil {
		t.Errorf("Expected an error")
		return
	}
	expected := "parse sdff: invalid URI for request"
	if err.Error() != expected {
		t.Errorf("expected '%s' but got '%s'", expected, err.Error())
	}
}

func TestSolrNoConnection(t *testing.T) {
	si := SolrInterface{}
	_, err := si.Update(nil, nil)
	if err == nil {
		t.Errorf("Expected an error")
		return
	}
	expected := "No connection found for making request to solr"
	if err.Error() != expected {
		t.Errorf("expected '%s' but got '%s'", expected, err.Error())
	}
}

func TestSolrSuccessSelect(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/success", "core0")

	if err != nil {
		t.Errorf("Can not instance a new solr interface, err: %s", err)
	}

	q := NewQuery()
	q.AddParam("q", "*:*")
	s := si.Search(q)

	res, err := s.Result(nil)

	if err != nil {
		t.Errorf("cannot seach %s", err)
	}

	if res.Status != 0 {
		t.Errorf("Status expected to be 0")
	}

	if res.Results.NumFound != 1 {
		t.Errorf("results.numFound expected to be 1")
	}

	if res.Results.Start != 0 {
		t.Errorf("results.start expected to be 0")
	}

	if len(res.Results.Docs) != 1 {
		t.Errorf("len of .docs should be 1")
	}

	if res.Results.Docs[0].Get("id").(string) != "change.me" {
		t.Errorf("id of first document should be change.me")
	}
}

func TestSolrRealTimeGetSuccess(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/realtimegetsuccess", "core0")
	if err != nil {
		t.Errorf("Can not instance a new solr interface, err: %s", err)
	}

	q := NewQuery()
	q.AddParam("id", "123")
	s := si.Search(q)
	res, err := s.RealTimeGet(nil)
	if err != nil {
		t.Errorf("cannot get %s", err)
	}

	if res.Results.NumFound != 1 {
		t.Errorf("results.numFound expected to be 1")
	}

	if len(res.Results.Docs) != 1 {
		t.Errorf("len of results.docs should be 1")
	}

	if res.Results.Docs[0].Get("id").(string) != "123" {
		t.Errorf("id of document should be 123")
	}
}

func TestSolrRealTimeGetFail(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/realtimegetfail", "core0")
	if err != nil {
		t.Errorf("Can not instance a new solr interface, err: %s", err)
	}

	q := NewQuery()
	q.AddParam("id", "")
	s := si.Search(q)
	_, err = s.RealTimeGet(nil)
	if err == nil {
		t.Errorf("Expected an error")
	}
}

func TestSolrConnectionPostWithoutDataSucces(t *testing.T) {
	_, err := HTTPPost(fmt.Sprintf("%s/collection1/schema", solrUrl), nil, nil, "", "", 0)
	if err != nil {
		t.Errorf("Not expected an error")
		return
	}
}

func TestSolrConnectionPostWithoutDataError(t *testing.T) {
	_, err := HTTPPost("http://www.fakedomain.tld/collection1/schema", nil, nil, "", "", 0)
	if err == nil {
		t.Errorf("Expected an error")
		return
	}
	expected := "Post http://www.fakedomain.tld/collection1/schema: dial tcp"
	error_report := err.Error()

	if strings.HasPrefix(error_report, expected) == false {
		t.Errorf("expected '%s' but got '%s'", expected, err.Error())
	}
}

func TestSolrConnectionGetWithHeadersError(t *testing.T) {
	_, err := HTTPGet("http://www.fakedomain.tld/collection1/schema", [][]string{{"Content-Type", "application/json"}}, "", "", 0)
	if err == nil {
		t.Errorf("Expected an error")
		return
	}
	expected := "Get http://www.fakedomain.tld/collection1/schema: dial tcp"
	error_report := err.Error()
	if strings.HasPrefix(error_report, expected) == false {
		t.Errorf("expected '%s' but got '%s'", expected, err.Error())
	}
}

func TestSolrFailSelect(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/fail", "core0")

	if err != nil {
		t.Errorf("Can not instance a new solr interface, err: %s", err)
	}

	q := NewQuery()
	q.AddParam("q", "*:*")
	s := si.Search(q)

	parser := new(StandardResultParser)
	res, err := s.Result(parser)

	if err != nil {
		t.Errorf("cannot seach %s", err)
	}

	if res.Status != 400 {
		t.Errorf("Status expected to be 400")
	}
	expectedMsg := "no field name specified in query and no default specified via 'df' param"
	msg, ok := res.Error["msg"].(string)
	if ok != true {
		t.Errorf("error expected to have a message")
	}

	if msg != expectedMsg {
		t.Errorf("Error msg expected to be '%s' but got '%s'", expectedMsg, msg)
	}

	if res.Results.NumFound != 0 {
		t.Errorf("results.numFound expected to be 0")
	}

	if res.Results.Start != 0 {
		t.Errorf("results.start expected to be 0")
	}

	if len(res.Results.Docs) != 0 {
		t.Errorf("len of .docs should be 0")
	}

}

func TestSolrFacetSelect(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/facet_counts", "core0")

	if err != nil {
		t.Errorf("Can not instance a new solr interface, err: %s", err)
	}

	q := NewQuery()
	q.AddParam("q", "*:*")
	q.AddParam("facet", "true")
	q.AddParam("facet.field", "id")

	s := si.Search(q)
	parser := new(StandardResultParser)
	res, err := s.Result(parser)

	if err != nil {
		t.Errorf("cannot seach %s", err)
	}

	if res.Status != 0 {
		t.Errorf("Status expected to be 0 but got %d", res.Status)
	}

	if res.Results.NumFound != 4 {
		t.Errorf("results.numFound expected to be 4 but got %d", res.Results.NumFound)
	}

	if res.Results.Start != 0 {
		t.Errorf("results.start expected to be 0 but got %d", res.Results.Start)
	}

	if len(res.Results.Docs) != 4 {
		t.Errorf("len of .docs should be 4 but got %d", len(res.Results.Docs))
	}

	third_doc := res.Results.Docs[2]

	if third_doc.Get("id") != "change.me3" {
		t.Errorf("id of third document expected to be 'change.me3' but got '%s'", third_doc.Get("id"))
	}

	if _, ok := res.FacetCounts["facet_fields"]; ok == false {
		t.Errorf("results.facet_counts.facet_fields expected")
		return
	}

	facet_fields := res.FacetCounts["facet_fields"].(map[string]interface{})
	id, ok := facet_fields["id"]

	if ok == false {
		t.Errorf("results.facet_counts.facet_fields.id expected")
		return
	}

	id_len := len(id.([]interface{}))

	if id_len != 6 {
		t.Errorf("results.facet_counts.facet_fields.id.len expected be 6 but got %d", id_len)
	}

	if _, ok := res.ResponseHeader["params"]; ok == false {
		t.Errorf("ResponseHeader should contain param key")
	}
}

func TestSolrHighlightSelect(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/highlight", "core0")

	if err != nil {
		t.Errorf("Can not instance a new solr interface, err: %s", err)
	}

	q := NewQuery()
	q.AddParam("q", "*:*")
	q.AddParam("hl", "true")

	s := si.Search(q)
	parser := new(StandardResultParser)
	res, err := s.Result(parser)

	if err != nil {
		t.Errorf("cannot seach %s", err)
	}

	if res.Status != 0 {
		t.Errorf("Status expected to be 0 but got %d", res.Status)
	}

	if res.Results.NumFound != 4 {
		t.Errorf("results.numFound expected to be 4 but got %d", res.Results.NumFound)
	}

	if res.Results.Start != 0 {
		t.Errorf("results.start expected to be 0 but got %d", res.Results.Start)
	}

	if len(res.Results.Docs) != 4 {
		t.Errorf("len of .docs should be 4 but got %d", len(res.Results.Docs))
	}

	third_doc := res.Results.Docs[2]

	if third_doc.Get("id") != "change.me3" {
		t.Errorf("id of third document expected to be 'change.me3' but got '%s'", third_doc.Get("id"))
	}

	_, ok := res.Highlighting["change.me"]

	if ok == false {
		t.Errorf("results.facet_counts.facet_fields.id expected")
		return
	}
}

func TestSolrResultLoopSelect(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/facet_counts", "core0")
	if err != nil {
		t.Errorf("Can not instance a new solr interface, err: %s", err)
	}
	q := NewQuery()
	q.AddParam("q", "*:*")
	q.AddParam("facet", "true")
	q.AddParam("facet.field", "id")
	s := si.Search(q)
	res, err := s.Result(nil)

	if err != nil {
		t.Errorf("Should not have an error here, skip assertions below. Please fix!")
		return
	}

	if cap(res.Results.Docs) != 4 {
		t.Errorf("Capacity expected to be 4 but got '%d'", cap(res.Results.Docs))
	}

	if len(res.Results.Docs) != 4 {
		t.Errorf("len of .docs should be 4 but got %d", len(res.Results.Docs))
	}

	for i, doc := range res.Results.Docs {
		if doc.Has("id") == false {
			t.Errorf("Document %d doesn't contain id", i)
		}
	}

	for i := 0; i < len(res.Results.Docs); i++ {
		if res.Results.Docs[i].Has("id") == false {
			t.Errorf("Document %d doesn't contain id", i)
		}
	}

}

func TestSolrSuccessStandaloneCommit(t *testing.T) {

	si, err := NewSolrInterface("http://127.0.0.1:12345/standalonecommit", "core0")

	if err != nil {
		t.Errorf("Can not instance a new solr interface, err: %s", err)
	}

	res, err := si.Commit()

	if err != nil {
		t.Errorf("cannot commit %s", err)
	}

	if res.Success != true {
		t.Errorf("success expected to be true")
	}
}

func TestSolrSuccessStandaloneSoftCommit(t *testing.T) {

	si, err := NewSolrInterface("http://127.0.0.1:12345/standalonesoftcommit", "core0")

	if err != nil {
		t.Errorf("Can not instance a new solr interface, err: %s", err)
	}

	res, err := si.SoftCommit()

	if err != nil {
		t.Errorf("cannot soft commit %s", err)
	}

	if res.Success != true {
		t.Errorf("success expected to be true")
	}
}

func TestMakeAddChunks(t *testing.T) {
	docs := make([]Document, 0, 100)
	for i := 0; i < 500; i++ {
		docs = append(docs, Document{"id": fmt.Sprintf("test_id_%d", i), "title": fmt.Sprintf("add sucess %d", i)})
	}
	chunks := makeAddChunks(docs, 100)
	expected_len := 5
	if len(chunks) != expected_len {
		t.Errorf("Chunks length expected to be '%d' but got '%d'", expected_len, len(chunks))
	}

	d := chunks[0]["add"].([]Document)[0]

	if d.Get("id") != "test_id_0" {
		t.Errorf("First element in first chunk should have id test_id_0 ")
	}

	d = chunks[1]["add"].([]Document)[0]

	if d.Get("id") != "test_id_100" {
		t.Errorf("First element in second chunk should have id test_id_100 ")
	}

	chunks = makeAddChunks(docs, 50)
	expected_len = 10
	if len(chunks) != expected_len {
		t.Errorf("Chunks length expected to be '%d' but got '%d'", expected_len, len(chunks))
	}

	chunks = makeAddChunks(docs, 301)
	expected_len = 2
	if len(chunks) != expected_len {
		t.Errorf("Chunks length expected to be '%d' but got '%d'", expected_len, len(chunks))
	}

	d = chunks[1]["add"].([]Document)[0]

	if d.Get("id") != "test_id_301" {
		t.Errorf("First element in second chunk should have id test_id_301 ")
	}

	if len(chunks[1]["add"].([]Document)) != 199 {
		t.Errorf("Last chunk should have length of 199 documents")
	}
}
func TestAdd(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/add", "core0")
	if err != nil {
		t.Errorf(err.Error())
	}
	si.SetBasicAuth("test", "post")

	docs := make([]Document, 0, 5)
	for i := 0; i < 5; i++ {
		docs = append(docs, Document{"id": fmt.Sprintf("test_id_%d", i), "title": fmt.Sprintf("add sucess %d", i)})
	}
	res, _ := si.Add(docs, 0, nil)
	res2, _ := si.Commit()
	// not sure what we can test here but at least run and see thing flows
	if res == nil {
		t.Errorf("Add response should not be nil")
	}

	if res.Success != true {
		t.Errorf("res.Success should be true but got false")
	}

	if res2 == nil {
		t.Errorf("Commit response should not be nil")
	}
}

func TestDelete(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/delete", "core0")
	if err != nil {
		t.Errorf(err.Error())
	}

	res, _ := si.Delete(M{"query": "id:test_id_1 OR id:test_id_2", "commitWithin": "500"}, nil)

	// not sure what we can test here but at least run and see thing flows
	if res == nil {
		t.Errorf("Delete response should not be nil")
	}

	params := &url.Values{}
	params.Add("commitWithin", "500")

	res2, _ := si.Delete(M{"query": "*:*"}, params)

	// not sure what we can test here but at least run and see thing flows
	if res2 == nil {
		t.Errorf("Delete response should not be nil")
	}
}

func TestXMLResponse(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/xml", "core0")
	if err != nil {
		t.Errorf(err.Error())
	}

	res, err := si.DeleteAll()

	if err == nil {
		t.Errorf("Error should be not nil since response is not json format")
	}

	if err.Error() != "invalid character '<' looking for beginning of value" {
		t.Errorf("Expected error message 'invalid character '<' looking for beginning of value' but got '%s'", err.Error())
	}

	if res != nil {
		t.Errorf("Response should be nil since response is not json format")
	}
}

func TestRollback(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/command", "core0")
	if err != nil {
		t.Errorf(err.Error())
	}

	res, _ := si.Rollback()

	// not sure what we can test here but at least run and see thing flows
	if res == nil {
		t.Errorf("Rollback response should not be nil")
	}
}

func TestOptimize(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/command", "core0")
	if err != nil {
		t.Errorf(err.Error())
	}

	res, _ := si.Optimize(nil)

	// not sure what we can test here but at least run and see thing flows
	if res == nil {
		t.Errorf("Optimize response should not be nil")
	}
	params := &url.Values{}
	params.Add("maxSegments", "10")
	params.Add("waitFlush", "false")
	res2, _ := si.Optimize(params)

	// not sure what we can test here but at least run and see thing flows
	if res2 == nil {
		t.Errorf("Optimize response should not be nil")
	}
}

func TestGrouped(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/grouped", "core0")
	if err != nil {
		t.Errorf(err.Error())
	}

	q := NewQuery()
	q.AddParam("q", "*:*")
	q.AddParam("group", "true")
	q.AddParam("group.field", "id")

	s := si.Search(q)
	si.SetBasicAuth("test", "get")
	res, err := s.Result(nil)

	if err != nil {
		t.Errorf("Error should be nil")
		return
	}
	if _, ok := res.Grouped["id"]; ok == false {
		t.Errorf("should have key id in grouped")
	}

	if res.Results.Docs != nil {
		t.Errorf("Docs should be nil")
	}
}

func TestStats(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/stats", "collection1")
	if err != nil {
		t.Errorf(err.Error())
	}

	q := NewQuery()
	q.AddParam("q", "*:*")
	q.AddParam("stats", "true")
	q.AddParam("stats.field", "id")

	s := si.Search(q)

	res, err := s.Result(nil)

	if err != nil {
		t.Errorf("Error should be nil")
		return
	}
	if _, ok := res.Stats["stats_fields"]; ok == false {
		t.Errorf("should have key stats_fields in Stats")
	}
}

func TestMoreLikeThisSuccess(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/success", "collection1")
	if err != nil {
		t.Errorf(err.Error())
	}
	q := NewQuery()
	q.AddParam("q", "id:tes*")
	q.AddParam("mlt.fl", "id,title")
	q.AddParam("mlt.mindf", "0")
	q.AddParam("mlt.mintf", "0")
	q.AddParam("mlt.match.include", "true")
	q.Rows(3)

	s := si.Search(q)

	res, err := s.MoreLikeThis(nil)

	if err != nil {
		t.Errorf("Error should be nil")
		return
	}
	if len(res.Results.Docs) != 3 {
		t.Errorf("Length of result should be 3 but got '%d'", len(res.Results.Docs))
	}
	if res.Match.Docs[0].Get("id") != "test_id_0" {
		t.Errorf("First doc in match should have id 'test_id_0' but got '%s'", res.Match.Docs[0].Get("id"))
	}
}

func TestSpellCheck(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/solr", "collection1")
	if err != nil {
		t.Errorf(err.Error())
	}
	q := NewQuery()
	q.DefType("edismax")
	q.Q("tets")
	q.QueryFields("id")
	q.SetParam("spellcheck", "true")
	q.SetParam("spellcheck.q", "tets")

	s := si.Search(q)

	res, err := s.SpellCheck(nil)

	if err != nil {
		t.Error(err)
		return
	}
	if _, ok := res.SpellCheck["suggestions"].([]interface{}); ok {
		return
	}
	t.Error("spellcheck component not responding, result should have 'spellcheck' entry")
}

func TestSpellCheckNotFound(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/stats", "collection1")
	if err != nil {
		t.Errorf(err.Error())
	}
	q := NewQuery()
	q.DefType("edismax")
	q.Q("tets")
	q.QueryFields("id")

	s := si.Search(q)

	res, err := s.Result(nil)

	if err != nil {
		t.Error(err)
		return
	}
	if len(res.SpellCheck) == 0 {
		return
	}

	t.Error("spellcheck component responding, result shouldn't have 'spellcheck' entry")
}

func TestMoreLikeThisError(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/error", "collection1")
	if err != nil {
		t.Errorf(err.Error())
	}
	q := NewQuery()
	q.AddParam("q", "id:tes*")
	q.AddParam("mlt.mindf", "0")
	q.AddParam("mlt.mintf", "0")
	q.AddParam("mlt.match.include", "true")
	q.Rows(3)

	s := si.Search(q)
	// missing mlt.fl
	res, err := s.MoreLikeThis(nil)

	if err != nil {
		t.Errorf("Error should be nil")
		return
	}

	if res.Status != 400 {
		t.Errorf("Status should be 400 but got '%d'", res.Status)
	}

	msg := res.Error["msg"].(string)
	expected := "Missing required parameter: mlt.fl"
	if msg != expected {
		t.Errorf("Error message expected to be '%s' but got '%s'", expected, msg)
	}

}

func TestNoResponseGrouped(t *testing.T) {
	si, err := NewSolrInterface("http://127.0.0.1:12345/noresponse", "core1")
	if err != nil {
		t.Errorf(err.Error())
	}

	q := NewQuery()
	q.AddParam("q", "*:*")
	q.AddParam("group", "true")
	q.AddParam("group.field", "id")
	si.SetCore("core0")
	s := si.Search(q)

	_, err = s.Result(nil)

	if err == nil {
		t.Errorf("Error should not be nil")
	}
	expected := `Standard parser can only parse solr response with response object,
					ie response.response and response.response.docs. Or grouped response
					Please use other parser or implement your own parser`
	if err.Error() != expected {
		t.Errorf("expected error '%s' but got '%s'", expected, err.Error())
	}
}

/*
func TestRealAdd(t *testing.T) {
	fmt.Println("test_real")
	si, err := NewSolrInterface("http://localhost:8983/solr", "collection1")
	if err != nil {
		t.Errorf(err.Error())
	}

	docs := make([]Document,0,100)
	for i := 0; i < 100; i++ {
		docs = append(docs, Document{"id": fmt.Sprintf("test_id_%d", i), "title": fmt.Sprintf("add sucess %d", i)})
	}
	res, _ := si.Add(docs, 0, nil)

	res2, _ := si.Commit()
	si.Delete(map[string]interface{}{"query":"*:*"}, nil)
	//si.DeleteAll()
	si.Rollback()
	//si.Optimize(nil)
	params := &url.Values{}
	params.Add("maxSegments", "10")
	params.Add("waitFlush", "false")
	si.Optimize(params)
	fmt.Println(res.Result)
	fmt.Println(res2.Result)

	s := si.Search(nil)
	query := NewQuery()
	query.AddParam("q", "title:add sucess 1")
	s.SetQuery(query)
	r, err := s.Result(nil)

	fmt.Println(r.Results)
}

func TestRealDelete(t *testing.T) {
	fmt.Println("test_real")
	si, err := NewSolrInterface("http://localhost:8983/solr", "collection1")
	if err != nil {
		t.Errorf(err.Error())
	}
	params := &url.Values{}
	params.Add("commitWithin", "500")
	res, _ := si.Delete(map[string]interface{}{ "query":"id:test_id_0 OR id:test_id_1"}, params)

	fmt.Println(res.Result)
}
*/
/*
func TestRealDeleteAll(t *testing.T) {
	fmt.Println("test_real")
	si, err := NewSolrInterface("http://localhost:8983/solr", "collection1")
	if err != nil {
		t.Errorf(err.Error())
	}

	res, _ := si.DeleteAll()

	fmt.Println(res.Result)
}
*/
func TestNewCoreAdmin(t *testing.T) {
	si, err := NewSolrInterface(solrUrl, "collection1")
	si.SetBasicAuth("test", "test")
	ca, err := si.CoreAdmin()
	if err != nil {
		t.Errorf("Should not get an error when creating a schema object")
		return
	}
	if ca.username != "test" || ca.password != "test" {
		t.Errorf("Wrong credidentials copied")
	}
	if ca.url.String() != solrUrl {
		t.Errorf("Wrong url copied")
	}
}

func TestCoreAdminCoresAction(t *testing.T) {

	ca, _ := NewCoreAdmin("http://127.0.0.1:12345/solr")

	params := &url.Values{}
	params.Add("core", "core0")
	res, err := ca.Action("RELOAD", params)
	if err != nil {
		t.Errorf("Should not be an error")
	}
	if res.Status != 0 {
		t.Errorf("Status expected to be 0 but got '%d'", res.Status)
	}
}

func TestCoreAdminCoresActionWrappers(t *testing.T) {

	ca, _ := NewCoreAdmin("http://127.0.0.1:12345/solr")

	// Status
	res, err := ca.Status("")
	if err != nil {
		t.Errorf("Should not be an error")
	}
	if res.Status != 0 {
		t.Errorf("Status expected to be 0 but got '%d'", res.Status)
	}

	res, err = ca.Status("core0")
	if err != nil {
		t.Errorf("Should not be an error")
	}
	if res.Status != 0 {
		t.Errorf("Status expected to be 0 but got '%d'", res.Status)
	}
	// Swap

	res, err = ca.Swap("core0", "core1")
	if err != nil {
		t.Errorf("Should not be an error")
	}
	if res.Status != 0 {
		t.Errorf("Status expected to be 0 but got '%d'", res.Status)
	}

	// Reload
	res, err = ca.Reload("core0")
	if err != nil {
		t.Errorf("Should not be an error")
	}
	if res.Status != 0 {
		t.Errorf("Status expected to be 0 but got '%d'", res.Status)
	}

	// Unload
	res, err = ca.Unload("core0")
	if err != nil {
		t.Errorf("Should not be an error")
	}
	if res.Status != 0 {
		t.Errorf("Status expected to be 0 but got '%d'", res.Status)
	}

	// Rename
	res, err = ca.Rename("core0", "core5")

	if err != nil {
		t.Errorf("Should not be an error")
	}
	if res.Status != 0 {
		t.Errorf("Status expected to be 0 but got '%d'", res.Status)
	}
	// Split
	res, err = ca.Split("core0", "core1")

	if err == nil {
		t.Errorf("Should be an error")
	}

	expected := "You must specify at least 2 target cores"

	if err.Error() != expected {
		t.Errorf("expcted '%s' but got '%s'", expected, err.Error())
	}

	res, err = ca.Split("core0", "core1", "core2")

	if err != nil {
		t.Errorf("Should not be an error")
	}

	if res.Status != 0 {
		t.Errorf("Status expected to be 0 but got '%d'", res.Status)
	}
}

func TestSupportedAction(t *testing.T) {

	ca, _ := NewCoreAdmin("http://127.0.0.1:12345/solr")

	params := &url.Values{}
	actions := []string{"CREATE", "mergeindexes"}
	for _, action := range actions {
		_, err := ca.Action(action, params)
		if err != nil {
			t.Errorf("Should not be an error but got '%s'", err.Error())
		}
	}
}

// Schema tests
func TestNewSchema(t *testing.T) {
	si, err := NewSolrInterface(solrUrl, "collection1")
	si.SetBasicAuth("test", "test")
	s, err := si.Schema()
	if err != nil {
		t.Errorf("Should not get an error when creating a schema object")
		return
	}
	if s.username != "test" || s.password != "test" {
		t.Errorf("Wrong credidentials copied")
	}
	if s.url.String() != solrUrl {
		t.Errorf("Wrong url copied")
	}
}

func TestSchemaGet(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")

	res, err := s.Get("fields", nil)
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}
	if _, ok := res.Response["fields"]; ok == false {
		t.Errorf("Result expected to have 'fields' key")
	}
}

func TestSchemaUniquekey(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")

	res, err := s.Uniquekey()
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}
	if _, ok := res.Response["uniqueKey"]; ok == false {
		t.Errorf("Result expected to have 'uniqueKey' key")
	}
}

func TestSchemaVersion(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")

	res, err := s.Version()
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}
	if _, ok := res.Response["version"]; ok == false {
		t.Errorf("Result expected to have 'version' key")
	}
}

func TestSchemaAll(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")
	s.SetBasicAuth("test", "test")
	res, err := s.All()
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}
	if _, ok := res.Response["schema"]; ok == false {
		t.Errorf("Result expected to have 'schema' key")
	}
}

func TestSchemaName(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")

	res, err := s.Name()
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}
	if _, ok := res.Response["name"]; ok == false {
		t.Errorf("Result expected to have 'name' key")
	}
}

func TestSchemaFields(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")

	res, err := s.Fields("", false, false)
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}
	if _, ok := res.Response["fields"]; ok == false {
		t.Errorf("Result expected to have 'fields' key")
	}
}

func TestSchemaFieldsName(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")

	res, err := s.FieldsName("title", false, false)
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}
	if _, ok := res.Response["field"]; ok == false {
		t.Errorf("Result expected to have 'field' key")
	}
}

func TestSchemaFieldtypes(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")

	res, err := s.Fieldtypes(false)
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}
	if _, ok := res.Response["fieldTypes"]; ok == false {
		t.Errorf("Result expected to have 'fieldTypes' key")
	}
}

func TestSchemaFieldtypesName(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")

	res, err := s.FieldtypesName("location", false)
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}
	if _, ok := res.Response["fieldType"]; ok == false {
		t.Errorf("Result expected to have 'fieldType' key")
	}
}

func TestSchemaDynamicFields(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")

	res, err := s.DynamicFields("", false)
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}
	if _, ok := res.Response["dynamicFields"]; ok == false {
		t.Errorf("Result expected to have 'dynamicFields' key")
	}
}

func TestSchemaDynamicFieldsName(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")

	res, err := s.DynamicFieldsName("*_coordinate", false)
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}
	if _, ok := res.Response["dynamicField"]; ok == false {
		t.Errorf("Result expected to have 'dynamicField' key")
	}
}

func TestSchemaPost(t *testing.T) {
	s, err := NewSchema(solrUrl, "collection1")
	data := []interface{}{M{"name": "newfield1", "type": "text", "copyFields": []string{"target1"}}, M{"name": "newfield2", "type": "text", "stored": "false"}}

	res, err := s.Post("fields", data)
	if err != nil {
		t.Errorf("Error should be nil but got '%s'", err.Error())
		return
	}

	if res.Success != true {
		t.Errorf("res.Success should be true but got false")
		return
	}

	// TODO: make sure mock response with a real one
	if _, ok := res.Result["fields"]; ok == false {
		t.Errorf("Result expected to have 'fields' key")
	}
}

func TestPing(t *testing.T) {
	si, _ := NewSolrInterface(solrUrl, "collection1")
	status, qtime, _ := si.Ping()
	if status != "OK" {
		t.Errorf("Status expected to be 'OK' but got '%s'", status)
	}
	if qtime < 0 {
		t.Errorf("Qtime expected to be larger than '-1' but got '%d'", qtime)
	}
}


text:
<?php

namespace MarketFlow\Yii2\TOTP\models;

use GAuth\Auth;
use MarketFlow\Yii2\TOTP\interfaces\TOTPInterface;
use yii\base\Model;
use yii\validators\BooleanValidator;
use yii\validators\RegularExpressionValidator;
use yii\validators\RequiredValidator;
use yii\validators\StringValidator;

class SecondFactorForm extends Model
{
    const SCENARIO_NO_REMEMBER = 'noRemember';

    /**
     * @var string
     */
    public $code;

    /**
     * @var TOTPInterface
     */
    private $identity;

    /**
     * @var bool
     */
    public $rememberDevice = false;

    /**
     * SecondFactorForm constructor.
     * @param TOTPInterface $identity
     * @param array $config
     */
    public function __construct(TOTPInterface $identity, bool $allowRemember = false, array $config = [])
    {
        $this->identity = $identity;
        $this->scenario = $allowRemember ? self::SCENARIO_DEFAULT : self::SCENARIO_NO_REMEMBER;
        parent::__construct($config);
    }

    public function attributeLabels()
    {
        return [
            'rememberDevice' => \Yii::t('yii2-totp', 'Remember device')
        ];
    }

    private function getGAuth(): Auth
    {
        $gAuth = new Auth($this->identity->getTOTPSecret());
        $gAuth->setCodeLength(6);
        return $gAuth;
    }

    public function rules()
    {
        $codeLength = $this->getGAuth()->getCodeLength();
        return [
            [['code'], RequiredValidator::class],
            [['code'], RegularExpressionValidator::class, 'pattern' => '/^\d{' . $codeLength . '}$/', 'message' => \Yii::t('yii2-totp', 'TOTP code must contain exactly {n} digits', ['n' => $codeLength])],
            [['code'], function($attribute, $params, $validator) {
                if (!$this->getGAuth()->validateCode($this->{$attribute})) {
                    $this->addError($attribute, \Yii::t('yii2-totp', 'Invalid TOTP code'));
                }
            }],
            [['rememberDevice'], BooleanValidator::class]
        ];
    }

    public function scenarios()
    {
        return array_merge(parent::scenarios(), [
            self::SCENARIO_NO_REMEMBER => ['code']
        ]);
    }

}


text:
""" Changes
    =================================================================

    sbutler1@illinois.edu: add JSONResponse subclass of HttpResponse;
        add some exceptions for subclass views to raise; simplify
        choosing a method to call; catch exceptions and return them
        to the client (always with an error field); move etag
        validation to here.
"""

from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.conf import settings
from django.http import HttpResponse
import simplejson as json
import traceback

class JSONResponse(HttpResponse):
    """
    A standard HttpResponse that will serialize the body to JSON
    and set the content-type to 'application/json'
    """

    def __init__(self, content="", *args, **kwargs):
        debug = getattr(settings, "DEBUG", False)
        pretty_print = getattr(settings, "JSON_PRETTY_PRINT", False)
        if content != "":
            if debug and pretty_print:
                content = json.dumps(content, sort_keys=True, indent=4 * " ")
            else:
                content = json.dumps(content)

        if not kwargs.get("content_type", None):
            kwargs["content_type"] = "application/json"

        super(JSONResponse, self).__init__(content, *args, **kwargs)

class RESTException(Exception):
    """
    Can be thrown inside RESTful methods. Accepts a specific
    status code to use, or 500 by default.
    """

    def __init__(self, message, status_code):
        super(RESTException, self).__init__(message)
        self.status_code = status_code

class RESTFormInvalidError(RESTException):
    """Thrown when a form is invalid, and holds all the errors."""

    def __init__(self, form):
        super(RESTFormInvalidError, self).__init__("Form is invalid", 400)
        self.form = form

class RESTDispatch:
    """Handles passing on the request to the correct view
    method based on the request type.
    """

    def run(self, *args, **named_args):
        request = args[0]
        method = request.META["REQUEST_METHOD"]

        try:
            if "GET" == method and hasattr(self, "GET"):
                response = self.GET(*args, **named_args)
            elif "POST" == method and hasattr(self, "POST"):
                response = self.POST(*args, **named_args)
            elif "PUT" == method and hasattr(self, "PUT"):
                response = self.PUT(*args, **named_args)
            elif "DELETE" == method and hasattr(self, "DELETE"):
                response = self.DELETE(*args, **named_args)
            else:
                raise RESTException("Method not allowed", 405)

        except ObjectDoesNotExist as odne:
            json_values = self.json_error(odne)
            response = JSONResponse(json_values, status=404)

        except ValidationError as ve:
            json_values = self.json_error(ve)
            response = JSONResponse(json_values, status=400)

        except RESTFormInvalidError as fie:
            json_values = self.json_error(fie)
            json_values.update(fie.form.errors)
            response = JSONResponse(json_values, status=fie.status_code)

        except RESTException as rest_e:
            json_values = self.json_error(rest_e)
            response = JSONResponse(json_values, status=rest_e.status_code)

        except Exception as e:
            json_values = self.json_error(e)
            response = JSONResponse(json_values, status=500)

        return response

    def json_error(self, ex):
        json_values = {"error": str(ex)}

        if getattr(settings, "DEBUG", False):
            json_values["stack"] = traceback.format_exc().splitlines()

        return json_values

    def validate_etag(self, request, obj):
        if "HTTP_IF_MATCH" not in request.META:
            if "If_Match" not in request.META:
                raise RESTException("If-Match header required", 400)
            else:
                request.META["HTTP_IF_MATCH"] = request.META["If_Match"]

        if request.META["HTTP_IF_MATCH"] != obj.etag:
            raise RESTException("Invalid ETag", 409)

    def _get_user(self, request):
        if "SS_OAUTH_USER" not in request.META:
            print(request.META)
            raise RESTException(
                "missing oauth user - improper auth backend?", 400
            )
        username = request.META["SS_OAUTH_USER"]

        user = User.objects.get(username=username)

        return user


text:
'use strict';

angular.module('activity')
	.service('sActivity', serviceActivity);
// -----------------------------------------------------------------------------------
//
// DIRECTIVE: Public Projects Main
//
// -----------------------------------------------------------------------------------
serviceActivity.$inject = ['$http'];
/* @ngInject */
function serviceActivity($http) {

	var getActivity = function(req) {
		return $http({method:'GET',url: '/api/activity/' + req.id});
	};

	var getProjectActivities = function(req) {
		return $http({method:'GET',url: '/api/activity/'});
	};

	return {
		getProjectActivities: getProjectActivities,
		getActivity: getActivity
	};
}