text:
import * as moment from "moment-timezone";

import getMockApp, { createFile, createFolder } from "src/testUtils/mockApp";

import * as dailyNotesInterface from "../index";
import * as vaultUtils from "../vault";
import { setDailyConfig, setPeriodicNotesConfig } from "../testUtils/utils";

describe("getDailyNoteSettings", () => {
  beforeEach(() => {
    window.app = getMockApp();
    window.existingFiles = {};
    window.moment = moment;
    moment.tz.setDefault("America/New_York");
  });

  test("returns all the daily note settings", () => {
    setDailyConfig({
      folder: "foo",
      format: "YYYY-MM-DD-HHmm",
      template: "template",
    });

    expect(dailyNotesInterface.getDailyNoteSettings()).toEqual({
      folder: "foo",
      format: "YYYY-MM-DD-HHmm",
      template: "template",
    });
  });

  test("cleanses data", () => {
    setDailyConfig({
      folder: " foo/bar ",
      format: "MMM YYYY-MM-DD",
      template: "   path/to/template  ",
    });

    expect(dailyNotesInterface.getDailyNoteSettings()).toEqual({
      folder: "foo/bar",
      format: "MMM YYYY-MM-DD",
      template: "path/to/template",
    });
  });

  test("returns defaults if daily note settings don't exist", () => {
    expect(dailyNotesInterface.getDailyNoteSettings()).toEqual({
      format: "YYYY-MM-DD",
      folder: "",
      template: "",
    });
  });

  test("uses settings from core daily notes if periodic-notes' `daily` is disabled", () => {
    setDailyConfig({
      folder: " foo ",
      format: "YYYY/MM/MMM/YYYY-MM-DD",
      template: "   path/to/daily  ",
    });

    setPeriodicNotesConfig("daily", {
      enabled: false,
      folder: " foo/bar ",
      format: "MMM YYYY-MM-DD",
      template: "   path/to/template  ",
    });

    expect(dailyNotesInterface.getDailyNoteSettings()).toEqual({
      folder: "foo",
      format: "YYYY/MM/MMM/YYYY-MM-DD",
      template: "path/to/daily",
    });
  });

  test("uses settings from Periodic Notes if periodic-notes and daily notes are both enabled", () => {
    setDailyConfig({
      folder: " foo/bar ",
      format: "YYYY/MM/MMM/YYYY-MM-DD",
      template: "   path/to/template  ",
    });

    setPeriodicNotesConfig("daily", {
      enabled: true,
      folder: " foo/bar ",
      format: "MMM YYYY-MM-DD",
      template: "   path/to/template  ",
    });

    expect(dailyNotesInterface.getDailyNoteSettings()).toEqual({
      format: "MMM YYYY-MM-DD",
      folder: "foo/bar",
      template: "path/to/template",
    });
  });
});

describe("appHasDailyNotesPluginLoaded", () => {
  beforeEach(() => {
    window.app = getMockApp();
    window.existingFiles = {};
    window.moment = moment;
  });

  test("returns true when daily notes plugin is enabled", () => {
    // eslint-disable-next-line
    (<any>window.app).internalPlugins.plugins["daily-notes"].enabled = true;

    expect(dailyNotesInterface.appHasDailyNotesPluginLoaded()).toEqual(true);
  });

  test("returns true when daily notes plugin is enabled", () => {
    // eslint-disable-next-line
    (<any>window.app).internalPlugins.plugins["daily-notes"].enabled = false;

    expect(dailyNotesInterface.appHasDailyNotesPluginLoaded()).toEqual(false);
  });
});

describe("getAllDailyNotes", () => {
  beforeEach(() => {
    window.app = getMockApp();
    window.moment = moment;
    window.existingFiles = {};
  });

  test("throws error if daily note folder can't be found", () => {
    setDailyConfig({
      folder: "missing-folder/",
      format: "YYYY-MM-DD",
      template: "template",
    });

    expect(dailyNotesInterface.getAllDailyNotes).toThrow(
      "Failed to find daily notes folder"
    );
  });

  test("returns a list of all daily notes with no nested folders", () => {
    setDailyConfig({
      folder: "/",
      format: "YYYY-MM-DD",
      template: "template",
    });

    const fileA = createFile("2020-12-01", "");
    const fileB = createFile("2020-12-02", "");
    const fileC = createFile("2020-12-03", "");
    createFolder("/", [fileA, fileB, fileC]);

    expect(dailyNotesInterface.getAllDailyNotes()).toEqual({
      "day-2020-12-01T00:00:00-05:00": fileA,
      "day-2020-12-02T00:00:00-05:00": fileB,
      "day-2020-12-03T00:00:00-05:00": fileC,
    });
  });

  test("returns a list of all daily notes including files nested in folders", () => {
    setDailyConfig({
      folder: "/",
      format: "YYYY-MM-DD",
      template: "template",
    });

    const fileA = createFile("2020-12-01", "");
    const fileB = createFile("2020-12-02", "");
    const fileC = createFile("2020-12-03", "");
    createFolder("/", [fileA, fileB, createFolder("foo", [fileC])]);

    expect(dailyNotesInterface.getAllDailyNotes()).toEqual({
      "day-2020-12-01T00:00:00-05:00": fileA,
      "day-2020-12-02T00:00:00-05:00": fileB,
      "day-2020-12-03T00:00:00-05:00": fileC,
    });
  });
});

describe("createDailyNote", () => {
  beforeEach(() => {
    window.app = getMockApp();
    window.moment = moment.bind(null, "2021-02-15T14:06:00-05:00");
    moment.tz.setDefault("America/New_York");
  });

  test("replaces all mustaches in template", async () => {
    const getTemplateInfo = jest.spyOn(vaultUtils, "getTemplateInfo");
    getTemplateInfo.mockResolvedValue([
      `
{{date}}
{{time}}
{{title}}
{{yesterday}}
{{tomorrow}}
{{date:YYYY}}-{{date:MM-DD}}
{{date-1d:YYYY-MM-DD}}
{{date+2d:YYYY-MM-DD}}
{{date+1M:YYYY-MM-DD}}
{{date+10y:YYYY-MM-DD}}
{{date +7d}}
`,
      null,
    ]);

    setDailyConfig({
      folder: "/",
      format: "YYYY-MM-DD",
      template: "template",
    });

    await dailyNotesInterface.createDailyNote(window.moment());

    expect(window.app.vault.create).toHaveBeenCalledWith(
      "/2021-02-15.md",
      `
2021-02-15
14:06
2021-02-15
2021-02-14
2021-02-16
2021-02-15
2021-02-14
2021-02-17
2021-03-15
2031-02-15
2021-02-22
`
    );
  });
});


text:
package org.apache.phoenix.expression;

import java.util.List;

import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.io.Writable;
import org.apache.phoenix.expression.visitor.ExpressionVisitor;
import org.apache.phoenix.schema.PDatum;
import org.apache.phoenix.schema.tuple.Tuple;

/**
 *
 * Interface for general expression evaluation
 *
 *
 * @since 0.1
 */
public interface Expression extends PDatum, Writable {
    /**
     * Access the value by setting a pointer to it (as opposed to making
     * a copy of it which can be expensive)
     * @param tuple Single row result during scan iteration
     * @param ptr Pointer to byte value being accessed
     * @return true if the expression could be evaluated (i.e. ptr was set)
     * and false otherwise
     */
    boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr);

    /**
     * Means of traversing expression tree through visitor.
     * @param visitor
     */
    <T> T accept(ExpressionVisitor<T> visitor);

    /**
     * @return the child expressions
     */
    List<Expression> getChildren();

    /**
     * Resets the state of a expression back to its initial state and
     * enables the expession to be evaluated incrementally (which
     * occurs during filter evaluation where we see one key value at
     * a time; it's possible to evaluate immediately rather than
     * wait until all key values have been seen). Note that when
     * evaluating incrementally, you must call this method before
     * processing a new row.
     */
    void reset();

    /**
     * @return true if the expression can be evaluated on the client
     * side with out server state. If a sequence is involved, you
     * still need a Tuple from a {@link org.apache.phoenix.iterate.SequenceResultIterator},
     * but otherwise the Tuple may be null.
     */
    boolean isStateless();

    /**
     * @return true if the expression returns the same output every
     * time given the same input.
     */
    boolean isDeterministic();

    /**
     * Determines if an evaluate is required after partial evaluation
     * is run. For example, in the case of an IS NULL expression, we
     * only know we can return TRUE after all KeyValues have been seen
     * while an expression is used in the context of a filter.
     * @return
     */
    boolean requiresFinalEvaluation();
}

redpajama_set_name: RedPajamaGithub


text:
package gov.sandia.cognition.learning.algorithm.hmm;

import gov.sandia.cognition.algorithm.ParallelAlgorithm;
import gov.sandia.cognition.algorithm.ParallelUtil;
import gov.sandia.cognition.annotation.PublicationReference;
import gov.sandia.cognition.annotation.PublicationType;
import gov.sandia.cognition.learning.algorithm.BatchLearner;
import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.statistics.ComputableDistribution;
import gov.sandia.cognition.statistics.ProbabilityFunction;
import gov.sandia.cognition.util.AbstractCloneableSerializable;
import gov.sandia.cognition.util.DefaultWeightedValue;
import gov.sandia.cognition.util.WeightedValue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * A Parallelized implementation of some of the methods of the
 * Baum-Welch Algorithm.
 * @param <ObservationType> Type of Observations handled by the HMM.
 * @author Kevin R. Dixon
 * @since 3.0
 */
