text:
#include "module_imu.h"
#include "imu_form.h"
#include <Module_UID/module_uid.h>
#include <Module_Simulation/module_simulation.h>

#define ADIS_REGISTER_POWER  0x02
#define ADIS_REGISTER_GYRO_X 0x04
#define ADIS_REGISTER_GYRO_Y 0x06
#define ADIS_REGISTER_GYRO_Z 0x08
#define ADIS_REGISTER_ACCEL_X 0x0A
#define ADIS_REGISTER_ACCEL_Y 0x0C
#define ADIS_REGISTER_ACCEL_Z 0x0E
#define ADIS_REGISTER_TEMP_X 0x10
#define ADIS_REGISTER_TEMP_Y 0x12
#define ADIS_REGISTER_TEMP_Z 0x14
#define ADIS_REGISTER_AUX_AD 0x16

#define ADIS_REGISTER_COMMAND_LO 0x3E

#define ADIS_COMMAND_NULL_CALIBRATION		0x01
#define ADIS_COMMAND_FACTORY_CALIBRATION	0x02
#define ADIS_COMMAND_AUX_DATA_LATCH			0x04
#define ADIS_COMMAND_FLASH_UPDATE			0x08
#define ADIS_COMMAND_PRECISION_CALIBRATION	0x10
#define ADIS_COMMAND_SOFTWARE_RESET			0x80

// Flash memory write count. (R)
#define ADIS_REGISTER_ENDURANCE 0x01

// Gyroscope bias offset factor. (R/W)
#define ADIS_REGISTER_XGYRO_OFF_HI 0x1B
#define ADIS_REGISTER_XGYRO_OFF_LO 0x1A
#define ADIS_REGISTER_YGYRO_OFF_HI 0x1D
#define ADIS_REGISTER_YGYRO_OFF_LO 0x1C
#define ADIS_REGISTER_ZGYRO_OFF_HI 0x1F
#define ADIS_REGISTER_ZGYRO_OFF_LO 0x1E

// Acceleration bias offset factor. (R/W)
#define ADIS_REGISTER_XACCL_OFF_HI 0x21
#define ADIS_REGISTER_XACCL_OFF_LO 0x20
#define ADIS_REGISTER_YACCL_OFF_HI 0x23
#define ADIS_REGISTER_YACCL_OFF_LO 0x22
#define ADIS_REGISTER_ZACCL_OFF_HI 0x25
#define ADIS_REGISTER_ZACCL_OFF_LO 0x24

// Alarm amplitude threshold. (R/W)
#define ADIS_REGISTER_ALM_MAG1_HI 0x27
#define ADIS_REGISTER_ALM_MAG1_LO 0x26
#define ADIS_REGISTER_ALM_MAG2_HI 0x29
#define ADIS_REGISTER_ALM_MAG2_LO 0x28

// Alarm sample period. (R/W)
#define ADIS_REGISTER_ALM_SMPL1_HI 0x2B
#define ADIS_REGISTER_ALM_SMPL1_LO 0x2A
#define ADIS_REGISTER_ALM_SMPL2_HI 0x2D
#define ADIS_REGISTER_ALM_SMPL2_LO 0x2C

// Alarm control. (R/W)
#define ADIS_REGISTER_ALM_CTRL_HI 0x2F
#define ADIS_REGISTER_ALM_CTRL_LO 0x2D

// Auxiliary DAC data. (R/W)
#define ADIS_REGISTER_AUX_DAC_HI 0x31
#define ADIS_REGISTER_AUX_DAC_LO 0x30

// Auxiliary digital input/output control. (R/W)
#define ADIS_REGISTER_GPIO_CTRL_HI 0x33
#define ADIS_REGISTER_GPIO_CTRL_LO 0x32

// Miscellaneous control. (R/W)
#define ADIS_REGISTER_MSC_CTRL_HI 0x35
#define ADIS_REGISTER_MSC_CTRL_LO 0x34

// Internal sample period (rate) control. (R/W)
#define ADIS_REGISTER_SMPL_PRD_HI 0x37
#define ADIS_REGISTER_SMPL_PRD_LO 0x36

// Dynamic range/digital filter control. (R/W)
#define ADIS_REGISTER_SENS_AVG_HI 0x39
#define ADIS_REGISTER_SENS_AVG_LO 0x38

// Sleep mode control. (R/W)
#define ADIS_REGISTER_SLP_CNT_HI 0x3B
#define ADIS_REGISTER_SLP_CNT_LO 0x3A

// System Status. (R)
#define ADIS_REGISTER_STATUS_HI 0x3D
#define ADIS_REGISTER_STATUS_LO 0x3C

Module_IMU::Module_IMU(QString id, Module_UID *uid, Module_Simulation *sim)
    : RobotModule(id)
{
    this->uid=uid;
    this->sim=sim;

    setDefaultValue("frequency", 10);
    setDefaultValue("ssLine", 1);
    setDefaultValue("g", 9.81);
    setDefaultValue("spiSpeed",3);
    setDefaultValue("biasComp",0);
    setDefaultValue("originAllign",0);
    setDefaultValue("smplTimeBase",0);
    setDefaultValue("smplTimeMult",1);
    setDefaultValue("filterTaps",2);
    setDefaultValue("gyroSens","300");
    timer.moveToThread(this);
}

Module_IMU::~Module_IMU()
{
}

void Module_IMU::terminate()
{
    timer.stop();
    RobotModule::terminate();
}

void Module_IMU::init()
{
    connect(&timer,SIGNAL(timeout()), this, SLOT(refreshData()));

    /* connect sim */
    connect(sim,SIGNAL(newIMUData(float,float,float,float,float,float)),this,SLOT(refreshSimData(float,float,float,float,float,float)));
    connect(this,SIGNAL(requestIMU()),sim,SLOT(requestIMUSlot()));

    reset();
}

void Module_IMU::reset()
{
    RobotModule::reset();

    if (!getSettingsValue("enabled").toBool())
        return;

    if(sim->isEnabled())
    {
        timer.setInterval(250);
        QTimer::singleShot(0,&timer,SLOT(start()));
        return;
    }

    int freq = 1000/getSettingsValue("frequency").toInt();
    if (freq>0) {
        timer.setInterval(freq);
        QTimer::singleShot(0, &timer, SLOT(start()));
    } else {
        QTimer::singleShot(0, &timer, SLOT(stop()));
    }
    setHealthToOk();

    // soft reset
    writeRegister(ADIS_REGISTER_COMMAND_LO, ADIS_COMMAND_SOFTWARE_RESET);

    // set volatile registers
    configureADIS();

    doSelfTest();

    updateBiasFields();
    printRegisters();

    addData("flashCounter", readRegister(ADIS_REGISTER_ENDURANCE));

}

void Module_IMU::refreshData()
{
    if (!getSettingsValue("enabled").toBool())
        return;

    if(sim->isEnabled())
    {
        logger->debug("request sim");
        emit requestIMU();
    }
    else
    {
    configureSPI();

    int currentGyroX;
    int currentGyroY;
    int currentGyroZ;
    int currentAccelX;
    int currentAccelY;
    int currentAccelZ;
    int gyroTempX;
    int gyroTempY;
    int gyroTempZ;

    currentGyroX = readDataRegister(ADIS_REGISTER_GYRO_X, 14);
    currentGyroY = readDataRegister(ADIS_REGISTER_GYRO_Y, 14);
    currentGyroZ = readDataRegister(ADIS_REGISTER_GYRO_Z, 14);
    currentAccelX = readDataRegister(ADIS_REGISTER_ACCEL_X, 14);
    currentAccelY = readDataRegister(ADIS_REGISTER_ACCEL_Y, 14);
    currentAccelZ = readDataRegister(ADIS_REGISTER_ACCEL_Z, 14);
    gyroTempX = readDataRegister(ADIS_REGISTER_TEMP_X, 12);
    gyroTempY = readDataRegister(ADIS_REGISTER_TEMP_Y, 12);
    gyroTempZ = readDataRegister(ADIS_REGISTER_TEMP_Z, 12);

    unsigned short voltage_raw = readRegister(ADIS_REGISTER_POWER);
    double voltage = (voltage_raw & 0x0FFF) *1.8315; // mV
    addData("voltage", voltage/1000);

    if (getHealthStatus().isHealthOk()) {

        addData("gyroX", currentGyroX * 0.07326);
        addData("gyroY", currentGyroY * 0.07326);
        addData("gyroZ", currentGyroZ * 0.07326);

        addData("accelX", currentAccelX * 0.4672 * getSettingsValue("g").toFloat() / 1000);
        addData("accelY", currentAccelY * 0.4672 * getSettingsValue("g").toFloat() / 1000);
        addData("accelZ", currentAccelZ * 0.4672 * getSettingsValue("g").toFloat() / 1000);

        addData("gyroTempX", gyroTempX * 0.1453 + 25);
        addData("gyroTempY", gyroTempY * 0.1453 + 25);
        addData("gyroTempZ", gyroTempZ * 0.1453 + 25);

        emit dataChanged(this);

    }

    }
}

void Module_IMU::refreshSimData(float accl_x, float accl_y, float accl_z, float angvel_x, float angvel_y, float angvel_z)
{
    logger->debug("new sim data");
    addData("gyroX",angvel_x);
    addData("gyroY",angvel_y);
    addData("gyroZ",angvel_z);

    addData("accelX",accl_x);
    addData("accelY",accl_y);
    addData("accelZ",accl_z);

    addData("gyroTempX",0);
    addData("gyroTempY",0);
    addData("gyroTempZ",0);

    if(getHealthStatus().isHealthOk())
        emit dataChanged(this);
}

QList<RobotModule*> Module_IMU::getDependencies()
{
    QList<RobotModule*> ret;
    ret.append(uid);
    ret.append(sim);
    return ret;
}

QWidget* Module_IMU::createView(QWidget* parent)
{
    return new IMU_Form(this, parent);
}

void Module_IMU::doHealthCheck()
{

//    qDebug() << "adis health THREAD ID";
//    qDebug() << QThread::currentThreadId();

    if (!getSettingsValue("enabled").toBool())
        return;

    if(sim->isEnabled())
        return;

    // we don't check for voltage. we just want to see if the device returns
    // some sensible data to rule out cable problems (SPI will return weired
    // data with connection problems)
    unsigned short voltage_raw = readRegister(ADIS_REGISTER_POWER);
    double voltage = (voltage_raw & 0x0FFF) *1.8315; // mV

    // 4400mV is way below spec.
    if (voltage < 4400 || voltage > 5250) {
        setHealthToSick("ADIS not responding.");
        return;
    }

    short status_reg = readRegister(ADIS_REGISTER_STATUS_LO);
    status_reg &= 0xFFFE; // clear out undervoltage warning. we're aware of it.

    addData("statusReg", status_reg);
    if (status_reg != 0x0000) {
        setHealthToSick("Status Register indicating an error: register content=0x" +QString::number(status_reg,16));
        // TODO: translate error bits
        return;
    }

    setHealthToOk();
}

