text:
import numpy as np
import itertools

from neurowriter.symbols import NULL, START, END

class Writer():
    def __init__(self, model, encoder, creativity=0, beamsize=5, batchsize=3):
        """Creates a writer using a pretrained model

        Arguments:
            model: keras model to use for generation
            encoder: character encoder used
            creativity: creativity rate (probability temperature
            beamsize: size of beam search
            batchsize: number of tokens generated at the same time in beam search
        """
        self.model = model
        self.encoder = encoder
        self.creativity = creativity
        self.beamsize = beamsize
        self.batchsize = batchsize

    def write(self, seed="", length=1000):
        """Start writing characters

        Arguments:
            seed: text to initialize generation
            length: length of the generated text

        Return the generated text.
        """
        # Iterate generation
        return itertools.islice(self.generate(seed), length)

    def generate(self, seed=""):
        """Infinite generator of text following the Writer style.

        Arguments:
            seed: text to initialize generation

        Returns one piece of text at a time.
        """
        # Prepare seed
        seedtokens = self.encoder.tokenizer.transform(seed)
        inputtokens = self.model.layers[0].input_shape[1]
        if len(seedtokens) < inputtokens:
            seedtokens = [NULL] * (inputtokens-len(seed)-1) + [START] + seedtokens
        seedcoded = self.encoder.encodetokens(seedtokens[-inputtokens:])

        # Iterate generation
        while True:
            # Predict token probabilities using model and beam search
            newcodes = self.beamsearch(seedcoded)
            # Drop old tokens, add new ones
            # Also drop tokens if longer than necessary
            seedcoded = np.append(seedcoded[len(newcodes):], newcodes)[:inputtokens]
            # Yield generated tokens (in text form)
            for code in newcodes:
                newtoken = self.encoder.index2char[code]
                yield newtoken
                # If yielded end token, restart seed
                if newtoken == END:
                    restart = [NULL] * (inputtokens-1) + [START]
                    seedcoded = self.encoder.encodetokens(restart)
                    break

    def beamsearch(self, seedcoded):
        """Generates token predictions using a beam search algorithm

        Inputs:
            seedcoded: numpy array with indexes of seed tokens

        Returns the best sequence of tokens found.
        """
        # Store original length of seed
        maxlen = len(seedcoded)
        # Predict first token probabilities
        probs = self.model.predict(np.array([seedcoded]), verbose=0)[0]
        # Initiate candidates for beam search
        newcandidates = [(np.log(p), [i]) for i, p in enumerate(probs)]
        # Select candidates for beam search
        candidates = self.drawcandidates(newcandidates, self.beamsize)
        # Beam depth extension steps
        for _ in range(1, self.batchsize):
            # Extend each candidate
            newcandidates = []
            for logprob, tokens in candidates:
                # Update seed with candidate tokens
                # Also drop tokens if longer than necessary
                candseed = np.append(seedcoded[len(tokens):], tokens)[:maxlen]
                # Predictions for next token
                probs = self.model.predict(np.array([candseed]), verbose=0)[0]
                # Add to pool of next round tokens
                newcandidates.extend([
                    (logprob + np.log(p), tokens + [idx])
                    for idx, p in enumerate(probs)
                ])
            # Select candidates for next step
            candidates = self.drawcandidates(newcandidates, self.beamsize)
        # Return tokens of best candidate found
        return max(candidates, key=lambda x: x[0])[1]

    def drawcandidates(self, candidates, n):
        """Draws n candidates from a candidates list

        If no creativity has been configured, just draw the best candidates.
        If creativy has been configured, draw with random sampling according
        to the probability of each candidate.
        """
        # No creativity: take the top with highest probability
        if self.creativity == 0:
            return topk(candidates, self.beamsize, key=lambda x: x[0])
        # Creativity: random sampling
        else:
            probs = np.array([prob for prob, tokens in candidates])
            return [candidates[sample(probs, self.creativity)] for _ in range(n)]

def normalize(probs):
    """Normalizes a list of probabilities, so that they sum up to 1"""
    prob_factor = 1 / sum(probs)
    return [prob_factor * p for p in probs]

def sample(logprobs, temperature=1.0):
    """Modifies probabilities with a given temperature, to add creativity"""
    probs = np.exp(logprobs / temperature)
    normprobs = normalize(probs)
    return np.argmax(np.random.multinomial(1, normprobs, 1))

def topk(l, k, key=lambda x: x):
    """Returns a sublist with the top k elements from a givenlist. Accepts key"""
    idx, _ = zip(*sorted(enumerate(l), key = lambda x: key(x[1]),
                         reverse=True))
    return [l[i] for i in idx[0:k]]


text:
package org.vaadin.addons.d3Gauge;

/**
 * Created by kaismh on 10/9/14.
 */
public enum GaugeStyle {

    STYLE_DEFAULT("default"), STYLE_LIGHT("light"),
    STYLE_DARK("dark"), STYLE_VALO("valo");

    private final String name;

