text:
package im.actor.model.droidkit.bser;

import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import im.actor.model.droidkit.bser.util.SparseArray;
import im.actor.model.tests.EmptyBserObj;
import im.actor.model.tests.MockSerialization;

import static im.actor.model.tests.Util.assertContent;
import static im.actor.model.tests.Util.assertSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Created by ex3ndr on 08.03.15.
 */
public class BserWriterTest {

    private final MockSerialization DEFAULT = new MockSerialization() {
        @Override
        protected void perform(BserWriter writer) throws IOException {
            writer.writeInt(1, 1);
            writer.writeInt(1, 2);
            writer.writeInt(1, 3);
            writer.writeInt(1, 4);
            writer.writeInt(1, 5);

            writer.writeInt(2, 6);

            writer.writeBytes(3, new byte[0]);
            writer.writeBytes(3, new byte[0]);

            writer.writeLongFixed(4, 0);
            writer.writeIntFixed(5, 0);

            writer.writeString(6, "???");

            writer.writeBool(7, true);
            writer.writeBool(7, false);

            writer.writeDouble(8, 0);

            writer.writeLong(9, 0);

            writer.writeObject(10, new EmptyBserObj());

            List<EmptyBserObj> objs = new ArrayList<EmptyBserObj>();
            objs.add(new EmptyBserObj());
            writer.writeRepeatedObj(11, objs);
        }
    };

    private final MockSerialization ERROR = new MockSerialization() {
        @Override
        protected void perform(BserWriter writer) throws IOException {
            writer.writeRaw(new byte[]{1 << 3 | 3});
        }
    };