void Module_IMU::doSelfTest()
{
    // start self test
    writeRegister(ADIS_REGISTER_MSC_CTRL_HI, 0x04);

    // test should take approx. 35 ms
    // while (readRegister(ADIS_REGISTER_STATUS_HI) & 0x040)
    msleep(35);

    short checkResult = readRegister(ADIS_REGISTER_STATUS_HI);
    if (checkResult != 0x0000) {
        setHealthToSick("Self-test failed: status=0x" +QString::number(checkResult,16));
    }
}

int Module_IMU::readDataRegister(uint8_t reg, int bits)
{
        unsigned int data = readRegister(reg);

// We check for health independently anyway.
//        if (data & 0x4000) {
//                setHealthToSick("Return data has the EA flag set.");
//        }

        if (bits==12)
            return shortToInteger(data,0x0FFF, bits);
        else
            return shortToInteger(data,0x3FFF, bits);
}

void Module_IMU::configureSPI()
{
        uid->SPI_SetPOL(true);
        uid->SPI_SetPHA(true);
        uid->SPI_Speed(getSettingsValue("spiSpeed").toInt()); // XXX: 14.67Mhz/X < 2Mhz
}

void Module_IMU::configureADIS()
{
    configureSPI();

    short filterTaps = getSettingsValue("filterTaps").toInt();

    short sens_avg_soll = 0;
    sens_avg_soll |= filterTaps;

    QString gyroSens = getSettingsValue("gyroSens").toString();
    if (gyroSens == "75") {
        sens_avg_soll |= 0x0100;
    } else if (gyroSens == "150") {
        sens_avg_soll |= 0x0200;
    } else if (gyroSens == "300") {
        sens_avg_soll |= 0x0400;
    }

    writeFullRegister(ADIS_REGISTER_SENS_AVG_LO, sens_avg_soll);

    short multiplier = getSettingsValue("smplTimeMult").toInt()-1;
    short smpl_prd_soll = multiplier;
    if (getSettingsValue("smplTimeBase").toBool()) {
            smpl_prd_soll |= (1 << 6);
    } else {
            smpl_prd_soll &= ~(1 << 6);
    }

    writeFullRegister(ADIS_REGISTER_SMPL_PRD_LO, smpl_prd_soll);

    uint8_t msc_ctrl = 0;
    if (getSettingsValue("originAllign").toBool()) {
        msc_ctrl |= 0x40;
    }
    if (getSettingsValue("biasComp").toBool()) {
        msc_ctrl |= 0x80;
    }
    writeRegister(ADIS_REGISTER_MSC_CTRL_LO, msc_ctrl);
}

void Module_IMU::printRegisters()
{
        for (uint8_t addr = 0x00; addr <= 0x3F; addr += 2)
        {
 //            data["reg-"+QString::number(addr,16)] = readRegister(addr);
             logger->debug("Content at address 0x"+QString::number((short)addr,16) + ": 0x" +QString::number(readRegister(addr),16));
        }
}

/**
 * Converts an unsigned short that is read from the bus to
 * a signed integer.
 *
 * @param s - value to convert in twos-complement
 * @param mask - mask to be applied to s, if the value is not
 * 		16 bits
 * @param bits - number of bits
 */
int Module_IMU::shortToInteger(unsigned short s, unsigned short mask, int bits)
{
        int ret;

        // Check if the number is negative. If so invert
        // s, apply the mask, and add one. (twos-complement)
        if (((s >> (bits-1)) & 1) == 1)
        {
                s = ~s;
                s &= mask;
                s++;
                ret = - (int) s;
        }
        // If the number is positive we can simply apply the mask and
        // cast to int.
        else
        {
                s &= mask;
                ret = (int) s;
        }
        return ret;
}

unsigned short Module_IMU::toShort(uint8_t high, uint8_t low)
{
        return ((unsigned short)high) << 8 | ((unsigned short)low);
}

unsigned short Module_IMU::readRegister(uint8_t address)
{
    char buf_recv[] = {0x00, 0x00};
    char buf_send[] = {address, 0x00};

    bool ret = uid->SPI_Write(getSettingsValue("ssLine").toInt(), buf_send, 2);
    if (!ret)
        setHealthToSick(uid->getLastError());
    ret = uid->SPI_Read(getSettingsValue("ssLine").toInt(), 2, buf_recv);
    if (!ret)
        setHealthToSick(uid->getLastError());
    return toShort(buf_recv[0],buf_recv[1]);
}

void Module_IMU::writeFullRegister(uint8_t address_lower, unsigned short data)
{
        // write upper register first, since the SENS/AVG register should
        // be programmed in this order
        writeRegister(address_lower+1, data>>8);
        writeRegister(address_lower, data & 0x00FF);
}

void Module_IMU::writeRegister(uint8_t address, uint8_t data)
{
    char buf_recv[] = {0x00, 0x00};
    char buf_send[] = {address, data};

    // set highest bit to indicate write
    buf_send[0] |= 0x80;

    bool ret = uid->SPI_Write(getSettingsValue("ssLine").toInt(), buf_send, 2);
    if (!ret)
        setHealthToSick(uid->getLastError());
    ret = uid->SPI_Read(getSettingsValue("ssLine").toInt(), 2, buf_recv);
    if (!ret)
        setHealthToSick(uid->getLastError());
}

float Module_IMU::getGyroX(void)
{
    return getDataValue("gyroX").toFloat();
}

float Module_IMU::getGyroY(void)
{
    return getDataValue("gyroY").toFloat();
}

float Module_IMU::getGyroZ(void)
{
    return getDataValue("gyroZ").toFloat();
}

float Module_IMU::getAccelX(void)
{
    return getDataValue("accelX").toFloat();
}

float Module_IMU::getAccelY(void)
{
    return getDataValue("accelY").toFloat();
}

float Module_IMU::getAccelZ(void)
{
    return getDataValue("accelZ").toFloat();
}

void Module_IMU::doNullCalib()
{
    writeRegister(ADIS_REGISTER_COMMAND_LO, ADIS_COMMAND_NULL_CALIBRATION);
}

void Module_IMU::doPrecisionCalib()
{
    writeRegister(ADIS_REGISTER_COMMAND_LO, ADIS_COMMAND_PRECISION_CALIBRATION);
}

void Module_IMU::updateBiasFields()
{
    addData("biasGyroX", readDataRegister(ADIS_REGISTER_XGYRO_OFF_LO, 12));
    addData("biasGyroY", readDataRegister(ADIS_REGISTER_YGYRO_OFF_LO, 12));
    addData("biasGyroZ", readDataRegister(ADIS_REGISTER_ZGYRO_OFF_LO, 12));
    addData("biasAccelX", readDataRegister(ADIS_REGISTER_XACCL_OFF_LO, 12));
    addData("biasAccelY", readDataRegister(ADIS_REGISTER_YACCL_OFF_LO, 12));
    addData("biasAccelZ", readDataRegister(ADIS_REGISTER_ZACCL_OFF_LO, 12));
}


text:
package org.infinispan.spark.suites

import java.net.{InetSocketAddress, SocketAddress}

import org.infinispan.spark.rdd.PreferredServerBalancingStrategy
import org.scalatest.{FunSuite, Matchers}

import scala.collection.JavaConverters._

class LocalitySuite extends FunSuite with Matchers {

   val servers: Set[SocketAddress] = Set(
      new InetSocketAddress("host1", 80),
      new InetSocketAddress("host2", 81),
      new InetSocketAddress("host3", 82)
   )

   test("start iteration on hinted server") {
      val preferred = new InetSocketAddress("host1", 80)

      val lbStrategy = new PreferredServerBalancingStrategy(preferred)
      lbStrategy.setServers(servers.asJava)

      lbStrategy.nextServer(Set[SocketAddress]().asJava) shouldBe preferred
      lbStrategy.nextServer(Set[SocketAddress](preferred).asJava) shouldNot be(preferred)
   }

   test("ignore invalid hinted server") {
      val invalid = new InetSocketAddress("invalidHost", 81)

      val lbStrategy = new PreferredServerBalancingStrategy(invalid)
      lbStrategy.setServers(servers.asJava)

      lbStrategy.nextServer(Set[SocketAddress](invalid).asJava) shouldNot be(invalid)
   }

}

redpajama_set_name: RedPajamaGithub


text:
@implementation UIScrollView (eLongRefresh)

- (CGFloat)offsetX{
   return self.contentOffset.x;
}

- (CGFloat)offsetY{
     return self.contentOffset.y;
}

- (CGFloat)insetTop{
    return self.contentInset.top;
}

- (CGFloat)insetLeft{
    return self.contentInset.left;
}

- (CGFloat)insetBottom{
    return self.contentInset.bottom;
}

- (CGFloat)insetRight{
    return self.contentInset.right;
}

- (CGFloat)contentH{
    return self.contentSize.height;
}

-(CGFloat)contentW{
    return self.contentSize.width;
}

- (void)setOffsetX:(CGFloat)offsetX{
    CGPoint point = self.contentOffset;
    point.x = offsetX;
    self.contentOffset = point;
}

- (void)setOffsetY:(CGFloat)offsetY{
    CGPoint point = self.contentOffset;
    point.y = offsetY;
    self.contentOffset = point;
}

- (void)setInsetTop:(CGFloat)insetTop{
    UIEdgeInsets contentInset = self.contentInset;
    contentInset.top = insetTop;
    self.contentInset = contentInset;
}

- (void)setInsetLeft:(CGFloat)insetLeft{
    UIEdgeInsets contentInset = self.contentInset;
    contentInset.left = insetLeft;
    self.contentInset = contentInset;
}

- (void)setInsetRight:(CGFloat)insetRight{
    UIEdgeInsets contentInset = self.contentInset;
    contentInset.right = insetRight;
    self.contentInset = contentInset;
}

- (void)setInsetBottom:(CGFloat)insetBottom{
    UIEdgeInsets contentInset = self.contentInset;
    contentInset.bottom = insetBottom;
    self.contentInset = contentInset;
}

- (void)setContentH:(CGFloat)contentH{
    CGSize size = self.contentSize;
    size.height = contentH;
    self.contentSize = size;
}

- (void)setContentW:(CGFloat)contentW{
    CGSize size = self.contentSize;
    size.width = contentW;
    self.contentSize = size;
}

#pragma mark - header
static const char refreshHeaderKey = '\0';
- (void)setHeader:(eLongRefreshHeader *)header
{
    if (header != self.header) {
        // 删除旧的,添加新的
        [self.header removeFromSuperview];
        [self addSubview:header];

        // 存储新的
        [self willChangeValueForKey:@"header"]; // KVO
        objc_setAssociatedObject(self, &refreshHeaderKey,
                                 header, OBJC_ASSOCIATION_ASSIGN);
        [self didChangeValueForKey:@"header"]; // KVO
    }
}

- (eLongRefreshHeader *)header
{
    return objc_getAssociatedObject(self, &refreshHeaderKey);
}

#pragma mark - footer
static const char refreshFooterKey = '\0';
- (void)setFooter:(eLongRefreshFooter *)footer
{
    if (footer != self.footer) {
        // 删除旧的,添加新的
        [self.footer removeFromSuperview];
        [self addSubview:footer];

        // 存储新的
        [self willChangeValueForKey:@"footer"]; // KVO
        objc_setAssociatedObject(self, &refreshFooterKey,
                                 footer, OBJC_ASSOCIATION_ASSIGN);
        [self didChangeValueForKey:@"footer"]; // KVO
    }
}

