<commit_before>package com.pearson.entech.elasticsearch.search.facet.approx.datehistogram;

/*
 * Copyright (C) 2011 Clearspring Technologies, 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.
 */

import java.io.ByteArrayInputStream;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.CacheRecycler;
import org.elasticsearch.common.trove.set.hash.THashSet;

import com.clearspring.analytics.stream.cardinality.AdaptiveCounting;
import com.clearspring.analytics.stream.cardinality.CardinalityMergeException;
import com.clearspring.analytics.stream.cardinality.HyperLogLog;
import com.clearspring.analytics.stream.cardinality.HyperLogLogPlus;
import com.clearspring.analytics.stream.cardinality.ICardinality;
import com.clearspring.analytics.stream.cardinality.LinearCounting;
import com.clearspring.analytics.stream.cardinality.LogLog;
import com.clearspring.analytics.util.ExternalizableUtil;
import com.clearspring.analytics.util.IBuilder;

/**
 * Exact -> Estimator cardinality counting
 * <p/>
 * <p>
 * Avoids allocating a large block of memory for cardinality estimation until
 * a specified "tipping point" cardinality is reached.
 * </p>
 * <p/>
 * Currently supports serialization with LinearCounting or AdaptiveCounting
 */
public class CountThenEstimateBytes implements ICardinality, Externalizable
{
    protected final static byte LC = 1;
    protected final static byte AC = 2;
    protected final static byte HLC = 3;
    protected final static byte LLC = 4;
    protected final static byte HLPC = 5;

    /**
     * Cardinality after which exact counting gives way to estimation
     */
    protected int tippingPoint;

    /**
     * True after switching to estimation
     */
    protected boolean tipped = false;

    /**
     * Factory for instantiating estimator after the tipping point is reached
     */
    protected IBuilder<ICardinality> builder;

    /**
     * Cardinality estimator
     * Null until tipping point is reached
     */
    protected ICardinality estimator;

    /**
     * Cardinality counter
     * Null after tipping point is reached
     */
    protected THashSet<BytesRef> counter;

    /**
     * Default constructor
     * Exact counts up to 1000, estimation done with default Builder
     */
    public CountThenEstimateBytes()
    {
        this(1000, AdaptiveCounting.Builder.obyCount(1000000000));
    }

    /**
     * @param tippingPoint Cardinality at which exact counting gives way to estimation
     * @param builder      Factory for instantiating estimator after the tipping point is reached
     */
    public CountThenEstimateBytes(final int tippingPoint, final IBuilder<ICardinality> builder)
    {
        this.tippingPoint = tippingPoint;
        this.builder = builder;
        this.counter = CacheRecycler.popHashSet();
    }

    /**
     * Deserialization constructor
     *
     * @param bytes
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public CountThenEstimateBytes(final byte[] bytes) throws IOException, ClassNotFoundException
    {
        readExternal(new ObjectInputStream(new ByteArrayInputStream(bytes)));

        if(!tipped && builder.sizeof() <= bytes.length)
        {
            tip();
        }
    }

    @Override
    public long cardinality()
    {
        if(tipped)
        {
            return estimator.cardinality();
        }
        return counter.size();
    }

    @Override
    public boolean offerHashed(final long hashedLong)
    {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean offerHashed(final int hashedInt)
    {
        throw new UnsupportedOperationException();
    }

    public boolean offerBytesRef(final BytesRef unsafe) {
        boolean modified = false;

        if(tipped)
        {
            // The estimator can use the original unsafe BytesRef as it
            // immediately calculates a hash and throws away the contents
            modified = estimator.offer(unsafe);
        }
        else
        {
            // The counter, however, must copy the bytes as they need to
            // stay intact
            if(counter.add(BytesRef.deepCopyOf(unsafe)))
            {
                modified = true;
                if(counter.size() > tippingPoint)<commit_msg>Can't do this optimization just yet...<commit_after>package com.pearson.entech.elasticsearch.search.facet.approx.datehistogram;

/*
 * Copyright (C) 2011 <NAME>, 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.
 */

import java.io.ByteArrayInputStream;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.CacheRecycler;
import org.elasticsearch.common.trove.set.hash.THashSet;

import com.clearspring.analytics.stream.cardinality.AdaptiveCounting;
import com.clearspring.analytics.stream.cardinality.CardinalityMergeException;
import com.clearspring.analytics.stream.cardinality.HyperLogLog;
import com.clearspring.analytics.stream.cardinality.HyperLogLogPlus;
import com.clearspring.analytics.stream.cardinality.ICardinality;
import com.clearspring.analytics.stream.cardinality.LinearCounting;
import com.clearspring.analytics.stream.cardinality.LogLog;
import com.clearspring.analytics.util.ExternalizableUtil;
import com.clearspring.analytics.util.IBuilder;

/**
 * Exact -> Estimator cardinality counting
 * <p/>
 * <p>
 * Avoids allocating a large block of memory for cardinality estimation until
 * a specified "tipping point" cardinality is reached.
 * </p>
 * <p/>
 * Currently supports serialization with LinearCounting or AdaptiveCounting
 */
public class CountThenEstimateBytes implements ICardinality, Externalizable
{
    protected final static byte LC = 1;
    protected final static byte AC = 2;
    protected final static byte HLC = 3;
    protected final static byte LLC = 4;
    protected final static byte HLPC = 5;