@PublicationReference(
    author="William Turin",
    title="Unidirectional and Parallel Baum–Welch Algorithms",
    type=PublicationType.Journal,
    publication="IEEE Transactions on Speech and Audio Processing",
    year=1998,
    url="http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=00725318"
)
public class ParallelBaumWelchAlgorithm<ObservationType>
    extends BaumWelchAlgorithm<ObservationType>
    implements ParallelAlgorithm
{

    /**
     * Thread pool used for parallelization.
     */
    transient private ThreadPoolExecutor threadPool;

    /**
     * Tasks for re-estimating the PDFs.
     */
    transient protected ArrayList<DistributionEstimatorTask<ObservationType>> distributionEstimatorTasks;

    /**
     * Default constructor
     */
    public ParallelBaumWelchAlgorithm()
    {
        super();
    }

    /**
     * Creates a new instance of ParallelBaumWelchAlgorithm
     * @param initialGuess
     * Initial guess for the iterations.
     * @param distributionLearner
     * Learner for the Distribution Functions of the HMM.
     * @param reestimateInitialProbabilities
     * Flag to re-estimate the initial probability Vector.
     */
    public ParallelBaumWelchAlgorithm(
        HiddenMarkovModel<ObservationType> initialGuess,
        BatchLearner<Collection<? extends WeightedValue<? extends ObservationType>>,? extends ComputableDistribution<ObservationType>> distributionLearner,
        boolean reestimateInitialProbabilities )
    {
        super( initialGuess, distributionLearner, reestimateInitialProbabilities );
    }

    public ThreadPoolExecutor getThreadPool()
    {
        if( this.threadPool == null )
        {
            this.setThreadPool( ParallelUtil.createThreadPool() );
        }
        return this.threadPool;
    }

    public void setThreadPool(
        ThreadPoolExecutor threadPool)
    {
        this.threadPool = threadPool;
    }

    public int getNumThreads()
    {
        return ParallelUtil.getNumThreads(this);
    }

    @Override
    protected boolean initializeAlgorithm()
    {
        this.distributionEstimatorTasks = this.createDistributionEstimatorTasks();
        return super.initializeAlgorithm();
    }

    @Override
    protected ArrayList<ProbabilityFunction<ObservationType>> updateProbabilityFunctions(
        ArrayList<Vector> sequenceGammas)
    {
        final int N = this.getResult().getNumStates();
        for( int i = 0; i < N; i++ )
        {
            this.distributionEstimatorTasks.get(i).setGammas( sequenceGammas );
        }

        ArrayList<ProbabilityFunction<ObservationType>> fs = null;
        try
        {
            fs = ParallelUtil.executeInParallel(
                this.distributionEstimatorTasks, this.getThreadPool() );
        }
        catch (Exception e)
        {
            throw new RuntimeException( e );
        }

        return fs;
    }

    /**
     * Creates the DistributionEstimatorTask
     * @return
     * DistributionEstimatorTask.
     */
    protected ArrayList<DistributionEstimatorTask<ObservationType>> createDistributionEstimatorTasks()
    {
        final int N = this.initialGuess.getNumStates();
        ArrayList<DistributionEstimatorTask<ObservationType>> tasks =
            new ArrayList<DistributionEstimatorTask<ObservationType>>( N );
        for( int i = 0; i < N; i++ )
        {
            tasks.add( new DistributionEstimatorTask<ObservationType>(
                this.data, this.distributionLearner, i ) );
        }
        return tasks;
    }

    /**
     * Re-estimates the PDF from the gammas.
     * @param <ObservationType> Type of Observations.
     */
    protected static class DistributionEstimatorTask<ObservationType>
        extends AbstractCloneableSerializable
        implements Callable<ProbabilityFunction<ObservationType>>
    {

        /**
         * Weighted values for the PDF estimator.
         */
        protected ArrayList<DefaultWeightedValue<ObservationType>> weightedValues;

        /**
         * My copy of the PDF estimator.
         */
        protected BatchLearner<Collection<? extends WeightedValue<? extends ObservationType>>,? extends ComputableDistribution<ObservationType>> distributionLearner;

        /**
         * Gammas used to weight the learner samples.
         */
        private ArrayList<Vector> gammas;

        /**
         * Index into the gammas to pull the weights.
         */
        protected int index;

        /**
         * Creates an instance of DistributionEstimatorTask
         * @param data
         * Data to stuff into the weightedValues
         * @param distributionLearner
         * Distribution Learner
         * @param index
         * Index into the gammas
         */
        public DistributionEstimatorTask(
            Collection<? extends ObservationType> data,
            BatchLearner<Collection<? extends WeightedValue<? extends ObservationType>>,? extends ComputableDistribution<ObservationType>> distributionLearner,
            int index )
        {
            this.index = index;
            this.distributionLearner = distributionLearner;
            this.weightedValues =
                new ArrayList<DefaultWeightedValue<ObservationType>>( data.size() );
            for( ObservationType v : data )
            {
                this.weightedValues.add( new DefaultWeightedValue<ObservationType>( v ) );
            }
        }

        /**
         * Sets the gamma samples pointer.
         * @param gammas
         * Gammas
         */
        public void setGammas(
            ArrayList<Vector> gammas )
        {
            this.gammas = gammas;
        }

        public ProbabilityFunction<ObservationType> call()
        {
            final int N = this.gammas.size();
            for( int n = 0; n < N; n++ )
            {
                this.weightedValues.get(n).setWeight(
                    this.gammas.get(n).getElement( this.index ) );
            }
            return this.distributionLearner.learn(this.weightedValues).getProbabilityFunction();
        }

    }

}


text:
package org.droidparts.fragment.support.v4;

import org.droidparts.Injector;
import org.droidparts.inner.fragments.SecretFragmentsSupportUtil;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class DialogFragment extends android.support.v4.app.DialogFragment {

	private boolean injected;

	@Override
	public final View onCreateView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		View view = onCreateView(savedInstanceState, inflater, container);
		if (view != null) {
			Injector.inject(view, this);
		} else {
			Injector.inject(getDialog(), this);
		}
		injected = true;
		return view;
	}

	public View onCreateView(Bundle savedInstanceState,
			LayoutInflater inflater, ViewGroup container) {
		return super.onCreateView(inflater, container, savedInstanceState);
	}

	public final boolean isInjected() {
		return injected;
	}

	public void show(FragmentActivity activity) {
		SecretFragmentsSupportUtil.dialogFragmentShowDialogFragment(activity,
				this);
	}

}


text:
<?xml version="1.0"?>
<phpunit
    bootstrap="./vendor/autoload.php"
    colors="true">
    <testsuites>
        <testsuite name="OneRing">
            <directory suffix="Test.php">./test</directory>
        </testsuite>
    </testsuites>
</phpunit>


text:
import rapmedusa
import redis
import unittest

from rapmedusa import emit, getMapReduceManager

class MapReduceTestCase(unittest.TestCase):

    def setUp(self):
        self.data = [{'id': 1, 'tags': ['red', 'green']},
                     {'id': 2, 'tags': ['green']},
                     {'id': 3, 'tags': ['blue', 'green']}]

        self.inKey = 'mr_input'
        self.sortKey = 'mr_sort'
        self.sortedKeySet = 'mr_sorted_keys'
        self.outKey = 'mr_output'
        self.conn = redis.StrictRedis(host='localhost',port=6379,db=0)

        index = 0
        for entry in self.data:
            for tag in entry['tags']:
                self.conn.hset(self.inKey, index, tag)
                index += 1

    def tearDown(self):
        self.conn.delete(self.inKey)
        getMapReduceManager().cleanUp()
        self.conn.delete(self.outKey)

    def mapFn(self, k, v):
        emit(v, 1)

    def reduceFn(self, key, vals):
        total = 0

        for v in vals:
            total += int(v)

        return total

    def test_map_reduce(self):
        rapmedusa.map_reduce(self.conn,
                            self.mapFn,
                            self.reduceFn,
                            self.inKey,
                            self.sortKey,
                            self.sortedKeySet,
                            self.outKey,
                            False)

        # after creating buckets according to map output keys, does the
        # result match what we expect?
        self.assertEquals(getMapReduceManager().getMappedVals(),
                          {'mr_sort:green': ['1', '1', '1'],
                           'mr_sort:red': ['1'],
                           'mr_sort:blue': ['1']})

        # check the outputs after running the reduce function
        self.assertEquals(getMapReduceManager().getOutput(),
                          {'blue': '1',
                           'red': '1',
                           'green': '3'})


text:
package org.apache.solr.servlet;

import static org.apache.solr.common.cloud.ZkStateReader.COLLECTION_PROP;
import static org.apache.solr.common.cloud.ZkStateReader.CORE_NAME_PROP;
import static org.apache.solr.common.cloud.ZkStateReader.NODE_NAME_PROP;
import static org.apache.solr.common.cloud.ZkStateReader.REPLICATION_FACTOR;
import static org.apache.solr.common.params.CollectionAdminParams.SYSTEM_COLL;
import static org.apache.solr.common.params.CollectionParams.CollectionAction.CREATE;
import static org.apache.solr.common.params.CommonParams.NAME;
import static org.apache.solr.common.params.CoreAdminParams.ACTION;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.ADMIN;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.FORWARD;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.PASSTHROUGH;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.PROCESS;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.REMOTEQUERY;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.RETRY;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.RETURN;

import io.opentracing.Span;
import io.opentracing.tag.Tags;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.InputStreamEntity;
import org.apache.solr.api.ApiBag;
import org.apache.solr.api.V2HttpCall;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpClientUtil;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.annotation.SolrThreadSafe;
import org.apache.solr.common.cloud.Aliases;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.CoreAdminParams;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.CommandOperation;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.common.util.JsonSchemaValidator;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.common.util.StrUtils;
import org.apache.solr.common.util.SuppressForbidden;
import org.apache.solr.common.util.TimeSource;
import org.apache.solr.common.util.Utils;
import org.apache.solr.common.util.ValidatingJsonMap;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrConfig;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.ContentStreamHandlerBase;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryRequestBase;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.request.SolrRequestInfo;
import org.apache.solr.response.QueryResponseWriter;
import org.apache.solr.response.QueryResponseWriterUtil;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.security.AuditEvent;
import org.apache.solr.security.AuditEvent.EventType;
import org.apache.solr.security.AuthenticationPlugin;
import org.apache.solr.security.AuthorizationContext;
import org.apache.solr.security.AuthorizationContext.CollectionRequest;
import org.apache.solr.security.AuthorizationContext.RequestType;
import org.apache.solr.security.AuthorizationUtils;
import org.apache.solr.security.HttpServletAuthorizationContext;
import org.apache.solr.security.PublicKeyHandler;
import org.apache.solr.servlet.SolrDispatchFilter.Action;
import org.apache.solr.servlet.cache.HttpCacheHeaderUtil;
import org.apache.solr.servlet.cache.Method;
import org.apache.solr.update.processor.DistributingUpdateProcessorFactory;
import org.apache.solr.util.RTimerTree;
import org.apache.solr.util.TimeOut;
import org.apache.solr.util.tracing.TraceUtils;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MarkerFactory;

/** This class represents a call made to Solr */
@SolrThreadSafe
public class HttpSolrCall {
  private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  public static final String ORIGINAL_USER_PRINCIPAL_HEADER = "originalUserPrincipal";