- (eLongRefreshFooter *)footer
{
    return objc_getAssociatedObject(self, &refreshFooterKey);
}

@end


text:
package org.uberfire.ext.editor.commons.service;

import org.jboss.errai.bus.server.annotations.Remote;
import org.uberfire.ext.editor.commons.service.support.SupportsDelete;

@Remote
public interface DeleteService extends SupportsDelete {

}


text:
Multiview clustering for stock assets

This is a preliminary work for studying the application of multiview clustering on stock assets in order to determine assets with similar behaviours analysing time series data.
This project has been developed during Computational Intelligence master's class at the department of Computer Science, University of Salerno.

Check the slides for further informations and details.

Authors:
A. De Angelis
B. Del Monte
E. Di Marino

Supervisors:
Prof. R. Tagliaferri
Prof. M. La Rocca
Dr.ssa A. Serra
Dr. M. Fratello


text:
package jp.co.yahoo.map.codezine_sample;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import jp.co.yahoo.map.codezine_sample.GL20SurfaceView;
import jp.co.yahoo.map.codezine_sample.MapView;
import jp.co.yahoo.map.codezine_sample.Shader;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;

public class GL20MyRenderer implements GLSurfaceView.Renderer{
	private MapView mMapView;	//MapView
	private Shader mShader;		//定義したShader
	private int muProjMatrix;	//投影変換用行列のハンドル
	private int muViewMatrix;	//視点変換用行列のハンドル
	private float[] mCoordList;	//頂点データ
	private int mVertexId;	//頂点データのVRAMの位置
	private int mNumVertices;	//頂点数
	private int mAPosition;	//位置ハンドル
	private GMatrix mFrontProjectionMatrix;	//コントローラーからの受け取り用投影変換用行列
	private GMatrix mFrontModelViewMatrix;	//コントローラーからの受け取り用視点変換用行列
	private GMatrix mBackProjectionMatrix;	//描画用投影変換用行列
	private GMatrix mBackModelViewMatrix;	//描画用視点変換用行列

	private final int FSIZE = Float.SIZE / Byte.SIZE;	//floatのバイトサイズ

	/**
	 * コンストラクタ
	 * @param context
	 * @param parent
	 * @param mapView
	 */
	public GL20MyRenderer(Context context, GL20SurfaceView parent , MapView mapView){
		mMapView = mapView;
		mShader = new Shader();
		mCoordList = mMapView.getCoordinateList();
		mFrontProjectionMatrix = new GMatrix();
		mFrontModelViewMatrix = new GMatrix();
		mBackProjectionMatrix = new GMatrix();
		mBackModelViewMatrix = new GMatrix();
	}

	/**
	 * 行列を設定
	 * @param viewmatrix
	 * @param projectionmatrix
	 */
	public void setMatrix(GMatrix viewmatrix, GMatrix projectionmatrix) {
		synchronized (mFrontModelViewMatrix) {
			viewmatrix.copy(mFrontModelViewMatrix);
			projectionmatrix.copy(mFrontProjectionMatrix);
		}
	}

	@Override
	public void onDrawFrame(GL10 arg0) {
		synchronized (mFrontModelViewMatrix) {
			mFrontModelViewMatrix.copy(mBackModelViewMatrix);
			mFrontProjectionMatrix.copy(mBackProjectionMatrix);
		}
		//行列をセット
		GLES20.glUniformMatrix4fv(muViewMatrix, 1, false, mBackModelViewMatrix.matrix, 0);
		GLES20.glUniformMatrix4fv(muProjMatrix, 1, false, mBackProjectionMatrix.matrix, 0);

		//背景色を設定します。
		GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

		//線幅を設定します
		GLES20.glLineWidth(2.0f);

		//頂点バッファを設定します
		GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, mVertexId);
		GLES20.glVertexAttribPointer(mAPosition, 3, GLES20.GL_FLOAT, false, FSIZE*3, 0);

		//描画
		GLES20.glDrawArrays(GLES20.GL_LINE_STRIP, 0, mNumVertices);
	}

	@Override
	public void onSurfaceChanged(GL10 arg0, int width, int height) {
		//ビューポートの設定します。
		GLES20.glViewport(0,0,width,height);
		//再描画
		mMapView.redraw();
	}

	@Override
	public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) {
		//位置ハンドル(a_Position)の取得と有効化。
		int program = mShader.initShaders();
		mAPosition = GLES20.glGetAttribLocation(program, "a_Position");
		if (mAPosition == -1) {
			throw new RuntimeException("a_Positionの格納場所の取得に失敗");
		}
		GLES20.glEnableVertexAttribArray(mAPosition);
		mNumVertices = initVertexBuffers();

		//ビューボリュームと視点の格納場所を取得し、を登録します。
		muViewMatrix = GLES20.glGetUniformLocation(program, "u_ViewMatrix");
		muProjMatrix = GLES20.glGetUniformLocation(program, "u_ProjMatrix");
		if (muViewMatrix == -1 || muProjMatrix == -1) {
			throw new RuntimeException("a_Positionの格納場所の取得に失敗");
		}
	}

	/**
	 * 描画用の頂点データを作成します。
	 * @return
	 */
	public int initVertexBuffers() {
		//FloatBufferオブジェクトを作成します。
		FloatBuffer vertices = makeFloatBuffer(mCoordList);
		int vertex_num = mCoordList.length / 3;	//頂点数

		//VRAMにデータを設定します。
		int[] vertexId = new int[1];
		GLES20.glGenBuffers(1, vertexId, 0);
		GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexId[0]);
		GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, FSIZE * vertices.limit(), vertices, GLES20.GL_STATIC_DRAW);
		mVertexId = vertexId[0];

		return vertex_num;
	}

	/**
	 * フロート配列からフロートバッファを作成します。
	 * @param array
	 * @return
	 */
	public FloatBuffer makeFloatBuffer(float[] array) {
		if (array == null) throw new IllegalArgumentException();
		ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * array.length);
		byteBuffer.order(ByteOrder.nativeOrder());
		FloatBuffer floatBuffer = byteBuffer.asFloatBuffer();
		floatBuffer.put(array);
		floatBuffer.position(0);
		return floatBuffer;
	}
}


text:
layout: post
title: Interesting Reads 1/4 - 1/10
date: '2014-01-10T10:41:00.001-05:00'
author: Allison McMillan
tags:
- things I've read
- learning
modified_time: '2014-01-10T10:41:34.994-05:00'
blogger_id: tag:blogger.com,1999:blog-6054545261088815023.post-1968482238558766986
blogger_orig_url: http://allisonsherenmcmillan.blogspot.com/2014/01/interesting-reads-14-110.html
---

Well, I have to be honest, there wasn't much out there this week. Maybe it's because everyone was focusing in their first full week back at work in a while but there just wasn't much that caught my eye. I do have two link though... not as much good reads as good resources.

Enjoy!

Full Stack Rails Developer Resources. Lots of good resources that really helps you think about what "full stack" really means.

This is an emoji cheat sheet because who doesn't need one of those handy.


text:
namespace {

// The |Connect| DBus call needs a longer timeout than the default in order to
// give BlueZ enough time to return the timeout error response.
// See crosbug.com/37607
const int kConnectTimeoutMs = 50 * 1000;

} // namespace

namespace chromeos {

const char BluetoothInputClient::kNoResponseError[] =
    "org.chromium.Error.NoResponse";

BluetoothInputClient::Properties::Properties(
    dbus::ObjectProxy* object_proxy,
    const PropertyChangedCallback& callback)
    : BluetoothPropertySet(object_proxy,
                           bluetooth_input::kBluetoothInputInterface,
                           callback) {
  RegisterProperty(bluetooth_input::kConnectedProperty, &connected);
}

BluetoothInputClient::Properties::~Properties() {
}

// The BluetoothInputClient implementation used in production.
class BluetoothInputClientImpl: public BluetoothInputClient,
                                private BluetoothAdapterClient::Observer {
 public:
  BluetoothInputClientImpl(dbus::Bus* bus,
                           BluetoothAdapterClient* adapter_client)
      : bus_(bus),
      weak_ptr_factory_(this) {
    DVLOG(1) << "Creating BluetoothInputClientImpl";

    DCHECK(adapter_client);
    adapter_client->AddObserver(this);
  }

  virtual ~BluetoothInputClientImpl() {
    // Clean up Properties structures
    for (ObjectMap::iterator iter = object_map_.begin();
         iter != object_map_.end(); ++iter) {
      Object object = iter->second;
      Properties* properties = object.second;
      delete properties;
    }
  }

  // BluetoothInputClient override.
  virtual void AddObserver(BluetoothInputClient::Observer* observer)
      OVERRIDE {
    DCHECK(observer);
    observers_.AddObserver(observer);
  }

  // BluetoothInputClient override.
  virtual void RemoveObserver(BluetoothInputClient::Observer* observer)
      OVERRIDE {
    DCHECK(observer);
    observers_.RemoveObserver(observer);
  }

  // BluetoothInputClient override.
  virtual Properties* GetProperties(const dbus::ObjectPath& object_path)
      OVERRIDE {
    return GetObject(object_path).second;
  }

  // BluetoothInputClient override.
  virtual void Connect(const dbus::ObjectPath& object_path,
                       const ConnectCallback& callback,
                       const ConnectErrorCallback& error_callback) OVERRIDE {
    dbus::MethodCall method_call(
        bluetooth_input::kBluetoothInputInterface,
        bluetooth_input::kConnect);

    dbus::ObjectProxy* object_proxy = GetObjectProxy(object_path);

    object_proxy->CallMethodWithErrorCallback(
        &method_call,
        kConnectTimeoutMs,
        base::Bind(&BluetoothInputClientImpl::OnConnect,
                   weak_ptr_factory_.GetWeakPtr(), object_path,
                   callback),
        base::Bind(&BluetoothInputClientImpl::OnConnectError,
                   weak_ptr_factory_.GetWeakPtr(), object_path,
                   error_callback));
  }

  // BluetoothInputClient override.
  virtual void Disconnect(const dbus::ObjectPath& object_path,
                          const InputCallback& callback) OVERRIDE {
    dbus::MethodCall method_call(
        bluetooth_input::kBluetoothInputInterface,
        bluetooth_input::kDisconnect);

    dbus::ObjectProxy* object_proxy = GetObjectProxy(object_path);

    object_proxy->CallMethod(
        &method_call,
        dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::Bind(&BluetoothInputClientImpl::OnDisconnect,
                   weak_ptr_factory_.GetWeakPtr(), object_path, callback));
  }

 private:
  // We maintain a collection of dbus object proxies and properties structures
  // for each input device.
  typedef std::pair<dbus::ObjectProxy*, Properties*> Object;
  typedef std::map<const dbus::ObjectPath, Object> ObjectMap;
  ObjectMap object_map_;

  // BluetoothAdapterClient::Observer override.
  virtual void DeviceCreated(const dbus::ObjectPath& adapter_path,
                             const dbus::ObjectPath& object_path) OVERRIDE {
  }

  // BluetoothAdapterClient::Observer override.
  virtual void DeviceRemoved(const dbus::ObjectPath& adapter_path,
                             const dbus::ObjectPath& object_path) OVERRIDE {
    RemoveObject(object_path);
  }

  // Ensures that we have an object proxy and properties structure for
  // an input device with object path |object_path|, creating it if not and
  // storing it in our |object_map_| map.
  Object GetObject(const dbus::ObjectPath& object_path) {
    ObjectMap::iterator iter = object_map_.find(object_path);
    if (iter != object_map_.end())
      return iter->second;

    // Create the object proxy.
    DCHECK(bus_);
    dbus::ObjectProxy* object_proxy = bus_->GetObjectProxy(
        bluetooth_input::kBluetoothInputServiceName, object_path);

    // Create the properties structure.
    Properties* properties = new Properties(
        object_proxy,
        base::Bind(&BluetoothInputClientImpl::OnPropertyChanged,
                   weak_ptr_factory_.GetWeakPtr(), object_path));

    properties->ConnectSignals();
    properties->GetAll();

    Object object = std::make_pair(object_proxy, properties);
    object_map_[object_path] = object;
    return object;
  }

  // Removes the dbus object proxy and properties for the input device with
  // dbus object path |object_path| from our |object_map_| map.
  void RemoveObject(const dbus::ObjectPath& object_path) {
    ObjectMap::iterator iter = object_map_.find(object_path);
    if (iter != object_map_.end()) {
      // Clean up the Properties structure.
      Object object = iter->second;
      Properties* properties = object.second;
      delete properties;

      object_map_.erase(iter);
    }
  }

  // Returns a pointer to the object proxy for |object_path|, creating
  // it if necessary.
  dbus::ObjectProxy* GetObjectProxy(const dbus::ObjectPath& object_path) {
    return GetObject(object_path).first;
  }

  // Called by BluetoothPropertySet when a property value is changed,
  // either by result of a signal or response to a GetAll() or Get()
  // call. Informs observers.
  void OnPropertyChanged(const dbus::ObjectPath& object_path,
                         const std::string& property_name) {
    FOR_EACH_OBSERVER(BluetoothInputClient::Observer, observers_,
                      InputPropertyChanged(object_path, property_name));
  }

  // Called when a response for Connect() is received.
  void OnConnect(const dbus::ObjectPath& object_path,
                 const ConnectCallback& callback,
                 dbus::Response* response) {
    DCHECK(response);
    callback.Run(object_path);
  }

  // Called when an error for Connect() is received.
  void OnConnectError(const dbus::ObjectPath& object_path,
                      const ConnectErrorCallback& error_callback,
                      dbus::ErrorResponse* response) {
    // Error response has optional error message argument.
    std::string error_name;
    std::string error_message;
    if (response) {
      dbus::MessageReader reader(response);
      error_name = response->GetErrorName();
      reader.PopString(&error_message);
    } else {
      error_name = kNoResponseError;
      error_message = "";
    }
    error_callback.Run(object_path, error_name, error_message);
  }

  // Called when a response for Disconnect() is received.
  void OnDisconnect(const dbus::ObjectPath& object_path,
                    const InputCallback& callback,
                    dbus::Response* response) {
    LOG_IF(WARNING, !response) << object_path.value()
                               << ": OnDisconnect: failed.";
    callback.Run(object_path, response);
  }

  dbus::Bus* bus_;

  // List of observers interested in event notifications from us.
  ObserverList<BluetoothInputClient::Observer> observers_;

  // Weak pointer factory for generating 'this' pointers that might live longer
  // than we do.
  // Note: This should remain the last member so it'll be destroyed and
  // invalidate its weak pointers before any other members are destroyed.
  base::WeakPtrFactory<BluetoothInputClientImpl> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(BluetoothInputClientImpl);
};

// The BluetoothInputClient implementation used on Linux desktop, which does
// nothing.
class BluetoothInputClientStubImpl : public BluetoothInputClient {
 public:
  // BluetoothInputClient override.
  virtual void AddObserver(Observer* observer) OVERRIDE {
  }