    @Test
    public void testWriter() throws Exception {
        SparseArray<Object> values = DEFAULT.buildArray();

        assertEquals(11, values.size());

        assertTrue(values.get(1) instanceof List);
        assertContent(values.get(1), Long.class);
        assertSize(values.get(1), 5);

        assertTrue(values.get(2) instanceof Long);

        assertTrue(values.get(3) instanceof List);
        assertContent(values.get(3), byte[].class);
        assertSize(values.get(3), 2);

        assertTrue(values.get(4) instanceof Long);
        assertTrue(values.get(5) instanceof Long);

        try {
            ERROR.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        new MockSerialization() {
            @Override
            protected void perform(BserWriter writer) throws IOException {
                writer.writeLong(1, -1);
            }
        }.buildArray();

        new MockSerialization() {
            @Override
            protected void perform(BserWriter writer) throws IOException {
                List<Boolean> b = new ArrayList<Boolean>();
                b.add(true);
                writer.writeRepeatedBool(1, b);

                List<Long> l = new ArrayList<Long>();
                l.add(0L);
                writer.writeRepeatedLong(1, l);

                List<Integer> i = new ArrayList<Integer>();
                i.add(0);
                writer.writeRepeatedInt(1, i);
            }
        }.buildArray();
    }

    @Test
    public void testIncorrect() throws Exception {

        try {
            new BserWriter(null);
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    writer.writeInt(0, 0);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    writer.writeBytes(1, null);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    writer.writeString(1, null);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    writer.writeRepeatedLong(1, null);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    writer.writeRepeatedInt(1, null);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    writer.writeRepeatedBool(1, null);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    writer.writeRepeatedObj(1, null);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    writer.writeObject(1, null);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    writer.writeRaw(null);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    List list = new ArrayList();
                    for (int i = 0; i < 2000; i++) {
                        list.add(null);
                    }
                    writer.writeRepeatedLong(1, list);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    List list = new ArrayList();
                    for (int i = 0; i < 2000; i++) {
                        list.add(null);
                    }
                    writer.writeRepeatedInt(1, list);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    List list = new ArrayList();
                    for (int i = 0; i < 2000; i++) {
                        list.add(null);
                    }
                    writer.writeRepeatedObj(1, list);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    List list = new ArrayList();
                    for (int i = 0; i < 2000; i++) {
                        list.add(null);
                    }
                    writer.writeRepeatedBool(1, list);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }

        try {
            new MockSerialization() {
                @Override
                protected void perform(BserWriter writer) throws IOException {
                    writer.writeBytes(1, new byte[2048 * 2048 + 1]);
                }
            }.buildArray();
            throw new AssertionError();
        } catch (Exception e) {
            // It is OK
        }
    }

    @Test
    public void testLimitsBool() throws Exception {
        DataOutput dataOutput = new DataOutput();
        BserWriter writer = new BserWriter(dataOutput);
        writer.writeBool(32, true);
        writer.writeBytes(33, new byte[26]);
        byte[] data = dataOutput.toByteArray();
        BserParser.deserialize(new DataInput(data));
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function() {
  'use strict';

  angular
  .module('roboconf.utils')
  .service('rShare', rShare);

  function rShare() {

    // Fields
    var lastItem;
    var service = {
        eatLastItem: eatLastItem,
        feedLastItem: feedLastItem
    };

    return service;

    // Functions
    function eatLastItem() {
      var result = lastItem;
      lastItem = null;
      return result;
    }

    function feedLastItem(newLastItem) {
      lastItem = newLastItem;
    }
  }
}());


text:
require 'spec_helper'

describe Gitlab::Ci::Config::Entry::Reports do
  let(:entry) { described_class.new(config) }

  describe 'validates ALLOWED_KEYS' do
    let(:artifact_file_types) { Ci::JobArtifact.file_types }

    described_class::ALLOWED_KEYS.each do |keyword, _|
      it "expects #{keyword} to be an artifact file_type" do
        expect(artifact_file_types).to include(keyword)
      end
    end
  end

  describe 'validation' do
    context 'when entry config value is correct' do
      using RSpec::Parameterized::TableSyntax

      shared_examples 'a valid entry' do |keyword, file|
        describe '#value' do
          it 'returns artifacts configuration' do
            expect(entry.value).to eq({ "#{keyword}": [file] } )
          end
        end

        describe '#valid?' do
          it 'is valid' do
            expect(entry).to be_valid
          end
        end
      end

      where(:keyword, :file) do
        :junit | 'junit.xml'
        :codequality | 'gl-code-quality-report.json'
        :sast | 'gl-sast-report.json'
        :dependency_scanning | 'gl-dependency-scanning-report.json'
        :container_scanning | 'gl-container-scanning-report.json'
        :dast | 'gl-dast-report.json'
        :license_management | 'gl-license-management-report.json'
        :performance | 'performance.json'
      end

      with_them do
        context 'when value is an array' do
          let(:config) { { "#{keyword}": [file] } }

          it_behaves_like 'a valid entry', params[:keyword], params[:file]
        end

        context 'when value is not array' do
          let(:config) { { "#{keyword}": file } }

          it_behaves_like 'a valid entry', params[:keyword], params[:file]
        end
      end
    end

    context 'when entry value is not correct' do
      describe '#errors' do
        context 'when value of attribute is invalid' do
          where(key: described_class::ALLOWED_KEYS) do
            let(:config) { { "#{key}": 10 } }

            it 'reports error' do
              expect(entry.errors)
                .to include "reports #{key} should be an array of strings or a string"
            end
          end
        end

        context 'when there is an unknown key present' do
          let(:config) { { codeclimate: 'codeclimate.json' } }

          it 'reports error' do
            expect(entry.errors)
              .to include 'reports config contains unknown keys: codeclimate'
          end
        end
      end
    end
  end
end


text:
@interface PodsDummy_Pods_Shoping_Car : NSObject
@end
@implementation PodsDummy_Pods_Shoping_Car
@end


text:
'use strict';

const { convertRegExpToPattern } = require('jpdate-lib');

const dateRegExps = {
  today: {
    regexp: /今日|きょう/,
    relative: 0
  },
  tomorrow: {
    regexp: /明日|あした|あす|みょうじつ|翌日|よくじつ/,
    relative: 1
  },
  twoDaysAfterTomorrow: {
    regexp: /明々後日|しあさって/,
    relative: 3
  },
  dayAfterTomorrow: {
    regexp: /明後日|あさって/,
    relative: 2
  },
  dayBeforeYesterday: {
    regexp: /一昨日|おととい/,
    relative: -2
  },
  yesterday: {
    regexp: /昨日|きのう|さくじつ/,
    relative: -1
  }
};

// 判定順
const datePriority = [
  dateRegExps.today,
  dateRegExps.tomorrow,
  dateRegExps.twoDaysAfterTomorrow,
  dateRegExps.dayAfterTomorrow,
  dateRegExps.dayBeforeYesterday,
  dateRegExps.yesterday
];

const allPattern = datePriority.map((e) => {
  return convertRegExpToPattern(e.regexp);
}).join('|');

module.exports = {
  pattern: allPattern,
  getRelative: (inputStr) => {
    for (const date of datePriority) {
      if (date.regexp.test(inputStr)) {
        return date.relative;
      }
    }
  }
};


text:
package org.springframework.osgi.compendium.config;

import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;

import junit.framework.TestCase;

import org.easymock.MockControl;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.osgi.TestUtils;
import org.springframework.osgi.compendium.internal.cm.ManagedServiceFactoryFactoryBean;
import org.springframework.osgi.compendium.internal.cm.UpdateStrategy;
import org.springframework.osgi.context.support.BundleContextAwareProcessor;
import org.springframework.osgi.mock.MockBundleContext;
import org.springframework.osgi.service.exporter.support.AutoExport;
import org.springframework.osgi.service.exporter.support.ExportContextClassLoader;

/**
 * Parsing test for ManagedServiceFactory/<managed-service-factory/>
 *
 * @author Costin Leau
 */
public class ManagedServiceFactoryTest extends TestCase {

	private GenericApplicationContext appContext;

	protected void setUp() throws Exception {

		MockControl mc = MockControl.createNiceControl(Configuration.class);
		final Configuration cfg = (Configuration) mc.getMock();
		mc.expectAndReturn(cfg.getProperties(), new Properties());
		mc.replay();

		BundleContext bundleContext = new MockBundleContext() {

			// always return a ConfigurationAdmin
			public Object getService(ServiceReference reference) {
				return new MockConfigurationAdmin() {

					public Configuration getConfiguration(String pid) throws IOException {
						return cfg;
					}
				};
			}
		};

		appContext = new GenericApplicationContext();
		appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
		appContext.setClassLoader(getClass().getClassLoader());

		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
		reader.loadBeanDefinitions(new ClassPathResource("managedServiceFactory.xml", getClass()));
		appContext.refresh();
	}

	protected void tearDown() throws Exception {
		appContext.close();
		appContext = null;
	}

	public void testBasicParsing() throws Exception {
		Object factory = appContext.getBean("&simple");
		assertTrue(factory instanceof ManagedServiceFactoryFactoryBean);
	}

	public void testBasicExportAttributes() throws Exception {
		Object factory = appContext.getBean("&simple");
		Object intfs = TestUtils.getFieldValue(factory, "interfaces");
		assertTrue(Arrays.equals((Object[]) intfs, new Class[] { Object.class }));
		Object autoExport = TestUtils.getFieldValue(factory, "autoExport");
		assertEquals(AutoExport.ALL_CLASSES, autoExport);
	}

	public void testNestedInterfaceElement() throws Exception {
		Object factory = appContext.getBean("&ccl");
		Object intfs = TestUtils.getFieldValue(factory, "interfaces");
		assertTrue(Arrays.equals((Object[]) intfs, new Class[] { Map.class, Serializable.class }));
	}

	public void testCCLAttribute() throws Exception {
		Object factory = appContext.getBean("&ccl");
		Object ccl = TestUtils.getFieldValue(factory, "ccl");
		assertEquals(ExportContextClassLoader.SERVICE_PROVIDER, ccl);
	}

	public void testContainerUpdateAttr() throws Exception {
		Object factory = appContext.getBean("&container-update");
		Object strategy = TestUtils.getFieldValue(factory, "updateStrategy");
		assertEquals(UpdateStrategy.CONTAINER_MANAGED, strategy);
	}

	public void testBeanManagedUpdateAttr() throws Exception {
		Object factory = appContext.getBean("&bean-update");
		Object strategy = TestUtils.getFieldValue(factory, "updateStrategy");
		Object method = TestUtils.getFieldValue(factory, "updateMethod");
		assertEquals(UpdateStrategy.BEAN_MANAGED, strategy);
		assertEquals("update", method);
	}
}


text:
package jacobi.core.classifier.bayes;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import jacobi.api.Matrices;
import jacobi.api.Matrix;
import jacobi.api.classifier.Column;
import jacobi.api.classifier.DataTable;
import jacobi.core.classifier.Reweightable;
import jacobi.core.classifier.bayes.NominalLikelihoodClassifier.Learner;
import jacobi.core.classifier.cart.util.JacobiEnums.Outlook;
import jacobi.core.classifier.cart.util.JacobiEnums.YesOrNo;
import jacobi.test.annotations.JacobiEquals;
import jacobi.test.annotations.JacobiImport;
import jacobi.test.annotations.JacobiInject;
import jacobi.test.annotations.JacobiResult;
import jacobi.test.util.JacobiDataDef;
import jacobi.test.util.JacobiJUnit4ClassRunner;

@RunWith(JacobiJUnit4ClassRunner.class)
@JacobiImport("/jacobi/test/data/NominalLikelihoodClassifierTest.xlsx")
public class NominalLikelihoodClassifierTest {

	private static final List<Class<?>> ENUMS = Arrays.asList(
		Outlook.class, YesOrNo.class
	);

	private Workbook workbook;

	@JacobiInject(0)
	public Matrix input;

	@JacobiInject(1)
	public Matrix outcome;

	@JacobiInject(2)
	public Matrix weights;

	@JacobiInject(3)
	public Matrix model;

	@JacobiInject(4)
	public Matrix props;

	@JacobiResult(10)
	public Matrix conj;

	@JacobiResult(11)
	public Matrix likelihood;

	@Before
	public void init() throws IOException, EncryptedDocumentException, InvalidFormatException {
		try(InputStream input = this.getClass().getResourceAsStream(
				"/jacobi/test/data/NominalLikelihoodClassifierTest.xlsx")){
			this.workbook = WorkbookFactory.create(input);
		}
	}

	@Test
	@JacobiImport("unweighted outlook and golf")
	@JacobiEquals(expected = 10, actual = 10)
	@JacobiEquals(expected = 11, actual = 11)
	public void shouldBeAbleToCountOutlookAndPlayInGolf() {
		DataTable<YesOrNo> dataTab = new JacobiDataDef(this.workbook, ENUMS)
				.loadDef("unweighted outlook and golf", YesOrNo.class)
				.apply(this.input, this.outcome);

		Column<?> outlookCol = dataTab.getColumns().get(0);

		Learner<YesOrNo> learner = new NominalLikelihoodClassifier.Learner<>(outlookCol);
		Matrix temp = learner.countWeights(dataTab);
		this.conj = Matrices.copy(temp);
		this.likelihood = this.exp(learner.toLnLikelihood(temp));
	}

	@Test
	@JacobiImport("unweighted windy and golf")
	@JacobiEquals(expected = 10, actual = 10)
	@JacobiEquals(expected = 11, actual = 11)
	public void shouldBeAbleToCountWindyAndPlayInGolf() {
		DataTable<YesOrNo> dataTab = new JacobiDataDef(this.workbook, ENUMS)
				.loadDef("unweighted windy and golf", YesOrNo.class)
				.apply(this.input, this.outcome);

		Column<?> windy = dataTab.getColumns().get(3);

		Learner<YesOrNo> learner = new NominalLikelihoodClassifier.Learner<>(windy);
		Matrix temp = learner.countWeights(dataTab);
		this.conj = Matrices.copy(temp);
		this.likelihood = this.exp(learner.toLnLikelihood(temp));
	}

	@Test
	@JacobiImport("weighted outlook and golf")
	@JacobiEquals(expected = 10, actual = 10)
	@JacobiEquals(expected = 11, actual = 11)
	public void shouldBeAbleToCountWeightedOutlookAndPlayInGolf() {
		DataTable<YesOrNo> dataTab = new JacobiDataDef(this.workbook, ENUMS)
				.loadDef("weighted outlook and golf", YesOrNo.class)
				.apply(this.input, this.outcome);

		dataTab = Reweightable.of(dataTab).reweight(
			IntStream.range(0, this.weights.getRowCount()).mapToDouble(i -> this.weights.get(i, 0)).toArray()
		);

		Column<?> outlookCol = dataTab.getColumns().get(0);

		Learner<YesOrNo> learner = new NominalLikelihoodClassifier.Learner<>(outlookCol);
		Matrix temp = learner.countWeights(dataTab);
		this.conj = Matrices.copy(temp);
		this.likelihood = this.exp(learner.toLnLikelihood(temp));
	}

	@Test
	@JacobiImport("outlook model predicts golf")
	public void shouldBeAbleToPredictPlayByOutlookModelUsingArgmax() {
		DataTable<YesOrNo> dataTab = new JacobiDataDef(this.workbook, ENUMS)
				.loadDef("weighted outlook and golf", YesOrNo.class)
				.apply(this.input, this.outcome);

		Column<?> outlookCol = dataTab.getColumns().get(0);
		NominalLikelihoodClassifier<YesOrNo> classifier = new NominalLikelihoodClassifier<>(
			dataTab.getOutcomeColumn(), outlookCol, this.model
		);

		for(int i = 0; i < outlookCol.cardinality(); i++){
			double[] features = new double[dataTab.getMatrix().getColCount()];
			features[outlookCol.getIndex()] = i;
			Assert.assertArrayEquals(this.model.getRow(i),
				classifier.eval(features, dataTab.getOutcomeColumn()), 1e-12);
		}
	}

	@Test
	@JacobiImport("laplace outlook and golf")
	//@JacobiEquals(expected = 10, actual = 10)
	@JacobiEquals(expected = 11, actual = 11)
	public void shouldBeAbleToUseLaplaceSmoothingOnOutlookAgainstGolf() {
		DataTable<YesOrNo> dataTab = new JacobiDataDef(this.workbook, ENUMS)
				.loadDef("laplace outlook and golf", YesOrNo.class)
				.apply(this.input, this.outcome);

		Column<YesOrNo> outCol = dataTab.getOutcomeColumn();
		Column<?> outlookCol = dataTab.getColumns().get(0);

		Learner<YesOrNo> learner = new NominalLikelihoodClassifier.Learner<>(outlookCol);
		NominalLikelihoodClassifier<YesOrNo> classifier = learner.learn(dataTab, this.props.get(0, 0));

		this.likelihood = Matrices.zeros(outlookCol.cardinality(), dataTab.getOutcomeColumn().cardinality());
		for(int i = 0; i < this.likelihood.getRowCount(); i++){
			double[] features = new double[dataTab.getMatrix().getColCount()];
			features[outlookCol.getIndex()] = i;

			this.likelihood.getAndSet(i, r -> {
				double[] lnP = classifier.eval(features, outCol);
				for(int k = 0; k < r.length; k++){
					r[k] = Math.exp(lnP[k]);
				}
			});
		}
	}

	@Test
	@JacobiImport("unweighted windy and golf")
	//@JacobiEquals(expected = 10, actual = 10)
	@JacobiEquals(expected = 11, actual = 11)
	public void shouldBeAbleToUseLaplaceSmoothingOnDemandInOutlookAgainstGolf() {
		DataTable<YesOrNo> dataTab = new JacobiDataDef(this.workbook, ENUMS)
				.loadDef("unweighted windy and golf", YesOrNo.class)
				.apply(this.input, this.outcome);

		Column<?> windy = dataTab.getColumns().get(3);
		Column<YesOrNo> outCol = dataTab.getOutcomeColumn();

		Learner<YesOrNo> learner = new NominalLikelihoodClassifier.Learner<>(windy);
		NominalLikelihoodClassifier<YesOrNo> classifier = learner.learn(dataTab, -0.1);

		this.likelihood = Matrices.zeros(windy.cardinality(), dataTab.getOutcomeColumn().cardinality());
		for(int i = 0; i < this.likelihood.getRowCount(); i++){
			double[] features = new double[dataTab.getMatrix().getColCount()];
			features[windy.getIndex()] = i;

			this.likelihood.getAndSet(i, r -> {
				double[] lnP = classifier.eval(features, outCol);
				for(int k = 0; k < r.length; k++){
					r[k] = Math.exp(lnP[k]);
				}
			});
		}
	}

	@Test
	@JacobiImport("laplace outlook and golf")
	//@JacobiEquals(expected = 10, actual = 10)
	@JacobiEquals(expected = 11, actual = 11)
	public void shouldBeAbleToDisableLaplaceSmoothingOnDemandInOutlookAgainstGolf() {
		DataTable<YesOrNo> dataTab = new JacobiDataDef(this.workbook, ENUMS)
				.loadDef("laplace outlook and golf", YesOrNo.class)
				.apply(this.input, this.outcome);

		Column<YesOrNo> outCol = dataTab.getOutcomeColumn();
		Column<?> outlookCol = dataTab.getColumns().get(0);

		Learner<YesOrNo> learner = new NominalLikelihoodClassifier.Learner<>(outlookCol);
		NominalLikelihoodClassifier<YesOrNo> classifier = learner.learn(dataTab, -this.props.get(0, 0));

		this.likelihood = Matrices.zeros(outlookCol.cardinality(), dataTab.getOutcomeColumn().cardinality());
		for(int i = 0; i < this.likelihood.getRowCount(); i++){
			double[] features = new double[dataTab.getMatrix().getColCount()];
			features[outlookCol.getIndex()] = i;

			this.likelihood.getAndSet(i, r -> {
				double[] lnP = classifier.eval(features, outCol);
				for(int k = 0; k < r.length; k++){
					r[k] = Math.exp(lnP[k]);
				}
			});
		}
	}

	@Test
	@JacobiImport("test mock model")
	public void shouldBeAbleToUseTestMockModel() {
		Column<Integer> featCol = Column.nominal(0, this.model.getRowCount(), v -> (int) v);
		Column<Integer> outCol = Column.nominal(-1, this.model.getColCount(), v -> (int) v);

		NominalLikelihoodClassifier<Integer> classifier = new NominalLikelihoodClassifier<>(outCol, featCol, this.model);
		for(int i = 0; i < featCol.cardinality(); i++){
			double[] feat = new double[]{i};
			int ans = classifier.apply(feat);

			Assert.assertEquals(this.argmax(this.model.getRow(i)), ans);
		}
	}

	protected Matrix exp(Matrix matrix) {
		Matrix result = Matrices.zeros(matrix.getRowCount(), matrix.getColCount());
		for(int i = 0; i < result.getRowCount(); i++){
			double[] lnL = matrix.getRow(i);
			result.getAndSet(i, r -> {
				for(int j = 0; j < r.length; j++){
					r[j] = Math.exp(lnL[j]);
				}
			});
		}
		return result;
	}

	protected int argmax(double[] array) {
		int max = 0;
		for(int i = 1; i < array.length; i++){
			if(array[i] > array[max]){
				max = i;
			}
		}
		return max;
	}

}


text:
ALTER TABLE users
ADD createdate_old VARCHAR(8) NULL ;

update users
set createdate_old = concat(DATEPART(yyyy,createdate),
  RIGHT('00' + CONVERT(NVARCHAR(2), DATEPART(MONTH, createdate)), 2),
  RIGHT('00' + CONVERT(NVARCHAR(2), DATEPART(DAY, createdate)), 2)
);

ALTER TABLE users
  DROP COLUMN createdate;

EXEC sp_RENAME 'users.createdate_old' , 'createdate', 'COLUMN'


text:
import bwapi.{Unit => ScUnit, _}
import bwta.BWTA

object TestBot {
  def main(args: Array[String]) =
    new TestBot().run()
}

class TestBot extends DefaultBWListener {
    val mirror = new Mirror()
    var game: Game = _
    var self: Player = _

    def run(): Unit = {
        mirror.getModule().setEventListener(this)
        mirror.startGame()
    }

    override def onUnitCreate(unit: ScUnit): Unit = {
        System.out.println("New unit " + unit.getType)
    }

    override def onStart(): Unit = {
        game = mirror.getGame
        self = game.self()

        //Use BWTA to analyze map
        //This may take a few minutes if the map is processed first time!
        System.out.println("Analyzing map...")
        BWTA.readMap()
        BWTA.analyze()
        System.out.println("Map data ready")
    }

    override def onFrame(): Unit = {
      //game.setTextSize(10);
      game.drawTextScreen(10, 10, "Playing as " + self.getName + " - " + self.getRace)

      import scala.collection.JavaConverters._

      self.getUnits.asScala
        .filter(_.getType == UnitType.Terran_Command_Center && self.minerals >= 50)
        .foreach(_.train(UnitType.Terran_SCV))

      self.getUnits.asScala
        .filter(_.getType.isWorker)
        .filter(_.isIdle)
        .foreach { worker =>
        val closestMineral = game.neutral.getUnits.asScala
          .filter(_.getType.isMineralField)
          .map(mineral => (mineral.getDistance(worker), mineral))
          .sortBy(_._1)
          .map(_._2)
          .headOption

        closestMineral.foreach(worker.gather)
      }
    }
}


text:
package org.apache.drill.exec.planner.physical;

import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.PathSegment;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.exec.physical.base.PhysicalOperator;
import org.apache.drill.exec.physical.config.FlattenPOP;
import org.apache.drill.exec.planner.common.DrillFilterRelBase;
import org.apache.drill.exec.planner.logical.DrillOptiq;
import org.apache.drill.exec.planner.logical.DrillParseContext;
import org.apache.drill.exec.planner.physical.visitor.PrelVisitor;
import org.apache.drill.exec.record.BatchSchema;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.RelWriter;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rex.RexNode;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class FlattenPrel extends SinglePrel implements Prel {

  RexNode toFlatten;

  public FlattenPrel(RelOptCluster cluster, RelTraitSet traits, RelNode child, RexNode toFlatten) {
    super(cluster, traits, child);
    this.toFlatten = toFlatten;
  }

  @Override
  public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) {
    return new FlattenPrel(getCluster(), traitSet, sole(inputs), toFlatten);
  }

  @Override
  public Iterator<Prel> iterator() {
    return PrelUtil.iter(getInput());
  }

  @Override
  public PhysicalOperator getPhysicalOperator(PhysicalPlanCreator creator) throws IOException {
    Prel child = (Prel) this.getInput();

    PhysicalOperator childPOP = child.getPhysicalOperator(creator);
    FlattenPOP f = new FlattenPOP(childPOP, (SchemaPath) getFlattenExpression(new DrillParseContext(PrelUtil.getSettings(getCluster()))));
    return creator.addMetadata(this, f);
  }

  public RelWriter explainTerms(RelWriter pw) {
    return super.explainTerms(pw).item("flattenField", this.toFlatten);
  }

  @Override
  public BatchSchema.SelectionVectorMode getEncoding() {
    return BatchSchema.SelectionVectorMode.NONE;
  }

  protected LogicalExpression getFlattenExpression(DrillParseContext context){
    return DrillOptiq.toDrill(context, getInput(), toFlatten);
  }
}


text:
Originally published: 2009-06-24 00:16:50
Last updated: 2009-06-25 13:54:34
Author: Mark Muzenhardt

PyGTK is a very powerful GUI-Toolkit. Nearly everything is well documented, except how to print. I messed around for hours just to solve this problem so I decided to share this cool piece of code!


text:
package org.jvnet.jaxb2_commons.plugin.util;

import org.jvnet.jaxb2_commons.plugin.Ignoring;

import com.sun.tools.xjc.outline.FieldOutline;

public class FieldOutlineUtils {