    /**
     * Cardinality after which exact counting gives way to estimation
     */
    protected int tippingPoint;

    /**
     * True after switching to estimation
     */
    protected boolean tipped = false;

    /**
     * Factory for instantiating estimator after the tipping point is reached
     */
    protected IBuilder<ICardinality> builder;

    /**
     * Cardinality estimator
     * Null until tipping point is reached
     */
    protected ICardinality estimator;

    /**
     * Cardinality counter
     * Null after tipping point is reached
     */
    protected THashSet<BytesRef> counter;

    /**
     * Default constructor
     * Exact counts up to 1000, estimation done with default Builder
     */
    public CountThenEstimateBytes()
    {
        this(1000, AdaptiveCounting.Builder.obyCount(1000000000));
    }

    /**
     * @param tippingPoint Cardinality at which exact counting gives way to estimation
     * @param builder      Factory for instantiating estimator after the tipping point is reached
     */
    public CountThenEstimateBytes(final int tippingPoint, final IBuilder<ICardinality> builder)
    {
        this.tippingPoint = tippingPoint;
        this.builder = builder;
        this.counter = CacheRecycler.popHashSet();
    }

    /**
     * Deserialization constructor
     *
     * @param bytes
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public CountThenEstimateBytes(final byte[] bytes) throws IOException, ClassNotFoundException
    {
        readExternal(new ObjectInputStream(new ByteArrayInputStream(bytes)));

        if(!tipped && builder.sizeof() <= bytes.length)
        {
            tip();
        }
    }

    @Override
    public long cardinality()
    {
        if(tipped)
        {
            return estimator.cardinality();
        }
        return counter.size();
    }

    @Override
    public boolean offerHashed(final long hashedLong)
    {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean offerHashed(final int hashedInt)
    {
        throw new UnsupportedOperationException();
    }

    public boolean offerBytesRef(final BytesRef unsafe) {
        boolean modified = false;

        if(tipped)
        {
            // TODO fork stream-lib and modify it all to work on BytesRef objects

            // Then the estimator could use the backing array of the original
            // unsafe BytesRef as it immediately calculates a hash and throws
            // away the contents; as it is we have to copy it out
            modified = estimator.offer(copyBytes(unsafe));
        }
        else
        {
            // The counter must copy the bytes as they need to stay intact
            if(counter.add(BytesRef.deepCopyOf(unsafe)))
            {
                modified = true;
                if(counter.size() > tippingPoint)
{'fraction_non_alphanumeric': 0.07939619682415212, 'fraction_numerical': 0.00607723975691041, 'mean_word_length': 2.9393822393822395, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5017993', 'n_tokens_mistral': 2802, 'n_tokens_neox': 2683, 'n_words': 834}