  // BluetoothInputClient override.
  virtual void RemoveObserver(Observer* observer) OVERRIDE {
  }

  // BluetoothInputClient override.
  virtual Properties* GetProperties(const dbus::ObjectPath& object_path)
      OVERRIDE {
    VLOG(1) << "GetProperties: " << object_path.value();
    return NULL;
  }

  // BluetoothInputClient override.
  virtual void Connect(const dbus::ObjectPath& object_path,
                       const ConnectCallback& callback,
                       const ConnectErrorCallback& error_callback) OVERRIDE {
    VLOG(1) << "Connect: " << object_path.value();
    error_callback.Run(object_path, "", "");
  }

  // BluetoothInputClient override.
  virtual void Disconnect(const dbus::ObjectPath& object_path,
                          const InputCallback& callback) OVERRIDE {
    VLOG(1) << "Disconnect: " << object_path.value();
    callback.Run(object_path, false);
  }
};

BluetoothInputClient::BluetoothInputClient() {
}

BluetoothInputClient::~BluetoothInputClient() {
}

BluetoothInputClient* BluetoothInputClient::Create(
    DBusClientImplementationType type,
    dbus::Bus* bus,
    BluetoothAdapterClient* adapter_client) {
  if (type == REAL_DBUS_CLIENT_IMPLEMENTATION)
    return new BluetoothInputClientImpl(bus, adapter_client);
  DCHECK_EQ(STUB_DBUS_CLIENT_IMPLEMENTATION, type);
  return new BluetoothInputClientStubImpl();
}

}  // namespace chromeos


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.iOS.Network
{
	/// <summary>
	/// Fired when data chunk was received over the network.
	/// </summary>
	[Event(ProtocolName.Network.DataReceived)]
	[SupportedBy("iOS")]
	public class DataReceivedEvent
	{
		/// <summary>
		/// Gets or sets Request identifier.
		/// </summary>
		public string RequestId { get; set; }
		/// <summary>
		/// Gets or sets Timestamp.
		/// </summary>
		public double Timestamp { get; set; }
		/// <summary>
		/// Gets or sets Data chunk length.
		/// </summary>
		public long DataLength { get; set; }
		/// <summary>
		/// Gets or sets Actual bytes received (might be less than dataLength for compressed encodings).
		/// </summary>
		public long EncodedDataLength { get; set; }
	}
}


text:
<?php

defined('_JEXEC') or die('RESTRICTED');

// load base model
require_once(dirname(__FILE__) . '/model.php');