	private FieldOutlineUtils() {

	}

	public static FieldOutline[] filter(final FieldOutline[] fieldOutlines,
			final Ignoring ignoring) {
		return ArrayUtils.filter(fieldOutlines, new Predicate<FieldOutline>() {
			public boolean evaluate(FieldOutline fieldOutline) {
				return !ignoring.isIgnored(fieldOutline);

			}
		}, FieldOutline.class);
	}
}


text:
#include "config.h"

#if USE(ACCELERATED_COMPOSITING)
#include "GraphicsLayerAnimation.h"

#include "UnitBezier.h"
#include <wtf/CurrentTime.h>

namespace WebCore {

static bool shouldReverseAnimationValue(Animation::AnimationDirection direction, int loopCount)
{
    if (((direction == Animation::AnimationDirectionAlternate) && (loopCount & 1))
        || ((direction == Animation::AnimationDirectionAlternateReverse) && !(loopCount & 1))
        || direction == Animation::AnimationDirectionReverse)
        return true;
    return false;
}

static double normalizedAnimationValue(double runningTime, double duration, Animation::AnimationDirection direction, double iterationCount)
{
    if (!duration)
        return 0;

    const int loopCount = runningTime / duration;
    const double lastFullLoop = duration * double(loopCount);
    const double remainder = runningTime - lastFullLoop;
    // Ignore remainder when we've reached the end of animation.
    const double normalized = (loopCount == iterationCount) ? 1.0 : (remainder / duration);

    return shouldReverseAnimationValue(direction, loopCount) ? 1 - normalized : normalized;
}

static double normalizedAnimationValueForFillsForwards(double iterationCount, Animation::AnimationDirection direction)
{
    if (direction == Animation::AnimationDirectionNormal)
        return 1;
    if (direction == Animation::AnimationDirectionReverse)
        return 0;
    return shouldReverseAnimationValue(direction, iterationCount) ? 1 : 0;
}

static float applyOpacityAnimation(float fromOpacity, float toOpacity, double progress)
{
    // Optimization: special case the edge values (0 and 1).
    if (progress == 1.0)
        return toOpacity;

    if (!progress)
        return fromOpacity;

    return fromOpacity + progress * (toOpacity - fromOpacity);
}

static inline double solveEpsilon(double duration)
{
    return 1.0 / (200.0 * duration);
}

static inline double solveCubicBezierFunction(double p1x, double p1y, double p2x, double p2y, double t, double duration)
{
    return UnitBezier(p1x, p1y, p2x, p2y).solve(t, solveEpsilon(duration));
}

static inline double solveStepsFunction(int numSteps, bool stepAtStart, double t)
{
    if (stepAtStart)
        return std::min(1.0, (floor(numSteps * t) + 1) / numSteps);
    return floor(numSteps * t) / numSteps;
}

static inline float applyTimingFunction(const TimingFunction* timingFunction, float progress, double duration)
{
    if (!timingFunction)
        return progress;

    if (timingFunction->isCubicBezierTimingFunction()) {
        const CubicBezierTimingFunction* ctf = static_cast<const CubicBezierTimingFunction*>(timingFunction);
        return solveCubicBezierFunction(ctf->x1(), ctf->y1(), ctf->x2(), ctf->y2(), progress, duration);
    }

    if (timingFunction->isStepsTimingFunction()) {
        const StepsTimingFunction* stf = static_cast<const StepsTimingFunction*>(timingFunction);
        return solveStepsFunction(stf->numberOfSteps(), stf->stepAtStart(), double(progress));
    }

    return progress;
}

static TransformationMatrix applyTransformAnimation(const TransformOperations* from, const TransformOperations* to, double progress, const IntSize& boxSize, bool listsMatch)
{
    TransformationMatrix matrix;

    // First frame of an animation.
    if (!progress) {
        from->apply(boxSize, matrix);
        return matrix;
    }

    // Last frame of an animation.
    if (progress == 1) {
        to->apply(boxSize, matrix);
        return matrix;
    }

    // If we have incompatible operation lists, we blend the resulting matrices.
    if (!listsMatch) {
        TransformationMatrix fromMatrix;
        to->apply(boxSize, matrix);
        from->apply(boxSize, fromMatrix);
        matrix.blend(fromMatrix, progress);
        return matrix;
    }

    // Animation to "-webkit-transform: none".
    if (!to->size()) {
        TransformOperations blended(*from);
        for (size_t i = 0; i < blended.operations().size(); ++i)
            blended.operations()[i]->blend(0, progress, true)->apply(matrix, boxSize);
        return matrix;
    }

    // Animation from "-webkit-transform: none".
    if (!from->size()) {
        TransformOperations blended(*to);
        for (size_t i = 0; i < blended.operations().size(); ++i)
            blended.operations()[i]->blend(0, 1. - progress, true)->apply(matrix, boxSize);
        return matrix;
    }

    // Normal animation with a matching operation list.
    TransformOperations blended(*to);
    for (size_t i = 0; i < blended.operations().size(); ++i)
        blended.operations()[i]->blend(from->at(i), progress, !from->at(i))->apply(matrix, boxSize);
    return matrix;
}

GraphicsLayerAnimation::GraphicsLayerAnimation(const String& name, const KeyframeValueList& keyframes, const IntSize& boxSize, const Animation* animation, double timeOffset, bool listsMatch)
    : m_keyframes(keyframes)
    , m_boxSize(boxSize)
    , m_animation(Animation::create(animation))
    , m_name(name)
    , m_listsMatch(listsMatch)
    , m_startTime(WTF::currentTime() - timeOffset)
    , m_pauseTime(0)
    , m_state(PlayingState)
{
}

void GraphicsLayerAnimation::applyInternal(Client* client, const AnimationValue* from, const AnimationValue* to, float progress)
{
    switch (m_keyframes.property()) {
    case AnimatedPropertyOpacity:
        client->setAnimatedOpacity(applyOpacityAnimation((static_cast<const FloatAnimationValue*>(from)->value()), (static_cast<const FloatAnimationValue*>(to)->value()), progress));
        return;
    case AnimatedPropertyWebkitTransform:
        client->setAnimatedTransform(applyTransformAnimation(static_cast<const TransformAnimationValue*>(from)->value(), static_cast<const TransformAnimationValue*>(to)->value(), progress, m_boxSize, m_listsMatch));
        return;
    default:
        ASSERT_NOT_REACHED();
    }
}

bool GraphicsLayerAnimation::isActive() const
{
    if (state() != StoppedState)
        return true;

    return m_animation->fillsForwards();
}

bool GraphicsLayerAnimations::hasActiveAnimationsOfType(AnimatedPropertyID type) const
{
    for (size_t i = 0; i < m_animations.size(); ++i) {
        if (m_animations[i].isActive() && m_animations[i].property() == type)
            return true;
    }
    return false;
}

bool GraphicsLayerAnimations::hasRunningAnimations() const
{
    for (size_t i = 0; i < m_animations.size(); ++i) {
        if (m_animations[i].state() == GraphicsLayerAnimation::PlayingState)
            return true;
    }

    return false;
}

void GraphicsLayerAnimation::apply(Client* client)
{
    if (!isActive())
        return;

    double totalRunningTime = m_state == PausedState ? m_pauseTime : WTF::currentTime() - m_startTime;
    double normalizedValue = normalizedAnimationValue(totalRunningTime, m_animation->duration(), m_animation->direction(), m_animation->iterationCount());

    if (m_animation->iterationCount() != Animation::IterationCountInfinite && totalRunningTime >= m_animation->duration() * m_animation->iterationCount()) {
        setState(StoppedState);
        if (m_animation->fillsForwards())
            normalizedValue = normalizedAnimationValueForFillsForwards(m_animation->iterationCount(), m_animation->direction());
    }

    if (!normalizedValue) {
        applyInternal(client, m_keyframes.at(0), m_keyframes.at(1), 0);
        return;
    }

    if (normalizedValue == 1.0) {
        applyInternal(client, m_keyframes.at(m_keyframes.size() - 2), m_keyframes.at(m_keyframes.size() - 1), 1);
        return;
    }
    if (m_keyframes.size() == 2) {
        normalizedValue = applyTimingFunction(m_animation->timingFunction().get(), normalizedValue, m_animation->duration());
        applyInternal(client, m_keyframes.at(0), m_keyframes.at(1), normalizedValue);
        return;
    }

    for (size_t i = 0; i < m_keyframes.size() - 1; ++i) {
        const AnimationValue* from = m_keyframes.at(i);
        const AnimationValue* to = m_keyframes.at(i + 1);
        if (from->keyTime() > normalizedValue || to->keyTime() < normalizedValue)
            continue;

        normalizedValue = (normalizedValue - from->keyTime()) / (to->keyTime() - from->keyTime());
        normalizedValue = applyTimingFunction(from->timingFunction(), normalizedValue, m_animation->duration());
        applyInternal(client, from, to, normalizedValue);
        break;
    }
}

void GraphicsLayerAnimation::pause(double offset)
{
    // FIXME: should apply offset here.
    setState(PausedState);
    m_pauseTime = WTF::currentTime() - offset;
}

void GraphicsLayerAnimations::add(const GraphicsLayerAnimation& animation)
{
    m_animations.append(animation);
}

void GraphicsLayerAnimations::pause(const String& name, double offset)
{
    for (size_t i = 0; i < m_animations.size(); ++i) {
        if (m_animations[i].name() == name)
            m_animations[i].pause(offset);
    }
}

void GraphicsLayerAnimations::remove(const String& name)
{
    for (int i = m_animations.size() - 1; i >= 0; --i) {
        if (m_animations[i].name() == name)
            m_animations.remove(i);
    }
}

void GraphicsLayerAnimations::apply(GraphicsLayerAnimation::Client* client)
{
    for (size_t i = 0; i < m_animations.size(); ++i)
        m_animations[i].apply(client);
}

}
#endif


text:
<?php

//This class exists in the Model namespace
namespace Model;

//Import the DB class and the Auth package
use DB;
use Auth;

/**
 * Represent the books table
 * This class is a Model
 * @Author Luis Miguel Mejía Suárez (BalmungSan)
 */
class BookModel extends \Model {
  /**
   * Get a Book
   * @param bookid the id of the book to get
   * @return a BoookDTO with all the data of the book
   * @see BookDTO
   */
  public static function getBook($bookid) {
    //get the data of the book
    $data = DB::select()->from('books')->join('categories')->on('books.category_id', '=', 'categories.category_id')->where('book_id', '=', $bookid)->execute();

    //save the data in new bookDTO
    $book = new BookDTO();
    $book->setId($data->get('book_id'));
    $book->setUser($data->get('user_id'));
    $book->setName($data->get('name'));
    $book->setAuthor($data->get('author'));
    $book->setIsNew($data->get('is_new'));
    $book->setCategory($data->get('category'));
    $book->setPrice($data->get('price'));
    $book->setPreview($data->get('preview'));
    $book->setUnits($data->get('units'));

    return $book;
  }