  public static final String INTERNAL_REQUEST_COUNT = "_forwardedCount";

  public static final Random random;

  static {
    // We try to make things reproducible in the context of our tests by initializing the random
    // instance based on the current seed
    String seed = System.getProperty("tests.seed");
    if (seed == null) {
      random = new Random();
    } else {
      random = new Random(seed.hashCode());
    }
  }

  protected final SolrDispatchFilter solrDispatchFilter;
  protected final CoreContainer cores;
  protected final HttpServletRequest req;
  protected final HttpServletResponse response;
  protected final boolean retry;
  protected SolrCore core = null;
  protected SolrQueryRequest solrReq = null;
  private boolean mustClearSolrRequestInfo = false;
  protected SolrRequestHandler handler = null;
  protected SolrParams queryParams;
  protected String path;
  protected Action action;
  protected String coreUrl;
  protected SolrConfig config;
  protected Map<String, Integer> invalidStates;

  // The states of client that is invalid in this request
  // What's in the URL path; might reference a collection/alias or a Solr core name
  protected String origCorename;
  // The list of SolrCloud collections if in SolrCloud (usually 1)
  protected List<String> collectionsList;

  protected RequestType requestType;

  public HttpSolrCall(
      SolrDispatchFilter solrDispatchFilter,
      CoreContainer cores,
      HttpServletRequest request,
      HttpServletResponse response,
      boolean retry) {
    this.solrDispatchFilter = solrDispatchFilter;
    this.cores = cores;
    this.req = request;
    this.response = response;
    this.retry = retry;
    this.requestType = RequestType.UNKNOWN;
    req.setAttribute(HttpSolrCall.class.getName(), this);
    // set a request timer which can be reused by requests if needed
    req.setAttribute(SolrRequestParsers.REQUEST_TIMER_SERVLET_ATTRIBUTE, new RTimerTree());
    // put the core container in request attribute
    req.setAttribute("org.apache.solr.CoreContainer", cores);
    path = ServletUtils.getPathAfterContext(req);
  }

  public String getPath() {
    return path;
  }

  public HttpServletRequest getReq() {
    return req;
  }

  public SolrCore getCore() {
    return core;
  }

  public SolrParams getQueryParams() {
    return queryParams;
  }

  /** The collection(s) referenced in this request. Populated in {@link #init()}. Not null. */
  public List<String> getCollectionsList() {
    return collectionsList != null ? collectionsList : Collections.emptyList();
  }

  @SuppressForbidden(
      reason =
          "Set the thread contextClassLoader for all 3rd party dependencies that we cannot control")
  protected void init() throws Exception {
    // check for management path
    String alternate = cores.getManagementPath();
    if (alternate != null && path.startsWith(alternate)) {
      path = path.substring(0, alternate.length());
    }

    queryParams = SolrRequestParsers.parseQueryString(req.getQueryString());

    // unused feature ?
    int idx = path.indexOf(':');
    if (idx > 0) {
      // save the portion after the ':' for a 'handler' path parameter
      path = path.substring(0, idx);
    }

    // Check for container handlers
    handler = cores.getRequestHandler(path);
    if (handler != null) {
      solrReq = SolrRequestParsers.DEFAULT.parse(null, path, req);
      solrReq.getContext().put(CoreContainer.class.getName(), cores);
      requestType = RequestType.ADMIN;
      action = ADMIN;
      return;
    }

    // Parse a core or collection name from the path and attempt to see if it's a core name
    idx = path.indexOf("/", 1);
    if (idx > 1) {
      origCorename = path.substring(1, idx);

      // Try to resolve a Solr core name
      core = cores.getCore(origCorename);
      if (core != null) {
        path = path.substring(idx);
      } else {
        // extra mem barriers, so don't look at this before trying to get core
        if (cores.isCoreLoading(origCorename)) {
          throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "SolrCore is loading");
        }
        // the core may have just finished loading
        core = cores.getCore(origCorename);
        if (core != null) {
          path = path.substring(idx);
        } else {
          if (!cores.isZooKeeperAware()) {
            core = cores.getCore("");
          }
        }
      }
    }

    if (cores.isZooKeeperAware()) {
      // init collectionList (usually one name but not when there are aliases)
      String def = core != null ? core.getCoreDescriptor().getCollectionName() : origCorename;
      collectionsList =
          resolveCollectionListOrAlias(
              queryParams.get(COLLECTION_PROP, def)); // &collection= takes precedence

      if (core == null) {
        // lookup core from collection, or route away if need to
        // route to 1st
        String collectionName = collectionsList.isEmpty() ? null : collectionsList.get(0);
        // TODO try the other collections if can't find a local replica of the first?   (and do to
        // V2HttpSolrCall)

        boolean isPreferLeader = (path.endsWith("/update") || path.contains("/update/"));

        // find a local replica/core for the collection
        core = getCoreByCollection(collectionName, isPreferLeader);
        if (core != null) {
          if (idx > 0) {
            path = path.substring(idx);
          }
        } else {
          // if we couldn't find it locally, look on other nodes
          if (idx > 0) {
            extractRemotePath(collectionName, origCorename);
            if (action == REMOTEQUERY) {
              path = path.substring(idx);
              return;
            }
          }
          // core is not available locally or remotely
          autoCreateSystemColl(collectionName);
          if (action != null) return;
        }
      }
    }

    // With a valid core...
    if (core != null) {
      Thread.currentThread().setContextClassLoader(core.getResourceLoader().getClassLoader());

      config = core.getSolrConfig();
      // get or create/cache the parser for the core
      SolrRequestParsers parser = config.getRequestParsers();

      // Determine the handler from the url path if not set
      // (we might already have selected the cores handler)
      extractHandlerFromURLPath(parser);
      if (action != null) return;

      // With a valid handler and a valid core...
      if (handler != null) {
        // if not a /select, create the request
        if (solrReq == null) {
          solrReq = parser.parse(core, path, req);
        }

        invalidStates =
            checkStateVersionsAreValid(solrReq.getParams().get(CloudSolrClient.STATE_VERSION));

        addCollectionParamIfNeeded(getCollectionsList());

        action = PROCESS;
        return; // we are done with a valid handler
      }
    }
    log.debug("no handler or core retrieved for {}, follow through...", path);