/**
 * Hello Model
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class WFModelUsers extends WFModel
{
}
?>


text:
About

I am a Data Scientist with more than six years of experience across different industries and roles, with a keen interest in Machine Learning and Artificial Intelligence. I am an avid learner, constantly striving to acquire new knowledge and expand my skillset. I have a particular interest in human interactions and how technology is used to influence our behaviours.

I am keen to apply my existing skills, interests and knowledge, and develop new ones by working on projects that bring together challenging contexts, interesting data sets and cutting-edge technology.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>JsonTuples (Edgent v1.1.0)</title>
<meta name="date" content="2017-02-26">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.edgent.samples.apps

Class JsonTuples

java.lang.Object

org.apache.edgent.samples.apps.JsonTuples

public class JsonTuples
extends java.lang.Object

Utilties to ease working working with sensor "samples" by wrapping them
 in JsonObjects.

 The Json Tuple sensor "samples" have a standard collection of properties.

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
KEY_AGG_BEGIN_TS

static java.lang.String
KEY_AGG_COUNT

static java.lang.String
KEY_ID

static java.lang.String
KEY_READING

static java.lang.String
KEY_TS

Constructor Summary

Constructors

Constructor and Description

JsonTuples()

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static com.google.gson.JsonElement
getStatistic(com.google.gson.JsonObject jo,
            Statistic stat)

Get a statistic value from a sample.

static com.google.gson.JsonElement
getStatistic(com.google.gson.JsonObject jo,
            java.lang.String valueKey,
            Statistic stat)

Get a statistic value from a sample.

static Function<com.google.gson.JsonObject,java.lang.String>
keyFn()

The partition key function for wrapped sensor samples.

static BiFunction<java.util.List<com.google.gson.JsonObject>,java.lang.String,com.google.gson.JsonObject>
statistics(Statistic... statistics)

Create a function that computes the specified statistics on the list of
 samples and returns a new sample containing the result.

static <T> com.google.gson.JsonObject
wrap(org.apache.commons.math3.util.Pair<java.lang.Long,T> sample,
    java.lang.String id)

Create a JsonObject wrapping a raw Pair<Long msec,T reading>> sample.

static <T> TStream<com.google.gson.JsonObject>
wrap(TStream<org.apache.commons.math3.util.Pair<java.lang.Long,T>> stream,
    java.lang.String id)

Create a stream of JsonObject wrapping a stream of
 raw Pair<Long msec,T reading>> samples.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

KEY_ID

public static final java.lang.String KEY_ID

See Also:

Constant Field Values

KEY_TS

public static final java.lang.String KEY_TS

See Also:

Constant Field Values

KEY_READING

public static final java.lang.String KEY_READING

See Also:

Constant Field Values

KEY_AGG_BEGIN_TS

public static final java.lang.String KEY_AGG_BEGIN_TS

See Also:

Constant Field Values

KEY_AGG_COUNT

public static final java.lang.String KEY_AGG_COUNT

See Also:

Constant Field Values

Constructor Detail

JsonTuples

public JsonTuples()

Method Detail

wrap

public static <T> com.google.gson.JsonObject wrap(org.apache.commons.math3.util.Pair<java.lang.Long,T> sample,
                                                  java.lang.String id)

Create a JsonObject wrapping a raw Pair<Long msec,T reading>> sample.

Type Parameters:

T - Tuple type

Parameters:

sample - the raw sample

id - the sensor's Id

Returns:

the wrapped sample

wrap

public static <T> TStream<com.google.gson.JsonObject> wrap(TStream<org.apache.commons.math3.util.Pair<java.lang.Long,T>> stream,
                                                           java.lang.String id)

Create a stream of JsonObject wrapping a stream of
 raw Pair<Long msec,T reading>> samples.

Type Parameters:

T - Tuple type

Parameters:

stream - the raw input stream

id - the sensor's Id

Returns:

the wrapped stream

keyFn

public static Function<com.google.gson.JsonObject,java.lang.String> keyFn()

The partition key function for wrapped sensor samples.

 The KEY_ID property is returned for the key.

Returns:

the function

getStatistic

public static com.google.gson.JsonElement getStatistic(com.google.gson.JsonObject jo,
                                                       Statistic stat)

Get a statistic value from a sample.

 Same as getStatistic(jo, JsonTuples.KEY_READING, stat).

Parameters:

jo - the sample

stat - the Statistic of interest

Returns:

the JsonElement for the Statistic

Throws:

java.lang.RuntimeException - of the stat isn't present

getStatistic

public static com.google.gson.JsonElement getStatistic(com.google.gson.JsonObject jo,
                                                       java.lang.String valueKey,
                                                       Statistic stat)

Get a statistic value from a sample.

 Convenience for working with samples containing a property
 whose value is one or more Statistic
 as created by
 JsonAnalytics.aggregate()

Parameters:

jo - the sample

valueKey - the name of the property containing the JsonObject of Statistics

stat - the Statistic of interest

Returns:

the JsonElement for the Statistic

Throws:

java.lang.RuntimeException - of the stat isn't present

statistics

public static BiFunction<java.util.List<com.google.gson.JsonObject>,java.lang.String,com.google.gson.JsonObject> statistics(Statistic... statistics)

Create a function that computes the specified statistics on the list of
 samples and returns a new sample containing the result.

 The single tuple contains the specified statistics computed over
 all of the JsonTuple.KEY_READING
 values from List<JsonObject>.

 The resulting sample contains the properties:

JsonTuple.KEY_ID

JsonTuple.KEY_MSEC - msecTimestamp of the last sample in the window

JsonTuple.KEY_AGG_BEGIN_MSEC - msecTimestamp of the first sample in the window

JsonTuple.KEY_AGG_COUNT - number of samples in the window (value=factor)

JsonTuple.KEY_READING - a JsonObject of the statistics
                      as defined by
                     JsonAnalytics.aggregate()

 Sample use:

 TStream<JsonObject> s = ...
 // reduce s by a factor of 100 with stats MEAN and STDEV
 TStream<JsonObject> reduced = s.batch(100, statistics(Statistic.MEAN, Statistic.STDDEV));

Parameters:

statistics - the statistics to calculate over the window

Returns:

TStream<JsonObject> for the reduced stream

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Apache Edgent (incubating)

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2017 The Apache Software Foundation. All Rights Reserved - 4744f56-20170226-1707


text:
/**
 * Autogenerated by Thrift Compiler (0.9.2)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.zeeman.thrifts.idl;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.TException;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import javax.annotation.Generated;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2016-1-27")
public class InvocationException extends TException implements org.apache.thrift.TBase<InvocationException, InvocationException._Fields>, java.io.Serializable, Cloneable, Comparable<InvocationException> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InvocationException");

  private static final org.apache.thrift.protocol.TField REQUEST_FIELD_DESC = new org.apache.thrift.protocol.TField("Request", org.apache.thrift.protocol.TType.STRUCT, (short)1);
  private static final org.apache.thrift.protocol.TField ERROR_MESSAGE_FIELD_DESC = new org.apache.thrift.protocol.TField("ErrorMessage", org.apache.thrift.protocol.TType.STRING, (short)2);
  private static final org.apache.thrift.protocol.TField ERROR_DESCRIPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("ErrorDescription", org.apache.thrift.protocol.TType.STRING, (short)3);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new InvocationExceptionStandardSchemeFactory());
    schemes.put(TupleScheme.class, new InvocationExceptionTupleSchemeFactory());
  }

  public ThriftSRequest Request; // required
  public String ErrorMessage; // required
  public String ErrorDescription; // optional

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    REQUEST((short)1, "Request"),
    ERROR_MESSAGE((short)2, "ErrorMessage"),
    ERROR_DESCRIPTION((short)3, "ErrorDescription");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // REQUEST
          return REQUEST;
        case 2: // ERROR_MESSAGE
          return ERROR_MESSAGE;
        case 3: // ERROR_DESCRIPTION
          return ERROR_DESCRIPTION;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private static final _Fields optionals[] = {_Fields.ERROR_DESCRIPTION};
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.REQUEST, new org.apache.thrift.meta_data.FieldMetaData("Request", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, ThriftSRequest.class)));
    tmpMap.put(_Fields.ERROR_MESSAGE, new org.apache.thrift.meta_data.FieldMetaData("ErrorMessage", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    tmpMap.put(_Fields.ERROR_DESCRIPTION, new org.apache.thrift.meta_data.FieldMetaData("ErrorDescription", org.apache.thrift.TFieldRequirementType.OPTIONAL,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(InvocationException.class, metaDataMap);
  }

  public InvocationException() {
  }

  public InvocationException(
    ThriftSRequest Request,
    String ErrorMessage)
  {
    this();
    this.Request = Request;
    this.ErrorMessage = ErrorMessage;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public InvocationException(InvocationException other) {
    if (other.isSetRequest()) {
      this.Request = new ThriftSRequest(other.Request);
    }
    if (other.isSetErrorMessage()) {
      this.ErrorMessage = other.ErrorMessage;
    }
    if (other.isSetErrorDescription()) {
      this.ErrorDescription = other.ErrorDescription;
    }
  }

  public InvocationException deepCopy() {
    return new InvocationException(this);
  }

  @Override
  public void clear() {
    this.Request = null;
    this.ErrorMessage = null;
    this.ErrorDescription = null;
  }

  public ThriftSRequest getRequest() {
    return this.Request;
  }

  public InvocationException setRequest(ThriftSRequest Request) {
    this.Request = Request;
    return this;
  }

  public void unsetRequest() {
    this.Request = null;
  }

  /** Returns true if field Request is set (has been assigned a value) and false otherwise */
  public boolean isSetRequest() {
    return this.Request != null;
  }

  public void setRequestIsSet(boolean value) {
    if (!value) {
      this.Request = null;
    }
  }

  public String getErrorMessage() {
    return this.ErrorMessage;
  }

  public InvocationException setErrorMessage(String ErrorMessage) {
    this.ErrorMessage = ErrorMessage;
    return this;
  }

  public void unsetErrorMessage() {
    this.ErrorMessage = null;
  }

  /** Returns true if field ErrorMessage is set (has been assigned a value) and false otherwise */
  public boolean isSetErrorMessage() {
    return this.ErrorMessage != null;
  }

  public void setErrorMessageIsSet(boolean value) {
    if (!value) {
      this.ErrorMessage = null;
    }
  }

  public String getErrorDescription() {
    return this.ErrorDescription;
  }

  public InvocationException setErrorDescription(String ErrorDescription) {
    this.ErrorDescription = ErrorDescription;
    return this;
  }

  public void unsetErrorDescription() {
    this.ErrorDescription = null;
  }

  /** Returns true if field ErrorDescription is set (has been assigned a value) and false otherwise */
  public boolean isSetErrorDescription() {
    return this.ErrorDescription != null;
  }

  public void setErrorDescriptionIsSet(boolean value) {
    if (!value) {
      this.ErrorDescription = null;
    }
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case REQUEST:
      if (value == null) {
        unsetRequest();
      } else {
        setRequest((ThriftSRequest)value);
      }
      break;

    case ERROR_MESSAGE:
      if (value == null) {
        unsetErrorMessage();
      } else {
        setErrorMessage((String)value);
      }
      break;

    case ERROR_DESCRIPTION:
      if (value == null) {
        unsetErrorDescription();
      } else {
        setErrorDescription((String)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case REQUEST:
      return getRequest();

    case ERROR_MESSAGE:
      return getErrorMessage();

    case ERROR_DESCRIPTION:
      return getErrorDescription();

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case REQUEST:
      return isSetRequest();
    case ERROR_MESSAGE:
      return isSetErrorMessage();
    case ERROR_DESCRIPTION:
      return isSetErrorDescription();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof InvocationException)
      return this.equals((InvocationException)that);
    return false;
  }

  public boolean equals(InvocationException that) {
    if (that == null)
      return false;

    boolean this_present_Request = true && this.isSetRequest();
    boolean that_present_Request = true && that.isSetRequest();
    if (this_present_Request || that_present_Request) {
      if (!(this_present_Request && that_present_Request))
        return false;
      if (!this.Request.equals(that.Request))
        return false;
    }

    boolean this_present_ErrorMessage = true && this.isSetErrorMessage();
    boolean that_present_ErrorMessage = true && that.isSetErrorMessage();
    if (this_present_ErrorMessage || that_present_ErrorMessage) {
      if (!(this_present_ErrorMessage && that_present_ErrorMessage))
        return false;
      if (!this.ErrorMessage.equals(that.ErrorMessage))
        return false;
    }

    boolean this_present_ErrorDescription = true && this.isSetErrorDescription();
    boolean that_present_ErrorDescription = true && that.isSetErrorDescription();
    if (this_present_ErrorDescription || that_present_ErrorDescription) {
      if (!(this_present_ErrorDescription && that_present_ErrorDescription))
        return false;
      if (!this.ErrorDescription.equals(that.ErrorDescription))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    List<Object> list = new ArrayList<Object>();

    boolean present_Request = true && (isSetRequest());
    list.add(present_Request);
    if (present_Request)
      list.add(Request);

    boolean present_ErrorMessage = true && (isSetErrorMessage());
    list.add(present_ErrorMessage);
    if (present_ErrorMessage)
      list.add(ErrorMessage);

    boolean present_ErrorDescription = true && (isSetErrorDescription());
    list.add(present_ErrorDescription);
    if (present_ErrorDescription)
      list.add(ErrorDescription);

    return list.hashCode();
  }

  @Override
  public int compareTo(InvocationException other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = Boolean.valueOf(isSetRequest()).compareTo(other.isSetRequest());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetRequest()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.Request, other.Request);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetErrorMessage()).compareTo(other.isSetErrorMessage());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetErrorMessage()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ErrorMessage, other.ErrorMessage);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetErrorDescription()).compareTo(other.isSetErrorDescription());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetErrorDescription()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ErrorDescription, other.ErrorDescription);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("InvocationException(");
    boolean first = true;

    sb.append("Request:");
    if (this.Request == null) {
      sb.append("null");
    } else {
      sb.append(this.Request);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("ErrorMessage:");
    if (this.ErrorMessage == null) {
      sb.append("null");
    } else {
      sb.append(this.ErrorMessage);
    }
    first = false;
    if (isSetErrorDescription()) {
      if (!first) sb.append(", ");
      sb.append("ErrorDescription:");
      if (this.ErrorDescription == null) {
        sb.append("null");
      } else {
        sb.append(this.ErrorDescription);
      }
      first = false;
    }
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    if (Request == null) {
      throw new org.apache.thrift.protocol.TProtocolException("Required field 'Request' was not present! Struct: " + toString());
    }
    if (ErrorMessage == null) {
      throw new org.apache.thrift.protocol.TProtocolException("Required field 'ErrorMessage' was not present! Struct: " + toString());
    }
    // check for sub-struct validity
    if (Request != null) {
      Request.validate();
    }
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class InvocationExceptionStandardSchemeFactory implements SchemeFactory {
    public InvocationExceptionStandardScheme getScheme() {
      return new InvocationExceptionStandardScheme();
    }
  }

  private static class InvocationExceptionStandardScheme extends StandardScheme<InvocationException> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, InvocationException struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // REQUEST
            if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
              struct.Request = new ThriftSRequest();
              struct.Request.read(iprot);
              struct.setRequestIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // ERROR_MESSAGE
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.ErrorMessage = iprot.readString();
              struct.setErrorMessageIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 3: // ERROR_DESCRIPTION
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.ErrorDescription = iprot.readString();
              struct.setErrorDescriptionIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();

      // check for required fields of primitive type, which can't be checked in the validate method
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, InvocationException struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.Request != null) {
        oprot.writeFieldBegin(REQUEST_FIELD_DESC);
        struct.Request.write(oprot);
        oprot.writeFieldEnd();
      }
      if (struct.ErrorMessage != null) {
        oprot.writeFieldBegin(ERROR_MESSAGE_FIELD_DESC);
        oprot.writeString(struct.ErrorMessage);
        oprot.writeFieldEnd();
      }
      if (struct.ErrorDescription != null) {
        if (struct.isSetErrorDescription()) {
          oprot.writeFieldBegin(ERROR_DESCRIPTION_FIELD_DESC);
          oprot.writeString(struct.ErrorDescription);
          oprot.writeFieldEnd();
        }
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class InvocationExceptionTupleSchemeFactory implements SchemeFactory {
    public InvocationExceptionTupleScheme getScheme() {
      return new InvocationExceptionTupleScheme();
    }
  }

  private static class InvocationExceptionTupleScheme extends TupleScheme<InvocationException> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, InvocationException struct) throws org.apache.thrift.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      struct.Request.write(oprot);
      oprot.writeString(struct.ErrorMessage);
      BitSet optionals = new BitSet();
      if (struct.isSetErrorDescription()) {
        optionals.set(0);
      }
      oprot.writeBitSet(optionals, 1);
      if (struct.isSetErrorDescription()) {
        oprot.writeString(struct.ErrorDescription);
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, InvocationException struct) throws org.apache.thrift.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      struct.Request = new ThriftSRequest();
      struct.Request.read(iprot);
      struct.setRequestIsSet(true);
      struct.ErrorMessage = iprot.readString();
      struct.setErrorMessageIsSet(true);
      BitSet incoming = iprot.readBitSet(1);
      if (incoming.get(0)) {
        struct.ErrorDescription = iprot.readString();
        struct.setErrorDescriptionIsSet(true);
      }
    }
  }

}