  /**
   * Create a new book in the database
   * @param book a BookDTO with all the data of the book
   * @return true on success false on failure
   * @note this function sets the id for the new book if succeed
   * @see BookDTO
   */
  public static function registerBook($book) {
    //get the category id for the book's category
    $category = DB::select('category_id')->from('categories')->where('category', '=', $book->getCategory())->execute();

    //prepare the columns an values
    $colums = array(
      'user_id',
      'name',
      'author',
      'is_new',
      'category_id',
      'price',
      'preview',
      'units'
    );

    $values = array(
      $book->getUser(),
      $book->getName(),
      $book->getAuthor(),
      $book->getIsNew(),
      $category->get('category_id'),
      $book->getPrice(),
      $book->getPreview(),
      $book->getUnits()
    );

    //insert the book
    $result = DB::insert('books')->columns($colums)->values($values)->execute();

    //check if the insert succeed
    if ($result[1] == 1) {
      $book->setId($result[0]);
      return true;
    } else {
      return false;
    }
  }

  /**
   * Update a book data
   * @param book a BookDTO with the id of the book to update and the modified data
   * @return true if at least one field is changed, else false
   * @see BookDTO
   */
  public static function updateBook($book) {
    //get the category id for the book's category
    $category = DB::select('category_id')->from('categories')->where('category', '=', $book->getCategory())->execute();

    //prepare the columns an values
    $set = array(
      'name' => $book->getName(),
      'author' => $book->getAuthor(),
      'is_new' => $book->getIsNew(),
      'category_id' => $category->get('category_id'),
      'price' => $book->getPrice(),
      'preview' => $book->getPreview(),
      'units' => $book->getUnits()
    );

    //update the data
    return DB::update('books')->set($set)->where('book_id', '=', $book->getId())->execute() == 1;
  }

  /**
   * Drop a book from the database
   * @param book the id of the book to delete
   * @return true on success false on failure
   */
  public static function deleteBook($book) {
    //delete the book
    return DB::delete('books')->where('book_id', '=', $book)->execute() == 1;
  }

  /**
   * Transform a result set into a collection of Books
   * @param array the result set as an array of arrays
   * @return an array of BookDTO
   * @see BookDTO
   */
  private static function toBooks($array) {
    $books = array();
    foreach ($array as $book) {
      $data    = array();
      $data[]  = $book['book_id'];
      $data[]  = $book['user_id'];
      $data[]  = $book['name'];
      $data[]  = $book['author'];
      $data[]  = $book['is_new'];
      $data[]  = $book['category'];
      $data[]  = $book['price'];
      $data[]  = $book['preview'];
      $data[]  = $book['units'];
      $books[] = (new BookDTO())->fill($data);
    }

    return $books;
  }

  /**
   * Get all books of the current user
   * @return an array of BookDTO with all books
   * @note this function uses the Auth package from FuelPHP
   * @see Auth
   * @see BookDTO
   * @see self::getBooksByUser($userId)
   */
  public static function getUserBooks() {
    return self::getBooksByUser(Auth::instance()->get_user_id()[1]);
  }

  /**
   * Get all books of a user
   * @param user the id of the user
   * @return an array of BookDTO with all books
   * @see BookDTO
   * @see self::toBooks
   */
  public static function getBooksByUser($user) {
    return self::toBooks(DB::select()->from('books')->join('categories')->on('books.category_id', '=', 'categories.category_id')->where('user_id', '=', $user)->execute());
  }

  /**
   * Get all books in the database
   * @return an array of BookDTO
   * @see BookDTO
   * @see self::toBooks
   */
  public static function getAll() {
    return self::toBooks(DB::select()->from('books')->join('categories')->on('books.category_id', '=', 'categories.category_id')->execute());
  }

  /**
   * Search books by category
   * @param category the category to search for
   * @return an array of books that conform to the search
   * @see BookDTO
   * @see self::toBooks
   */
  public static function searchByCategory($category) {
    //get the category id
    $categoryid = DB::select('category_id')->from('categories')->where('category', '=', $category)->execute()->get('category_id');

    //get all books with that category
    $result = DB::select()->from('books')->join('categories')->on('books.category_id', '=', 'categories.category_id')->where('books.category_id', '=', $categoryid)->execute();

    //transform the result set into an array of BookDTO
    return self::toBooks($result);
  }

  /**
   * Search books by name
   * @param name the pattern to search for in names
   * @return an array of books that conform to the search
   * @see BookDTO
   * @see self::toBooks
   */
  public static function searchByName($name) {
    //prepare the pattern
    $pattern = '%' . str_replace(' ', '%', $name) . '%';

    //get all books with that pattern in their names
    $result = DB::select()->from('books')->join('categories')->on('books.category_id', '=', 'categories.category_id')->where('name', 'like', $pattern)->execute();

    //transform the result set into an array of BookDTO
    return self::toBooks($result);
  }

  /**
   * Search books by author
   * @param author the pattern to search for in author
   * @return an array of books that conform to the search
   * @see BookDTO
   * @see self::toBooks
   */
  public static function searchByAuthor($author) {
    //prepare the pattern
    $pattern = '%' . str_replace(' ', '%', $author) . '%';

    //get all books with that pattern in their author
    $result = DB::select()->from('books')->join('categories')->on('books.category_id', '=', 'categories.category_id')->where('author', 'like', $pattern)->execute();

    //transform the result set into an array of BookDTO
    return self::toBooks($result);
  }

  /**
   * Search books by price
   * @param lower the minimum price (0 means any)
   * @param upper the maximun price (0 means any)
   * @return an array of books that conform to the search
   * @see BookDTO
   * @see self::toBooks
   */
  public static function searchByPrice($lower, $upper) {
    //prepare the query
    $query = DB::select()->from('books')->join('categories')->on('books.category_id', '=', 'categories.category_id');

    //add the lower bound
    if ($lower > 0) $query = $query->where('price', '>=', $lower);

    //add the upper bound
    if ($upper > 0 && $upper >= $lower) $query = $query->where('price', '<=', $upper);

    //get the books
    $result = $query->execute();

    //transform the result set into an array of BookDTO
    return self::toBooks($result);
  }