    action = PASSTHROUGH;
  }

  protected void autoCreateSystemColl(String corename) throws Exception {
    if (core == null
        && SYSTEM_COLL.equals(corename)
        && "POST".equals(req.getMethod())
        && !cores.getZkController().getClusterState().hasCollection(SYSTEM_COLL)) {
      log.info("Going to auto-create {} collection", SYSTEM_COLL);
      SolrQueryResponse rsp = new SolrQueryResponse();
      String repFactor =
          String.valueOf(
              Math.min(3, cores.getZkController().getClusterState().getLiveNodes().size()));
      cores
          .getCollectionsHandler()
          .handleRequestBody(
              new LocalSolrQueryRequest(
                  null,
                  new ModifiableSolrParams()
                      .add(ACTION, CREATE.toString())
                      .add(NAME, SYSTEM_COLL)
                      .add(REPLICATION_FACTOR, repFactor)),
              rsp);
      if (rsp.getValues().get("success") == null) {
        throw new SolrException(
            ErrorCode.SERVER_ERROR,
            "Could not auto-create "
                + SYSTEM_COLL
                + " collection: "
                + Utils.toJSONString(rsp.getValues()));
      }
      TimeOut timeOut = new TimeOut(3, TimeUnit.SECONDS, TimeSource.NANO_TIME);
      for (; ; ) {
        if (cores.getZkController().getClusterState().getCollectionOrNull(SYSTEM_COLL) != null) {
          break;
        } else {
          if (timeOut.hasTimedOut()) {
            throw new SolrException(
                ErrorCode.SERVER_ERROR,
                "Could not find " + SYSTEM_COLL + " collection even after 3 seconds");
          }
          timeOut.sleep(50);
        }
      }

      action = RETRY;
    }
  }

  /**
   * Resolves the parameter as a potential comma delimited list of collections, and resolves aliases
   * too. One level of aliases pointing to another alias is supported. De-duplicates and retains the
   * order. {@link #getCollectionsList()}
   */
  protected List<String> resolveCollectionListOrAlias(String collectionStr) {
    if (collectionStr == null || collectionStr.trim().isEmpty()) {
      return Collections.emptyList();
    }
    List<String> result = null;
    LinkedHashSet<String> uniqueList = null;
    Aliases aliases = cores.getAliases();
    List<String> inputCollections = StrUtils.splitSmart(collectionStr, ",", true);
    if (inputCollections.size() > 1) {
      uniqueList = new LinkedHashSet<>();
    }
    for (String inputCollection : inputCollections) {
      List<String> resolvedCollections = aliases.resolveAliases(inputCollection);
      if (uniqueList != null) {
        uniqueList.addAll(resolvedCollections);
      } else {
        result = resolvedCollections;
      }
    }
    if (uniqueList != null) {
      return new ArrayList<>(uniqueList);
    } else {
      return result;
    }
  }

  /** Extract handler from the URL path if not set. */
  protected void extractHandlerFromURLPath(SolrRequestParsers parser) throws Exception {
    if (handler == null && path.length() > 1) { // don't match "" or "/" as valid path
      handler = core.getRequestHandler(path);
      // no handler yet but <requestDispatcher> allows us to handle /select with a 'qt' param
      if (handler == null && parser.isHandleSelect()) {
        if ("/select".equals(path) || "/select/".equals(path)) {
          solrReq = parser.parse(core, path, req);
          String qt = solrReq.getParams().get(CommonParams.QT);
          handler = core.getRequestHandler(qt);
          if (handler == null) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "unknown handler: " + qt);
          }
          if (qt != null && qt.startsWith("/") && (handler instanceof ContentStreamHandlerBase)) {
            // For security reasons it's a bad idea to allow a leading '/', ex: /select?qt=/update
            // see SOLR-3161
            // There was no restriction from Solr 1.4 thru 3.5 and it's not supported for update
            // handlers.
            throw new SolrException(
                SolrException.ErrorCode.BAD_REQUEST,
                "Invalid Request Handler ('qt').  Do not use /select to access: " + qt);
          }
        }
      }
    }
  }

  protected void extractRemotePath(String collectionName, String origCorename)
      throws UnsupportedEncodingException, KeeperException, InterruptedException, SolrException {
    assert core == null;
    coreUrl = getRemoteCoreUrl(collectionName, origCorename);
    // don't proxy for internal update requests
    invalidStates = checkStateVersionsAreValid(queryParams.get(CloudSolrClient.STATE_VERSION));
    if (coreUrl != null
        && queryParams.get(DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM) == null) {
      if (invalidStates != null) {
        // it does not make sense to send the request to a remote node
        throw new SolrException(
            SolrException.ErrorCode.INVALID_STATE,
            new String(Utils.toJSON(invalidStates), org.apache.lucene.util.IOUtils.UTF_8));
      }
      action = REMOTEQUERY;
    } else {
      if (!retry) {
        // we couldn't find a core to work with, try reloading aliases & this collection
        cores.getZkController().getZkStateReader().aliasesManager.update();
        cores.getZkController().zkStateReader.forceUpdateCollection(collectionName);
        action = RETRY;
      }
    }
  }

  protected void sendRemoteQuery() throws IOException {
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, new SolrQueryResponse(), action));
    mustClearSolrRequestInfo = true;
    remoteQuery(coreUrl + path, response);
  }

  /** This method processes the request. */
  public Action call() throws IOException {

    if (cores == null) {
      sendError(503, "Server is shutting down or failed to initialize");
      return RETURN;
    }

    if (solrDispatchFilter.abortErrorMessage != null) {
      sendError(500, solrDispatchFilter.abortErrorMessage);
      if (shouldAudit(EventType.ERROR)) {
        cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.ERROR, getReq()));
      }
      return RETURN;
    }

    try {
      init();

      TraceUtils.ifNotNoop(getSpan(), this::populateTracingSpan);

      // Perform authorization here, if:
      //    (a) Authorization is enabled, and
      //    (b) The requested resource is not a known static file
      //    (c) And this request should be handled by this node (see NOTE below)
      // NOTE: If the query is to be handled by another node, then let that node do the
      // authorization.
      // In case of authentication using BasicAuthPlugin, for example, the internode request
      // is secured using PKI authentication and the internode request here will contain the
      // original user principal as a payload/header, using which the receiving node should be
      // able to perform the authorization.
      if (cores.getAuthorizationPlugin() != null
          && shouldAuthorize()
          && !(action == REMOTEQUERY || action == FORWARD)) {
        final AuthorizationContext authzContext = getAuthCtx();
        AuthorizationUtils.AuthorizationFailure authzFailure =
            AuthorizationUtils.authorize(req, response, cores, authzContext);
        if (authzFailure != null) {
          sendError(authzFailure.getStatusCode(), authzFailure.getMessage());
          return RETURN;
        }
      }

      HttpServletResponse resp = response;
      switch (action) {
        case ADMIN_OR_REMOTEQUERY:
          handleAdminOrRemoteRequest();
          return RETURN;
        case ADMIN:
          handleAdminRequest();
          return RETURN;
        case REMOTEQUERY:
          sendRemoteQuery();
          return RETURN;
        case PROCESS:
          final Method reqMethod = Method.getMethod(req.getMethod());
          HttpCacheHeaderUtil.setCacheControlHeader(config, resp, reqMethod);
          // unless we have been explicitly told not to, do cache validation
          // if we fail cache validation, execute the query
          if (config.getHttpCachingConfig().isNever304()
              || !HttpCacheHeaderUtil.doCacheHeaderValidation(solrReq, req, reqMethod, resp)) {
            SolrQueryResponse solrRsp = new SolrQueryResponse();
            /* even for HEAD requests, we need to execute the handler to
             * ensure we don't get an error (and to make sure the correct
             * QueryResponseWriter is selected and we get the correct
             * Content-Type)
             */
            SolrRequestInfo.setRequestInfo(new SolrRequestInfo(solrReq, solrRsp, action));
            mustClearSolrRequestInfo = true;
            executeCoreRequest(solrRsp);
            if (shouldAudit(cores)) {
              EventType eventType =
                  solrRsp.getException() == null ? EventType.COMPLETED : EventType.ERROR;
              if (shouldAudit(cores, eventType)) {
                cores
                    .getAuditLoggerPlugin()
                    .doAudit(
                        new AuditEvent(
                            eventType,
                            req,
                            getAuthCtx(),
                            solrReq.getRequestTimer().getTime(),
                            solrRsp.getException()));
              }
            }
            HttpCacheHeaderUtil.checkHttpCachingVeto(solrRsp, resp, reqMethod);
            Iterator<Map.Entry<String, String>> headers = solrRsp.httpHeaders();
            while (headers.hasNext()) {
              Map.Entry<String, String> entry = headers.next();
              resp.addHeader(entry.getKey(), entry.getValue());
            }
            QueryResponseWriter responseWriter = getResponseWriter();
            if (invalidStates != null)
              solrReq.getContext().put(CloudSolrClient.STATE_VERSION, invalidStates);
            writeResponse(solrRsp, responseWriter, reqMethod);
          }
          return RETURN;
        default:
          return action;
      }
    } catch (Throwable ex) {
      if (shouldAudit(EventType.ERROR)) {
        cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.ERROR, ex, req));
      }
      sendError(ex);
      // walk the entire cause chain to search for an Error
      Throwable t = ex;
      while (t != null) {
        if (t instanceof Error) {
          if (t != ex) {
            log.error(
                "An Error was wrapped in another exception - please report complete stacktrace on SOLR-6161",
                ex);
          }
          throw (Error) t;
        }
        t = t.getCause();
      }
      return RETURN;
    }
  }

  /**
   * Handle a request whose "type" could not be discerned in advance and may be either "admin" or
   * "remotequery".
   *
   * <p>Some implementations (such as {@link V2HttpCall}) may find it difficult to differentiate all
   * request types in advance. This method serves as a hook; allowing those implementations to
   * handle these cases gracefully.
   *
   * @see V2HttpCall
   */
  protected void handleAdminOrRemoteRequest() throws IOException {
    throw new IllegalStateException(
        "handleOrForwardRequest should not be invoked when serving v1 requests.");
  }

  /** Get the span for this request. Not null. */
  protected Span getSpan() {
    // Span was put into the request by SolrDispatchFilter
    return (Span) Objects.requireNonNull(req.getAttribute(Span.class.getName()));
  }

  // called after init().
  protected void populateTracingSpan(Span span) {
    // Set db.instance
    String coreOrColName = HttpSolrCall.this.origCorename;
    if (coreOrColName == null && getCore() != null) {
      coreOrColName = getCore().getName();
    }
    if (coreOrColName != null) {
      span.setTag(Tags.DB_INSTANCE, coreOrColName);
    }

    // Set operation name.
    String path = getPath();
    if (coreOrColName != null) {
      // prefix path by core or collection name
      if (getCore() != null && getCore().getName().equals(coreOrColName)) {
        path = "/{core}" + path;
      } else {
        path = "/{collection}" + path;
      }
    }
    String verb =
        getQueryParams().get(CoreAdminParams.ACTION, req.getMethod()).toLowerCase(Locale.ROOT);
    span.setOperationName(verb + ":" + path);
  }

  public boolean shouldAudit() {
    return shouldAudit(cores);
  }

  public boolean shouldAudit(AuditEvent.EventType eventType) {
    return shouldAudit(cores, eventType);
  }

  public static boolean shouldAudit(CoreContainer cores) {
    return cores.getAuditLoggerPlugin() != null;
  }

  public static boolean shouldAudit(CoreContainer cores, AuditEvent.EventType eventType) {
    return shouldAudit(cores) && cores.getAuditLoggerPlugin().shouldLog(eventType);
  }

  private boolean shouldAuthorize() {
    if (PublicKeyHandler.PATH.equals(path)) return false;
    // admin/info/key is the path where public key is exposed . it is always unsecured
    if ("/".equals(path) || "/solr/".equals(path))
      return false; // Static Admin UI files must always be served
    if (cores.getPkiAuthenticationSecurityBuilder() != null && req.getUserPrincipal() != null) {
      boolean b = cores.getPkiAuthenticationSecurityBuilder().needsAuthorization(req);
      log.debug("PkiAuthenticationPlugin says authorization required : {} ", b);
      return b;
    }
    return true;
  }

  void destroy() {
    try {
      if (solrReq != null) {
        log.debug("Closing out SolrRequest: {}", solrReq);
        solrReq.close();
      }
    } finally {
      try {
        if (core != null) core.close();
      } finally {
        if (mustClearSolrRequestInfo) {
          SolrRequestInfo.clearRequestInfo();
        }
      }
      AuthenticationPlugin authcPlugin = cores.getAuthenticationPlugin();
      if (authcPlugin != null) authcPlugin.closeRequest();
    }
  }

  // TODO using Http2Client
  private void remoteQuery(String coreUrl, HttpServletResponse resp) throws IOException {
    HttpRequestBase method;
    HttpEntity httpEntity = null;

    ModifiableSolrParams updatedQueryParams = new ModifiableSolrParams(queryParams);
    int forwardCount = queryParams.getInt(INTERNAL_REQUEST_COUNT, 0) + 1;
    updatedQueryParams.set(INTERNAL_REQUEST_COUNT, forwardCount);
    String queryStr = updatedQueryParams.toQueryString();

    try {
      String urlstr = coreUrl + queryStr;

      boolean isPostOrPutRequest = "POST".equals(req.getMethod()) || "PUT".equals(req.getMethod());
      if ("GET".equals(req.getMethod())) {
        method = new HttpGet(urlstr);
      } else if ("HEAD".equals(req.getMethod())) {
        method = new HttpHead(urlstr);
      } else if (isPostOrPutRequest) {
        HttpEntityEnclosingRequestBase entityRequest =
            "POST".equals(req.getMethod()) ? new HttpPost(urlstr) : new HttpPut(urlstr);
        InputStream in = req.getInputStream();
        HttpEntity entity = new InputStreamEntity(in, req.getContentLength());
        entityRequest.setEntity(entity);
        method = entityRequest;
      } else if ("DELETE".equals(req.getMethod())) {
        method = new HttpDelete(urlstr);
      } else if ("OPTIONS".equals(req.getMethod())) {
        method = new HttpOptions(urlstr);
      } else {
        throw new SolrException(
            SolrException.ErrorCode.SERVER_ERROR, "Unexpected method type: " + req.getMethod());
      }

      for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements(); ) {
        String headerName = e.nextElement();
        if (!"host".equalsIgnoreCase(headerName)
            && !"authorization".equalsIgnoreCase(headerName)
            && !"accept".equalsIgnoreCase(headerName)) {
          method.addHeader(headerName, req.getHeader(headerName));
        }
      }
      // These headers not supported for HttpEntityEnclosingRequests
      if (method instanceof HttpEntityEnclosingRequest) {
        method.removeHeaders(TRANSFER_ENCODING_HEADER);
        method.removeHeaders(CONTENT_LENGTH_HEADER);
      }

      final HttpResponse response =
          solrDispatchFilter
              .getHttpClient()
              .execute(method, HttpClientUtil.createNewHttpClientRequestContext());
      int httpStatus = response.getStatusLine().getStatusCode();
      httpEntity = response.getEntity();

      resp.setStatus(httpStatus);
      for (HeaderIterator responseHeaders = response.headerIterator();
          responseHeaders.hasNext(); ) {
        Header header = responseHeaders.nextHeader();

        // We pull out these two headers below because they can cause chunked
        // encoding issues with Tomcat
        if (header != null
            && !header.getName().equalsIgnoreCase(TRANSFER_ENCODING_HEADER)
            && !header.getName().equalsIgnoreCase(CONNECTION_HEADER)) {

          // NOTE: explicitly using 'setHeader' instead of 'addHeader' so that
          // the remote nodes values for any response headers will overide any that
          // may have already been set locally (ex: by the local jetty's RewriteHandler config)
          resp.setHeader(header.getName(), header.getValue());
        }
      }

      if (httpEntity != null) {
        if (httpEntity.getContentEncoding() != null)
          resp.setHeader(
              httpEntity.getContentEncoding().getName(),
              httpEntity.getContentEncoding().getValue());
        if (httpEntity.getContentType() != null)
          resp.setContentType(httpEntity.getContentType().getValue());

        InputStream is = httpEntity.getContent();
        OutputStream os = resp.getOutputStream();

        is.transferTo(os);
      }

    } catch (IOException e) {
      sendError(
          new SolrException(
              SolrException.ErrorCode.SERVER_ERROR,
              "Error trying to proxy request for url: "
                  + coreUrl
                  + " with _forwardCount: "
                  + forwardCount,
              e));
    } finally {
      Utils.consumeFully(httpEntity);
    }
  }

  protected void sendError(Throwable ex) throws IOException {
    Exception exp = null;
    SolrCore localCore = null;
    try {
      SolrQueryResponse solrResp = new SolrQueryResponse();
      if (ex instanceof Exception) {
        solrResp.setException((Exception) ex);
      } else {
        solrResp.setException(new RuntimeException(ex));
      }
      localCore = core;
      if (solrReq == null) {
        final SolrParams solrParams;
        if (req != null) {
          // use GET parameters if available:
          solrParams = SolrRequestParsers.parseQueryString(req.getQueryString());
        } else {
          // we have no params at all, use empty ones:
          solrParams = new MapSolrParams(Collections.emptyMap());
        }
        solrReq = new SolrQueryRequestBase(core, solrParams) {};
      }
      QueryResponseWriter writer = getResponseWriter();
      writeResponse(solrResp, writer, Method.GET);
    } catch (Exception e) { // This error really does not matter
      exp = e;
    } finally {
      try {
        if (exp != null) {
          SimpleOrderedMap<Object> info = new SimpleOrderedMap<>();
          int code = ResponseUtils.getErrorInfo(ex, info, log);
          sendError(code, info.toString());
        }
      } finally {
        if (core == null && localCore != null) {
          localCore.close();
        }
      }
    }
  }

  protected void sendError(int code, String message) throws IOException {
    try {
      response.sendError(code, message);
    } catch (EOFException e) {
      log.info(
          "Unable to write error response, client closed connection or we are shutting down", e);
    }
  }

  protected void executeCoreRequest(SolrQueryResponse rsp) {
    // a custom filter could add more stuff to the request before passing it on.
    // for example: sreq.getContext().put( "HttpServletRequest", req );
    // used for logging query stats in SolrCore.execute()
    solrReq.getContext().put("webapp", req.getContextPath());
    solrReq.getCore().execute(handler, solrReq, rsp);
  }

  private void handleAdminRequest() throws IOException {
    SolrQueryResponse solrResp = new SolrQueryResponse();
    handleAdmin(solrResp);
    logAndFlushAdminRequest(solrResp);
  }

  protected void logAndFlushAdminRequest(SolrQueryResponse solrResp) throws IOException {
    if (solrResp.getToLog().size() > 0) {
      // has to come second and in it's own if to keep ./gradlew check happy.
      if (log.isInfoEnabled()) {
        log.info(
            handler != null
                ? MarkerFactory.getMarker(handler.getClass().getName())
                : MarkerFactory.getMarker(HttpSolrCall.class.getName()),
            solrResp.getToLogAsString("[admin]"));
      }
    }
    QueryResponseWriter respWriter =
        SolrCore.DEFAULT_RESPONSE_WRITERS.get(solrReq.getParams().get(CommonParams.WT));
    if (respWriter == null) respWriter = getResponseWriter();
    writeResponse(solrResp, respWriter, Method.getMethod(req.getMethod()));
    if (shouldAudit()) {
      EventType eventType = solrResp.getException() == null ? EventType.COMPLETED : EventType.ERROR;
      if (shouldAudit(eventType)) {
        cores
            .getAuditLoggerPlugin()
            .doAudit(
                new AuditEvent(
                    eventType,
                    req,
                    getAuthCtx(),
                    solrReq.getRequestTimer().getTime(),
                    solrResp.getException()));
      }
    }
  }

  /**
   * Returns {@link QueryResponseWriter} to be used. When {@link CommonParams#WT} not specified in
   * the request or specified value doesn't have corresponding {@link QueryResponseWriter} then,
   * returns the default query response writer Note: This method must not return null
   */
  protected QueryResponseWriter getResponseWriter() {
    String wt = solrReq.getParams().get(CommonParams.WT);
    if (core != null) {
      return core.getQueryResponseWriter(wt);
    } else {
      return SolrCore.DEFAULT_RESPONSE_WRITERS.getOrDefault(
          wt, SolrCore.DEFAULT_RESPONSE_WRITERS.get("standard"));
    }
  }

  protected void handleAdmin(SolrQueryResponse solrResp) {
    SolrCore.preDecorateResponse(solrReq, solrResp);
    handler.handleRequest(solrReq, solrResp);
    SolrCore.postDecorateResponse(handler, solrReq, solrResp);
  }

  /**
   * Sets the "collection" parameter on the request to the list of alias-resolved collections for
   * this request. It can be avoided sometimes. Note: {@link
   * org.apache.solr.handler.component.HttpShardHandler} processes this param.
   *
   * @see #getCollectionsList()
   */
  protected void addCollectionParamIfNeeded(List<String> collections) {
    if (collections.isEmpty()) {
      return;
    }
    assert cores.isZooKeeperAware();
    String collectionParam = queryParams.get(COLLECTION_PROP);
    // if there is no existing collection param and the core we go to is for the expected
    // collection, then we needn't add a collection param
    if (collectionParam == null
        && // if collection param already exists, we may need to over-write it
        core != null
        && collections.equals(
            Collections.singletonList(core.getCoreDescriptor().getCollectionName()))) {
      return;
    }
    String newCollectionParam = StrUtils.join(collections, ',');
    if (newCollectionParam.equals(collectionParam)) {
      return;
    }
    // TODO add a SolrRequest.getModifiableParams ?
    ModifiableSolrParams params = new ModifiableSolrParams(solrReq.getParams());
    params.set(COLLECTION_PROP, newCollectionParam);
    solrReq.setParams(params);
  }

  protected void writeResponse(
      SolrQueryResponse solrRsp, QueryResponseWriter responseWriter, Method reqMethod)
      throws IOException {
    try {
      Object invalidStates = solrReq.getContext().get(CloudSolrClient.STATE_VERSION);
      // This is the last item added to the response and the client would expect it that way.
      // If that assumption is changed , it would fail. This is done to avoid an O(n) scan on
      // the response for each request
      if (invalidStates != null) solrRsp.add(CloudSolrClient.STATE_VERSION, invalidStates);
      // Now write it out
      final String ct = responseWriter.getContentType(solrReq, solrRsp);
      // don't call setContentType on null
      if (null != ct) response.setContentType(ct);

      if (solrRsp.getException() != null) {
        NamedList<Object> info = new SimpleOrderedMap<>();
        int code = ResponseUtils.getErrorInfo(solrRsp.getException(), info, log);
        solrRsp.add("error", info);
        response.setStatus(code);
      }

      if (Method.HEAD != reqMethod) {
        OutputStream out = response.getOutputStream();
        QueryResponseWriterUtil.writeQueryResponse(out, responseWriter, solrReq, solrRsp, ct);
      }
      // else http HEAD request, nothing to write out, waited this long just to get ContentType
    } catch (EOFException e) {
      log.info("Unable to write response, client closed connection or we are shutting down", e);
    }
  }

  /**
   * Returns null if the state ({@link CloudSolrClient#STATE_VERSION}) is good; otherwise returns
   * state problems.
   */
  private Map<String, Integer> checkStateVersionsAreValid(String stateVer) {
    Map<String, Integer> result = null;
    String[] pairs;
    if (stateVer != null && !stateVer.isEmpty() && cores.isZooKeeperAware()) {
      // many have multiple collections separated by |
      pairs = StringUtils.split(stateVer, '|');
      for (String pair : pairs) {
        String[] pcs = StringUtils.split(pair, ':');
        if (pcs.length == 2 && !pcs[0].isEmpty() && !pcs[1].isEmpty()) {
          Integer status =
              cores
                  .getZkController()
                  .getZkStateReader()
                  .compareStateVersions(pcs[0], Integer.parseInt(pcs[1]));
          if (status != null) {
            if (result == null) result = new HashMap<>();
            result.put(pcs[0], status);
          }
        }
      }
    }
    return result;
  }

  protected SolrCore getCoreByCollection(String collectionName, boolean isPreferLeader) {
    ZkStateReader zkStateReader = cores.getZkController().getZkStateReader();

    ClusterState clusterState = zkStateReader.getClusterState();
    DocCollection collection = clusterState.getCollectionOrNull(collectionName, true);
    if (collection == null) {
      return null;
    }

    Set<String> liveNodes = clusterState.getLiveNodes();

    if (isPreferLeader) {
      List<Replica> leaderReplicas =
          collection.getLeaderReplicas(cores.getZkController().getNodeName());
      SolrCore core = randomlyGetSolrCore(liveNodes, leaderReplicas);
      if (core != null) return core;
    }

    List<Replica> replicas = collection.getReplicas(cores.getZkController().getNodeName());
    return randomlyGetSolrCore(liveNodes, replicas);
  }

  private SolrCore randomlyGetSolrCore(Set<String> liveNodes, List<Replica> replicas) {
    if (replicas != null) {
      RandomIterator<Replica> it = new RandomIterator<>(random, replicas);
      while (it.hasNext()) {
        Replica replica = it.next();
        if (liveNodes.contains(replica.getNodeName())
            && replica.getState() == Replica.State.ACTIVE) {
          SolrCore core = checkProps(replica);
          if (core != null) return core;
        }
      }
    }
    return null;
  }

  private SolrCore checkProps(ZkNodeProps zkProps) {
    String corename;
    SolrCore core = null;
    if (cores.getZkController().getNodeName().equals(zkProps.getStr(NODE_NAME_PROP))) {
      corename = zkProps.getStr(CORE_NAME_PROP);
      core = cores.getCore(corename);
    }
    return core;
  }

  private void getSlicesForCollections(
      ClusterState clusterState, Collection<Slice> slices, boolean activeSlices) {
    if (activeSlices) {
      for (Map.Entry<String, DocCollection> entry : clusterState.getCollectionsMap().entrySet()) {
        final Slice[] activeCollectionSlices = entry.getValue().getActiveSlicesArr();
        if (activeCollectionSlices != null) {
          Collections.addAll(slices, activeCollectionSlices);
        }
      }
    } else {
      for (Map.Entry<String, DocCollection> entry : clusterState.getCollectionsMap().entrySet()) {
        final Collection<Slice> collectionSlices = entry.getValue().getSlices();
        if (collectionSlices != null) {
          slices.addAll(collectionSlices);
        }
      }
    }
  }

  protected String getRemoteCoreUrl(String collectionName, String origCorename)
      throws SolrException {
    ClusterState clusterState = cores.getZkController().getClusterState();
    final DocCollection docCollection = clusterState.getCollectionOrNull(collectionName);
    Slice[] slices = (docCollection != null) ? docCollection.getActiveSlicesArr() : null;
    List<Slice> activeSlices = new ArrayList<>();
    boolean byCoreName = false;

    int totalReplicas = 0;

    if (slices == null) {
      byCoreName = true;
      activeSlices = new ArrayList<>();
      getSlicesForCollections(clusterState, activeSlices, true);
      if (activeSlices.isEmpty()) {
        getSlicesForCollections(clusterState, activeSlices, false);
      }
    } else {
      Collections.addAll(activeSlices, slices);
    }

    for (Slice s : activeSlices) {
      totalReplicas += s.getReplicas().size();
    }
    if (activeSlices.isEmpty()) {
      return null;
    }

    // XXX (ab) most likely this is not needed? it seems all code paths
    // XXX already make sure the collectionName is on the list
    if (!collectionsList.contains(collectionName)) {
      collectionsList = new ArrayList<>(collectionsList);
      collectionsList.add(collectionName);
    }

    // Avoid getting into a recursive loop of requests being forwarded by
    // stopping forwarding and erroring out after (totalReplicas) forwards
    if (queryParams.getInt(INTERNAL_REQUEST_COUNT, 0) > totalReplicas) {
      throw new SolrException(
          SolrException.ErrorCode.INVALID_STATE,
          "No active replicas found for collection: " + collectionName);
    }

    String coreUrl =
        getCoreUrl(collectionName, origCorename, clusterState, activeSlices, byCoreName, true);

    if (coreUrl == null) {
      coreUrl =
          getCoreUrl(collectionName, origCorename, clusterState, activeSlices, byCoreName, false);
    }

    return coreUrl;
  }

  private String getCoreUrl(
      String collectionName,
      String origCorename,
      ClusterState clusterState,
      List<Slice> slices,
      boolean byCoreName,
      boolean activeReplicas) {
    String coreUrl;
    Set<String> liveNodes = clusterState.getLiveNodes();
    Collections.shuffle(slices, random);

    for (Slice slice : slices) {
      List<Replica> randomizedReplicas = new ArrayList<>(slice.getReplicas());
      Collections.shuffle(randomizedReplicas, random);

      for (Replica replica : randomizedReplicas) {
        if (!activeReplicas
            || (liveNodes.contains(replica.getNodeName())
                && replica.getState() == Replica.State.ACTIVE)) {

          if (byCoreName && !origCorename.equals(replica.getStr(CORE_NAME_PROP))) {
            // if it's by core name, make sure they match
            continue;
          }
          if (replica.getBaseUrl().equals(cores.getZkController().getBaseUrl())) {
            // don't count a local core
            continue;
          }

          if (origCorename != null) {
            coreUrl = replica.getBaseUrl() + "/" + origCorename;
          } else {
            coreUrl = replica.getCoreUrl();
            if (coreUrl.endsWith("/")) {
              coreUrl = coreUrl.substring(0, coreUrl.length() - 1);
            }
          }

          return coreUrl;
        }
      }
    }
    return null;
  }

  protected Object _getHandler() {
    return handler;
  }

  private AuthorizationContext getAuthCtx() {

    String resource = getPath();

    final List<CollectionRequest> collectionRequests =
        AuthorizationUtils.getCollectionRequests(getPath(), getCollectionsList(), getQueryParams());

    // Populate the request type if the request is select or update
    if (requestType == RequestType.UNKNOWN) {
      if (resource.startsWith("/select") || resource.startsWith("/get"))
        requestType = RequestType.READ;
      if (resource.startsWith("/update")) requestType = RequestType.WRITE;
    }

    return new HttpServletAuthorizationContext(getReq()) {
      @Override
      public SolrParams getParams() {
        return null == solrReq ? null : solrReq.getParams();
      }

      @Override
      public List<CollectionRequest> getCollectionRequests() {
        return collectionRequests;
      }

      @Override
      public String getResource() {
        return path;
      }

      @Override
      public RequestType getRequestType() {
        return requestType;
      }

      @Override
      public Object getHandler() {
        return _getHandler();
      }

      @Override
      public String toString() {
        StringBuilder response =
            new StringBuilder("userPrincipal: [")
                .append(getUserPrincipal())
                .append("]")
                .append(" type: [")
                .append(requestType.toString())
                .append("], collections: [");
        for (CollectionRequest collectionRequest : collectionRequests) {
          response.append(collectionRequest.collectionName).append(", ");
        }
        if (collectionRequests.size() > 0)
          response.delete(response.length() - 1, response.length());

        response.append("], Path: [").append(resource).append("]");
        response.append(" path : ").append(path).append(" params :").append(getParams());
        return response.toString();
      }
    };
  }

  static final String CONNECTION_HEADER = "Connection";
  static final String TRANSFER_ENCODING_HEADER = "Transfer-Encoding";
  static final String CONTENT_LENGTH_HEADER = "Content-Length";
  List<CommandOperation> parsedCommands;

  public List<CommandOperation> getCommands(boolean validateInput) {
    if (parsedCommands == null) {
      Iterable<ContentStream> contentStreams = solrReq.getContentStreams();
      if (contentStreams == null) parsedCommands = Collections.emptyList();
      else {
        parsedCommands =
            ApiBag.getCommandOperations(
                contentStreams.iterator().next(), getValidators(), validateInput);
      }
    }
    return CommandOperation.clone(parsedCommands);
  }

  protected ValidatingJsonMap getSpec() {
    return null;
  }

  protected Map<String, JsonSchemaValidator> getValidators() {
    return Collections.emptyMap();
  }

  /** A faster method for randomly picking items when you do not need to consume all items. */
  private static class RandomIterator<E> implements Iterator<E> {
    private Random rand;
    private ArrayList<E> elements;
    private int size;

    public RandomIterator(Random rand, Collection<E> elements) {
      this.rand = rand;
      this.elements = new ArrayList<>(elements);
      this.size = elements.size();
    }

    @Override
    public boolean hasNext() {
      return size > 0;
    }

    @Override
    public E next() {
      int idx = rand.nextInt(size);
      E e1 = elements.get(idx);
      E e2 = elements.get(size - 1);
      elements.set(idx, e2);
      size--;
      return e1;
    }
  }
}