text:
host: Boris Rozinov
github-user: oofp
city: Richmond Hill
country: Canada
project: "Type-Sets, Cmptype, and MagicTyFams"
project-url: "https://github.com/isovector/type-sets"
arrival-date: 2019-08-03
departure-date: 2019-08-05
---

Boris has been working on a library for tracking dependent state management of
resources over application lifetimes, complete with refinement of the
possibilities based on specific filters. It's wicked cool, though performs
compiles aggressively slowly. We looked at the performance, and realized the
primary problem is that everything is encoded as type-level lists. We thought
that maybe having a better type-level data structure would be effective.

So I implemented a plugin that solves a type-level `CmpType` for ordering types.
Such a thing means we can effectively write binary search trees for arbitrary
types of kind `*`, and now get all sorts of great performance improvements. We
hunkered down on that, and then on writing BSTs in terms of it. But then I
realized most of the work was actually in getting the plugin to solve the type
family, and not in comparing types, so we spun out another library for
generating plugins.

The result: three libraries. `type-sets`, `cmptype` and `magic-tyfams`; not bad
for a weekend of work.

On Boris' project, we found a bug in GHC's `TypeError` machinery --- it explodes
in the wrong place in the presence of partial type signatures. Having tracked
that down, we did some work on existentializing his types so the partial ty sigs
weren't required. We then thought about how to reduce the boilerplate in his
library, and came up with a combination of Servant and HKD for expressing the
state transition graph.


text:
"""
Categorize people according to their year of birth and death.

The following parameters are supported:

&params;

-auto             If given, run in autonomous mode.

-dry              If given, doesn't do any real changes, but only shows
                  what would have been changed.

All other parameters will be regarded as part of the title of a single page,
and the bot will only work on that single page.
"""
__version__ = '$Id$'
import wikipedia as pywikibot
import catlib, pagegenerators, os.path, re, urllib, time

# This is required for the text that is shown when you run this script
# with the parameter -help.
docuReplacements = {
    '&params;': pagegenerators.parameterHelp
}

class BirthCatBot:
    # Edit summary message that should be used.
    # NOTE: Put a good description here, and add translations, if possible!
    msg = {
        'fi': u'Botti lisäsi: %s',
    }

    msgNewCat = {
        'fi': u'Botti loi uuden luokan',
    }

    # TODO: Implement BC years
    dateFormat = {
        'fi': ur'(?:\[*\d+\.\s+\S+kuuta\]*,?\s+)?\[*(\d+)\]*',
        }

    birthDeathCats = {
        'fi': {
            u'Vuonna %s syntyneet' : {
                'templates' :{
                    u'Syntymäaika ja ikä': 3,
                    u'Syntymä- ja kuolinaika': 3,
                    u'Kuolinaika ja ikä': 3,
                    },
                're1': [
                    re.compile(ur'syntynyt\s*=\s*' + dateFormat['fi']),
# Old silvonen's regex
#                    re.compile(ur"'''[^)]*(?:\bs\.\s+|,\s+|\(|(?<!&ndash);\s+)" + dateFormat['fi']),
                    ],
                're2': [
                    # Searches "s. [[26. huhtikuuta]] [[1971]] " type birthdate string.
                    re.compile(ur"(?:s\.|synt?\.|syntynyt) ?\[?\[?[0-9]{1,2}\. [A-Za-zäö]*kuuta[^()]*?([0-9]{1,4})\]?\]?[\-\–\-\& .,)<]"),
                    # Searches "([[26. huhtikuuta]] [[1971]] " type birthdate string.
                    re.compile(ur"\(\[?\[?[0-9]{1,2}\. [A-Za-zäö]*kuuta[^()]*?([0-9]{1,4})\]?\]?[\-\–\-\& .,)<]"),
                    # Searches "s. [[1971]] " type birthdate string.
                    re.compile(ur"(?:s\.|synt?\.|syntynyt) ?\[?\[?([0-9]{1,4})\]?\]?[\-\–\-\& .,)<]"),
                    ],
                'newcat': lambda yr: u'{{Syntymävuosiluokka|%s|%s}}\n\n[[en:Category:%s births]]' % (yr[:-1], yr[-1], yr)
                },
            u'Vuonna %s kuolleet' : {
                'templates' :{
                    u'Syntymä- ja kuolinaika': 6,
                    u'Kuolinaika ja ikä': 6,
                    },
                're1': [
                    re.compile(ur'kuollut\s*=\s*' + dateFormat['fi']),
# Old silvonen's regex
#                    re.compile(ur"'''[^()]*\((?:[^)]|\([^)]*\))*(?:\bk\.\s+|(?:[M-bM-^@M-^SM-bM-^@M-^T-]|–)\s*)" + dateFormat['fi']),
                    ],
                're2': [
                    # Searches "k. [[26. huhtikuuta]] [[1971]] " or "‐ [[26. huhtikuuta]] [[1971]] " type deathdate string.
                    re.compile(ur"(?:-|–|-|‐|–|—|k\.) +?\[?\[?[0-9]{1,2}\. [A-Za-zäö]*kuuta[^()]*?([0-9]{1,4})\]?\]?[ ,.;)<]"),
                    # Searches "k. [[huhtikuu]] [[1971]] " or "‐ [[huhtikuu]] [[1971]] " type deathdate string.
                    re.compile(ur"(?:-|–|-|‐|–|—|k\.) +?\[?\[?[A-Za-zäö]*kuu +[^()]*?([0-9]{1,4})\]?\]?[ ,.;)<]"),
                    # Searches "k. [[1971]] " or "‐ [[1971]] " type deathdate string.
                    re.compile(ur"'''.{1,100}(?:-|–|-|‐|–|—|k\.) +?\[?\[?([0-9]{1,4})\]?\]?[ ,.;)<]"),
                    ],
                'newcat': lambda yr: u'{{Kuolinvuosiluokka|%s|%s}}\n\n[[en:Category:%s deaths]]' % (yr[:-1], yr[-1], yr)
                }
            }
        }

    def __init__(self, generator, auto, dry):
        """
        Constructor. Parameters:
            * generator - The page generator that determines on which pages
                          to work on.
            * auto      - If True, run in autonomous mode.
            * dry       - If True, doesn't do any real changes, but only shows
                          what would have been changed.
        """
        self.generator = generator
        self.auto = auto
        self.dry = dry
        self.lang = pywikibot.getSite().lang

        # Get the correct localized parameters
        self.site = pywikibot.getSite()
        self.summary = pywikibot.translate(self.site, self.msg)
        self.summaryNewCat = pywikibot.translate(self.site, self.msgNewCat)
        self.bdCats = pywikibot.translate(self.site, self.birthDeathCats)

        self.defaultSortMatcher = None
        defaultSortLabels = self.site.getmagicwords('defaultsort')
        if defaultSortLabels:
            self.defaultSortMatcher = re.compile('\{\{(' + '|'.join(defaultSortLabels) + ')')

    def run(self):
        try:
            for page in self.generator:
                self.treat(page)
        except KeyboardInterrupt:
            pywikibot.output('\nQuitting program...')

    def getSortKey(self, cats, text):
        if not self.defaultSortMatcher or not cats or self.defaultSortMatcher.search(text):
            sortKey = None
        else:
            sortKey = cats[0].sortKey
            if sortKey and sortKey[0] in '* ':
                sortKey = None

        return sortKey

    def treat(self, page):
        """
        Adds the page to the appropriate birth and death year categories.
        """
        pywikibot.output(u"Processing page %s..." % page.title(asLink=True))
        text = self.load(page)
        if not text:
            return

        # Just print beginning of the article; strip full ref-tags
        reMatcher= re.compile(u"(?:\A|\n)([^\n|{]*?'''.*?)(\n|\Z)")
        match=reMatcher.search(text)
        headertext=None
        if match:
            headertext=re.sub('<ref[^/]*?>.*?</ref>', '', match.group(1))
            pywikibot.output("\n---- CLIP ---\n%s\n--- CLIP ---\n" % headertext)
        else:
            pywikibot.output("\n---- CLIP ---\n%s\n--- CLIP ---\n" % text)

        cats = page.categories()
        addCats = []
        newCatContent = {}
        foundTemplates = False
        for tmpl, params in page.templatesWithParams():
            numParams = filter(lambda s: s.isdigit(), params) # Filter out birthplace fields
            for bdCat, bdCatInfo in self.bdCats.iteritems():
                if tmpl in bdCatInfo['templates']:
                    pywikibot.output(u'Found template {{%s|%s}}' % (tmpl, u'|'.join(params)))
                    foundTemplates = True
                    try:
                        year = numParams[bdCatInfo['templates'][tmpl] - 1].strip()
                    except IndexError:
                        continue
                    sortKey = self.getSortKey(cats, text)
                    newCat = catlib.Category(self.site, bdCat % year, sortKey=sortKey)
                    if newCat in cats or newCat in addCats:
                        pywikibot.output(u"%s is already in %s." % (page.title(), newCat.title()))
                    else:
                        addCats.append(newCat)
                        newCatContent[newCat.title()] = bdCatInfo['newcat'](year)

# First set of regex against full articletext
        if not addCats and not foundTemplates:
            for bdCat, bdCatInfo in self.bdCats.iteritems():
                for reMatcher in bdCatInfo['re1']:
                    match = reMatcher.search(text)
                    if match:
                        pywikibot.output(u"%s" % match.groups())
                        year = match.group(1)
                        pywikibot.output(u'Found %s in %s' % (year, match.group(0)))
                        sortKey = self.getSortKey(cats, text)
                        newCat = catlib.Category(self.site, bdCat % year, sortKey=sortKey)
                        if newCat in cats or newCat in addCats:
                            pywikibot.output(u"%s is already in %s." % (page.title(), newCat.title()))
                        else:
                            addCats.append(newCat)
                            newCatContent[newCat.title()] = bdCatInfo['newcat'](year)
                        break;