  /**
   * Get all categories saved in the database
   * @return an array with the categories
   */
  public static function getCategories() {
    $result = DB::select('category')->from('categories')->execute();
    $categories = array();
    foreach ($result as $r) $categories[] = $r['category'];
    return $categories;
  }
}
?>


text:
package memorymanager

import (
	"fmt"
	"reflect"
	"sort"

	cadvisorapi "github.com/google/cadvisor/info/v1"

	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	"k8s.io/klog/v2"
	corehelper "k8s.io/kubernetes/pkg/apis/core/v1/helper"
	v1qos "k8s.io/kubernetes/pkg/apis/core/v1/helper/qos"
	"k8s.io/kubernetes/pkg/kubelet/cm/memorymanager/state"
	"k8s.io/kubernetes/pkg/kubelet/cm/topologymanager"
	"k8s.io/kubernetes/pkg/kubelet/cm/topologymanager/bitmask"
)

const policyTypeStatic policyType = "Static"

type systemReservedMemory map[int]map[v1.ResourceName]uint64
type reusableMemory map[string]map[string]map[v1.ResourceName]uint64

// staticPolicy is implementation of the policy interface for the static policy
type staticPolicy struct {
	// machineInfo contains machine memory related information
	machineInfo *cadvisorapi.MachineInfo
	// reserved contains memory that reserved for kube
	systemReserved systemReservedMemory
	// topology manager reference to get container Topology affinity
	affinity topologymanager.Store
	// initContainersReusableMemory contains the memory allocated for init containers that can be reused
	initContainersReusableMemory reusableMemory
}

var _ Policy = &staticPolicy{}

// NewPolicyStatic returns new static policy instance
func NewPolicyStatic(machineInfo *cadvisorapi.MachineInfo, reserved systemReservedMemory, affinity topologymanager.Store) (Policy, error) {
	var totalSystemReserved uint64
	for _, node := range reserved {
		if _, ok := node[v1.ResourceMemory]; !ok {
			continue
		}
		totalSystemReserved += node[v1.ResourceMemory]
	}

	// check if we have some reserved memory for the system
	if totalSystemReserved <= 0 {
		return nil, fmt.Errorf("[memorymanager] you should specify the system reserved memory")
	}

	return &staticPolicy{
		machineInfo:                  machineInfo,
		systemReserved:               reserved,
		affinity:                     affinity,
		initContainersReusableMemory: reusableMemory{},
	}, nil
}

func (p *staticPolicy) Name() string {
	return string(policyTypeStatic)
}

func (p *staticPolicy) Start(s state.State) error {
	if err := p.validateState(s); err != nil {
		klog.ErrorS(err, "Invalid state, please drain node and remove policy state file")
		return err
	}
	return nil
}

// Allocate call is idempotent
func (p *staticPolicy) Allocate(s state.State, pod *v1.Pod, container *v1.Container) error {
	// allocate the memory only for guaranteed pods
	if v1qos.GetPodQOS(pod) != v1.PodQOSGuaranteed {
		return nil
	}

	podUID := string(pod.UID)
	klog.InfoS("Allocate", "pod", klog.KObj(pod), "containerName", container.Name)
	if blocks := s.GetMemoryBlocks(podUID, container.Name); blocks != nil {
		p.updatePodReusableMemory(pod, container, blocks)

		klog.InfoS("Container already present in state, skipping", "pod", klog.KObj(pod), "containerName", container.Name)
		return nil
	}

	// Call Topology Manager to get the aligned affinity across all hint providers.
	hint := p.affinity.GetAffinity(podUID, container.Name)
	klog.InfoS("Got topology affinity", "pod", klog.KObj(pod), "podUID", pod.UID, "containerName", container.Name, "hint", hint)

	requestedResources, err := getRequestedResources(container)
	if err != nil {
		return err
	}

	machineState := s.GetMachineState()
	bestHint := &hint
	// topology manager returned the hint with NUMA affinity nil
	// we should use the default NUMA affinity calculated the same way as for the topology manager
	if hint.NUMANodeAffinity == nil {
		defaultHint, err := p.getDefaultHint(machineState, pod, requestedResources)
		if err != nil {
			return err
		}

		if !defaultHint.Preferred && bestHint.Preferred {
			return fmt.Errorf("[memorymanager] failed to find the default preferred hint")
		}
		bestHint = defaultHint
	}

	// topology manager returns the hint that does not satisfy completely the container request
	// we should extend this hint to the one who will satisfy the request and include the current hint
	if !isAffinitySatisfyRequest(machineState, bestHint.NUMANodeAffinity, requestedResources) {
		extendedHint, err := p.extendTopologyManagerHint(machineState, pod, requestedResources, bestHint.NUMANodeAffinity)
		if err != nil {
			return err
		}

		if !extendedHint.Preferred && bestHint.Preferred {
			return fmt.Errorf("[memorymanager] failed to find the extended preferred hint")
		}
		bestHint = extendedHint
	}

	var containerBlocks []state.Block
	maskBits := bestHint.NUMANodeAffinity.GetBits()
	for resourceName, requestedSize := range requestedResources {
		// update memory blocks
		containerBlocks = append(containerBlocks, state.Block{
			NUMAAffinity: maskBits,
			Size:         requestedSize,
			Type:         resourceName,
		})

		podReusableMemory := p.getPodReusableMemory(pod, bestHint.NUMANodeAffinity, resourceName)
		if podReusableMemory >= requestedSize {
			requestedSize = 0
		} else {
			requestedSize -= podReusableMemory
		}

		// Update nodes memory state
		p.updateMachineState(machineState, maskBits, resourceName, requestedSize)
	}

	p.updatePodReusableMemory(pod, container, containerBlocks)

	s.SetMachineState(machineState)
	s.SetMemoryBlocks(podUID, container.Name, containerBlocks)

	// update init containers memory blocks to reflect the fact that we re-used init containers memory
	// it is possible that the size of the init container memory block will have 0 value, when all memory
	// allocated for it was re-used
	// we only do this so that the sum(memory_for_all_containers) == total amount of allocated memory to the pod, even
	// though the final state here doesn't accurately reflect what was (in reality) allocated to each container
	// TODO: we should refactor our state structs to reflect the amount of the re-used memory
	p.updateInitContainersMemoryBlocks(s, pod, container, containerBlocks)

	return nil
}

func (p *staticPolicy) updateMachineState(machineState state.NUMANodeMap, numaAffinity []int, resourceName v1.ResourceName, requestedSize uint64) {
	for _, nodeID := range numaAffinity {
		machineState[nodeID].NumberOfAssignments++
		machineState[nodeID].Cells = numaAffinity

		// we need to continue to update all affinity mask nodes
		if requestedSize == 0 {
			continue
		}

		// update the node memory state
		nodeResourceMemoryState := machineState[nodeID].MemoryMap[resourceName]
		if nodeResourceMemoryState.Free <= 0 {
			continue
		}

		// the node has enough memory to satisfy the request
		if nodeResourceMemoryState.Free >= requestedSize {
			nodeResourceMemoryState.Reserved += requestedSize
			nodeResourceMemoryState.Free -= requestedSize
			requestedSize = 0
			continue
		}

		// the node does not have enough memory, use the node remaining memory and move to the next node
		requestedSize -= nodeResourceMemoryState.Free
		nodeResourceMemoryState.Reserved += nodeResourceMemoryState.Free
		nodeResourceMemoryState.Free = 0
	}
}

func (p *staticPolicy) getPodReusableMemory(pod *v1.Pod, numaAffinity bitmask.BitMask, resourceName v1.ResourceName) uint64 {
	podReusableMemory, ok := p.initContainersReusableMemory[string(pod.UID)]
	if !ok {
		return 0
	}

	numaReusableMemory, ok := podReusableMemory[numaAffinity.String()]
	if !ok {
		return 0
	}

	return numaReusableMemory[resourceName]
}

// RemoveContainer call is idempotent
func (p *staticPolicy) RemoveContainer(s state.State, podUID string, containerName string) {
	blocks := s.GetMemoryBlocks(podUID, containerName)
	if blocks == nil {
		return
	}

	klog.InfoS("RemoveContainer", "podUID", podUID, "containerName", containerName)
	s.Delete(podUID, containerName)

	// Mutate machine memory state to update free and reserved memory
	machineState := s.GetMachineState()
	for _, b := range blocks {
		releasedSize := b.Size
		for _, nodeID := range b.NUMAAffinity {
			machineState[nodeID].NumberOfAssignments--

			// once we do not have any memory allocations on this node, clear node groups
			if machineState[nodeID].NumberOfAssignments == 0 {
				machineState[nodeID].Cells = []int{nodeID}
			}

			// we still need to pass over all NUMA node under the affinity mask to update them
			if releasedSize == 0 {
				continue
			}

			nodeResourceMemoryState := machineState[nodeID].MemoryMap[b.Type]

			// if the node does not have reserved memory to free, continue to the next node
			if nodeResourceMemoryState.Reserved == 0 {
				continue
			}

			// the reserved memory smaller than the amount of the memory that should be released
			// release as much as possible and move to the next node
			if nodeResourceMemoryState.Reserved < releasedSize {
				releasedSize -= nodeResourceMemoryState.Reserved
				nodeResourceMemoryState.Free += nodeResourceMemoryState.Reserved
				nodeResourceMemoryState.Reserved = 0
				continue
			}

			// the reserved memory big enough to satisfy the released memory
			nodeResourceMemoryState.Free += releasedSize
			nodeResourceMemoryState.Reserved -= releasedSize
			releasedSize = 0
		}
	}

	s.SetMachineState(machineState)
}

func regenerateHints(pod *v1.Pod, ctn *v1.Container, ctnBlocks []state.Block, reqRsrc map[v1.ResourceName]uint64) map[string][]topologymanager.TopologyHint {
	hints := map[string][]topologymanager.TopologyHint{}
	for resourceName := range reqRsrc {
		hints[string(resourceName)] = []topologymanager.TopologyHint{}
	}

	if len(ctnBlocks) != len(reqRsrc) {
		klog.ErrorS(nil, "The number of requested resources by the container differs from the number of memory blocks", "containerName", ctn.Name)
		return nil
	}

	for _, b := range ctnBlocks {
		if _, ok := reqRsrc[b.Type]; !ok {
			klog.ErrorS(nil, "Container requested resources do not have resource of this type", "containerName", ctn.Name, "type", b.Type)
			return nil
		}

		if b.Size != reqRsrc[b.Type] {
			klog.ErrorS(nil, "Memory already allocated with different numbers than requested", "podUID", pod.UID, "type", b.Type, "containerName", ctn.Name, "requestedResource", reqRsrc[b.Type], "allocatedSize", b.Size)
			return nil
		}

		containerNUMAAffinity, err := bitmask.NewBitMask(b.NUMAAffinity...)
		if err != nil {
			klog.ErrorS(err, "Failed to generate NUMA bitmask")
			return nil
		}

		klog.InfoS("Regenerating TopologyHints, resource was already allocated to pod", "resourceName", b.Type, "pod", klog.KObj(pod), "podUID", pod.UID, "containerName", ctn.Name)
		hints[string(b.Type)] = append(hints[string(b.Type)], topologymanager.TopologyHint{
			NUMANodeAffinity: containerNUMAAffinity,
			Preferred:        true,
		})
	}
	return hints
}

func getPodRequestedResources(pod *v1.Pod) (map[v1.ResourceName]uint64, error) {
	reqRsrcsByInitCtrs := make(map[v1.ResourceName]uint64)
	reqRsrcsByAppCtrs := make(map[v1.ResourceName]uint64)

	for _, ctr := range pod.Spec.InitContainers {
		reqRsrcs, err := getRequestedResources(&ctr)

		if err != nil {
			return nil, err
		}
		for rsrcName, qty := range reqRsrcs {
			if _, ok := reqRsrcsByInitCtrs[rsrcName]; !ok {
				reqRsrcsByInitCtrs[rsrcName] = uint64(0)
			}

			if reqRsrcs[rsrcName] > reqRsrcsByInitCtrs[rsrcName] {
				reqRsrcsByInitCtrs[rsrcName] = qty
			}
		}
	}

	for _, ctr := range pod.Spec.Containers {
		reqRsrcs, err := getRequestedResources(&ctr)

		if err != nil {
			return nil, err
		}
		for rsrcName, qty := range reqRsrcs {
			if _, ok := reqRsrcsByAppCtrs[rsrcName]; !ok {
				reqRsrcsByAppCtrs[rsrcName] = uint64(0)
			}

			reqRsrcsByAppCtrs[rsrcName] += qty
		}
	}

	for rsrcName := range reqRsrcsByAppCtrs {
		if reqRsrcsByInitCtrs[rsrcName] > reqRsrcsByAppCtrs[rsrcName] {
			reqRsrcsByAppCtrs[rsrcName] = reqRsrcsByInitCtrs[rsrcName]
		}
	}
	return reqRsrcsByAppCtrs, nil
}

func (p *staticPolicy) GetPodTopologyHints(s state.State, pod *v1.Pod) map[string][]topologymanager.TopologyHint {
	if v1qos.GetPodQOS(pod) != v1.PodQOSGuaranteed {
		return nil
	}

	reqRsrcs, err := getPodRequestedResources(pod)
	if err != nil {
		klog.ErrorS(err, "Failed to get pod requested resources", "pod", klog.KObj(pod), "podUID", pod.UID)
		return nil
	}

	for _, ctn := range append(pod.Spec.InitContainers, pod.Spec.Containers...) {
		containerBlocks := s.GetMemoryBlocks(string(pod.UID), ctn.Name)
		// Short circuit to regenerate the same hints if there are already
		// memory allocated for the container. This might happen after a
		// kubelet restart, for example.
		if containerBlocks != nil {
			return regenerateHints(pod, &ctn, containerBlocks, reqRsrcs)
		}
	}

	// the pod topology hints calculated only once for all containers, so no need to pass re-usable state
	return p.calculateHints(s.GetMachineState(), pod, reqRsrcs)
}

// GetTopologyHints implements the topologymanager.HintProvider Interface
// and is consulted to achieve NUMA aware resource alignment among this
// and other resource controllers.
func (p *staticPolicy) GetTopologyHints(s state.State, pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint {
	if v1qos.GetPodQOS(pod) != v1.PodQOSGuaranteed {
		return nil
	}

	requestedResources, err := getRequestedResources(container)
	if err != nil {
		klog.ErrorS(err, "Failed to get container requested resources", "pod", klog.KObj(pod), "podUID", pod.UID, "containerName", container.Name)
		return nil
	}

	containerBlocks := s.GetMemoryBlocks(string(pod.UID), container.Name)
	// Short circuit to regenerate the same hints if there are already
	// memory allocated for the container. This might happen after a
	// kubelet restart, for example.
	if containerBlocks != nil {
		return regenerateHints(pod, container, containerBlocks, requestedResources)
	}

	return p.calculateHints(s.GetMachineState(), pod, requestedResources)
}

func getRequestedResources(container *v1.Container) (map[v1.ResourceName]uint64, error) {
	requestedResources := map[v1.ResourceName]uint64{}
	for resourceName, quantity := range container.Resources.Requests {
		if resourceName != v1.ResourceMemory && !corehelper.IsHugePageResourceName(resourceName) {
			continue
		}
		requestedSize, succeed := quantity.AsInt64()
		if !succeed {
			return nil, fmt.Errorf("[memorymanager] failed to represent quantity as int64")
		}
		requestedResources[resourceName] = uint64(requestedSize)
	}
	return requestedResources, nil
}

func (p *staticPolicy) calculateHints(machineState state.NUMANodeMap, pod *v1.Pod, requestedResources map[v1.ResourceName]uint64) map[string][]topologymanager.TopologyHint {
	var numaNodes []int
	for n := range machineState {
		numaNodes = append(numaNodes, n)
	}
	sort.Ints(numaNodes)

	// Initialize minAffinitySize to include all NUMA Cells.
	minAffinitySize := len(numaNodes)

	hints := map[string][]topologymanager.TopologyHint{}
	bitmask.IterateBitMasks(numaNodes, func(mask bitmask.BitMask) {
		maskBits := mask.GetBits()
		singleNUMAHint := len(maskBits) == 1

		totalFreeSize := map[v1.ResourceName]uint64{}
		totalAllocatableSize := map[v1.ResourceName]uint64{}
		// calculate total free and allocatable memory for the node mask
		for _, nodeID := range maskBits {
			for resourceName := range requestedResources {
				if _, ok := totalFreeSize[resourceName]; !ok {
					totalFreeSize[resourceName] = 0
				}
				totalFreeSize[resourceName] += machineState[nodeID].MemoryMap[resourceName].Free

				if _, ok := totalAllocatableSize[resourceName]; !ok {
					totalAllocatableSize[resourceName] = 0
				}
				totalAllocatableSize[resourceName] += machineState[nodeID].MemoryMap[resourceName].Allocatable
			}
		}

		// verify that for all memory types the node mask has enough allocatable resources
		for resourceName, requestedSize := range requestedResources {
			if totalAllocatableSize[resourceName] < requestedSize {
				return
			}
		}

		// set the minimum amount of NUMA nodes that can satisfy the container resources requests
		if mask.Count() < minAffinitySize {
			minAffinitySize = mask.Count()
		}

		// the node already in group with another node, it can not be used for the single NUMA node allocation
		if singleNUMAHint && len(machineState[maskBits[0]].Cells) > 1 {
			return
		}

		for _, nodeID := range maskBits {
			// the node already used for the memory allocation
			if !singleNUMAHint && machineState[nodeID].NumberOfAssignments > 0 {
				// the node used for the single NUMA memory allocation, it can not be used for the multi NUMA node allocation
				if len(machineState[nodeID].Cells) == 1 {
					return
				}

				// the node already used with different group of nodes, it can not be use with in the current hint
				if !areGroupsEqual(machineState[nodeID].Cells, maskBits) {
					return
				}
			}
		}

		// verify that for all memory types the node mask has enough free resources
		for resourceName, requestedSize := range requestedResources {
			podReusableMemory := p.getPodReusableMemory(pod, mask, resourceName)
			if totalFreeSize[resourceName]+podReusableMemory < requestedSize {
				return
			}
		}

		// add the node mask as topology hint for all memory types
		for resourceName := range requestedResources {
			if _, ok := hints[string(resourceName)]; !ok {
				hints[string(resourceName)] = []topologymanager.TopologyHint{}
			}
			hints[string(resourceName)] = append(hints[string(resourceName)], topologymanager.TopologyHint{
				NUMANodeAffinity: mask,
				Preferred:        false,
			})
		}
	})

	// update hints preferred according to multiNUMAGroups, in case when it wasn't provided, the default
	// behaviour to prefer the minimal amount of NUMA nodes will be used
	for resourceName := range requestedResources {
		for i, hint := range hints[string(resourceName)] {
			hints[string(resourceName)][i].Preferred = p.isHintPreferred(hint.NUMANodeAffinity.GetBits(), minAffinitySize)
		}
	}

	return hints
}

func (p *staticPolicy) isHintPreferred(maskBits []int, minAffinitySize int) bool {
	return len(maskBits) == minAffinitySize
}

func areGroupsEqual(group1, group2 []int) bool {
	sort.Ints(group1)
	sort.Ints(group2)

	if len(group1) != len(group2) {
		return false
	}

	for i, elm := range group1 {
		if group2[i] != elm {
			return false
		}
	}
	return true
}

func (p *staticPolicy) validateState(s state.State) error {
	machineState := s.GetMachineState()
	memoryAssignments := s.GetMemoryAssignments()

	if len(machineState) == 0 {
		// Machine state cannot be empty when assignments exist
		if len(memoryAssignments) != 0 {
			return fmt.Errorf("[memorymanager] machine state can not be empty when it has memory assignments")
		}

		defaultMachineState := p.getDefaultMachineState()
		s.SetMachineState(defaultMachineState)

		return nil
	}

	// calculate all memory assigned to containers
	expectedMachineState := p.getDefaultMachineState()
	for pod, container := range memoryAssignments {
		for containerName, blocks := range container {
			for _, b := range blocks {
				requestedSize := b.Size
				for _, nodeID := range b.NUMAAffinity {
					nodeState, ok := expectedMachineState[nodeID]
					if !ok {
						return fmt.Errorf("[memorymanager] (pod: %s, container: %s) the memory assignment uses the NUMA that does not exist", pod, containerName)
					}

					nodeState.NumberOfAssignments++
					nodeState.Cells = b.NUMAAffinity

					memoryState, ok := nodeState.MemoryMap[b.Type]
					if !ok {
						return fmt.Errorf("[memorymanager] (pod: %s, container: %s) the memory assignment uses memory resource that does not exist", pod, containerName)
					}

					if requestedSize == 0 {
						continue
					}

					// this node does not have enough memory continue to the next one
					if memoryState.Free <= 0 {
						continue
					}

					// the node has enough memory to satisfy the request
					if memoryState.Free >= requestedSize {
						memoryState.Reserved += requestedSize
						memoryState.Free -= requestedSize
						requestedSize = 0
						continue
					}

					// the node does not have enough memory, use the node remaining memory and move to the next node
					requestedSize -= memoryState.Free
					memoryState.Reserved += memoryState.Free
					memoryState.Free = 0
				}
			}
		}
	}

	// State has already been initialized from file (is not empty)
	// Validate that total size, system reserved and reserved memory not changed, it can happen, when:
	// - adding or removing physical memory bank from the node
	// - change of kubelet system-reserved, kube-reserved or pre-reserved-memory-zone parameters
	if !areMachineStatesEqual(machineState, expectedMachineState) {
		return fmt.Errorf("[memorymanager] the expected machine state is different from the real one")
	}

	return nil
}

func areMachineStatesEqual(ms1, ms2 state.NUMANodeMap) bool {
	if len(ms1) != len(ms2) {
		klog.ErrorS(nil, "Node states are different", "lengthNode1", len(ms1), "lengthNode2", len(ms2))
		return false
	}

	for nodeID, nodeState1 := range ms1 {
		nodeState2, ok := ms2[nodeID]
		if !ok {
			klog.ErrorS(nil, "Node state does not have node ID", "nodeID", nodeID)
			return false
		}

		if nodeState1.NumberOfAssignments != nodeState2.NumberOfAssignments {
			klog.ErrorS(nil, "Node states number of assignments are different", "assignment1", nodeState1.NumberOfAssignments, "assignment2", nodeState2.NumberOfAssignments)
			return false
		}

		if !areGroupsEqual(nodeState1.Cells, nodeState2.Cells) {
			klog.ErrorS(nil, "Node states groups are different", "stateNode1", nodeState1.Cells, "stateNode2", nodeState2.Cells)
			return false
		}

		if len(nodeState1.MemoryMap) != len(nodeState2.MemoryMap) {
			klog.ErrorS(nil, "Node states memory map have different lengths", "lengthNode1", len(nodeState1.MemoryMap), "lengthNode2", len(nodeState2.MemoryMap))
			return false
		}

		for resourceName, memoryState1 := range nodeState1.MemoryMap {
			memoryState2, ok := nodeState2.MemoryMap[resourceName]
			if !ok {
				klog.ErrorS(nil, "Memory state does not have resource", "resource", resourceName)
				return false
			}

			if !reflect.DeepEqual(*memoryState1, *memoryState2) {
				klog.ErrorS(nil, "Memory states for the NUMA node and resource are different", "node", nodeID, "resource", resourceName, "memoryState1", *memoryState1, "memoryState2", *memoryState2)
				return false
			}
		}
	}
	return true
}

func (p *staticPolicy) getDefaultMachineState() state.NUMANodeMap {
	defaultMachineState := state.NUMANodeMap{}
	nodeHugepages := map[int]uint64{}
	for _, node := range p.machineInfo.Topology {
		defaultMachineState[node.Id] = &state.NUMANodeState{
			NumberOfAssignments: 0,
			MemoryMap:           map[v1.ResourceName]*state.MemoryTable{},
			Cells:               []int{node.Id},
		}

		// fill memory table with huge pages values
		for _, hugepage := range node.HugePages {
			hugepageQuantity := resource.NewQuantity(int64(hugepage.PageSize)*1024, resource.BinarySI)
			resourceName := corehelper.HugePageResourceName(*hugepageQuantity)
			systemReserved := p.getResourceSystemReserved(node.Id, resourceName)
			totalHugepagesSize := hugepage.NumPages * hugepage.PageSize * 1024
			allocatable := totalHugepagesSize - systemReserved
			defaultMachineState[node.Id].MemoryMap[resourceName] = &state.MemoryTable{
				Allocatable:    allocatable,
				Free:           allocatable,
				Reserved:       0,
				SystemReserved: systemReserved,
				TotalMemSize:   totalHugepagesSize,
			}
			if _, ok := nodeHugepages[node.Id]; !ok {
				nodeHugepages[node.Id] = 0
			}
			nodeHugepages[node.Id] += totalHugepagesSize
		}

		// fill memory table with regular memory values
		systemReserved := p.getResourceSystemReserved(node.Id, v1.ResourceMemory)

		allocatable := node.Memory - systemReserved
		// remove memory allocated by hugepages
		if allocatedByHugepages, ok := nodeHugepages[node.Id]; ok {
			allocatable -= allocatedByHugepages
		}
		defaultMachineState[node.Id].MemoryMap[v1.ResourceMemory] = &state.MemoryTable{
			Allocatable:    allocatable,
			Free:           allocatable,
			Reserved:       0,
			SystemReserved: systemReserved,
			TotalMemSize:   node.Memory,
		}
	}
	return defaultMachineState
}

func (p *staticPolicy) getResourceSystemReserved(nodeID int, resourceName v1.ResourceName) uint64 {
	var systemReserved uint64
	if nodeSystemReserved, ok := p.systemReserved[nodeID]; ok {
		if nodeMemorySystemReserved, ok := nodeSystemReserved[resourceName]; ok {
			systemReserved = nodeMemorySystemReserved
		}
	}
	return systemReserved
}

func (p *staticPolicy) getDefaultHint(machineState state.NUMANodeMap, pod *v1.Pod, requestedResources map[v1.ResourceName]uint64) (*topologymanager.TopologyHint, error) {
	hints := p.calculateHints(machineState, pod, requestedResources)
	if len(hints) < 1 {
		return nil, fmt.Errorf("[memorymanager] failed to get the default NUMA affinity, no NUMA nodes with enough memory is available")
	}

	// hints for all memory types should be the same, so we will check hints only for regular memory type
	return findBestHint(hints[string(v1.ResourceMemory)]), nil
}

func isAffinitySatisfyRequest(machineState state.NUMANodeMap, mask bitmask.BitMask, requestedResources map[v1.ResourceName]uint64) bool {
	totalFreeSize := map[v1.ResourceName]uint64{}
	for _, nodeID := range mask.GetBits() {
		for resourceName := range requestedResources {
			if _, ok := totalFreeSize[resourceName]; !ok {
				totalFreeSize[resourceName] = 0
			}
			totalFreeSize[resourceName] += machineState[nodeID].MemoryMap[resourceName].Free
		}
	}

	// verify that for all memory types the node mask has enough resources
	for resourceName, requestedSize := range requestedResources {
		if totalFreeSize[resourceName] < requestedSize {
			return false
		}
	}

	return true
}

// extendTopologyManagerHint extends the topology manager hint, in case when it does not satisfy to the container request
// the topology manager uses bitwise AND to merge all topology hints into the best one, so in case of the restricted policy,
// it possible that we will get the subset of hint that we provided to the topology manager, in this case we want to extend
// it to the original one
func (p *staticPolicy) extendTopologyManagerHint(machineState state.NUMANodeMap, pod *v1.Pod, requestedResources map[v1.ResourceName]uint64, mask bitmask.BitMask) (*topologymanager.TopologyHint, error) {
	hints := p.calculateHints(machineState, pod, requestedResources)

	var filteredHints []topologymanager.TopologyHint
	// hints for all memory types should be the same, so we will check hints only for regular memory type
	for _, hint := range hints[string(v1.ResourceMemory)] {
		affinityBits := hint.NUMANodeAffinity.GetBits()
		// filter all hints that does not include currentHint
		if isHintInGroup(mask.GetBits(), affinityBits) {
			filteredHints = append(filteredHints, hint)
		}
	}

	if len(filteredHints) < 1 {
		return nil, fmt.Errorf("[memorymanager] failed to find NUMA nodes to extend the current topology hint")
	}

	// try to find the preferred hint with the minimal number of NUMA nodes, relevant for the restricted policy
	return findBestHint(filteredHints), nil
}

func isHintInGroup(hint []int, group []int) bool {
	sort.Ints(hint)
	sort.Ints(group)

	hintIndex := 0
	for i := range group {
		if hintIndex == len(hint) {
			return true
		}

		if group[i] != hint[hintIndex] {
			continue
		}
		hintIndex++
	}

	return hintIndex == len(hint)
}

func findBestHint(hints []topologymanager.TopologyHint) *topologymanager.TopologyHint {
	// try to find the preferred hint with the minimal number of NUMA nodes, relevant for the restricted policy
	bestHint := topologymanager.TopologyHint{}
	for _, hint := range hints {
		if bestHint.NUMANodeAffinity == nil {
			bestHint = hint
			continue
		}

		// preferred of the current hint is true, when the extendedHint preferred is false
		if hint.Preferred && !bestHint.Preferred {
			bestHint = hint
			continue
		}

		// both hints has the same preferred value, but the current hint has less NUMA nodes than the extended one
		if hint.Preferred == bestHint.Preferred && hint.NUMANodeAffinity.IsNarrowerThan(bestHint.NUMANodeAffinity) {
			bestHint = hint
		}
	}
	return &bestHint
}

// GetAllocatableMemory returns the amount of allocatable memory for each NUMA node
func (p *staticPolicy) GetAllocatableMemory(s state.State) []state.Block {
	var allocatableMemory []state.Block
	machineState := s.GetMachineState()
	for numaNodeID, numaNodeState := range machineState {
		for resourceName, memoryTable := range numaNodeState.MemoryMap {
			if memoryTable.Allocatable == 0 {
				continue
			}

			block := state.Block{
				NUMAAffinity: []int{numaNodeID},
				Type:         resourceName,
				Size:         memoryTable.Allocatable,
			}
			allocatableMemory = append(allocatableMemory, block)
		}
	}
	return allocatableMemory
}

func (p *staticPolicy) updatePodReusableMemory(pod *v1.Pod, container *v1.Container, memoryBlocks []state.Block) {
	podUID := string(pod.UID)

	// If pod entries to m.initContainersReusableMemory other than the current pod exist, delete them.
	for uid := range p.initContainersReusableMemory {
		if podUID != uid {
			delete(p.initContainersReusableMemory, uid)
		}
	}

	if isInitContainer(pod, container) {
		if _, ok := p.initContainersReusableMemory[podUID]; !ok {
			p.initContainersReusableMemory[podUID] = map[string]map[v1.ResourceName]uint64{}
		}

		for _, block := range memoryBlocks {
			blockBitMask, _ := bitmask.NewBitMask(block.NUMAAffinity...)
			blockBitMaskString := blockBitMask.String()

			if _, ok := p.initContainersReusableMemory[podUID][blockBitMaskString]; !ok {
				p.initContainersReusableMemory[podUID][blockBitMaskString] = map[v1.ResourceName]uint64{}
			}

			if blockReusableMemory := p.initContainersReusableMemory[podUID][blockBitMaskString][block.Type]; block.Size > blockReusableMemory {
				p.initContainersReusableMemory[podUID][blockBitMaskString][block.Type] = block.Size
			}
		}

		return
	}

	// update re-usable memory once it used by the app container
	for _, block := range memoryBlocks {
		blockBitMask, _ := bitmask.NewBitMask(block.NUMAAffinity...)
		if podReusableMemory := p.getPodReusableMemory(pod, blockBitMask, block.Type); podReusableMemory != 0 {
			if block.Size >= podReusableMemory {
				p.initContainersReusableMemory[podUID][blockBitMask.String()][block.Type] = 0
			} else {
				p.initContainersReusableMemory[podUID][blockBitMask.String()][block.Type] -= block.Size
			}
		}
	}
}

func (p *staticPolicy) updateInitContainersMemoryBlocks(s state.State, pod *v1.Pod, container *v1.Container, containerMemoryBlocks []state.Block) {
	podUID := string(pod.UID)

	for _, containerBlock := range containerMemoryBlocks {
		blockSize := containerBlock.Size
		for _, initContainer := range pod.Spec.InitContainers {
			// we do not want to continue updates once we reach the current container
			if initContainer.Name == container.Name {
				break
			}

			if blockSize == 0 {
				break
			}

			initContainerBlocks := s.GetMemoryBlocks(podUID, initContainer.Name)
			if len(initContainerBlocks) == 0 {
				continue
			}

			for i := range initContainerBlocks {
				initContainerBlock := &initContainerBlocks[i]
				if initContainerBlock.Size == 0 {
					continue
				}

				if initContainerBlock.Type != containerBlock.Type {
					continue
				}

				if !isNUMAAffinitiesEqual(initContainerBlock.NUMAAffinity, containerBlock.NUMAAffinity) {
					continue
				}

				if initContainerBlock.Size > blockSize {
					initContainerBlock.Size -= blockSize
					blockSize = 0
				} else {
					blockSize -= initContainerBlock.Size
					initContainerBlock.Size = 0
				}
			}

			s.SetMemoryBlocks(podUID, initContainer.Name, initContainerBlocks)
		}
	}
}

func isInitContainer(pod *v1.Pod, container *v1.Container) bool {
	for _, initContainer := range pod.Spec.InitContainers {
		if initContainer.Name == container.Name {
			return true
		}
	}

	return false
}

func isNUMAAffinitiesEqual(numaAffinity1, numaAffinity2 []int) bool {
	bitMask1, err := bitmask.NewBitMask(numaAffinity1...)
	if err != nil {
		klog.ErrorS(err, "failed to create bit mask", "numaAffinity1", numaAffinity1)
		return false
	}

	bitMask2, err := bitmask.NewBitMask(numaAffinity2...)
	if err != nil {
		klog.ErrorS(err, "failed to create bit mask", "numaAffinity2", numaAffinity2)
		return false
	}

	return bitMask1.IsEqual(bitMask2)
}


text:
#ifndef __stl_config__solaris_h
#define __stl_config__solaris_h

#define _STLP_PLATFORM "Sun Solaris"

/* include system features file */
#include <sys/feature_tests.h>

/* system-dependent defines */
#define _STLP_USE_UNIX_IO

#ifdef __GNUC__
/*
 * See comments (and configuration defines) in the host.h
 */
#  if !(defined(__SunOS_5_5_1) || defined(__SunOS_5_6) || defined(__SunOS_5_7) || \
        defined(__SunOS_5_8) || defined(__SunOS_5_9) || defined(__SunOS_5_10))
#    error Uncomment one of the defines (__SunOS_5_x) in the file stlport/stl/config/host.h
#  endif
#endif

#if defined (__SunOS_5_8) && ! defined (_STLP_HAS_NO_NEW_C_HEADERS) && ( __cplusplus >= 199711L)
#  define _STLP_HAS_NATIVE_FLOAT_ABS
#endif

# define _STLP_RAND48 1

#if (defined(_XOPEN_SOURCE) && (_XOPEN_VERSION - 0 == 4)) || defined (__SunOS_5_6)
# define _STLP_WCHAR_SUNPRO_EXCLUDE 1
# define _STLP_NO_NATIVE_WIDE_FUNCTIONS 1
#endif

#if defined(__SunOS_5_5_1) || defined(__SunOS_5_6)
#  ifndef _STLP_NO_NATIVE_MBSTATE_T
#    define _STLP_NO_NATIVE_MBSTATE_T 1
#  endif
#endif

/* For SPARC we use lightweight synchronization */
#if defined (__sparc) /* && (defined (_REENTRANT) || defined (_PTHREADS)) */
#  if ( (defined (__GNUC__) && defined (__sparc_v9__)) || \
        defined (__sparcv9) ) \
       && !defined(_NOTHREADS) && !defined (_STLP_NO_SPARC_SOLARIS_THREADS)