    GaugeStyle(final String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.pentaho.hadoop.shim.pvfs.conf;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.pentaho.di.connections.ConnectionDetails;
import org.pentaho.di.core.variables.VariableSpace;

import java.util.Map;
import java.util.Objects;

/**
 * Base class for filesystem configuration classes.  Implementations
 * will handle population of hadoop Configuration objects based on
 * named vfs ConnectionDetails, as well as mapping paths to/from
 * pvfs:// schemes.
 */
public abstract class PvfsConf {

  protected final ConnectionDetails details;

  PvfsConf( ConnectionDetails details ) {
    this.details = details;
  }

  /**
   * Tests whether this PvfsConf can be used for the connection
   * details provided.  HCP connection details, for example, cannot
   * be used with S3Conf.
   */
  public abstract boolean supportsConnection();

  /**
   * Maps a given path with scheme 'pvfs:' to the appropriate
   * "real" filesystem path by looking up the connection details from
   * the named vfs connection.
   */
  public abstract Path mapPath( Path pvfsPath );

  /**
   * Maps a "real" filesystem path to the pvfs:// form.
   * For example, given pvfsPath 'pvfs://s3Conn/path' and
   * realFsPath 's3://bucket/somedir/somefile.txt', this
   * method will determine the correct pvfs path for 'somefile.txt':
   *   'pvfs://s3Conn/bucket/somedir/somefile.txt'
   *
   * Different PvfsConf implementations will have different rules
   * for mapping a realFsPath back to a pvfsPath.
   */
  public abstract Path mapPath( Path pvfsPath, Path realFsPath );

  public abstract Configuration conf( Path pvfsPath );

  void validatePath( Path pvfsPath ) {
    if ( !supportsConnection() || !pvfsPath.toUri().getScheme().equals( "pvfs" ) ) {
      throw new IllegalStateException( pvfsPath.toString() + " not supported by " + details.getClass().getName() );
    }
  }

  @FunctionalInterface
  public interface ConfFactory {
    PvfsConf get( ConnectionDetails details );
  }

  @Override public boolean equals( Object o ) {
    if ( this == o ) {
      return true;
    }
    if ( o == null || getClass() != o.getClass() ) {
      return false;
    }

    PvfsConf pvfsConf = (PvfsConf) o;
    if ( details == null && pvfsConf.details == null ) {
      return true;
    }
    if ( details == null || pvfsConf.details == null ) {
      // one but not the other is null
      return false;
    }
    return Objects.equals( details.getProperties(), pvfsConf.details.getProperties() );
  }

  @Override public int hashCode() {
    if ( details == null ) {
      return Objects.hash( this );
    }
    return Objects.hash( details.getProperties() );
  }

  @SuppressWarnings( "squid:S1172" )
  public String generateAlias( String pvfsPath ) {
    return null;
  }

  protected String getVar( String value ) {
    if ( details.getSpace() != null ) {
      return details.getSpace().environmentSubstitute( value );
    }
    return value;
  }

  protected String getVar( Map<String, String> properties, String fieldName ) {
    return getVar( properties.get( fieldName ) );
  }
}


text:
<?php namespace Devise\Languages;

use Mockery as m;

class LanguageDetectorTest extends \DeviseTestCase
{
	public function setUp()
	{
		parent::setUp();
		$this->Framework = new \Devise\Support\Framework;
		$this->LanguageDetector = new LanguageDetector(new LocaleDetector($this->Framework), new \DvsLanguage);
	}

	public function test_it_can_detect_current_language()
	{
		$language = $this->LanguageDetector->current();
		assertEquals('en', $language->code);
	}

	public function test_it_can_detect_universal_language()
	{
		$language = $this->LanguageDetector->universal();
		assertEquals('en', $language->code);
	}

	public function test_it_can_update_language()
	{
		$LocaleDetector = m::mock('Devise\Languages\LocaleDetector');
        $LocaleDetector->shouldReceive('update')->times(1);

		$LanguageDetector = new LanguageDetector($LocaleDetector, new \DvsLanguage);
		$LanguageDetector->update(new \DvsLanguage);
	}

    public function test_it_can_give_me_primary_language_id()
    {
        $Config = m::mock('Illuminate\Config\Repository');
        $Config->shouldReceive('get')->times(1)->andReturn(45);
        $LanguageDetector = new LanguageDetector(new LocaleDetector($this->Framework), new \DvsLanguage, $Config);
        assertEquals(45, $LanguageDetector->primaryLanguageId());
    }
}


text:
import * as ts from 'typescript';
import MagicString from 'magic-string';
import {makeProgram} from '../helpers/utils';
import {Analyzer} from '../../src/analyzer';
import {Esm2015ReflectionHost} from '../../src/host/esm2015_host';
import {Esm2015FileParser} from '../../src/parsing/esm2015_parser';
import {Esm2015Renderer} from '../../src/rendering/esm2015_renderer';

function setup(file: {name: string, contents: string}) {
  const program = makeProgram(file);
  const host = new Esm2015ReflectionHost(program.getTypeChecker());
  const parser = new Esm2015FileParser(program, host);
  const analyzer = new Analyzer(program.getTypeChecker(), host);
  const renderer = new Esm2015Renderer(host);
  return {analyzer, host, parser, program, renderer};
}

function analyze(parser: Esm2015FileParser, analyzer: Analyzer, file: ts.SourceFile) {
  const parsedFiles = parser.parseFile(file);
  return parsedFiles.map(file => analyzer.analyzeFile(file))[0];
}

describe('Esm2015Renderer', () => {

  describe('addImports', () => {
    it('should insert the given imports at the start of the source file', () => {
      const PROGRAM = {
        name: 'some/file.js',
        contents: `
/* A copyright notice */
import {Directive} from '@angular/core';
export class A {}
A.decorators = [
  { type: Directive, args: [{ selector: '[a]' }] },
  { type: Other }
];
// Some other content`
      };
      const {renderer} = setup(PROGRAM);
      const output = new MagicString(PROGRAM.contents);
      renderer.addImports(
          output, [{name: '@angular/core', as: 'i0'}, {name: '@angular/common', as: 'i1'}]);
      expect(output.toString())
          .toEqual(
              `import * as i0 from '@angular/core';\n` +
              `import * as i1 from '@angular/common';\n` + PROGRAM.contents);
    });
  });

  describe('addDefinitions', () => {
    it('should insert the definitions directly after the class declaration', () => {
      const PROGRAM = {
        name: 'some/file.js',
        contents: `
/* A copyright notice */
import {Directive} from '@angular/core';
export class A {}
A.decorators = [
  { type: Directive, args: [{ selector: '[a]' }] },
  { type: Other }
];
// Some other content`
      };
      const {analyzer, parser, program, renderer} = setup(PROGRAM);
      const analyzedFile = analyze(parser, analyzer, program.getSourceFile(PROGRAM.name) !);
      const output = new MagicString(PROGRAM.contents);
      renderer.addDefinitions(output, analyzedFile.analyzedClasses[0], 'SOME DEFINITION TEXT');
      expect(output.toString()).toEqual(`
/* A copyright notice */
import {Directive} from '@angular/core';
export class A {}
SOME DEFINITION TEXT
A.decorators = [
  { type: Directive, args: [{ selector: '[a]' }] },
  { type: Other }
];
// Some other content`);
    });

  });

  describe('removeDecorators', () => {

    it('should delete the decorator (and following comma) that was matched in the analysis', () => {
      const PROGRAM = {
        name: 'some/file.js',
        contents: `
/* A copyright notice */
import {Directive} from '@angular/core';
export class A {}
A.decorators = [
  { type: Directive, args: [{ selector: '[a]' }] },
  { type: Other }
];
// Some other content`
      };
      const {analyzer, parser, program, renderer} = setup(PROGRAM);
      const analyzedFile = analyze(parser, analyzer, program.getSourceFile(PROGRAM.name) !);
      const output = new MagicString(PROGRAM.contents);
      const analyzedClass = analyzedFile.analyzedClasses[0];
      const decoratorsToRemove = new Map<ts.Node, ts.Node[]>();
      decoratorsToRemove.set(
          analyzedClass.decorators[0].node.parent !, [analyzedClass.decorators[0].node]);
      renderer.removeDecorators(output, decoratorsToRemove);
      expect(output.toString()).toEqual(`
/* A copyright notice */
import {Directive} from '@angular/core';
export class A {}
A.decorators = [
  { type: Other }
];
// Some other content`);
    });

    it('should delete the decorator (but cope with no trailing comma) that was matched in the analysis',
       () => {
         const PROGRAM = {
           name: 'some/file.js',
           contents: `
/* A copyright notice */
import {Directive} from '@angular/core';
export class A {}
A.decorators = [
  { type: Other },
  { type: Directive, args: [{ selector: '[a]' }] }
];
// Some other content`
         };
         const {analyzer, parser, program, renderer} = setup(PROGRAM);
         const analyzedFile = analyze(parser, analyzer, program.getSourceFile(PROGRAM.name) !);
         const output = new MagicString(PROGRAM.contents);
         const analyzedClass = analyzedFile.analyzedClasses[0];
         const decoratorsToRemove = new Map<ts.Node, ts.Node[]>();
         decoratorsToRemove.set(
             analyzedClass.decorators[0].node.parent !, [analyzedClass.decorators[1].node]);
         renderer.removeDecorators(output, decoratorsToRemove);
         expect(output.toString()).toEqual(`
/* A copyright notice */
import {Directive} from '@angular/core';
export class A {}
A.decorators = [
  { type: Other },
];
// Some other content`);
       });

    it('should delete the decorator (and its container if there are not other decorators left) that was matched in the analysis',
       () => {
         const PROGRAM = {
           name: 'some/file.js',
           contents: `
/* A copyright notice */
import {Directive} from '@angular/core';
export class A {}
A.decorators = [
  { type: Directive, args: [{ selector: '[a]' }] }
];
// Some other content`
         };
         const {analyzer, parser, program, renderer} = setup(PROGRAM);
         const analyzedFile = analyze(parser, analyzer, program.getSourceFile(PROGRAM.name) !);
         const output = new MagicString(PROGRAM.contents);
         const analyzedClass = analyzedFile.analyzedClasses[0];
         const decoratorsToRemove = new Map<ts.Node, ts.Node[]>();
         decoratorsToRemove.set(
             analyzedClass.decorators[0].node.parent !, [analyzedClass.decorators[0].node]);
         renderer.removeDecorators(output, decoratorsToRemove);
         expect(output.toString()).toEqual(`
/* A copyright notice */
import {Directive} from '@angular/core';
export class A {}
// Some other content`);
       });

  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestDataReader
{
    class OperationLog
    {
        public int ID;
        public DateTime LogTime;
        public int CustomerID;
        public string MobileNo;
    }
}


text:
describe Tracee::Preprocessors::Formatter do
  [:tracee, :logger_formatter, :plain, :empty].each do |template|
    let(template) {Tracee::Preprocessors::Formatter.new template}
  end

  let(:now) {DateTime.parse '2015.01.01 00:00:00'}

  describe 'when a template contains %{message} key' do

    it 'renders a string message without quotes' do
      expect(tracee.('info', now, nil, 'hello')).to match(/(^|[^"])hello([^"]|$)/)
    end

    it 'renders a non-string message inspected' do
      expect(tracee.('info', now, nil, ['hello'])).to match(/\["hello"\]/)
    end

      end

  describe 'as tracee' do

    it 'renders a tracee template containing time, log level, caller and message' do
      expect(tracee.('info', now, 'world', 'hello', caller(0)[0..1])).to match(/00:00:00.000 \S+INFO\S+ \[\S+:\S+ .+ -> \S+#{File.basename __FILE__}:#{__LINE__}\S+ .+\]: hello/)
    end

  end

  describe 'as logger_formatter' do

    it 'renders a logger_formatter template containing time, log level, pid, progname and message' do
      expect(logger_formatter.('info', now, 'world', 'hello')).to \
        match(/I, \[2015-01-01T00:00:00.000000 ##{Process.pid}\] INFO -- world: hello/)
    end

  end

  describe 'as empty' do

    it 'renders only newline' do
      expect(empty.('info', now, 'world', 'hello')).to eq "\n"
    end

  end

end


text:
var fs = require('fs'),
    path = require('path');

var loader = {
  load: function (context) {
    //debug('Starting external modules...');
    fs.readdirSync(__dirname).forEach(function(file) {
      var p = path.join(__dirname, file);
      var stats = fs.statSync(p);
      if (stats.isDirectory()) {
        //debug('Loading module ' + file);
        require(p)(context);
      }
    });
  }
};

module.exports = loader;


text:
//-----------------------------------------------------------------------
// <copyright file="ObjectiveAttribute.cs" company="Benjamin Woodall">
//     Copyright Benjamin Woodall 2014. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;

namespace Game
{
    /// Attribute for Objectives
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    public class ObjectiveAttribute : Attribute
    {
        /// Prevents initialization of default instances of the ObjectiveAttribute class
        private ObjectiveAttribute() { }

        /// Initializes a new instance of the <see cref="Game.ObjectiveAttribute"/> class.
        /// <param name="name">Objective id</param>
        public ObjectiveAttribute(string id)
        {
            this.Id = id;
        }

        /// Gets the identifier
        public string Id { get; private set; }
    }
}


text:
package podautoscaler

import (
	"fmt"
	"math"
	"testing"
	"time"

	autoscalingv2 "k8s.io/api/autoscaling/v2beta2"
	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/meta/testrestmapper"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/client-go/kubernetes/fake"
	core "k8s.io/client-go/testing"
	"k8s.io/kubernetes/pkg/api/legacyscheme"
	metricsclient "k8s.io/kubernetes/pkg/controller/podautoscaler/metrics"
	cmapi "k8s.io/metrics/pkg/apis/custom_metrics/v1beta2"
	emapi "k8s.io/metrics/pkg/apis/external_metrics/v1beta1"
	metricsapi "k8s.io/metrics/pkg/apis/metrics/v1beta1"
	metricsfake "k8s.io/metrics/pkg/client/clientset/versioned/fake"
	cmfake "k8s.io/metrics/pkg/client/custom_metrics/fake"
	emfake "k8s.io/metrics/pkg/client/external_metrics/fake"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

type resourceInfo struct {
	name     v1.ResourceName
	requests []resource.Quantity
	levels   []int64
	// only applies to pod names returned from "heapster"
	podNames []string

	targetUtilization   int32
	expectedUtilization int32
	expectedValue       int64
}

type metricType int

const (
	objectMetric metricType = iota
	externalMetric
	externalPerPodMetric
	podMetric
)

type metricInfo struct {
	name         string
	levels       []int64
	singleObject *autoscalingv2.CrossVersionObjectReference
	selector     *metav1.LabelSelector
	metricType   metricType

	targetUtilization       int64
	perPodTargetUtilization int64
	expectedUtilization     int64
}

type replicaCalcTestCase struct {
	currentReplicas  int32
	expectedReplicas int32
	expectedError    error

	timestamp time.Time

	resource            *resourceInfo
	metric              *metricInfo
	metricLabelSelector labels.Selector

	podReadiness         []v1.ConditionStatus
	podStartTime         []metav1.Time
	podPhase             []v1.PodPhase
	podDeletionTimestamp []bool
}

const (
	testNamespace       = "test-namespace"
	podNamePrefix       = "test-pod"
	numContainersPerPod = 2
)

func (tc *replicaCalcTestCase) prepareTestClientSet() *fake.Clientset {
	fakeClient := &fake.Clientset{}
	fakeClient.AddReactor("list", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) {
		obj := &v1.PodList{}
		podsCount := int(tc.currentReplicas)
		// Failed pods are not included in tc.currentReplicas
		if tc.podPhase != nil && len(tc.podPhase) > podsCount {
			podsCount = len(tc.podPhase)
		}
		for i := 0; i < podsCount; i++ {
			podReadiness := v1.ConditionTrue
			if tc.podReadiness != nil && i < len(tc.podReadiness) {
				podReadiness = tc.podReadiness[i]
			}
			var podStartTime metav1.Time
			if tc.podStartTime != nil {
				podStartTime = tc.podStartTime[i]
			}
			podPhase := v1.PodRunning
			if tc.podPhase != nil {
				podPhase = tc.podPhase[i]
			}
			podDeletionTimestamp := false
			if tc.podDeletionTimestamp != nil {
				podDeletionTimestamp = tc.podDeletionTimestamp[i]
			}
			podName := fmt.Sprintf("%s-%d", podNamePrefix, i)
			pod := v1.Pod{
				Status: v1.PodStatus{
					Phase:     podPhase,
					StartTime: &podStartTime,
					Conditions: []v1.PodCondition{
						{
							Type:   v1.PodReady,
							Status: podReadiness,
						},
					},
				},
				ObjectMeta: metav1.ObjectMeta{
					Name:      podName,
					Namespace: testNamespace,
					Labels: map[string]string{
						"name": podNamePrefix,
					},
				},
				Spec: v1.PodSpec{
					Containers: []v1.Container{{}, {}},
				},
			}
			if podDeletionTimestamp {
				pod.DeletionTimestamp = &metav1.Time{Time: time.Now()}
			}

			if tc.resource != nil && i < len(tc.resource.requests) {
				pod.Spec.Containers[0].Resources = v1.ResourceRequirements{
					Requests: v1.ResourceList{
						tc.resource.name: tc.resource.requests[i],
					},
				}
				pod.Spec.Containers[1].Resources = v1.ResourceRequirements{
					Requests: v1.ResourceList{
						tc.resource.name: tc.resource.requests[i],
					},
				}
			}
			obj.Items = append(obj.Items, pod)
		}
		return true, obj, nil
	})
	return fakeClient
}

func (tc *replicaCalcTestCase) prepareTestMetricsClient() *metricsfake.Clientset {
	fakeMetricsClient := &metricsfake.Clientset{}
	// NB: we have to sound like Gollum due to gengo's inability to handle already-plural resource names
	fakeMetricsClient.AddReactor("list", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) {
		if tc.resource != nil {
			metrics := &metricsapi.PodMetricsList{}
			for i, resValue := range tc.resource.levels {
				podName := fmt.Sprintf("%s-%d", podNamePrefix, i)
				if len(tc.resource.podNames) > i {
					podName = tc.resource.podNames[i]
				}
				// NB: the list reactor actually does label selector filtering for us,
				// so we have to make sure our results match the label selector
				podMetric := metricsapi.PodMetrics{
					ObjectMeta: metav1.ObjectMeta{
						Name:      podName,
						Namespace: testNamespace,
						Labels:    map[string]string{"name": podNamePrefix},
					},
					Timestamp:  metav1.Time{Time: tc.timestamp},
					Window:     metav1.Duration{Duration: time.Minute},
					Containers: make([]metricsapi.ContainerMetrics, numContainersPerPod),
				}

				for i := 0; i < numContainersPerPod; i++ {
					podMetric.Containers[i] = metricsapi.ContainerMetrics{
						Name: fmt.Sprintf("container%v", i),
						Usage: v1.ResourceList{
							v1.ResourceName(tc.resource.name): *resource.NewMilliQuantity(
								int64(resValue),
								resource.DecimalSI),
						},
					}
				}
				metrics.Items = append(metrics.Items, podMetric)
			}
			return true, metrics, nil
		}

		return true, nil, fmt.Errorf("no pod resource metrics specified in test client")
	})
	return fakeMetricsClient
}

func (tc *replicaCalcTestCase) prepareTestCMClient(t *testing.T) *cmfake.FakeCustomMetricsClient {
	fakeCMClient := &cmfake.FakeCustomMetricsClient{}
	fakeCMClient.AddReactor("get", "*", func(action core.Action) (handled bool, ret runtime.Object, err error) {
		getForAction, wasGetFor := action.(cmfake.GetForAction)
		if !wasGetFor {
			return true, nil, fmt.Errorf("expected a get-for action, got %v instead", action)
		}

		if tc.metric == nil {
			return true, nil, fmt.Errorf("no custom metrics specified in test client")
		}

		assert.Equal(t, tc.metric.name, getForAction.GetMetricName(), "the metric requested should have matched the one specified")

		if getForAction.GetName() == "*" {
			metrics := cmapi.MetricValueList{}

			// multiple objects
			assert.Equal(t, "pods", getForAction.GetResource().Resource, "the type of object that we requested multiple metrics for should have been pods")

			for i, level := range tc.metric.levels {
				podMetric := cmapi.MetricValue{
					DescribedObject: v1.ObjectReference{
						Kind:      "Pod",
						Name:      fmt.Sprintf("%s-%d", podNamePrefix, i),
						Namespace: testNamespace,
					},
					Timestamp: metav1.Time{Time: tc.timestamp},
					Metric: cmapi.MetricIdentifier{
						Name: tc.metric.name,
					},
					Value: *resource.NewMilliQuantity(level, resource.DecimalSI),
				}
				metrics.Items = append(metrics.Items, podMetric)
			}

			return true, &metrics, nil
		}
		name := getForAction.GetName()
		mapper := testrestmapper.TestOnlyStaticRESTMapper(legacyscheme.Scheme)
		metrics := &cmapi.MetricValueList{}
		assert.NotNil(t, tc.metric.singleObject, "should have only requested a single-object metric when calling GetObjectMetricReplicas")
		gk := schema.FromAPIVersionAndKind(tc.metric.singleObject.APIVersion, tc.metric.singleObject.Kind).GroupKind()
		mapping, err := mapper.RESTMapping(gk)
		if err != nil {
			return true, nil, fmt.Errorf("unable to get mapping for %s: %v", gk.String(), err)
		}
		groupResource := mapping.Resource.GroupResource()

		assert.Equal(t, groupResource.String(), getForAction.GetResource().Resource, "should have requested metrics for the resource matching the GroupKind passed in")
		assert.Equal(t, tc.metric.singleObject.Name, name, "should have requested metrics for the object matching the name passed in")

		metrics.Items = []cmapi.MetricValue{
			{
				DescribedObject: v1.ObjectReference{
					Kind:       tc.metric.singleObject.Kind,
					APIVersion: tc.metric.singleObject.APIVersion,
					Name:       name,
				},
				Timestamp: metav1.Time{Time: tc.timestamp},
				Metric: cmapi.MetricIdentifier{
					Name: tc.metric.name,
				},
				Value: *resource.NewMilliQuantity(int64(tc.metric.levels[0]), resource.DecimalSI),
			},
		}

		return true, metrics, nil
	})
	return fakeCMClient
}

func (tc *replicaCalcTestCase) prepareTestEMClient(t *testing.T) *emfake.FakeExternalMetricsClient {
	fakeEMClient := &emfake.FakeExternalMetricsClient{}
	fakeEMClient.AddReactor("list", "*", func(action core.Action) (handled bool, ret runtime.Object, err error) {
		listAction, wasList := action.(core.ListAction)
		if !wasList {
			return true, nil, fmt.Errorf("expected a list-for action, got %v instead", action)
		}

		if tc.metric == nil {
			return true, nil, fmt.Errorf("no external metrics specified in test client")
		}

		assert.Equal(t, tc.metric.name, listAction.GetResource().Resource, "the metric requested should have matched the one specified")

		selector, err := metav1.LabelSelectorAsSelector(tc.metric.selector)
		if err != nil {
			return true, nil, fmt.Errorf("failed to convert label selector specified in test client")
		}
		assert.Equal(t, selector, listAction.GetListRestrictions().Labels, "the metric selector should have matched the one specified")

		metrics := emapi.ExternalMetricValueList{}

		for _, level := range tc.metric.levels {
			metric := emapi.ExternalMetricValue{
				Timestamp:  metav1.Time{Time: tc.timestamp},
				MetricName: tc.metric.name,
				Value:      *resource.NewMilliQuantity(level, resource.DecimalSI),
			}
			metrics.Items = append(metrics.Items, metric)
		}

		return true, &metrics, nil
	})
	return fakeEMClient
}

func (tc *replicaCalcTestCase) prepareTestClient(t *testing.T) (*fake.Clientset, *metricsfake.Clientset, *cmfake.FakeCustomMetricsClient, *emfake.FakeExternalMetricsClient) {
	fakeClient := tc.prepareTestClientSet()
	fakeMetricsClient := tc.prepareTestMetricsClient()
	fakeCMClient := tc.prepareTestCMClient(t)
	fakeEMClient := tc.prepareTestEMClient(t)
	return fakeClient, fakeMetricsClient, fakeCMClient, fakeEMClient
}

func (tc *replicaCalcTestCase) runTest(t *testing.T) {
	testClient, testMetricsClient, testCMClient, testEMClient := tc.prepareTestClient(t)
	metricsClient := metricsclient.NewRESTMetricsClient(testMetricsClient.MetricsV1beta1(), testCMClient, testEMClient)

	replicaCalc := NewReplicaCalculator(metricsClient, testClient.Core(), defaultTestingTolerance, defaultTestingCpuInitializationPeriod, defaultTestingDelayOfInitialReadinessStatus)

	selector, err := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{
		MatchLabels: map[string]string{"name": podNamePrefix},
	})
	if err != nil {
		require.Nil(t, err, "something went horribly wrong...")
	}

	if tc.resource != nil {
		outReplicas, outUtilization, outRawValue, outTimestamp, err := replicaCalc.GetResourceReplicas(tc.currentReplicas, tc.resource.targetUtilization, tc.resource.name, testNamespace, selector)

		if tc.expectedError != nil {
			require.Error(t, err, "there should be an error calculating the replica count")
			assert.Contains(t, err.Error(), tc.expectedError.Error(), "the error message should have contained the expected error message")
			return
		}
		require.NoError(t, err, "there should not have been an error calculating the replica count")
		assert.Equal(t, tc.expectedReplicas, outReplicas, "replicas should be as expected")
		assert.Equal(t, tc.resource.expectedUtilization, outUtilization, "utilization should be as expected")
		assert.Equal(t, tc.resource.expectedValue, outRawValue, "raw value should be as expected")
		assert.True(t, tc.timestamp.Equal(outTimestamp), "timestamp should be as expected")
		return
	}

	var outReplicas int32
	var outUtilization int64
	var outTimestamp time.Time
	switch tc.metric.metricType {
	case objectMetric:
		if tc.metric.singleObject == nil {
			t.Fatal("Metric specified as objectMetric but metric.singleObject is nil.")
		}
		outReplicas, outUtilization, outTimestamp, err = replicaCalc.GetObjectMetricReplicas(tc.currentReplicas, tc.metric.targetUtilization, tc.metric.name, testNamespace, tc.metric.singleObject, selector, nil)
	case externalMetric:
		if tc.metric.selector == nil {
			t.Fatal("Metric specified as externalMetric but metric.selector is nil.")
		}
		if tc.metric.targetUtilization <= 0 {
			t.Fatalf("Metric specified as externalMetric but metric.targetUtilization is %d which is <=0.", tc.metric.targetUtilization)
		}
		outReplicas, outUtilization, outTimestamp, err = replicaCalc.GetExternalMetricReplicas(tc.currentReplicas, tc.metric.targetUtilization, tc.metric.name, testNamespace, tc.metric.selector, selector)
	case externalPerPodMetric:
		if tc.metric.selector == nil {
			t.Fatal("Metric specified as externalPerPodMetric but metric.selector is nil.")
		}
		if tc.metric.perPodTargetUtilization <= 0 {
			t.Fatalf("Metric specified as externalPerPodMetric but metric.perPodTargetUtilization is %d which is <=0.", tc.metric.perPodTargetUtilization)
		}

		outReplicas, outUtilization, outTimestamp, err = replicaCalc.GetExternalPerPodMetricReplicas(tc.currentReplicas, tc.metric.perPodTargetUtilization, tc.metric.name, testNamespace, tc.metric.selector)
	case podMetric:
		outReplicas, outUtilization, outTimestamp, err = replicaCalc.GetMetricReplicas(tc.currentReplicas, tc.metric.targetUtilization, tc.metric.name, testNamespace, selector, nil)
	default:
		t.Fatalf("Unknown metric type: %d", tc.metric.metricType)
	}

	if tc.expectedError != nil {
		require.Error(t, err, "there should be an error calculating the replica count")
		assert.Contains(t, err.Error(), tc.expectedError.Error(), "the error message should have contained the expected error message")
		return
	}
	require.NoError(t, err, "there should not have been an error calculating the replica count")
	assert.Equal(t, tc.expectedReplicas, outReplicas, "replicas should be as expected")
	assert.Equal(t, tc.metric.expectedUtilization, outUtilization, "utilization should be as expected")
	assert.True(t, tc.timestamp.Equal(outTimestamp), "timestamp should be as expected")
}

func TestReplicaCalcDisjointResourcesMetrics(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas: 1,
		expectedError:   fmt.Errorf("no metrics returned matched known pods"),
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0")},
			levels:   []int64{100},
			podNames: []string{"an-older-pod-name"},

			targetUtilization: 100,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUp(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 5,
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{300, 500, 700},

			targetUtilization:   30,
			expectedUtilization: 50,
			expectedValue:       numContainersPerPod * 500,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpUnreadyLessScale(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 4,
		podReadiness:     []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{300, 500, 700},

			targetUtilization:   30,
			expectedUtilization: 60,
			expectedValue:       numContainersPerPod * 600,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpHotCpuLessScale(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 4,
		podStartTime:     []metav1.Time{hotCpuCreationTime(), coolCpuCreationTime(), coolCpuCreationTime()},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{300, 500, 700},

			targetUtilization:   30,
			expectedUtilization: 60,
			expectedValue:       numContainersPerPod * 600,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpUnreadyNoScale(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 3,
		podReadiness:     []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{400, 500, 700},

			targetUtilization:   30,
			expectedUtilization: 40,
			expectedValue:       numContainersPerPod * 400,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleHotCpuNoScale(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 3,
		podReadiness:     []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse},
		podStartTime:     []metav1.Time{coolCpuCreationTime(), hotCpuCreationTime(), hotCpuCreationTime()},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{400, 500, 700},

			targetUtilization:   30,
			expectedUtilization: 40,
			expectedValue:       numContainersPerPod * 400,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpIgnoresFailedPods(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  2,
		expectedReplicas: 4,
		podReadiness:     []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse},
		podPhase:         []v1.PodPhase{v1.PodRunning, v1.PodRunning, v1.PodFailed, v1.PodFailed},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{500, 700},

			targetUtilization:   30,
			expectedUtilization: 60,
			expectedValue:       numContainersPerPod * 600,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpIgnoresDeletionPods(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:      2,
		expectedReplicas:     4,
		podReadiness:         []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse},
		podPhase:             []v1.PodPhase{v1.PodRunning, v1.PodRunning, v1.PodRunning, v1.PodRunning},
		podDeletionTimestamp: []bool{false, false, true, true},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{500, 700},

			targetUtilization:   30,
			expectedUtilization: 60,
			expectedValue:       numContainersPerPod * 600,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpCM(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 4,
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{20000, 10000, 30000},
			targetUtilization:   15000,
			expectedUtilization: 20000,
			metricType:          podMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpCMUnreadyHotCpuNoLessScale(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 6,
		podReadiness:     []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse},
		podStartTime:     []metav1.Time{coolCpuCreationTime(), coolCpuCreationTime(), hotCpuCreationTime()},
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{50000, 10000, 30000},
			targetUtilization:   15000,
			expectedUtilization: 30000,
			metricType:          podMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpCMUnreadyHotCpuScaleWouldScaleDown(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 7,
		podReadiness:     []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionFalse},
		podStartTime:     []metav1.Time{hotCpuCreationTime(), coolCpuCreationTime(), hotCpuCreationTime()},
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{50000, 15000, 30000},
			targetUtilization:   15000,
			expectedUtilization: 31666,
			metricType:          podMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpCMObject(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 4,
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{20000},
			targetUtilization:   15000,
			expectedUtilization: 20000,
			singleObject: &autoscalingv2.CrossVersionObjectReference{
				Kind:       "Deployment",
				APIVersion: "extensions/v1beta1",
				Name:       "some-deployment",
			},
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpCMObjectIgnoresUnreadyPods(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 5, // If we did not ignore unready pods, we'd expect 15 replicas.
		podReadiness:     []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionFalse},
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{50000},
			targetUtilization:   10000,
			expectedUtilization: 50000,
			singleObject: &autoscalingv2.CrossVersionObjectReference{
				Kind:       "Deployment",
				APIVersion: "extensions/v1beta1",
				Name:       "some-deployment",
			},
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpCMExternal(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  1,
		expectedReplicas: 2,
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{8600},
			targetUtilization:   4400,
			expectedUtilization: 8600,
			selector:            &metav1.LabelSelector{MatchLabels: map[string]string{"label": "value"}},
			metricType:          podMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpCMExternalIgnoresUnreadyPods(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 2, // Would expect 6 if we didn't ignore unready pods
		podReadiness:     []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionFalse},
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{8600},
			targetUtilization:   4400,
			expectedUtilization: 8600,
			selector:            &metav1.LabelSelector{MatchLabels: map[string]string{"label": "value"}},
			metricType:          externalMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpCMExternalNoLabels(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  1,
		expectedReplicas: 2,
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{8600},
			targetUtilization:   4400,
			expectedUtilization: 8600,
			metricType:          podMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleUpPerPodCMExternal(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 4,
		metric: &metricInfo{
			name:                    "qps",
			levels:                  []int64{8600},
			perPodTargetUtilization: 2150,
			expectedUtilization:     2867,
			selector:                &metav1.LabelSelector{MatchLabels: map[string]string{"label": "value"}},
			metricType:              externalPerPodMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleDown(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  5,
		expectedReplicas: 3,
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{100, 300, 500, 250, 250},

			targetUtilization:   50,
			expectedUtilization: 28,
			expectedValue:       numContainersPerPod * 280,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleDownCM(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  5,
		expectedReplicas: 3,
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{12000, 12000, 12000, 12000, 12000},
			targetUtilization:   20000,
			expectedUtilization: 12000,
			metricType:          podMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleDownCMObject(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  5,
		expectedReplicas: 3,
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{12000},
			targetUtilization:   20000,
			expectedUtilization: 12000,
			singleObject: &autoscalingv2.CrossVersionObjectReference{
				Kind:       "Deployment",
				APIVersion: "extensions/v1beta1",
				Name:       "some-deployment",
			},
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleDownCMExternal(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  5,
		expectedReplicas: 3,
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{8600},
			targetUtilization:   14334,
			expectedUtilization: 8600,
			selector:            &metav1.LabelSelector{MatchLabels: map[string]string{"label": "value"}},
			metricType:          externalMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleDownPerPodCMExternal(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  5,
		expectedReplicas: 3,
		metric: &metricInfo{
			name:                    "qps",
			levels:                  []int64{8600},
			perPodTargetUtilization: 2867,
			expectedUtilization:     1720,
			selector:                &metav1.LabelSelector{MatchLabels: map[string]string{"label": "value"}},
			metricType:              externalPerPodMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleDownIncludeUnreadyPods(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  5,
		expectedReplicas: 2,
		podReadiness:     []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{100, 300, 500, 250, 250},

			targetUtilization:   50,
			expectedUtilization: 30,
			expectedValue:       numContainersPerPod * 300,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleDownIgnoreHotCpuPods(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  5,
		expectedReplicas: 2,
		podStartTime:     []metav1.Time{coolCpuCreationTime(), coolCpuCreationTime(), coolCpuCreationTime(), hotCpuCreationTime(), hotCpuCreationTime()},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{100, 300, 500, 250, 250},

			targetUtilization:   50,
			expectedUtilization: 30,
			expectedValue:       numContainersPerPod * 300,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleDownIgnoresFailedPods(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  5,
		expectedReplicas: 3,
		podReadiness:     []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse},
		podPhase:         []v1.PodPhase{v1.PodRunning, v1.PodRunning, v1.PodRunning, v1.PodRunning, v1.PodRunning, v1.PodFailed, v1.PodFailed},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{100, 300, 500, 250, 250},

			targetUtilization:   50,
			expectedUtilization: 28,
			expectedValue:       numContainersPerPod * 280,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcScaleDownIgnoresDeletionPods(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:      5,
		expectedReplicas:     3,
		podReadiness:         []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse},
		podPhase:             []v1.PodPhase{v1.PodRunning, v1.PodRunning, v1.PodRunning, v1.PodRunning, v1.PodRunning, v1.PodRunning, v1.PodRunning},
		podDeletionTimestamp: []bool{false, false, false, false, false, true, true},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{100, 300, 500, 250, 250},

			targetUtilization:   50,
			expectedUtilization: 28,
			expectedValue:       numContainersPerPod * 280,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcTolerance(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 3,
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("0.9"), resource.MustParse("1.0"), resource.MustParse("1.1")},
			levels:   []int64{1010, 1030, 1020},

			targetUtilization:   100,
			expectedUtilization: 102,
			expectedValue:       numContainersPerPod * 1020,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcToleranceCM(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 3,
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{20000, 21000, 21000},
			targetUtilization:   20000,
			expectedUtilization: 20666,
			metricType:          podMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcToleranceCMObject(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 3,
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{20666},
			targetUtilization:   20000,
			expectedUtilization: 20666,
			singleObject: &autoscalingv2.CrossVersionObjectReference{
				Kind:       "Deployment",
				APIVersion: "extensions/v1beta1",
				Name:       "some-deployment",
			},
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcToleranceCMExternal(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 3,
		metric: &metricInfo{
			name:                "qps",
			levels:              []int64{8600},
			targetUtilization:   8888,
			expectedUtilization: 8600,
			selector:            &metav1.LabelSelector{MatchLabels: map[string]string{"label": "value"}},
			metricType:          externalMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcTolerancePerPodCMExternal(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 3,
		metric: &metricInfo{
			name:                    "qps",
			levels:                  []int64{8600},
			perPodTargetUtilization: 2900,
			expectedUtilization:     2867,
			selector:                &metav1.LabelSelector{MatchLabels: map[string]string{"label": "value"}},
			metricType:              externalPerPodMetric,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcSuperfluousMetrics(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  4,
		expectedReplicas: 24,
		resource: &resourceInfo{
			name:                v1.ResourceCPU,
			requests:            []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:              []int64{4000, 9500, 3000, 7000, 3200, 2000},
			targetUtilization:   100,
			expectedUtilization: 587,
			expectedValue:       numContainersPerPod * 5875,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcMissingMetrics(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  4,
		expectedReplicas: 3,
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{400, 95},

			targetUtilization:   100,
			expectedUtilization: 24,
			expectedValue:       495, // numContainersPerPod * 247, for sufficiently large values of 247
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcEmptyMetrics(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas: 4,
		expectedError:   fmt.Errorf("unable to get metrics for resource cpu: no metrics returned from resource metrics API"),
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{},

			targetUtilization: 100,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcEmptyCPURequest(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas: 1,
		expectedError:   fmt.Errorf("missing request for"),
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{},
			levels:   []int64{200},

			targetUtilization: 100,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcMissingMetricsNoChangeEq(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  2,
		expectedReplicas: 2,
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{1000},

			targetUtilization:   100,
			expectedUtilization: 100,
			expectedValue:       numContainersPerPod * 1000,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcMissingMetricsNoChangeGt(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  2,
		expectedReplicas: 2,
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{1900},

			targetUtilization:   100,
			expectedUtilization: 190,
			expectedValue:       numContainersPerPod * 1900,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcMissingMetricsNoChangeLt(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  2,
		expectedReplicas: 2,
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{600},

			targetUtilization:   100,
			expectedUtilization: 60,
			expectedValue:       numContainersPerPod * 600,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcMissingMetricsUnreadyChange(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 3,
		podReadiness:     []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{100, 450},

			targetUtilization:   50,
			expectedUtilization: 45,
			expectedValue:       numContainersPerPod * 450,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcMissingMetricsHotCpuNoChange(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 3,
		podStartTime:     []metav1.Time{hotCpuCreationTime(), coolCpuCreationTime(), coolCpuCreationTime()},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{100, 450},

			targetUtilization:   50,
			expectedUtilization: 45,
			expectedValue:       numContainersPerPod * 450,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcMissingMetricsUnreadyScaleUp(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 4,
		podReadiness:     []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{100, 2000},

			targetUtilization:   50,
			expectedUtilization: 200,
			expectedValue:       numContainersPerPod * 2000,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcMissingMetricsHotCpuScaleUp(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  3,
		expectedReplicas: 4,
		podReadiness:     []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue},
		podStartTime:     []metav1.Time{hotCpuCreationTime(), coolCpuCreationTime(), coolCpuCreationTime()},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{100, 2000},

			targetUtilization:   50,
			expectedUtilization: 200,
			expectedValue:       numContainersPerPod * 2000,
		},
	}
	tc.runTest(t)
}

func TestReplicaCalcMissingMetricsUnreadyScaleDown(t *testing.T) {
	tc := replicaCalcTestCase{
		currentReplicas:  4,
		expectedReplicas: 3,
		podReadiness:     []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue},
		resource: &resourceInfo{
			name:     v1.ResourceCPU,
			requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
			levels:   []int64{100, 100, 100},

			targetUtilization:   50,
			expectedUtilization: 10,
			expectedValue:       numContainersPerPod * 100,
		},
	}
	tc.runTest(t)
}

// TestComputedToleranceAlgImplementation is a regression test which
// back-calculates a minimal percentage for downscaling based on a small percentage
// increase in pod utilization which is calibrated against the tolerance value.
func TestReplicaCalcComputedToleranceAlgImplementation(t *testing.T) {

	startPods := int32(10)
	// 150 mCPU per pod.
	totalUsedCPUOfAllPods := int64(startPods * 150)
	// Each pod starts out asking for 2X what is really needed.
	// This means we will have a 50% ratio of used/requested
	totalRequestedCPUOfAllPods := int32(2 * totalUsedCPUOfAllPods)
	requestedToUsed := float64(totalRequestedCPUOfAllPods / int32(totalUsedCPUOfAllPods))
	// Spread the amount we ask over 10 pods.  We can add some jitter later in reportedLevels.
	perPodRequested := totalRequestedCPUOfAllPods / startPods

	// Force a minimal scaling event by satisfying  (tolerance < 1 - resourcesUsedRatio).
	target := math.Abs(1/(requestedToUsed*(1-defaultTestingTolerance))) + .01
	finalCPUPercentTarget := int32(target * 100)
	resourcesUsedRatio := float64(totalUsedCPUOfAllPods) / float64(float64(totalRequestedCPUOfAllPods)*target)

	// i.e. .60 * 20 -> scaled down expectation.
	finalPods := int32(math.Ceil(resourcesUsedRatio * float64(startPods)))

	// To breach tolerance we will create a utilization ratio difference of tolerance to usageRatioToleranceValue)
	tc := replicaCalcTestCase{
		currentReplicas:  startPods,
		expectedReplicas: finalPods,
		resource: &resourceInfo{
			name: v1.ResourceCPU,
			levels: []int64{
				totalUsedCPUOfAllPods / 10,
				totalUsedCPUOfAllPods / 10,
				totalUsedCPUOfAllPods / 10,
				totalUsedCPUOfAllPods / 10,
				totalUsedCPUOfAllPods / 10,
				totalUsedCPUOfAllPods / 10,
				totalUsedCPUOfAllPods / 10,
				totalUsedCPUOfAllPods / 10,
				totalUsedCPUOfAllPods / 10,
				totalUsedCPUOfAllPods / 10,
			},
			requests: []resource.Quantity{
				resource.MustParse(fmt.Sprint(perPodRequested+100) + "m"),
				resource.MustParse(fmt.Sprint(perPodRequested-100) + "m"),
				resource.MustParse(fmt.Sprint(perPodRequested+10) + "m"),
				resource.MustParse(fmt.Sprint(perPodRequested-10) + "m"),
				resource.MustParse(fmt.Sprint(perPodRequested+2) + "m"),
				resource.MustParse(fmt.Sprint(perPodRequested-2) + "m"),
				resource.MustParse(fmt.Sprint(perPodRequested+1) + "m"),
				resource.MustParse(fmt.Sprint(perPodRequested-1) + "m"),
				resource.MustParse(fmt.Sprint(perPodRequested) + "m"),
				resource.MustParse(fmt.Sprint(perPodRequested) + "m"),
			},

			targetUtilization:   finalCPUPercentTarget,
			expectedUtilization: int32(totalUsedCPUOfAllPods*100) / totalRequestedCPUOfAllPods,
			expectedValue:       numContainersPerPod * totalUsedCPUOfAllPods / 10,
		},
	}

	tc.runTest(t)

	// Reuse the data structure above, now testing "unscaling".
	// Now, we test that no scaling happens if we are in a very close margin to the tolerance
	target = math.Abs(1/(requestedToUsed*(1-defaultTestingTolerance))) + .004
	finalCPUPercentTarget = int32(target * 100)
	tc.resource.targetUtilization = finalCPUPercentTarget
	tc.currentReplicas = startPods
	tc.expectedReplicas = startPods
	tc.runTest(t)
}

func TestGroupPods(t *testing.T) {
	tests := []struct {
		name                string
		pods                []v1.Pod
		metrics             metricsclient.PodMetricsInfo
		resource            v1.ResourceName
		expectReadyPodCount int
		expectIgnoredPods   sets.String
		expectMissingPods   sets.String
	}{
		{
			"void",
			[]v1.Pod{},
			metricsclient.PodMetricsInfo{},
			v1.ResourceCPU,
			0,
			sets.NewString(),
			sets.NewString(),
		},
		{
			"count in a ready pod - memory",
			[]v1.Pod{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "bentham",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
					},
				},
			},
			metricsclient.PodMetricsInfo{
				"bentham": metricsclient.PodMetric{Value: 1, Timestamp: time.Now(), Window: time.Minute},
			},
			v1.ResourceMemory,
			1,
			sets.NewString(),
			sets.NewString(),
		},
		{
			"ignore a pod without ready condition - CPU",
			[]v1.Pod{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "lucretius",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
						StartTime: &metav1.Time{
							Time: time.Now(),
						},
					},
				},
			},
			metricsclient.PodMetricsInfo{
				"lucretius": metricsclient.PodMetric{Value: 1},
			},
			v1.ResourceCPU,
			0,
			sets.NewString("lucretius"),
			sets.NewString(),
		},
		{
			"count in a ready pod with fresh metrics during initialization period - CPU",
			[]v1.Pod{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "bentham",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
						StartTime: &metav1.Time{
							Time: time.Now().Add(-1 * time.Minute),
						},
						Conditions: []v1.PodCondition{
							{
								Type:               v1.PodReady,
								LastTransitionTime: metav1.Time{Time: time.Now().Add(-30 * time.Second)},
								Status:             v1.ConditionTrue,
							},
						},
					},
				},
			},
			metricsclient.PodMetricsInfo{
				"bentham": metricsclient.PodMetric{Value: 1, Timestamp: time.Now(), Window: 30 * time.Second},
			},
			v1.ResourceCPU,
			1,
			sets.NewString(),
			sets.NewString(),
		},
		{
			"ignore a ready pod without fresh metrics during initialization period - CPU",
			[]v1.Pod{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "bentham",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
						StartTime: &metav1.Time{
							Time: time.Now().Add(-1 * time.Minute),
						},
						Conditions: []v1.PodCondition{
							{
								Type:               v1.PodReady,
								LastTransitionTime: metav1.Time{Time: time.Now().Add(-30 * time.Second)},
								Status:             v1.ConditionTrue,
							},
						},
					},
				},
			},
			metricsclient.PodMetricsInfo{
				"bentham": metricsclient.PodMetric{Value: 1, Timestamp: time.Now(), Window: 60 * time.Second},
			},
			v1.ResourceCPU,
			0,
			sets.NewString("bentham"),
			sets.NewString(),
		},
		{
			"ignore an unready pod during initialization period - CPU",
			[]v1.Pod{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "lucretius",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
						StartTime: &metav1.Time{
							Time: time.Now().Add(-10 * time.Minute),
						},
						Conditions: []v1.PodCondition{
							{
								Type:               v1.PodReady,
								LastTransitionTime: metav1.Time{Time: time.Now().Add(-9*time.Minute - 54*time.Second)},
								Status:             v1.ConditionFalse,
							},
						},
					},
				},
			},
			metricsclient.PodMetricsInfo{
				"lucretius": metricsclient.PodMetric{Value: 1},
			},
			v1.ResourceCPU,
			0,
			sets.NewString("lucretius"),
			sets.NewString(),
		},
		{
			"count in a ready pod without fresh metrics after initialization period - CPU",
			[]v1.Pod{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "bentham",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
						StartTime: &metav1.Time{
							Time: time.Now().Add(-3 * time.Minute),
						},
						Conditions: []v1.PodCondition{
							{
								Type:               v1.PodReady,
								LastTransitionTime: metav1.Time{Time: time.Now().Add(-3 * time.Minute)},
								Status:             v1.ConditionTrue,
							},
						},
					},
				},
			},
			metricsclient.PodMetricsInfo{
				"bentham": metricsclient.PodMetric{Value: 1, Timestamp: time.Now().Add(-2 * time.Minute), Window: time.Minute},
			},
			v1.ResourceCPU,
			1,
			sets.NewString(),
			sets.NewString(),
		},

		{
			"count in an unready pod that was ready after initialization period - CPU",
			[]v1.Pod{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "lucretius",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
						StartTime: &metav1.Time{
							Time: time.Now().Add(-10 * time.Minute),
						},
						Conditions: []v1.PodCondition{
							{
								Type:               v1.PodReady,
								LastTransitionTime: metav1.Time{Time: time.Now().Add(-9 * time.Minute)},
								Status:             v1.ConditionFalse,
							},
						},
					},
				},
			},
			metricsclient.PodMetricsInfo{
				"lucretius": metricsclient.PodMetric{Value: 1},
			},
			v1.ResourceCPU,
			1,
			sets.NewString(),
			sets.NewString(),
		},
		{
			"ignore pod that has never been ready after initialization period - CPU",
			[]v1.Pod{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "lucretius",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
						StartTime: &metav1.Time{
							Time: time.Now().Add(-10 * time.Minute),
						},
						Conditions: []v1.PodCondition{
							{
								Type:               v1.PodReady,
								LastTransitionTime: metav1.Time{Time: time.Now().Add(-9*time.Minute - 50*time.Second)},
								Status:             v1.ConditionFalse,
							},
						},
					},
				},
			},
			metricsclient.PodMetricsInfo{
				"lucretius": metricsclient.PodMetric{Value: 1},
			},
			v1.ResourceCPU,
			1,
			sets.NewString(),
			sets.NewString(),
		},
		{
			"a missing pod",
			[]v1.Pod{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "epicurus",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
						StartTime: &metav1.Time{
							Time: time.Now().Add(-3 * time.Minute),
						},
					},
				},
			},
			metricsclient.PodMetricsInfo{},
			v1.ResourceCPU,
			0,
			sets.NewString(),
			sets.NewString("epicurus"),
		},
		{
			"several pods",
			[]v1.Pod{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "lucretius",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
						StartTime: &metav1.Time{
							Time: time.Now(),
						},
					},
				},
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "niccolo",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
						StartTime: &metav1.Time{
							Time: time.Now().Add(-3 * time.Minute),
						},
						Conditions: []v1.PodCondition{
							{
								Type:               v1.PodReady,
								LastTransitionTime: metav1.Time{Time: time.Now().Add(-3 * time.Minute)},
								Status:             v1.ConditionTrue,
							},
						},
					},
				},
				{
					ObjectMeta: metav1.ObjectMeta{
						Name: "epicurus",
					},
					Status: v1.PodStatus{
						Phase: v1.PodSucceeded,
						StartTime: &metav1.Time{
							Time: time.Now().Add(-3 * time.Minute),
						},
					},
				},
			},
			metricsclient.PodMetricsInfo{
				"lucretius": metricsclient.PodMetric{Value: 1},
				"niccolo":   metricsclient.PodMetric{Value: 1},
			},
			v1.ResourceCPU,
			1,
			sets.NewString("lucretius"),
			sets.NewString("epicurus"),
		},
	}
	for _, tc := range tests {
		readyPodCount, ignoredPods, missingPods := groupPods(tc.pods, tc.metrics, tc.resource, defaultTestingCpuInitializationPeriod, defaultTestingDelayOfInitialReadinessStatus)
		if readyPodCount != tc.expectReadyPodCount {
			t.Errorf("%s got readyPodCount %d, expected %d", tc.name, readyPodCount, tc.expectReadyPodCount)
		}
		if !ignoredPods.Equal(tc.expectIgnoredPods) {
			t.Errorf("%s got unreadyPods %v, expected %v", tc.name, ignoredPods, tc.expectIgnoredPods)
		}
		if !missingPods.Equal(tc.expectMissingPods) {
			t.Errorf("%s got missingPods %v, expected %v", tc.name, missingPods, tc.expectMissingPods)
		}
	}
}

// TODO: add more tests


text:
<?php
// {$setting_id}[$id] - Contains the setting id, this is what it will be stored in the db as.
// $class - optional class value
// $id - setting id
// $options[$id] value from the db
if(empty($options[ $id ])){
	$options[ $id ] = '';
}
$content   = $options[ $id ];
$editor_id = $id;
$args      = array(
     'textarea_name' => "{$setting_id}[$id]"
);

wp_editor( $content, $editor_id, $args );


text:
<?php

namespace Zephir\Optimizers\FunctionCall;

use Zephir\Call;
use Zephir\CompilationContext;
use Zephir\CompilerException;
use Zephir\CompiledExpression;
use Zephir\Optimizers\OptimizerAbstract;
use Zephir\HeadersManager;

class PhvoltParseViewOptimizer extends OptimizerAbstract
{

	/**
	 * @param array $expression
	 * @param Call $call
	 * @param CompilationContext $context
	 * @return bool|CompiledExpression
	 * @throws CompilerException
	 */
	public function optimize(array $expression, Call $call, CompilationContext $context)
	{
		if (!isset($expression['parameters'])) {
			return false;
		}

		if (count($expression['parameters']) != 2) {
			throw new CompilerException("'phvolt_parse_view' only accepts two parameters", $expression);
		}

		/**
		 * Process the expected symbol to be returned
		 */
		$call->processExpectedReturn($context);

		$symbolVariable = $call->getSymbolVariable();
		if ($symbolVariable->getType() != 'variable') {
			throw new CompilerException("Returned values by functions can only be assigned to variant variables", $expression);
		}

		if ($call->mustInitSymbolVariable()) {
			$symbolVariable->initVariant($context);
		}

		$symbolVariable->setDynamicTypes('array');

		$resolvedParams = $call->getReadOnlyResolvedParams($expression['parameters'], $context, $expression);

		$context->headersManager->add('phalcon/mvc/view/engine/volt/scanner', HeadersManager::POSITION_LAST);
		$context->headersManager->add('phalcon/mvc/view/engine/volt/volt',    HeadersManager::POSITION_LAST);

		$call->addCallStatusFlag($context);

		$symbol = $context->backend->getVariableCode($symbolVariable);
		$context->codePrinter->output('ZEPHIR_LAST_CALL_STATUS = phvolt_parse_view(' . $symbol . ', ' . $resolvedParams[0] . ', ' . $resolvedParams[1] . ' TSRMLS_CC);');

		$call->checkTempParameters($context);
		$call->addCallStatusOrJump($context);

		return new CompiledExpression('variable', $symbolVariable->getRealName(), $expression);
	}

}


text:
This example shows how to deploy [SuperTuxKart](https://supertuxkart.net/Main_Page) and a dedicated game server to GKE for a fully in-cluster game streaming and server hosting demo.

## Dependencies

- App Launcher: [v1.0.0+](https://github.com/GoogleCloudPlatform/solutions-k8s-stateful-workload-operator/tree/v1.0.0)
- WebRTC Streaming Stack: [v1.4.0+](https://github.com/GoogleCloudPlatform/solutions-webrtc-gpu-streaming/tree/v1.4.0)

## Features

- Fully in-cluster multiplayer gaming.
- Dedicated server and match making pod.
- Gamepad support
- Option to save local progress to persistent disk.

## Installed Software

- SuperTuxKart game and dedicated server.

## Tutorials

This tutorial will walk you through the following:

- Verifying cluster pre-requisites.
- Building the image and deploying the manifests with Cloud Build.

## Setup

1. Set the project, replace `YOUR_PROJECT` with your project ID:

```bash
export PROJECT_ID=YOUR_PROJECT
```

```bash
gcloud config set project ${PROJECT_ID?}
```

## Pre-requisites

This tutorial requires that you have already deployed the Kubernetes App Launcher Operator in your GKE cluster.

If you have not already deployed the operator, follow this Cloud Shell tutorial to do so:

[![Open in Cloud Shell](https://gstatic.com/cloudssh/images/open-btn.svg)](https://ssh.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https://github.com/GoogleCloudPlatform/solutions-k8s-stateful-workload-operator&cloudshell_git_branch=v1.0.0&cloudshell_tutorial=setup/README.md)

This tutorial requires that you have deployed the WebRTC streaming app launcher stack to the cluster.

If you have not installed the WebRTC stack, follow this Cloud Shell tutorial to do so:

[![Open in Cloud Shell](https://gstatic.com/cloudssh/images/open-btn.svg)](https://ssh.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https://github.com/GoogleCloudPlatform/solutions-webrtc-gpu-streaming&cloudshell_git_branch=v1.0.0&&cloudshell_tutorial=tutorials/gke/00_Setup.md).

## Platform verification

3. Obtain cluster credentials:

```bash
REGION=us-west1
```

> NOTE: change this to the region of your cluster.

```bash
gcloud --project ${PROJECT_ID?} container clusters get-credentials broker-${REGION?} --region ${REGION?}
```

2. Verify that the WebRTC streaming manifest bundle is present:

```bash
kubectl get configmap webrtc-gpu-streaming-manifests-1.4.0 -n pod-broker-system
```

3. Verify that GPU sharing is enabled:

```bash
kubectl describe node -l cloud.google.com/gke-accelerator-initialized=true | grep nvidia.com/gpu
```

Example output:

```
 nvidia.com/gpu:             48
 nvidia.com/gpu:             48
```

> Verify that the number of availble GPUs is greater than 1.

## Build the app image

1. Build the container image using cloud build:

```bash
(cd images && gcloud builds submit)
```

## Deploy the app manifests

1. Deploy manifests to the cluster:

```bash
gcloud builds submit --substitutions=_REGION=${REGION?}
```

2. Open the app launcher web interface and launch the app.

> NOTE: after the Cloud Build has completed from the previous step, it will take a few minutes for the nodes to pre-pull the image. As a result, the first launch may take longer than usual.


text:
package csv

import (
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"reflect"
	"strconv"
	"time"
)

var (
	ErrNotPointer = errors.New("csv2: non-pointer receiver")
	ErrNotSlice   = errors.New("csv2: receiver must be a slice of structs")
	ErrNotStruct  = errors.New("csv2: receiver must be a struct")
	ErrUnwritable = errors.New("csv2: writers accept struct or struct slices")
)

// GetFieldNames returns a string array of the given interface's field names
// if the given interface is a struct or slice of structs
func GetFieldNames(i interface{}) ([]string, error) {
	value := reflect.Indirect(reflect.ValueOf(i))
	var elem reflect.Type
	switch value.Kind() {
	case reflect.Struct:
		elem = value.Type()
	case reflect.Slice:
		elem = value.Type().Elem()
		if elem.Kind() == reflect.Ptr {
			elem = elem.Elem()
		}
		if elem.Kind() != reflect.Struct {
			return nil, ErrUnwritable
		}
	default:
		return nil, ErrUnwritable
	}

	// Get the names of the struct fields
	fields := make([]string, elem.NumField())
	for index := 0; index < elem.NumField(); index += 1 {
		fields[index] = elem.Field(index).Name
	}
	return fields, nil
}

// setLayout checks the given struct type for any "csv" tags.
// This layout is used for alternative parse formats.
func setLayout(v reflect.Type) map[int]string {
	layout := make(map[int]string)
	for i := 0; i < v.NumField(); i += 1 {
		f := v.Field(i)
		tag := f.Tag.Get("csv")
		if tag != "" {
			layout[i] = tag
		}
	}
	return layout
}

// Reader wraps the csv.Reader and adds a map of csv struct tags.
type Reader struct {
	*csv.Reader
	layout map[int]string
}

// Unmarshal reads the entire Reader into the given destination.
// The destination interface must of pointer of type slice.
func (r *Reader) Unmarshal(i interface{}) error {
	sv := reflect.ValueOf(i)
	if sv.Kind() != reflect.Ptr {
		return ErrNotPointer
	}

	sliceValue := sv.Elem()
	if sliceValue.Kind() != reflect.Slice {
		return ErrNotSlice
	}

	// Get the type of the slice element
	elem := sliceValue.Type().Elem()
	if elem.Kind() != reflect.Struct {
		return ErrNotSlice
	}

	// Check the struct tags for any custom csv layout tags
	// TODO Check if already set?
	r.layout = setLayout(elem)

	// Read all
	for {
		record, err := r.Read()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}

		// Create a new slice element and append to the slice
		n := reflect.New(elem)
		newElem := n.Elem()

		err = r.setValue(record, &newElem)
		if err != nil {
			return err
		}

		sliceValue.Set(reflect.Append(sliceValue, newElem))
	}
	return nil
}

// UnmarshalOne reads a single row of the Reader into the given struct.
// The destination interface must of pointer of type struct.
func (r *Reader) UnmarshalOne(i interface{}) error {
	// Get the value of the given interface
	value := reflect.ValueOf(i)
	if value.Kind() != reflect.Ptr {
		return ErrNotPointer
	}

	elem := value.Elem()
	if elem.Kind() != reflect.Struct {
		return ErrNotStruct
	}

	// Get the next record from the reader
	record, err := r.Read()
	if err != nil {
		return err
	}

	// Get the type of the interface to check for layouts
	t := reflect.TypeOf(i)
	r.layout = setLayout(t.Elem())
	return r.setValue(record, &elem)
}

// Set the values of the given struct with the reflect package.
// Fields are processed in sequential order.
// TODO Each field setter should be separate func to allow pointer calls
// and non-duplicated behavior
func (r *Reader) setValue(values []string, elem *reflect.Value) error {
	// TODO wrap the errors with the current field
	for i := 0; i < elem.NumField(); i += 1 {
		f := elem.Field(i)
		if !f.IsValid() || !f.CanSet() {
			return fmt.Errorf("csv2: field %d cannot be set", i)
		}

		// TODO What about using a type switch instead? benchmark it.
		switch f.Kind() {
		case reflect.String:
			f.SetString(values[i])
		case reflect.Int64, reflect.Int:
			// Attempt to convert the value to an int64
			v, err := strconv.ParseInt(values[i], 10, 64)
			if err != nil {
				return err
			}
			f.SetInt(v)
		case reflect.Uint64:
			// Attempt to convert the value to an uint64
			v, err := strconv.ParseUint(values[i], 10, 64)
			if err != nil {
				return err
			}
			f.SetUint(v)
		case reflect.Float64:
			// Attempt to convert the value to a float64
			v, err := strconv.ParseFloat(values[i], 64)
			if err != nil {
				return err
			}
			f.SetFloat(v)
		case reflect.Bool:
			// Attempt to convert the value to a boolean
			v, err := strconv.ParseBool(values[i])
			if err != nil {
				return err
			}
			f.SetBool(v)
		case reflect.Struct:
			switch f.Interface().(type) {
			case time.Time:
				// Check if an alternative layout should be used
				layout := r.layout[i]
				if layout == "" {
					layout = time.RFC3339
				}
				parsed, err := time.Parse(layout, values[i])

				if err != nil {
					return err
				}
				f.Set(reflect.ValueOf(parsed))
			default:
				return fmt.Errorf(
					"csv2: unknown destination struct for field %d",
					i,
				)
			}
		case reflect.Ptr:
			// If the value is empty, set the field to nil (except for strings)
			// TODO functions for each reflect type
			ptrElem := f.Type().Elem()
			switch ptrElem.Kind() {
			case reflect.String:
				// Never set strings to nil, always set to blank
				v := values[i]
				f.Set(reflect.ValueOf(&v))
			case reflect.Int64:
				// Leave nil if the value is empty
				// Attempt to convert the value to an int64
				if values[i] != "" {
					v, err := strconv.ParseInt(values[i], 10, 64)
					if err != nil {
						return err
					}
					f.Set(reflect.ValueOf(&v))
				}
			case reflect.Int:
				// Leave nil if the value is empty
				// Attempt to convert the value to an int
				if values[i] != "" {
					v, err := strconv.Atoi(values[i])
					if err != nil {
						return err
					}
					f.Set(reflect.ValueOf(&v))
				}
			case reflect.Uint64:
				// Leave nil if the value is empty
				// Attempt to convert the value to an uint64
				if values[i] != "" {
					v, err := strconv.ParseUint(values[i], 10, 64)
					if err != nil {
						return err
					}
					f.Set(reflect.ValueOf(&v))
				}
			case reflect.Float64:
				// Attempt to convert the value to a float64
				if values[i] != "" {
					v, err := strconv.ParseFloat(values[i], 64)
					if err != nil {
						return err
					}
					f.Set(reflect.ValueOf(&v))
				}
			case reflect.Bool:
				// Attempt to convert the value to a boolean
				if values[i] != "" {
					v, err := strconv.ParseBool(values[i])
					if err != nil {
						return err
					}
					f.Set(reflect.ValueOf(&v))
				}
			case reflect.Struct:
				switch f.Interface().(type) {
				case *time.Time:
					// Check if an alternative layout should be used
					if values[i] != "" {
						layout := r.layout[i]
						if layout == "" {
							layout = time.RFC3339
						}
						parsed, err := time.Parse(layout, values[i])

						if err != nil {
							return err
						}
						f.Set(reflect.ValueOf(&parsed))
					}
				default:
					return fmt.Errorf(
						"csv2: unknown destination struct for field %d",
						i,
					)
				}
			default:
				return fmt.Errorf(
					"csv2: unsupported type %s for field %d",
					f.Kind(),
					i,
				)
			}
		default:
			return fmt.Errorf(
				"csv2: unsupported type %s for field %d",
				f.Kind(),
				i,
			)
		}
	}
	return nil
}

// NewReader returns a new csv2 Reader by wrapping a csv Reader.
func NewReader(r io.Reader) *Reader {
	return &Reader{Reader: csv.NewReader(r)}
}

// Writer wraps the csv.Writer and adds a map of csv struct tags.
type Writer struct {
	*csv.Writer
	layout map[int]string
}

// WriteHeader will write the names of the underlying struct fields as a row.
// It accepts a struct or a slice of structs.
func (w *Writer) WriteHeader(i interface{}) error {
	headers, err := GetFieldNames(i)
	if err != nil {
		return err
	}
	if err = w.Write(headers); err != nil {
		return err
	}
	return nil
}

func (w *Writer) getStrings(elem reflect.Value) ([]string, error) {
	output := make([]string, elem.NumField())
	for i := 0; i < elem.NumField(); i += 1 {
		f := elem.Field(i)

		// TODO What about using a type switch instead? benchmark it.
		switch f.Kind() {
		case reflect.String:
			output[i] = f.String()
		case reflect.Int64, reflect.Int:
			// TODO additional base output
			output[i] = strconv.FormatInt(f.Int(), 10)
		case reflect.Uint64:
			// TODO additional base output
			output[i] = strconv.FormatUint(f.Uint(), 10)
		case reflect.Float64:
			// TODO additional formats, precision
			output[i] = strconv.FormatFloat(f.Float(), 'f', -1, 64)
		case reflect.Bool:
			// Attempt to convert the value to a boolean
			output[i] = strconv.FormatBool(f.Bool())
		case reflect.Struct:
			switch f.Interface().(type) {
			case time.Time:
				// Get the underlying time
				t := f.Interface().(time.Time)

				// Check if an alternative layout should be used
				layout := w.layout[i]
				if layout == "" {
					layout = time.RFC3339
				}
				output[i] = t.Format(layout)
			default:
				return output, fmt.Errorf(
					"csv2: unsupported struct for field %d",
					i,
				)
			}
		case reflect.Ptr:
			fallthrough
		default:
			return output, fmt.Errorf(
				"csv2: unsupported type %s for field %d",
				f.Kind(),
				i,
			)
		}
	}
	return output, nil
}

// Marshal writes a slice of structs to the Writer.
// The destination interface must of pointer of type slice.
func (w *Writer) Marshal(i interface{}) error {
	sv := reflect.ValueOf(i)
	if sv.Kind() != reflect.Ptr {
		return ErrNotPointer
	}

	sliceValue := sv.Elem()
	if sliceValue.Kind() != reflect.Slice {
		return ErrNotSlice
	}

	// Get the type of the slice element
	elem := sliceValue.Type().Elem()

	// Check the struct tags for any custom csv layout tags
	w.layout = setLayout(elem)

	// Read all
	for index := 0; index < sliceValue.Len(); index += 1 {
		s, err := w.getStrings(sliceValue.Index(index))
		if err != nil {
			return err
		}
		if err = w.Write(s); err != nil {
			return err
		}
	}

	// csv writer is buffered
	w.Flush()
	return nil
}

// NewWriter returns a new csv2 Writer by wrapping a csv Writer.
func NewWriter(r io.Writer) *Writer {
	return &Writer{Writer: csv.NewWriter(r)}
}


text:
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/notClickableButton"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    >
</Button>


text:
.styleSans701.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 701.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 1.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 11.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 10.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 7.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 8.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 6.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 5.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 2.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans207.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 207.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans27.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 27.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 12pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 12.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans35.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 35.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 4.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 9.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans43.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 43.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans472.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 472.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans191.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 191.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans20.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 20.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans24.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 24.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans116.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 116.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans155.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 155.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 18.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans16.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 16.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans241.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 241.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans387.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 387.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans721.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 721.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans730.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 730.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans527.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 527.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans23.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 23.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans56.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 56.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans30.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 30.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans428.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 428.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans792.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 792.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans32.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 32.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans3.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 3.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans29.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 29.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans39.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 39.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans41.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 41.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans492.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 492.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans97.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 97.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans14.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 14.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans614.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 614.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans204.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 204.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans201.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 201.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans186.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 186.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans574.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 574.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans111.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 111.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="mc_title_bar">#FF16C2DD</color>
    <color name="mc_state_pressed">#FF1088DD</color>

    <color name="flat_state_normal">#D5D5D5</color>
    <color name="flat_state_pressed">#FF6F00</color>

</resources>