text:
[![NPM version](https://badgen.net/npm/v/terra-badge)](https://www.npmjs.org/package/terra-badge)
[![Build Status](https://badgen.net/travis/cerner/terra-core)](https://travis-ci.org/cerner/terra-core)

The terra-badge component displays content classification.

- [Getting Started](#getting-started)
- [Documentation](https://github.com/cerner/terra-core/tree/master/packages/terra-badge/docs)
- [LICENSE](#license)

## Getting Started

- Install with [npm](https://www.npmjs.com): `npm install terra-badge`

## LICENSE

Copyright 2017 - 2019 Cerner Innovation, Inc.

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.


text:
package com.androidproductions.myfinances;

/**
 * Created by scott.jones on 01/11/13.
 */
public final class Actions {
    public static final int AccountSummary = 0;
    public static final int ScheduledTransactions = 1;
    public static final int IncomingTransactions = 2;
    public static final int OutgoingTransactions = 3;
    public static final int Budgeting = 4;
    public static final int AddNew = 5;
    public static final int Alerts = 6;
    public static final int Accounts = 7;
}


text:
/*
 * iptables module to match IP address ranges
 *
 * (C) 2003 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/netfilter_ipv4/ipt_iprange.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("iptables arbitrary IP range match module");

#if 0
#define DEBUGP printk
#else
#define DEBUGP(format, args...)
#endif

static int
match(const struct sk_buff *skb,
      const struct net_device *in,
      const struct net_device *out,
      const void *matchinfo,
      int offset, unsigned int protoff, int *hotdrop)
{
	const struct ipt_iprange_info *info = matchinfo;
	const struct iphdr *iph = skb->nh.iph;

	if (info->flags & IPRANGE_SRC) {
		if (((ntohl(iph->saddr) < ntohl(info->src.min_ip))
			  || (ntohl(iph->saddr) > ntohl(info->src.max_ip)))
			 ^ !!(info->flags & IPRANGE_SRC_INV)) {
			DEBUGP("src IP %u.%u.%u.%u NOT in range %s"
			       "%u.%u.%u.%u-%u.%u.%u.%u\n",
				NIPQUAD(iph->saddr),
			        info->flags & IPRANGE_SRC_INV ? "(INV) " : "",
				NIPQUAD(info->src.min_ip),
				NIPQUAD(info->src.max_ip));
			return 0;
		}
	}
	if (info->flags & IPRANGE_DST) {
		if (((ntohl(iph->daddr) < ntohl(info->dst.min_ip))
			  || (ntohl(iph->daddr) > ntohl(info->dst.max_ip)))
			 ^ !!(info->flags & IPRANGE_DST_INV)) {
			DEBUGP("dst IP %u.%u.%u.%u NOT in range %s"
			       "%u.%u.%u.%u-%u.%u.%u.%u\n",
				NIPQUAD(iph->daddr),
			        info->flags & IPRANGE_DST_INV ? "(INV) " : "",
				NIPQUAD(info->dst.min_ip),
				NIPQUAD(info->dst.max_ip));
			return 0;
		}
	}
	return 1;
}

static int check(const char *tablename,
		 const void *inf,
		 void *matchinfo,
		 unsigned int matchsize,
		 unsigned int hook_mask)
{
	/* verify size */
	if (matchsize != IPT_ALIGN(sizeof(struct ipt_iprange_info)))
		return 0;

	return 1;
}

static struct ipt_match iprange_match =
{
	.list = { NULL, NULL },
	.name = "iprange",
	.match = &match,
	.checkentry = &check,
	.destroy = NULL,
	.me = THIS_MODULE
};

static int __init init(void)
{
	return ipt_register_match(&iprange_match);
}

static void __exit fini(void)
{
	ipt_unregister_match(&iprange_match);
}

module_init(init);
module_exit(fini);


text:
Given "The view title labelled $title" do |title|
  navBarTitle = "//UIAApplication[1]/UIAWindow[1]/UIANavigationBar[1]/UIAStaticText[1]"
  find_element(:xpath, navBarTitle).label.should eq title
end

Given /^I enter (.+) into field (\d+) of the application$/ do |value, field|
  # Get a textfield by index
  textfield(field.to_i).type value
end

Given "I enter $value into a field of the application showing $text" do |value, field|
  textfield(field).type value
end

And /^I press button (\d+)$/ do |button_index|
  # Find a button by index
  button(button_index.to_i).click
end

And "I press a button labelled $text" do |button_text|
  # Find a button by text
  button(button_text).click
end

Then /^The result should be displayed as (\d+)$/ do |expected|
  # You can get just the first of a class of elements
  first_text.value.should eq expected
end

Then "The view title was $title" do |title|
  navBarTitle = "//UIAApplication[1]/UIAWindow[1]/UIANavigationBar[1]/UIAStaticText[1]"
  find_element(:xpath, navBarTitle).label.should eq title
end

Then "The modal view title was $title" do |title|
  element = find_element(:xpath, "//UIAApplication[1]/UIAWindow[1]/UIAStaticText[1]")
  element.label.should eq title
end


text:
package generator

import (
	"fmt"
	"strings"
	"testing"

	"github.com/pkg/errors"
	loggingconfig "github.com/rancher/rancher/pkg/controllers/user/logging/config"
	v3 "github.com/rancher/types/apis/management.cattle.io/v3"
)

func TestValidateFragments(t *testing.T) {

	projectWrap := ProjectLoggingTemplateWrap{
		ContainerLogSourceTag: loggingconfig.ProjectLevel,
		LoggingCommonField:    v3.LoggingCommonField{},
	}

	clusterWrap := ClusterLoggingTemplateWrap{
		ContainerLogSourceTag: loggingconfig.ClusterLevel,
		LoggingCommonField:    v3.LoggingCommonField{},
	}
	// case:
	// 1. custom tags key include valid custom key value, expected validate success
	customTags := map[string]string{
		"key": "value",
	}
	if err := compareCustomTags(clusterWrap, projectWrap, customTags, ""); err != nil {
		t.Error(err)
		return
	}

	// 2. custom tags key include fluentd configure element, expected validate failed
	customTags = map[string]string{
		"<source>":  "value",
		"</source>": "value",
	}
	if err := compareCustomTags(clusterWrap, projectWrap, customTags, "mismatched tags"); err != nil {
		t.Errorf("validate custom tags key include fluentd configure element should return mismatched tags error, %v", err)
		return
	}

	// 3. custom tags key include embedded Ruby code, expected validate failed
	customTags = map[string]string{
		"key#{Ruby}": "value",
	}
	if err := compareCustomTags(clusterWrap, projectWrap, customTags, "embedded Ruby code"); err != nil {
		t.Errorf("validate custom tags key include embedded Ruby code should return embedded Ruby code error, %v", err)
		return
	}

	// 4. custom tags value include embedded Ruby code, expected validate failed
	customTags = map[string]string{
		"key": "value#{Ruby}",
	}
	if err := compareCustomTags(clusterWrap, projectWrap, customTags, "embedded Ruby code"); err != nil {
		t.Errorf("validate custom tags value include embedded Ruby code should return embedded Ruby code error, %v", err)
		return
	}

	// 5. custom tags value include line break and fluentd configure element, expected be convert to escape string success
	customTags = map[string]string{
		"key": `begin
		</record>
	  </filter>
	  <source>
		@type tail
		path /etc/passwd
		tag injection
		read_from_head true
		<parse>
		  @type none
		</parse>
	  </source>

	  <match injection>
		  @type remote_syslog
		  host rancher.com
		  port 60514
		  severity notice
		  protocol udp
		  program injection
	  </match>

	  <filter injection.**>
		@type record_transformer
		<record>`,
	}

	if err := compareCustomTags(clusterWrap, projectWrap, customTags, ""); err != nil {
		t.Errorf("custom tags value include line break and fluentd configure element should not return err, %v", err)
		return
	}

	// 6. valid custom configure, expected validate success
	content := `
	@type remote_syslog
	host rancher.com
	port 8088
	`
	if err := compareCustomConfigure(clusterWrap, projectWrap, content, ""); err != nil {
		t.Errorf("valid custom configure, expected validate success should not return err, %v", err)
		return
	}

	// 7. custom configure include not allowed configure element, expected validate failed
	content = `
	@type remote_syslog
	host rancher.com
	port 8088
	<source>
	  @type tail
	  path /etc/passwd
	  tag injection
	  read_from_head true
	  <parse>
	    @type none
	  </parse>
	</source>
	`
	if err := compareCustomConfigure(clusterWrap, projectWrap, content, "unexpected configure element"); err != nil {
		t.Errorf("custom configure include not allowed configure element should return error, %v", err)
		return
	}

	// 8. custom configure include embedded Ruby code, expected validate failed
	content = `
	@type remote_syslog
	host rancher.com
	port 8088
	key #{ruby}
	`
	if err := compareCustomConfigure(clusterWrap, projectWrap, content, "embedded Ruby code"); err != nil {
		t.Errorf("custom configure include embedded Ruby code should return embedded Ruby code err, %v", err)
		return
	}
}

func compareCustomTags(clusterWrap ClusterLoggingTemplateWrap, projectWrap ProjectLoggingTemplateWrap, customTags map[string]string, expectedErrMsg string) error {
	var actualErrMsg string
	clusterWrap.OutputTags = customTags
	if err := ValidateCustomTags(clusterWrap); err != nil {
		actualErrMsg = err.Error()
	}

	projectWrap.OutputTags = customTags
	if err := ValidateCustomTags(projectWrap); err != nil {
		actualErrMsg = err.Error()
	}
	if err := compareErr(actualErrMsg, expectedErrMsg); err != nil {
		return err
	}

	return compareErr(actualErrMsg, expectedErrMsg)
}

func compareCustomConfigure(clusterWrap ClusterLoggingTemplateWrap, projectWrap ProjectLoggingTemplateWrap, content, expectedErrMsg string) error {
	var actualErrMsg string
	clusterWrap.Content = content
	clusterWrap.CurrentTarget = loggingconfig.CustomTarget
	if err := ValidateCustomTarget(clusterWrap); err != nil {
		actualErrMsg = err.Error()
	}
	if err := compareErr(actualErrMsg, expectedErrMsg); err != nil {
		return err
	}

	projectWrap.Content = content
	projectWrap.CurrentTarget = loggingconfig.CustomTarget
	if err := ValidateCustomTarget(projectWrap); err != nil {
		actualErrMsg = err.Error()
	}

	return compareErr(actualErrMsg, expectedErrMsg)
}

func compareErr(actualErrMsg, expectedErrMsg string) error {
	if !strings.Contains(actualErrMsg, expectedErrMsg) {
		return errors.New("expected compare message: " + expectedErrMsg + ", actual :" + actualErrMsg)
	}
	return nil
}

func TestEscapeString(t *testing.T) {
	testDate := map[string]string{
		//before: after
		"test":     `"test"`,
		"\"test\"": `"\\\"test\\\""`,
		"\ttest":   `"\\ttest"`,
		"\rtest":   `"\\rtest"`,
		"\ntest":   `"\\ntest"`,
		"\btest":   `"\\btest"`,
		"\ftest":   `"\\ftest"`,
		"\r\ntest": `"\\r\\ntest"`,
		"\\test":   `"\\\\test"`,
	}

	for before, after := range testDate {
		if err := compareEscapeString(before, after); err != nil {
			t.Error(err)
		}
	}
}

func compareEscapeString(input, expected string) error {
	actual := escapeString(input)
	if actual != expected {
		return fmt.Errorf("string %s escape output %s not equal to expected %s", input, actual, expected)
	}
	return nil
}


text:
<!-- Standard stuff -->
<link rel="alternate" type="application/rss+xml" href="{{ "/feed.xml" | prepend: site.baseurl }}" title="Sitewide RSS Feed" />
<link rel="author" type="text/plain" href="{{ site.baseurl }}/humans.txt" />


text:
package wm

import (
	"errors"

	"github.com/mibitzi/stwm/entities/workspace"
)

func (wm *WM) AddWorkspace(ws *workspace.Workspace) error {
	if wm.HasWorkspace(ws.Id()) {
		return errors.New("wm: already added this workspace")
	}

	wm.Workspaces = append(wm.Workspaces, ws)

	if wm.CurWs == nil {
		wm.CurWs = ws
		wm.CurWs.Show()
	}

	return nil
}

func (wm *WM) HasWorkspace(id string) bool {
	for _, ws := range wm.Workspaces {
		if ws.Id() == id {
			return true
		}
	}
	return false
}


text:
using System;
using System.Threading.Tasks;
using System.Management.Automation;
using OpenStack.Compute;
using OpenStack;

namespace OpenStackCmdlets
{
	[Cmdlet(VerbsCommon.Get, "Images")]
	public class GetImagesCmdlet : OpenStackCommandBase
	{
		protected async override Task ProcessRecordAsync()
		{
			IOpenStackClient client = this.GetOpenStackClient ();
			var computeServiceClient = client.CreateServiceClient<IComputeServiceClient>();

			var images = await computeServiceClient.GetImages();

			foreach (var image in images) {
				WriteObject (image);
			}
		}
	}
}


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/query_tiles/internal/tile_store.h"

#include <utility>

#include "components/query_tiles/internal/proto_conversion.h"

namespace leveldb_proto {

void DataToProto(query_tiles::TileGroup* data,
                 query_tiles::proto::TileGroup* proto) {
  TileGroupToProto(data, proto);
}

void ProtoToData(query_tiles::proto::TileGroup* proto,
                 query_tiles::TileGroup* data) {
  TileGroupFromProto(proto, data);
}

}  // namespace leveldb_proto

namespace query_tiles {

TileStore::TileStore(TileProtoDb db) : db_(std::move(db)) {}

TileStore::~TileStore() = default;

void TileStore::InitAndLoad(LoadCallback callback) {
  db_->Init(base::BindOnce(&TileStore::OnDbInitialized,
                           weak_ptr_factory_.GetWeakPtr(),
                           std::move(callback)));
}

void TileStore::Update(const std::string& key,
                       const TileGroup& group,
                       UpdateCallback callback) {
  auto entries_to_save = std::make_unique<KeyEntryVector>();
  TileGroup entry_to_save = group;
  entries_to_save->emplace_back(key, std::move(entry_to_save));
  db_->UpdateEntries(std::move(entries_to_save),
                     std::make_unique<KeyVector>() /*keys_to_remove*/,
                     std::move(callback));
}

void TileStore::Delete(const std::string& key, DeleteCallback callback) {
  auto keys_to_delete = std::make_unique<KeyVector>();
  keys_to_delete->emplace_back(key);
  db_->UpdateEntries(std::make_unique<KeyEntryVector>() /*entries_to_save*/,
                     std::move(keys_to_delete), std::move(callback));
}

void TileStore::OnDbInitialized(LoadCallback callback,
                                leveldb_proto::Enums::InitStatus status) {
  if (status != leveldb_proto::Enums::InitStatus::kOK) {
    std::move(callback).Run(false, KeysAndEntries());
    return;
  }

  db_->LoadKeysAndEntries(base::BindOnce(&TileStore::OnDataLoaded,
                                         weak_ptr_factory_.GetWeakPtr(),
                                         std::move(callback)));
}

void TileStore::OnDataLoaded(
    LoadCallback callback,
    bool success,
    std::unique_ptr<std::map<std::string, TileGroup>> loaded_keys_and_entries) {
  if (!success || !loaded_keys_and_entries) {
    std::move(callback).Run(success, KeysAndEntries());
    return;
  }

  KeysAndEntries keys_and_entries;
  for (auto& it : *loaded_keys_and_entries) {
    std::unique_ptr<TileGroup> group =
        std::make_unique<TileGroup>(std::move(it.second));
    keys_and_entries.emplace(it.first, std::move(group));
  }

  std::move(callback).Run(true, std::move(keys_and_entries));
}

}  // namespace query_tiles


text:
/*
 * GLX overlay test/demo.
 *
 * Brian Paul
 * 18 July 2005
 */

#include <GL/gl.h>
#include <GL/glx.h>
#include <X11/keysym.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

static int WinWidth = 300, WinHeight = 300;
static Window NormalWindow = 0;
static Window OverlayWindow = 0;
static GLXContext NormalContext = 0;
static GLXContext OverlayContext = 0;
static GLboolean RGBOverlay = GL_FALSE;
static GLfloat Angle = 0.0;

static void
RedrawNormal(Display *dpy)
{
   glXMakeCurrent(dpy, NormalWindow, NormalContext);
   glViewport(0, 0, WinWidth, WinHeight);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
   glMatrixMode(GL_MODELVIEW);
   glClearColor(0.5, 0.5, 0.5, 1.0);
   glClear(GL_COLOR_BUFFER_BIT);
   glColor3f(1.0, 1.0, 0.0);
   glPushMatrix();
   glRotatef(Angle, 0, 0, 1);
   glRectf(-0.8, -0.8, 0.8, 0.8);
   glPopMatrix();
   glXSwapBuffers(dpy, NormalWindow);
}

static void
RedrawOverlay(Display *dpy)
{
   glXMakeCurrent(dpy, OverlayWindow, OverlayContext);
   glViewport(0, 0, WinWidth, WinHeight);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
   glMatrixMode(GL_MODELVIEW);
   glClear(GL_COLOR_BUFFER_BIT);
   if (RGBOverlay) {
      glColor3f(0.0, 1.0, 1.0);
   }
   else {
      glIndexi(2);
   }
   glBegin(GL_LINES);
   glVertex2f(-1, -1);
   glVertex2f(1, 1);
   glVertex2f(1, -1);
   glVertex2f(-1, 1);
   glEnd();
   glXSwapBuffers(dpy, OverlayWindow);
}

static Window
MakeWindow(Display *dpy, XVisualInfo *visinfo, Window parent,
             unsigned int width, unsigned int height)
{
   int scrnum;
   XSetWindowAttributes attr;
   unsigned long mask;
   Window root;
   Window win;

   scrnum = DefaultScreen(dpy);
   root = RootWindow(dpy, scrnum);

   /* window attributes */
   attr.background_pixel = 0;
   attr.border_pixel = 0;
   attr.colormap = XCreateColormap(dpy, root, visinfo->visual, AllocNone);
   attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

   win = XCreateWindow(dpy, parent, 0, 0, width, height,
		        0, visinfo->depth, InputOutput,
		        visinfo->visual, mask, &attr);
   return win;
}

static void
MakeNormalWindow(Display *dpy)
{
   int attrib[] = { GLX_RGBA,
		    GLX_RED_SIZE, 1,
		    GLX_GREEN_SIZE, 1,
		    GLX_BLUE_SIZE, 1,
		    GLX_DOUBLEBUFFER,
		    None };
   int scrnum;
   Window root;
   XVisualInfo *visinfo;

   scrnum = DefaultScreen(dpy);
   root = RootWindow(dpy, scrnum);

   visinfo = glXChooseVisual(dpy, scrnum, attrib);
   if (!visinfo) {
      printf("Error: couldn't get an RGB, Double-buffered visual\n");
      exit(1);
   }

   NormalWindow = MakeWindow(dpy, visinfo, root, WinWidth, WinHeight);
   assert(NormalWindow);

   NormalContext = glXCreateContext(dpy, visinfo, NULL, True);
   assert(NormalContext);
}

static void
MakeOverlayWindow(Display *dpy)
{
   int rgbAttribs[] = {
      GLX_RGBA,
      GLX_RED_SIZE, 1,
      GLX_GREEN_SIZE, 1,
      GLX_BLUE_SIZE, 1,
      GLX_DOUBLEBUFFER,
      GLX_LEVEL, 1,
      None
   };
   int indexAttribs[] = {
      /*GLX_RGBA, leave this out */
      GLX_RED_SIZE, 1,
      GLX_GREEN_SIZE, 1,
      GLX_BLUE_SIZE, 1,
      GLX_DOUBLEBUFFER,
      GLX_LEVEL, 1,
      None
   };
   int scrnum;
   XVisualInfo *visinfo;

   scrnum = DefaultScreen(dpy);

   visinfo = glXChooseVisual(dpy, scrnum, rgbAttribs);
   if (visinfo) {
      printf("Found RGB overlay visual 0x%x\n", (int) visinfo->visualid);
      RGBOverlay = GL_TRUE;
   }
   else {
      visinfo = glXChooseVisual(dpy, scrnum, indexAttribs);
      if (visinfo) {
         printf("Found Color Index overlay visual 0x%x\n",
                (int) visinfo->visualid);
         /* XXX setup the colormap entries! */
      }
      else {
         printf("Couldn't get an overlay visual.\n");
         printf("Your hardware probably doesn't support framebuffer overlay planes.\n");
         exit(1);
      }
   }

   OverlayWindow = MakeWindow(dpy, visinfo, NormalWindow, WinWidth, WinHeight);
   assert(OverlayWindow);

   OverlayContext = glXCreateContext(dpy, visinfo, NULL, True);
   assert(OverlayContext);
}

static void
EventLoop(Display *dpy)
{
   XEvent event;

   while (1) {
      XNextEvent(dpy, &event);

      switch (event.type) {
	 case Expose:
	    RedrawNormal(dpy);
	    RedrawOverlay(dpy);
	    break;
	 case ConfigureNotify:
            WinWidth = event.xconfigure.width;
            WinHeight = event.xconfigure.height;
            if (event.xconfigure.window == NormalWindow)
               XResizeWindow(dpy, OverlayWindow, WinWidth, WinHeight);
	    break;
         case KeyPress:
            {
               char buffer[10];
	       XLookupString(&event.xkey, buffer, sizeof(buffer),
                             NULL, NULL);
	       if (buffer[0] == 27) {
                  /* escape */
                  return;
               }
               else if (buffer[0] == ' ') {
                  Angle += 5.0;
                  RedrawNormal(dpy);
               }
            }
            break;
         default:
            ; /* nothing */
      }
   }
}

int
main(int argc, char *argv[])
{
   Display *dpy = XOpenDisplay(NULL);

   assert(dpy);

   MakeNormalWindow(dpy);
   MakeOverlayWindow(dpy);

   XMapWindow(dpy, NormalWindow);
   XMapWindow(dpy, OverlayWindow);

   EventLoop(dpy);

   glXDestroyContext(dpy, OverlayContext);
   glXDestroyContext(dpy, NormalContext);
   XDestroyWindow(dpy, OverlayWindow);
   XDestroyWindow(dpy, NormalWindow);

   return 0;
}


text:
from base import (F, Map, FillMissing, Normalize, Log,
                  FittedFeature,
                  AsFactor, AsFactorIndicators)
import base
import combo
import text
import trained


text:
from django.db import models

from ..utils import now

class AccessTokenManager(models.Manager):
    def get_token(self, token):
        return self.get(token=token, expires__gt=now())