#    define _STLP_SPARC_SOLARIS_THREADS
#    define _STLP_THREADS_DEFINED
#  endif
#endif

/* gcc does not support ELF64 yet ; however; it supports ultrasparc + v8plus.
 * limits.h contains invalid values for this combination
 */
#ifdef __GNUC__
#  if (defined  (__sparc_v9__) || defined (__sparcv9)) && !defined ( __WORD64 ) && !defined(__arch64__)
#    define __LONG_MAX__ 2147483647L
#  endif
#endif

/*
 * Attention! See comments (and configuration defines) in the host.h
 * (you host may has MATH_F and MATH_L functions)
 *
 */
#if !defined(__SunOS_5_10) && !defined(_STLP_SOLARIS_MATH_PATCH)
#  define _STLP_NO_VENDOR_MATH_F
#  define _STLP_NO_VENDOR_MATH_L
#endif

#ifdef __GNUC__
#  define _STLP_WCHAR_BORLAND_EXCLUDE
#  define _STLP_NO_NATIVE_WIDE_FUNCTIONS 1
#endif

#endif /* __stl_config__solaris_h */


text:
import RSVP from 'rsvp';
import { createLoadElement, nodeLoader } from './utilities';

/**
 * Default loader function for CSS assets. Loads them by inserting a link tag
 * with onload/onerror handlers that correspond to the resolve/reject callbacks
 * of the return Promise.
 *
 * In the event that a browser does not support onload/onerror handlers for link
 * elements, we fallback to polling the document.styleSheets property. In those
 * cases, the Promise will always resolve successfully.
 *
 * @param {String} uri
 * @return {Promise}
 */