#second set of regex against the header text if available. If not then failback to full text
        if not addCats and not foundTemplates:
            for bdCat, bdCatInfo in self.bdCats.iteritems():
                for reMatcher in bdCatInfo['re2']:
                    if headertext:
                        match = reMatcher.search(headertext)
                    else:
                        match= reMatcher.search(text);

                    if match:
                        pywikibot.output(u"%s" % match.groups())
                        year = match.group(1)
                        pywikibot.output(u'Found %s in %s' % (year, match.group(0)))
                        sortKey = self.getSortKey(cats, text)
                        newCat = catlib.Category(self.site, bdCat % year, sortKey=sortKey)
                        if newCat in cats or newCat in addCats:
                            pywikibot.output(u"%s is already in %s." % (page.title(), newCat.title()))
                        else:
                            addCats.append(newCat)
                            newCatContent[newCat.title()] = bdCatInfo['newcat'](year)
                        break;

        if addCats:
            cats.extend(addCats)

            # This will Add category living people if needed
            birth, death=self.getBirthDeathFromCats(cats, 'fi')
            if birth>1885  and death==None:
                newCat = catlib.Category(self.site, u'Elävät henkilöt', sortKey=sortKey)
                if newCat not in cats:
                    addCats.append(newCat)
                    cats.append(newCat)

            text = pywikibot.replaceCategoryLinks(text, cats)
            summary = self.summary % ', '.join(map(lambda c: c.title(asLink=True), addCats))
            if not self.save(text, page, summary):
                pywikibot.output(u'Page %s not saved.' % page.title(asLink=True))
                return
            for cat in addCats:
                if not cat.exists():
                    pywikibot.output(u'%s should be created.' % (cat.title()))
                    if not self.save(newCatContent[cat.title()], cat, self.summaryNewCat, minorEdit=False):
                        pywikibot.output(u'%s not created.' % cat.title(asLink=True))
                    time.sleep(2)

    def load(self, page):
        """
        Loads the given page, does some changes, and saves it.
        """
        try:
            # Load the page
            text = page.get()
        except pywikibot.NoPage:
            pywikibot.output(u"Page %s does not exist; skipping."
                             % page.title(asLink=True))
        except pywikibot.IsRedirectPage:
            pywikibot.output(u"Page %s is a redirect; skipping."
                             % page.title(asLink=True))
        else:
            return text
        return None

    def getBirthDeathFromCats(self,cats, lang):
        birthDeathMatch = {
          'fi': {
             'birth' : u"Vuonna ([0-9]{1,4}) syntyneet",
             'death' : u"Vuonna ([0-9]{1,4}) kuolleet"
          },
          'en': {
             'birth' : u"Category:([0-9]{1,4}) births",
             'death' : u"Category:([0-9]{1,4}) deaths"
           },
          'de': {
             'birth' : u"Geboren ([0-9]{1,4})\Z",
             'death' : u"Gestorben ([0-9]{1,4})\Z"
           },
          'fr': {
             'birth' : u"Naissance en ([0-9]{1,4})",
             'death' : u"Décès en ([0-9]{1,4})"
           },
          'es': {
             'birth' : u"Nacidos en ([0-9]{1,4})\Z",
             'death' : u"Fallecidos en ([0-9]{1,4})\Z"
           }
        }

        if lang in birthDeathMatch:
            death=None
            birth=None
            reMatcher= re.compile(birthDeathMatch[lang]['birth'])
            for cat in cats:
                match=reMatcher.search(cat.title())
                if match:
                    birth=match.group(1)

            reMatcher= re.compile(birthDeathMatch[lang]['death'])
            for cat in cats:
                match=reMatcher.search(cat.title())
                if match:
                    death=match.group(1)
            return birth, death
        return None, None

    def iwYearCheck(self,page, birth, death):

        iwMatch=False
        deathOK=False
        birthOK=False
        if birth==None:
            return False

        if death!=None:
            age=int(death) - int(birth)
            if age<0 or age>125:
                pywikibot.output(
                        u'Skipping %s because age of %s'
                        % (page.title(), age))
                return False

        iw=page.interwiki()
        for linkedPage in iw:
            if linkedPage.site().lang not in ['de', 'es']:
                continue
            try:
                iwbirth, iwdeath = self.getBirthDeathFromCats(linkedPage.categories(), linkedPage.site().lang)
            except pywikibot.IsRedirectPage:
                continue

            time.sleep(0.1)

            if (iwbirth==None):
                iwMatch=iwMatch
            elif birth==iwbirth:
                pywikibot.output(u'%s\t%s\tBirth match OK: %s : iw= %s' % (linkedPage.site().lang,  page.title(asLink=True), birth, iwbirth))
                iwMatch=True
                birthOK=True
            else:
                pywikibot.output(u'%s\t%s\tBirth match FAILED: %s : iw= %s' % (linkedPage.site().lang,  page.title(asLink=True), birth, iwbirth))
                iwMatch=False
                return iwMatch

            if (iwdeath==None):
                iwMatch=iwMatch
            elif (death==iwdeath):
                pywikibot.output(u'%s\t%s\tDeath match OK: %s : iw= %s' % (linkedPage.site().lang,  page.title(asLink=True), death, iwdeath))
                iwMatch=True
                deathOK=True
            else:
                pywikibot.output(u'%s\t%s\tDeath match FAILED: %s : iw= %s' % (linkedPage.site().lang,  page.title(asLink=True), death, iwdeath))
                iwMatch=False
                return iwMatch

        if (death!=None and deathOK==False):
            return False
        if (birth!=None and birthOK==False):
            return False
        return iwMatch

    def save(self, text, page, comment, minorEdit=True, botflag=True):
        # only save if something was changed
        try:
            oldText = page.get()
        except pywikibot.NoPage:
            oldText = ""
        if text != oldText:
            # Show the title of the page we're working on.
            # Highlight the title in purple.
            pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
                             % page.title())
            # show what was changed
            pywikibot.showDiff(oldText, text)
            pywikibot.output(u'Comment: %s' %comment)

            # if we are not adding the new category then check years
            reMatcher= re.compile(u"\ALuokka:")
            match=reMatcher.search(page.title())

            if not match:

                reMatcher= re.compile(u"Luokka:Vuonna ([0-9]{1,4}) syntyneet")
                match=reMatcher.findall(text)
                if len(match)>1:
                    pywikibot.output(
                        u'Skipping %s because of multiple birth cats'
                        % (page.title()))
                    return False
                else:
                    match=reMatcher.search(text)
                    if match:
                       birth=match.group(1)
                    else:
                       birth=None

                reMatcher= re.compile(u"Luokka:Vuonna ([0-9]{1,4}) kuolleet")
                match=reMatcher.findall(text)
                if len(match)>1:
                    pywikibot.output(
                        u'Skipping %s because of multiple death cats'
                        % (page.title()))
                    return False
                else:
                    match=reMatcher.search(text)
                    if match:
                        death=match.group(1)
                    else:
                        death=None

                if self.auto:
                    iwCheck=self.iwYearCheck(page, birth, death)
                    if iwCheck == False:
                        pywikibot.output(
                            u'Skipping %s because of edit iwcheck failed'
                            % (page.title()))
                        return False

            if not self.dry:
                if self.auto:
                    choice = 'y'
                else:
                    choice = pywikibot.inputChoice(
                        u'Do you want to accept these changes?',
                        ['Yes', 'No'], ['y', 'N'], 'N')
                if choice == 'y':
                    try:
                        # Save the page
                        page.put(text, comment=comment,
                                 minorEdit=minorEdit, botflag=botflag)
                    except pywikibot.LockedPage:
                        pywikibot.output(u"Page %s is locked; skipping."
                                         % page.title(asLink=True))
                    except pywikibot.EditConflict:
                        pywikibot.output(
                            u'Skipping %s because of edit conflict'
                            % (page.title()))
                    except pywikibot.SpamfilterError, error:
                        pywikibot.output(u'Cannot change %s because of spam blacklist entry %s'
                            % (page.title(), error.url))
                    else:
                        return True
        return False

def main():
    # HACK: This can be removed when pywikipedia bug 3315395 has been fixed
    safetyLock = 'birthcat-unlock.dat'
    if not os.path.exists(safetyLock):
        choice = pywikibot.inputChoice(u'Have you patched textlib.py in pywikipedia?',
            ['Yes', 'No'], ['y', 'N'], 'N')
        if choice == 'y':
            open(safetyLock, 'w').close()
        else:
            return False
    # END OF HACK

    # This factory is responsible for processing command line arguments
    # that are also used by other scripts and that determine on which pages
    # to work on.
    genFactory = pagegenerators.GeneratorFactory()
    # The generator gives the pages that should be worked upon.
    gen = None
    # This temporary array is used to read the page title if one single
    # page to work on is specified by the arguments.
    pageTitleParts = []
    # If dry is True, doesn't do any real changes, but only show
    # what would have been changed.
    dry = False
    # If auto is True, run in autonomous mode.
    auto = False

    # Parse command line arguments
    for arg in pywikibot.handleArgs():
        if arg.startswith("-dry"):
            dry = True
        elif arg.startswith("-auto"):
            auto = True
        else:
            # check if a standard argument like
            # -start:XYZ or -ref:Asdf was given.
            if not genFactory.handleArg(arg):
                pageTitleParts.append(arg)

    if pageTitleParts != []:
        # We will only work on a single page.
        pageTitle = ' '.join(pageTitleParts)
        page = pywikibot.Page(pywikibot.getSite(), pageTitle)
        gen = iter([page])

    if not gen:
        gen = genFactory.getCombinedGenerator()
    if gen:
        # The preloading generator is responsible for downloading multiple
        # pages from the wiki simultaneously.
        gen = pagegenerators.PreloadingGenerator(gen)
        bot = BirthCatBot(gen, auto, dry)
        bot.run()
    else:
        pywikibot.showHelp()

if __name__ == "__main__":
    try:
        main()
    finally:
        pywikibot.stopme()


text:
package eu.aniketos.securebpmn.xacml.api.autho;

import java.util.List;

public interface IContextProvider {
	/**
	 * resolves one attribute
	 *
	 * writes the result to attr and returns it as string
	 *
	 * @param attr
	 * @return
	 */
	String resolveAttribute(AuthoAttribute attr);
	/**
	 * resolves a set of attributes, returns number of errors
	 * @param attr
	 * @return
	 */
	int resolveAttributes(List<AuthoAttribute> attr);
}


text:
A collection of JvectorMap maps of North America.

Available Maps:

- northAmericaMill
- northAmericaMerc

## Installation:

```
    yarn add @react-jvectormap/northamerica
```

or:

```
    npm install --save @react-jvectormap/northamerica
```

## Usage

```
    import { northAmericaMill } from '@react-jvectormap/northamerica';
```

or:

```
    import northAmericaMill from '@react-jvectormap/northamerica/dist/northAmericaMill';
```


text:
package twittercounter4j.internal;

import twittercounter4j.TwitterCounterException;
import twittercounter4j.User;

import com.google.gson.JsonObject;

/**
 *
 * @author Venil Noronha
 *
 */
public interface IObjectFactory {

	public User createUser(JsonObject jsonObject) throws TwitterCounterException;

}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import model_utils.fields
import django.utils.timezone
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('apartments', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Comment',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)),
                ('message', models.TextField()),
                ('apartment', models.ForeignKey(to='apartments.Apartment')),
                ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Vote',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)),
                ('vote', models.SmallIntegerField(default=0, choices=[(1, b'Like'), (0, b"Don't care"), (-1, b'Dislike')])),
                ('apartment', models.ForeignKey(to='apartments.Apartment')),
                ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
    ]


text:
"""
Genetic algorithm example
In this example we will create a generic genetic algorithm
that can be applied to solve many problems.
"""

from abc import ABC, abstractmethod
from copy import deepcopy
from enum import Enum
from heapq import nlargest
from random import choices, random, randrange
from statistics import mean

class Chromosome(ABC):
    @abstractmethod
    def fitness(self):
        pass

    @classmethod
    @abstractmethod
    def random_instance(cls):
        pass

    @abstractmethod
    def crossover(self, other):
        pass

    @abstractmethod
    def mutate(self):
        pass

SelectionType = Enum('SelectionType', 'ROULETTE TOURNAMENT')

class GeneticAlgorithm:
    def __init__(
        self,
        initial_population,
        threshold,
        max_generations=100,
        mutation_chance=0.01,
        crossover_chance=0.7,
        selection_type=SelectionType.TOURNAMENT,
    ):
        self._population = initial_population
        self._threshold = threshold
        self._max_generations = max_generations
        self._mutation_chance = mutation_chance
        self._crossover_chance = crossover_chance
        self._selection_type = selection_type
        self._fitness_key = type(self._population[0]).fitness

    def _pick_roulette(self, wheel):
        """Choose 2 random participants based on probability (fitness)."""
        return tuple(choices(self._population, weights=wheel, k=2))

    def _pick_tournament(self, num_participants):
        """Choose the 2 best participants from a random list."""
        participants = choices(self._population, k=num_participants)
        return tuple(nlargest(2, participants, key=self._fitness_key))

    def _reproduce_and_replace(self):
        """Create a new generation of population."""
        new_population = list()
        while len(new_population) < len(self._population):
            if self._selection_type == SelectionType.ROULETTE:
                parents = self._pick_roulette(
                    [p.fitness() for p in self._population]
                )
            else:
                parents = self._pick_tournament(len(self._population) // 2)
            # Try to perform a crossover with parents
            if random() < self._crossover_chance:
                new_population.extend(parents[0].crossover(parents[1]))
            else:
                new_population.extend(parents)
        if len(new_population) > len(self._population):
            new_population.pop()
        self._population = new_population

    def _mutate(self):
        """Try to perform a mutation for each individual."""
        for individual in self._population:
            if random() < self._mutation_chance:
                individual.mutate()

    def run(self):
        """Main function responsible for running the algorithm."""
        best = max(self._population, key=self._fitness_key)
        for generation in range(self._max_generations):
            if best.fitness() >= self._threshold:
                return best
            print(
                f'Generation {generation} Best {best.fitness()} '
                f'Avg {mean(map(self._fitness_key, self._population))}'
            )
            self._reproduce_and_replace()
            self._mutate()
            highest = max(self._population, key=self._fitness_key)
            if highest.fitness() > best.fitness():
                best = highest
        return best

# Now, let's use the generic algorithm to solve a simple equation.
# In this example we want to maximize the following equation:
# 6x - x^2 + 4y - y^2
# Tip: the answer should be: x = 3 and y = 2

class SimpleEquation(Chromosome):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def fitness(self):
        """Calculate the equation."""
        return 6 * self.x - self.x * self.x + 4 * self.y - self.y * self.y

    @classmethod
    def random_instance(cls):
        """Create a new random object of SimpleEquation."""
        return SimpleEquation(randrange(100), randrange(100))

    def crossover(self, other):
        """Combine two SimpleEquation parents."""
        child1 = deepcopy(self)
        child2 = deepcopy(other)
        child1.y = other.y
        child2.y = self.y
        return child1, child2

    def mutate(self):
        """Mutate the current SimpleEquation object."""
        # Try to mutate X
        if random() < 0.5:
            if random() < 0.5:
                self.x += 1
            else:
                self.y -= 1
        else:
            if random() < 0.5:
                self.y += 1
            else:
                self.y -= 1

    def __str__(self):
        return f'X: {self.x} Y: {self.y} Fitness: {self.fitness()}'

if __name__ == '__main__':
    initial_population = [SimpleEquation.random_instance() for _ in range(20)]
    ga = GeneticAlgorithm(
        initial_population=initial_population,
        threshold=13.0,
        max_generations=100,
        mutation_chance=0.1,
        crossover_chance=0.7,
    )
    result = ga.run()
    print(result)


text:
title: "Sunday Gathering"
venue: Whitemoor centre
address: John O\' Gaunt\'s Way
postcode: DE56 0DB
allday: false
description:
    The children will be staying in during the morning's gathering.
when: 2018-08-05
starttime: 1030
finishtime: 1215
category: Gathering
layout: event
---


text:
import argparse
import mosquitto
#from pushover import PushoverClient
import os, sys
import urllib2
import json, base64
import ConfigParser

#Posting data to couchDB
def post(doc):

	global config

	url = 'http://%(server)s/%(database)s/_design/energy_data/_update/measurement' % config

	#print "********DEBUG********"
	#print config
	request = urllib2.Request(url, data=json.dumps(doc))
	auth = base64.encodestring('%(user)s:%(password)s' % config).replace('\n', '')
	request.add_header('Authorization', 'Basic ' + auth)
	request.add_header('Content-Type', 'application/json')
	request.get_method = lambda: 'POST'
	urllib2.urlopen(request, timeout=1)

	return

if __name__ == '__main__':

    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('-h', dest='host', default="localhost", help='MQTT host send results to')
    parser.add_argument('-t', dest='topic', default="", help='MQTT topic to process')
    parser.add_argument('-m', dest='message', default="", help='MQTT message to process')

    args = parser.parse_args()

    #Where am I
    path = os.path.abspath(os.path.dirname(sys.argv[0]))

    #Load config file...

    ConfigFile = path + "/couchm.cfg"

    #print "******DEBUG*******"
    #print ConfigFile

    try:
        f = open(ConfigFile,"r")
        f.close()
    except:
        print "Please provide a valid config file! In the same folder as the couchDB script!"
        exit(1)

    #Read config file.
    configfile = ConfigParser.RawConfigParser(allow_no_value=True)
    configfile.read(ConfigFile)

    #Load basic config.

    config = {}
    config["user"] = configfile.get("CouchDB","user")
    config["password"] = configfile.get("CouchDB","password")
    config["server"] = configfile.get("CouchDB","server")
    config["database"] = configfile.get("CouchDB","database")

    source = configfile.get("CouchM","source")

    if args.message[0] == '"':
	args.message = args.message[1:]
    if args.message[-1] == '"':
        args.message = args.message[:-1]

    data = json.loads(args.message)

    #Remove trailing slash
    if args.topic[-1] == "/":
    	topic = args.topic[:-1]
    else:
    	topic = args.topic

    field = topic.split("/")[-1].lower()

    if "value" in data:
    	#Assume power stream only.

    	#Interpolate energy counter
    	try:
    		#Read from file
    		file = open(path + "/couchm.context","r")

    		MeterEvent = json.load(file)
    		file.close()

    		#THIS NEEDS TO BE CHANGED TO MS in other scripts. i.e. 3600000.0
    		deltaT = (data["time"] - MeterEvent["time"])/3600.0

    		MeterEvent["energy"] += (MeterEvent["power"] * deltaT)
    		MeterEvent["power"] = data["value"]
    		MeterEvent["time"] = data["time"]

    	#Or create new
    	except:
    		print "DEBUG:  Creating first MeterEvent"
    		MeterEvent = {}
    		MeterEvent["time"] = data["time"]
    		MeterEvent["power"] = data["value"]
    		MeterEvent["energy"] = 0.0
    		MeterEvent["threshold"] = 1.0

    	#Save
    	try:
    		file = open(path + "/couchm.context","w")
    		json.dump(MeterEvent,file)
    		file.close()
    	except:
    		print "CouchM reactor: Unable to save context!"

    	power = MeterEvent["power"]
    	energy_counter = MeterEvent["energy"]
        power_threshhold = MeterEvent["threshold"]

    elif "threshold" in data:
    	#Assume meterevent
    	power = data["power"]
    	energy_counter = data["energy"]
        power_threshhold = data["threshold"]
    else:
    	print "CouchM reactor: Unable to interpret data"
    	exit(0)

    #Post data to couchm
    post({
                        	"source": source,
	                        "timestamp": str(data["time"]),
	                        "ElectricPower": str(power),
	                        "ElectricEnergy": str(energy_counter),
	                        "PowerThreshold": str(power_threshhold),
				"ElectricPowerUnoccupied": "0.0",
				"ElectricEnergyOccupied": str(energy_counter),
				"ElectricEnergyUnoccupied": "10.0"
                        })


text:
package controller

import (
	"hash/adler32"
	"sync"

	"github.com/golang/groupcache/lru"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	hashutil "k8s.io/kubernetes/pkg/util/hash"
)

type objectWithMeta interface {
	metav1.Object
}

// keyFunc returns the key of an object, which is used to look up in the cache for it's matching object.
// Since we match objects by namespace and Labels/Selector, so if two objects have the same namespace and labels,
// they will have the same key.
func keyFunc(obj objectWithMeta) uint64 {
	hash := adler32.New()
	hashutil.DeepHashObject(hash, &equivalenceLabelObj{
		namespace: obj.GetNamespace(),
		labels:    obj.GetLabels(),
	})
	return uint64(hash.Sum32())
}

type equivalenceLabelObj struct {
	namespace string
	labels    map[string]string
}

// MatchingCache save label and selector matching relationship
type MatchingCache struct {
	mutex sync.RWMutex
	cache *lru.Cache
}

// NewMatchingCache return a NewMatchingCache, which save label and selector matching relationship.
func NewMatchingCache(maxCacheEntries int) *MatchingCache {
	return &MatchingCache{
		cache: lru.New(maxCacheEntries),
	}
}

// Add will add matching information to the cache.
func (c *MatchingCache) Add(labelObj objectWithMeta, selectorObj objectWithMeta) {
	key := keyFunc(labelObj)
	c.mutex.Lock()
	defer c.mutex.Unlock()
	c.cache.Add(key, selectorObj)
}

// GetMatchingObject lookup the matching object for a given object.
// Note: the cache information may be invalid since the controller may be deleted or updated,
// we need check in the external request to ensure the cache data is not dirty.
func (c *MatchingCache) GetMatchingObject(labelObj objectWithMeta) (controller interface{}, exists bool) {
	key := keyFunc(labelObj)
	// NOTE: we use Lock() instead of RLock() here because lru's Get() method also modifies state(
	// it need update the least recently usage information). So we can not call it concurrently.
	c.mutex.Lock()
	defer c.mutex.Unlock()
	return c.cache.Get(key)
}

// Update update the cached matching information.
func (c *MatchingCache) Update(labelObj objectWithMeta, selectorObj objectWithMeta) {
	c.Add(labelObj, selectorObj)
}

// InvalidateAll invalidate the whole cache.
func (c *MatchingCache) InvalidateAll() {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	c.cache = lru.New(c.cache.MaxEntries)
}