export default nodeLoader(function css(uri) {
  return new RSVP.Promise((resolve, reject) => {
    if (document.querySelector(`link[href="${uri}"]`)) {
      return resolve();
    }

    // Try using the default onload/onerror handlers...
    const link = createLoadElement('link', resolve, function (error) {
      if (this.parentNode) {
        this.parentNode.removeChild(this);
      }
      reject(error);
    });

    link.rel = 'stylesheet';
    link.href = uri;

    document.head.appendChild(link);

    // In case the browser doesn't fire onload/onerror events, we poll the
    // the list of stylesheets to see when it loads...
    function checkSheetLoad() {
      const resolvedHref = link.href;
      const stylesheets = document.styleSheets;
      let i = stylesheets.length;

      while (i--) {
        const sheet = stylesheets[i];
        if (sheet.href === resolvedHref) {
          // Unfortunately we have no way of knowing if the load was
          // successful or not, so we always resolve.
          setTimeout(resolve);
          return;
        }
      }

      setTimeout(checkSheetLoad);
    }

    setTimeout(checkSheetLoad);
  });
});


text:
using Machine.Specifications;

namespace PowerBIDotNet.Specs.for_Communication.given
{
    public class a_communication_instance : all_dependencies
    {
        protected static Communication communication;

        Establish context = () => communication = new Communication(web_request_factory_mock.Object, serializer_mock.Object);
    }
}


text:
/**
 * Module dependencies
 */

var stack = require('poe-ui/server');
var glob = require('glob').sync;
var Path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = function(opts) {
  var app = module.exports = stack(opts);
  var root = process.cwd();
  var builder = app.builder;

  builder.resolve.modulesDirectories.push('./src');

  builder.module.loaders = builder.module.loaders.filter(function(loader) {
    if (!loader.extensions) return true;
    return !~loader.extensions.indexOf('jade');
  });

  builder.entry.main = [builder.entry.main];

  var SITE_URL = process.env.SITE_URL || '';

  var pages = root + '/src/modules/pages';
  glob(pages + '/**/*.jade').forEach(function(source) {
    page(source);
  });

  glob(pages + '/**/*.md').forEach(function(source) {
    page(source, '!' + __dirname + '/lib/jade-frontmatter-loader!yaml-frontmatter-loader');
  });

  function page(source, loaders) {
    loaders = loaders || '';

    var relative = formatRelativeName(source, pages);

    var plugin = new ExtractTextPlugin(source, relative, {extract: true, remove: true});
    builder.plugins.push(plugin);

    var path = ('/' + relative.replace('index.html', '')).replace(/\/$/, '');

    var opts = {
      url: SITE_URL + path,
      path: path,
      filename: Path.relative(root, source)
    };

    var loader = plugin.extract('html-loader?attrs=img:src img:data-src *:style&root=' + root + '/src!jade-html-loader?' + JSON.stringify(opts) + loaders);
    builder.module.loaders.push({test: new RegExp(source), loader: loader, loaders: loader});

    builder.entry.main.push(source);
  }

  builder.output.publicPath = process.env.CDN_URL || '/';

  return app;
};

function formatRelativeName(source, root) {
  var relative = Path.relative(root, source).replace('.md', '').replace('.jade', '');
  if (relative === 'index' || relative === 'index/index') return 'index.html';
  var filename = relative.split('/').slice(-1)[0];
  if (filename === 'index') return relative + '.html';
  return relative + '/index.html';
}


text:
**Material de apoyo: [aquí](https://mega.co.nz/#!iMASVQSS!UqEwruKuHl65LtalUdAdF242f4QdfvbaMhOx2JkoRl4)**

**Usabilidad:** efectividad, eficiencia, satisfacción.

Debe proporcionar aprendizaje, de fácil memorización, con baja tasa de errores
y con alta satisfacción del usuario.

**ISO 9241-11**: Medida en la que un producto se puede usar por determinados
usuarios Usabilidad para conseguir objetivos específicos con efectividad,
eficiencia y satisfacción en un contexto de uso especificado.

Dimensiones de usabilidad:

 * Aprendizaje
 * Eficiencia
 * Retención
 * Tasa de error
 * Satisfacción

**¿Por qué es importante la usabilidad?**

 * Una reducción de los costos de producción
 * Reducción de los costos de mantenimiento y apoyo.
 * Reducción de los costos de uso
 * Mejora en la calidad del producto

¿Qué es la evaluación?: Conjunto de metodologías y técnicas que analizan la
usabilidad de un sistema interactivo en diferentes etapas del ciclo de vida.

Métodos de evaluación
 * Inspección: Conjunto de métodos basados en evaluadores que inspeccionan o examinan aspectos relacionados con la usabilidad de la interfaz.
 * Indagación: La información acerca de los gustos del usuario, desagrados, necesidades y la identificación de requisitos son informaciones indispensables en una etapa temprana del proceso de desarrollo. También es importante obtener información del producto en uso una vez acabado.
 * Test: Usuarios representativos trabajan en tareas (o el prototipo) y los evaluadores utilizan los resultados para ver cómo la interfaz de usuario soporta a los usuarios con sus tareas.

La evaluación heurística fue desarrollada por Jacob Nielsen, consiste en analizar la conformidad de la interfaz con unos principios reconocidos de usabilidad mediante la inspección de varios evaluadores expertos.

### 10 Heurísticas

 1. El estado del sistema ha de estar siempre visible
 - Se ha de utilizar el lenguaje de los usuarios
 - El usuario tiene control y libertad
 - Hay consistencia y se siguen estándares
 - Existe prevención de errores
 - Se minimiza la carga de la memoria del usuario
 - Existe flexibilidad y eficiencia de uso
 - Los diálogos son estéticos y diseño minimalista
 - Se reconocen, diagnostican y se recupera de errores
 - Existe ayuda y documentación

Una persona en promedio puede recordar **7 +- 2** opciones diferentes.

### Checklist para revisar las Heuristicas

**Errores - ayuda a diagnosticar, reconocer y recuperarse de ellos**

 1. ¿Son los lenguajes claros y en lenguaje sencillo?
 - ¿Son los mensajes de errores útiles (sugieren una causa del error)?
 - ¿Los mensajes de error proveen un claro punto de salida del error?
 - ¿Los mensajes de error proveen datos de contacto para asistencia técnica?
 - ¿Es fácil contactar a Soporte a través de e-mail o un formulario Web?

**Prevención de Errores**

 1. ¿Son los errores potenciales[^1] reconocidos antes de que se transformen
    en un problema?
 - ¿El sistema previene que los usuarios cometan errores cada vez que es posible?
 - ¿El sistema advierte a los usuarios si es que están a punto de cometer un
   error potencial o de otros tipos?

[^1]: **Errores potenciales:** Errores que pueden bloquear el sistema.

**Ayuda y Documentación**

 1. ¿Existe ayuda online?
 - ¿La ayuda disponible es útil?
 - ¿Está disponible un mapa del sitio o otro tipo de asistencia de navegación
   siempre visible?
 - ¿La documentación disponible es muy extensa?
 - Si es que existe, ¿Es la ayuda informativa[^2] acertada, completa y entendible?

[^2]: **Ayuda Informativa:** Mensajes de ayuda para acciones especificas.

**Consistencia y Estándares**

 1. ¿El sistema sigue convenciones y expectaciones?
 - ¿Se provee una leyenda si se usan numerosos colores o si es que no son obvios en su significado?
 - ¿Son los comandos usados los mismos, hacen lo mismo y significan lo mismo en todas partes del sistema?

**Reconocimiento en ves de Memoria**

 1. ¿Han sido los items agrupados en zonas lógicas, y se han usado títulos
    para distinguir entre zonas?
 - Son los códigos de colores consistentes a través de todo el sistema?
 - ¿Son los items inactivos en los menús de un color más gris u omitidos?
 - ¿Son las opciones disponibles siempre claramente presentes?
 - ¿Son las etiquetas y links descritos claramente?

**Control y Libertado del Usuario**

 1. Cuando una tarea de usuario es completada, ¿El sistema espera por alguna señal del usuario antes de continuar?
 - Existe alguna funcionalidad "undo" al nivel de una acción, una entrada de datos y sobre un completo grupo de acciones?
 - ¿Pueden los usuarios cancelar operaciones en progreso?
 - ¿Son los menús generales (muchos items por menú) en ves de ser menús muy profundos (muchos niveles de menús)?
 - Si el sistema tiene múltiples niveles de menú, ¿Existe algún mecanismo que permite a los usuarios volver al menú anterior?

**Visibilidad del estado del sistema**

 1. ¿Es claro que información está disponible en la ubicación actual?
 - ¿La información actual cumple con la información esperada?
 - ¿Es claro hacia donde puedes ir desde la posición actual?
 - ¿Es siempre claro que es lo que está ocurriendo al realizar una acción en
   el sistema?
 - ¿Las instrucciones del menú, pop-ups y mensajes de errores aparecen en el
   mismo lugar en cada pagina?
 - ¿Existe algún tipo de retroalimentación (feedback) por cada acción
   realizada?
 - ¿Existe retroalimentación en menús o cajas de diálogos sobre que opciones
   son seleccionables?
 - ¿Existe retroalimentación en menús o cajas de diálogos sobre la opción en
   la que el mouse está ubicado?
 - Si múltiples opciones son seleccionables en un menú o caja de diálogos,
   ¿Existe alguna retroalimentacion sobre que opciones han sido seleccionadas?
 - Si hay retrasos observables (más grande de 15s) en el tiempo de respuesta
   del sistema, ¿Es el usuario informado del progreso del sistema?

**Flexibilidad y eficiencia de uso**

 1. ¿El sistema permite que usuarios novatos usen los comandos más básicos del sistema y que los usuarios experimentados agreguen parámetros?
 - Si el sistema usa algún sistema de puntero, ¿Los usuarios tienen la opción de ya sea, usar el mouse para hacer click en los campos o usar comandos de teclado?
 - En menús, ¿Los usuarios tienen la opción de, ya sea, hacer click directamente en una caja de dialogo o de usar un comando de teclado?

**Presentación - Estética y diseño minimalista**

 1. ¿Ha sido el sistema construido de forma simple y limpia?
 - ¿Las elecciones de colores permiten una lectura fácil?
 - ¿Es la estética del sitio placentera?
 - ¿Son las etiquetas cortas, familiares y descriptivas?
 - ¿Son los títulos de los menús cortos, aunque suficientemente largos como
   para comunicar?

**Similitud entre el sistema y el mundo real**

 1. ¿Son los iconos concretos y familiares?
 - ¿Están las opciones en los menús ordenadas de la forma más lógica?
 - ¿Son los colores seleccionados comunes de forma que cumplen con las expectativas de los códigos de colores?
 - ¿Son los códigos de Inputs significativos?
 - ¿Es el vocabulario usado apropiado para la audiencia esperada?


text:
@interface CustomQRCodeVC ()

@property (weak, nonatomic) IBOutlet UIView *scanbackView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scanViewBottomConstraint;

@end

@implementation CustomQRCodeVC

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    [self beginScanAnimation];
    [self beginScan];
}

// 开始扫描
- (void)beginScan {

    [XMGQRCodeTool sharedXMGQRCodeTool].isDrawQRCodeRect = YES;
    [[XMGQRCodeTool sharedXMGQRCodeTool] setInsteretRect:self.scanbackView.frame];
    [[XMGQRCodeTool sharedXMGQRCodeTool] beginScanInView:self.view result:^(NSArray<NSString *> *resultStrs) {
        NSLog(@"%@", resultStrs);
        [[XMGQRCodeTool sharedXMGQRCodeTool] stopScan];

    }];
}

// 开始扫描动画
- (void)beginScanAnimation {
    self.scanViewBottomConstraint.constant = self.scanbackView.frame.size.height;
    [self.view layoutIfNeeded];

    [UIView animateWithDuration:1 animations:^{
        [UIView setAnimationRepeatCount:CGFLOAT_MAX];
        self.scanViewBottomConstraint.constant = - self.scanbackView.frame.size.height;
        [self.view layoutIfNeeded];

    }];
}

@end