text:
var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

cpz.CheckMove = {
  From: 0,
  To: 1,
  ToBefore: 2,
  Ko: 3,
  Ok: 4
};

cpz.Game = cc.Layer.extend({
  _touchListener: null,
  _board: {},
  _gs: null,
  _gl: null,
  _gc: null,
  _lastTouchLocation: null,
  _dragCard: null,
  _dragCardCoord: null,
  _touchLastCard: null,
  _hintCard: null,
  _switchBoardCard: null,
  _makeMoveEnd: function() {
    this._switchBoardCard.setVisible(false);
    if (this._dragCard) {
      this.reorderChild(this._dragCard, cpz.GameZOrder.Card);
      this._dragCard = null;
    }
    return this._hintMove();
  },
  _makeMoveSound: function() {
    return this.getGameScene().playSound('card_move');
  },
  _makeMoveUndoSound: function() {
    return this.getGameScene().playSound('card_undo');
  },
  _hintMove: function() {
    var cTo, coord, move;
    if (this._dragCard) {
      cTo = this._gc.checkRectNode(this._dragCard, cpz.Game.filterCardBoard);
      if (cTo) {
        if (this._hintCard && this._hintCard !== cTo) {
          this._hintCard.setState(cpz.CardBoardState.Empty);
        }
        this._hintCard = cTo;
        coord = this._gl.getPositionInGridCoord(cTo.getPosition());
        move = cpz.mv(this._dragCardCoord, coord);
        if (this.checkMoveCoord(move) === cpz.CheckMove.Ok) {
          return this._hintCard.setState(cpz.CardBoardState.Yes);
        } else {
          return this._hintCard.setState(cpz.CardBoardState.No);
        }
      } else if (this._hintCard) {
        this._hintCard.setState(cpz.CardBoardState.Empty);
        return this._hintCard = null;
      }
    } else if (this._hintCard) {
      this._hintCard.setState(cpz.CardBoardState.Empty);
      return this._hintCard = null;
    }
  },
  _randInitBoard: function() {
    var color, coord, deck, i, initBoard, j, k, rank, _i, _j, _k, _l, _len, _len1, _ref, _ref1, _results;
    deck = [];
    for (k = _i = 1; _i <= 2; k = ++_i) {
      _ref = cc.ObjectValues(cpz.CardPlayColor);
      for (_j = 0, _len = _ref.length; _j < _len; _j++) {
        color = _ref[_j];
        _ref1 = cc.ObjectValues(cpz.CardPlayRank);
        for (_k = 0, _len1 = _ref1.length; _k < _len1; _k++) {
          rank = _ref1[_k];
          deck.push({
            color: color,
            rank: rank
          });
        }
      }
    }
    deck = cc.ArrayShuffle(deck);
    initBoard = this._gs.getConf().getInitBoard();
    initBoard.removeAllObjects();
    k = 0;
    _results = [];
    for (i = _l = 0; _l <= 7; i = ++_l) {
      _results.push((function() {
        var _m, _results1;
        _results1 = [];
        for (j = _m = 1; _m <= 13; j = ++_m) {
          coord = cpz.gc(i, j);
          initBoard.setObject(deck[k], coord);
          _results1.push(k++);
        }
        return _results1;
      })());
    }
    return _results;
  },
  _loadBoard: function() {
    var c, cSwitch, card, cardBoards, cardPlays, conf, coord, data, i, initBoard, j, move, _i, _j, _k, _l, _len, _len1, _len2, _len3, _m, _n, _o, _p, _ref, _ref1, _results;
    conf = this._gs.getConf();
    cardBoards = [];
    cardPlays = [];
    for (i = _i = 0; _i <= 7; i = ++_i) {
      for (j = _j = 0; _j <= 13; j = ++_j) {
        card = this._board[i][j];
        if (card instanceof cpz.CardPlay) {
          cardPlays.push(card);
        } else if (card instanceof cpz.CardBoard) {
          cardBoards.push(card);
        }
      }
    }
    for (i = _k = 0; _k <= 7; i = ++_k) {
      card = null;
      for (_l = 0, _len = cardBoards.length; _l < _len; _l++) {
        c = cardBoards[_l];
        card = c;
        cc.arrayRemoveObject(cardBoards, c);
        break;
      }
      if (!card) {
        card = cpz.CardBoard.createWithConf(conf);
      }
      coord = cpz.gc(i, 0);
      this._board[coord.i][coord.j] = card;
    }
    initBoard = this._gs.getConf().getInitBoard();
    _ref = initBoard.allKeys();
    for (_m = 0, _len1 = _ref.length; _m < _len1; _m++) {
      coord = _ref[_m];
      data = initBoard.object(coord);
      card = null;
      for (_n = 0, _len2 = cardPlays.length; _n < _len2; _n++) {
        c = cardPlays[_n];
        if (data.color === c.getColor() && data.rank === c.getRank()) {
          card = c;
          cc.arrayRemoveObject(cardPlays, c);
          break;
        }
      }
      if (!card) {
        card = cpz.CardPlay.decode(conf, data);
      }
      card.setIsLocked(false);
      this._board[coord.i][coord.j] = card;
    }
    _ref1 = this._gs.getConf().getMoves();
    for (_o = 0, _len3 = _ref1.length; _o < _len3; _o++) {
      move = _ref1[_o];
      cSwitch = this.getCard(move.to);
      this._board[move.to.i][move.to.j] = this._board[move.from.i][move.from.j];
      this._board[move.from.i][move.from.j] = cSwitch;
    }
    _results = [];
    for (i = _p = 0; _p <= 7; i = ++_p) {
      _results.push((function() {
        var _q, _results1;
        _results1 = [];
        for (j = _q = 0; _q <= 13; j = ++_q) {
          coord = cpz.gc(i, j);
          card = this.getCard(coord);
          if (!card.getParent()) {
            this._gc.addNode(card);
            this.addChild(card, cpz.GameZOrder.Card);
            _results1.push(card.setPosition(this._gl.getPositionInBoardPoint(coord)));
          } else {
            _results1.push(void 0);
          }
        }
        return _results1;
      }).call(this));
    }
    return _results;
  },
  ctor: function() {
    var i, j, _i, _results;
    this._super();
    _results = [];
    for (i = _i = 0; _i <= 7; i = ++_i) {
      this._board[i] = {};
      _results.push((function() {
        var _j, _results1;
        _results1 = [];
        for (j = _j = 0; _j <= 13; j = ++_j) {
          _results1.push(this._board[i][j] = null);
        }
        return _results1;
      }).call(this));
    }
    return _results;
  },
  initWithGameScene: function(gs) {
    var initBoard,
      _this = this;
    if (!this.init()) {
      return false;
    }
    this._gs = gs;
    this._gl = new cpz.GameLayout(this);
    this._gc = new cpz.GameControlNode();
    cc.eventManager.addListener(cc.EventListener.create({
      event: cc.EventListener.TOUCH_ONE_BY_ONE,
      swallowTouches: true,
      onTouchBegan: function(touch, event) {
        var location;
        location = touch.getLocation();
        _this.tapDownAt(location);
        return true;
      },
      onTouchMoved: function(touch, event) {
        var location;
        location = touch.getLocation();
        return _this.tapMoveAt(location);
      },
      onTouchEnded: function(touch, event) {
        var location;
        location = touch.getLocation();
        return _this.tapUpAt(location);
      },
      onTouchCancelled: function(touch, event) {
        var location;
        location = touch.getLocation();
        return _this.tapUpAt(location);
      }
    }), this);
    this.layout();
    initBoard = this._gs.getConf().getInitBoard();
    if (initBoard.count() === 0) {
      this._randInitBoard();
    }
    this._loadBoard();
    this.layout();
    this.schedule(this.step);
    return true;
  },
  newGame: function() {
    this._randInitBoard();
    return this.retryGame();
  },
  retryGame: function() {
    this._gs.getConf().clearMoves();
    this._loadBoard();
    this.layout();
    return this._gs.getConf().save();
  },
  step: function(dt) {
    return this._gc.step(dt);
  },
  layout: function(anim) {
    var actions, card, conf, coord, coordPos, i, j, _i, _j, _results;
    if (anim == null) {
      anim = true;
    }
    this._gl.layout(anim);
    conf = this._gs.getConf();
    if (!this._touchLastCard) {
      this._touchLastCard = new cpz.Card();
      this._touchLastCard.initWithTexture(cc.textureNull(), 4);
      this._touchLastCard.setVisible(false);
      this.addChild(this._touchLastCard, cpz.GameZOrder.HintCard);
    }
    conf.getNodeThemePath('cardtouched', this._touchLastCard);
    if (!this._switchBoardCard) {
      this._switchBoardCard = new cpz.CardBoard();
      this._switchBoardCard.initWithTexture(cc.textureNull(), 4);
      this._switchBoardCard.setVisible(false);
      this.addChild(this._switchBoardCard, cpz.GameZOrder.Board);
    }
    this._switchBoardCard.setConf(conf);
    _results = [];
    for (i = _i = 0; _i <= 7; i = ++_i) {
      for (j = _j = 0; _j <= 13; j = ++_j) {
        coord = cpz.gc(i, j);
        card = this.getCard(coord);
        if (card) {
          card.setConf(conf);
          if (card instanceof cpz.CardBoard) {
            card.setPosition(this._gl.getPositionInBoardPoint(coord));
          } else if (card instanceof cpz.CardPlay) {
            coordPos = this._gl.getPositionInBoardPoint(coord);
            if (anim) {
              actions = [];
              actions.push(cc.DelayTime.create(0.05 * (7 - coord.i + coord.j - 1)));
              if (!cc.pointEqualToPoint(card.getPosition(), coordPos)) {
                actions.push(cc.MoveTo.create(1.0, coordPos));
              }
              if (!card.getIsFaceUp()) {
                actions.push(cc.OrbitCamera.create(0.1, 1, 0, 0, 90, 0, 0));
                actions.push(cc.CallFunc.create(card.setIsFaceUp, card, true));
                actions.push(cc.OrbitCamera.create(0.1, 1, 0, 270, 90, 0, 0));
              }
              card.runAction(cc.Sequence.create(actions));
            } else {
              card.setPosition(coordPos);
              card.setIsFaceUp(true);
            }
          }
        }
      }
      _results.push(this.lockLine(i));
    }
    return _results;
  },
  isBusy: function() {
    var i, j, _i, _j;
    for (i = _i = 0; _i <= 7; i = ++_i) {
      for (j = _j = 0; _j <= 13; j = ++_j) {
        if (this._board[i][j] && this._board[i][j].getNumberOfRunningActions() > 0) {
          return true;
        }
      }
    }
    return false;
  },
  getCard: function(coord) {
    if (0 <= coord.i && coord.i < 8 && 0 <= coord.j && coord.j < 14) {
      return this._board[coord.i][coord.j];
    } else {
      return null;
    }
  },
  checkMoveCoord: function(move) {
    var cFrom, cTo, cToBefore, toBefore;
    cFrom = this.getCard(move.from);
    if (!(cFrom instanceof cpz.CardPlay)) {
      return cpz.CheckMove.From;
    }
    cTo = this.getCard(move.to);
    if (!(cTo instanceof cpz.CardBoard)) {
      return cpz.CheckMove.From;
    }
    toBefore = cpz.gc(move.to.i, move.to.j);
    toBefore.j--;
    if (toBefore.j === -1) {
      if (cFrom.getRank() === cpz.CardPlayRank.Ace) {
        return cpz.CheckMove.Ok;
      }
    } else {
      cToBefore = this.getCard(toBefore);
      if (!(cToBefore instanceof cpz.CardPlay)) {
        return cpz.CheckMove.ToBefore;
      }
      if (cFrom.isNextToCardPlay(cToBefore)) {
        return cpz.CheckMove.Ok;
      }
    }
    return cpz.CheckMove.Ko;
  },
  checkMoveCard: function(from, to) {
    return this.checkMoveCoord(cpz.mv(this._gl.getPositionInGridCoord(from), this._gl.getPositionInGridCoord(to)));
  },
  makeMoveCoord: function(move) {
    var cFrom, cSwitch, check;
    check = this.checkMoveCoord(move);
    cFrom = this.getCard(move.from);
    if (check === cpz.CheckMove.Ok) {
      cSwitch = this.getCard(move.to);
      this._board[move.to.i][move.to.j] = this._board[move.from.i][move.from.j];
      this._board[move.from.i][move.from.j] = cSwitch;
      cFrom.runAction(cc.Sequence.create([cc.MoveTo.create(0.5, this._gl.getPositionInBoardPoint(move.to)), cc.CallFunc.create(this._makeMoveEnd, this), cc.CallFunc.create(this._makeMoveSound, this)]));
      if (cSwitch) {
        cSwitch.setPosition(this._gl.getPositionInBoardPoint(move.from));
        if (cSwitch instanceof cpz.CardBoard) {
          cSwitch.setState(cpz.CardBoard.Empty);
        }
      }
      this._switchBoardCard.setPosition(this._gl.getPositionInBoardPoint(move.to));
      this.lockLine(move.to.i);
      this._gs.getConf().pushMove(move);
      this._gs.getConf().save();
    } else if (cFrom) {
      cFrom.runAction(cc.Sequence.create([cc.MoveTo.create(0.5, this._gl.getPositionInBoardPoint(move.from)), cc.CallFunc.create(this._makeMoveEnd, this)]));
    } else {
      this.makeMoveEnd();
    }
    return check;
  },
  makeMoveCard: function(from, to) {
    return this.makeMoveCoord(cpz.mv(this._gl.getPositionInGridCoord(from), this._gl.getPositionInGridCoord(to)));
  },
  undoMove: function() {
    var cSwitch, cTo, move;
    if (this._gs.getConf().getMoves().length === 0 || this.isBusy()) {
      return;
    }
    move = this._gs.getConf().popMove();
    cTo = this.getCard(move.to);
    cSwitch = this.getCard(move.from);
    this._board[move.from.i][move.from.j] = this._board[move.to.i][move.to.j];
    this._board[move.to.i][move.to.j] = cSwitch;
    cTo.runAction(cc.Sequence.create([cc.MoveTo.create(0.5, this._gl.getPositionInBoardPoint(move.from)), cc.CallFunc.create(this._makeMoveEnd, this), cc.CallFunc.create(this._makeMoveUndoSound, this)]));
    if (cSwitch) {
      cSwitch.setPosition(this._gl.getPositionInBoardPoint(move.to));
      if (cSwitch instanceof cpz.CardBoard) {
        cSwitch.setState(cpz.CardBoardState.Empty);
      }
    }
    this._switchBoardCard.setPosition(this._gl.getPositionInBoardPoint(move.from));
    this._switchBoardCard.setVisible(true);
    this.lockLine(move.from.i);
    this.lockLine(move.to.i);
    return move;
  },
  lockLine: function(i) {
    var cBefore, card, j, nb, _i;
    if (__indexOf.call([0, 1, 2, 3, 4, 5, 6, 7], i) < 0) {
      return 0;
    }
    nb = 0;
    for (j = _i = 0; _i <= 13; j = ++_i) {
      card = this._board[i][j];
      if (!(card instanceof cpz.CardPlay)) {
        continue;
      }
      cBefore = j === 0 ? null : this._board[i][j - 1];
      if (j === 0 && card.getRank() === cpz.CardPlayRank.Ace || cBefore instanceof cpz.CardPlay && cBefore.getIsLocked() && card.isNextToCardPlay(cBefore)) {
        card.setIsLocked(true);
        nb++;
      } else {
        card.setIsLocked(false);
      }
    }
    return nb;
  },
  tapDownAt: function(location) {
    var dragCardPos, tapCard;
    if (this._gl.tapDownAt(location)) {
      return;
    }
    if (!this._dragCard && !this.isBusy()) {
      tapCard = this._gc.checkPoint(location);
      if (tapCard instanceof cpz.CardBoard && this._touchLastCard.isVisible() && this.checkMoveCard(this._touchLastCard, tapCard) === cpz.CheckMove.Ok) {
        this._switchBoardCard.setPosition(this._touchLastCard.getPosition());
        this._switchBoardCard.setVisible(true);
        this.makeMoveCard(this._touchLastCard, tapCard);
      }
      if (tapCard instanceof cpz.CardPlay && !tapCard.getIsLocked()) {
        this._dragCardCoord = this._gl.getPositionInGridCoord(tapCard.getPosition());
        this._dragCard = tapCard;
        dragCardPos = this._gl.getPositionInBoardPoint(this._dragCardCoord);
        this._switchBoardCard.setPosition(dragCardPos);
        this._switchBoardCard.setVisible(true);
        this._touchLastCard.setPosition(dragCardPos);
        this.reorderChild(this._dragCard, cpz.GameZOrder.MoveCard);
      }
      this._touchLastCard.setVisible(false);
    }
    this._hintMove();
    return this._lastTouchLocation = cc.p(location);
  },
  tapMoveAt: function(location) {
    var movePos;
    if (this._gl.tapMoveAt(location)) {
      return;
    }
    this._touchLastCard.setVisible(false);
    movePos = cc.pAdd(location, cc.pNeg(this._lastTouchLocation));
    if (this._dragCard) {
      this._dragCard.setPosition(cc.pAdd(this._dragCard.getPosition(), movePos));
    }
    this._hintMove();
    return this._lastTouchLocation = cc.p(location);
  },
  tapUpAt: function(location) {
    var cToCard, check, coord, move;
    if (this._gl.tapUpAt(location)) {
      return;
    }
    if (this._dragCard) {
      cToCard = this._gc.checkRectNode(this._dragCard, cpz.Game.filterCardBoard);
      if (!cToCard) {
        cToCard = this._dragCard;
      }
      coord = this._gl.getPositionInGridCoord(cToCard.getPosition());
      move = cpz.mv(this._dragCardCoord, coord);
      check = this.makeMoveCoord(move);
      if (check !== cpz.CheckMove.Ok && cc.pointEqualToPoint(this._dragCard.getPosition(), this._touchLastCard.getPosition())) {
        this._touchLastCard.setVisible(true);
      }
      this._dragCard = null;
    }
    return this._lastTouchLocation = cc.p(location);
  },
  getGameScene: function() {
    return this._gs;
  },
  getLayout: function() {
    return this._gl;
  },
  getControl: function() {
    return this._gc;
  }
});

cpz.Game.create = function(gs) {
  var obj;
  obj = new cpz.Game();
  if (obj && obj.initWithGameScene(gs)) {
    return obj;
  }
  return null;
};

cpz.Game.filterCardBoard = function(node) {
  return node instanceof cpz.CardBoard;
};


text:
<?php

namespace Lyc\Log;
use Exception;
class LogException extends Exception{

}

?>

redpajama_set_name: RedPajamaGithub


text:
package memap.websocket;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.github.cliftonlabs.json_simple.JsonObject;
import com.github.cliftonlabs.json_simple.Jsoner;
import javax.ws.rs.Consumes;

@Path("/memap")
public class EntryPoint {

    @POST
    @Path("message")
    @Consumes(MediaType.TEXT_PLAIN)
    public Response receiveStartMessage(String startMessage) throws Exception {

    	String response;
    	JsonObject messageJson = (JsonObject) Jsoner.deserialize(startMessage);
    	MemapWebController mwc = new MemapWebController(messageJson);

    	if (messageJson.containsKey("disconnect")) {
			mwc.stopMemap();
			response = "[MEMAP] Simulation terminated. Client Disconnected.";
			System.out.println(response);
		} else {
			response = "[MEMAP] Your startMessage will be processed... ";
			mwc.startMemap();
		}

    	return Response.status(201).entity(response).build();

    }

}


text:
using System;
using System.Data;
using CPTT.BusinessRule;
using CPTT.DataAccess;
using CPTT.SystemFramework;
namespace CPTT.BusinessFacade
{
	/// <summary>
	/// StuVisitInfo µÄժҪ˵Ã÷¡£
	/// </summary>
	public class StuVisitInfoSystem
	{
		StuVisitInfoRule stuVisitInfoRule;
		public StuVisitInfoSystem()
		{
			//
			// TODO: ÔÚ´Ë´¦Ìí¼Ó¹¹Ô캯ÊýÂß¼
			//
			stuVisitInfoRule = new StuVisitInfoRule();
		}

		public DataSet Get2DaysAbsence(string getGrade,string getClass,DateTime getDate)
		{
			using ( StuVisitInfoDataAccess stuVisitInfoDataAccess = new StuVisitInfoDataAccess() )
			{
				try
				{
					return stuVisitInfoDataAccess.Set2DaysAbs(getGrade,getClass,getDate);
				}
				catch(Exception e)
				{
					Util.WriteLog(e.Message,Util.EXCEPTION_LOG_TITLE);
					return null;
				}
			}
		}

		public DataSet GetAbsenceDetail(string getGrade,string getClass,string getName,string getNumber,
			DateTime getBegDate,DateTime getEndDate)
		{
			using ( StuVisitInfoDataAccess stuVisitInfoDataAccess = new StuVisitInfoDataAccess() )
			{
				try
				{
					return stuVisitInfoDataAccess.SetAbsenceDetail(getGrade,getClass,getName,getNumber,
						getBegDate,getEndDate);
				}
				catch(Exception e)
				{
					Util.WriteLog(e.Message,Util.EXCEPTION_LOG_TITLE);
					return null;
				}
			}
		}

		public int DoAbsenceInfoInsert()
		{
			return stuVisitInfoRule.DoAbsenceInfoInsert();
		}

		public void DoAbsenceInfoDelete()
		{
			stuVisitInfoRule.DoAbsenceDelete();
		}

		public void DoAbsenceInfoUpdate()
		{
			stuVisitInfoRule.DoAbsenceUpdate();
		}

		public string GetAbsenceDetailInMonth(int getNumber,DateTime getDate)
		{
			return stuVisitInfoRule.GetAbsDetail(getNumber,getDate);
		}

		public void GetNumber(int getNumber)
		{
			stuVisitInfoRule.SetStuNumber(getNumber);
		}

		public void GetReason(string getReason)
		{
			stuVisitInfoRule.SetAbsReason(getReason);
		}

		public void GetMode(string getMode)
		{
			stuVisitInfoRule.SetVisitMode(getMode);
		}

		public void GetDate(DateTime getDate)
		{
			stuVisitInfoRule.SetVisitDate(getDate);
		}

		public void GetSign(string getSign)
		{
			stuVisitInfoRule.SetVisitTeaSign(getSign);
		}

		public void GetRemark(string getRemark)
		{
			stuVisitInfoRule.SetAbsRemark(getRemark);
		}

		public void GetSourceReason(string getReason)
		{
			stuVisitInfoRule.GetAbsReason(getReason);
		}

		public void GetSourceMode(string getMode)
		{
			stuVisitInfoRule.GetVisitMode(getMode);
		}

		public void GetSourceDate(DateTime getDate)
		{
			stuVisitInfoRule.GetVisitDate(getDate);
		}

		public void GetSourceSign(string getSign)
		{
			stuVisitInfoRule.GetVisitTeaSign(getSign);
		}

		public void GetSourceRemark(string getRemark)
		{
			stuVisitInfoRule.GetAbsRemark(getRemark);
		}
	}
}


text:
// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_fuzzy.h"
// --------------------------------------------------------------------------------

OPEN_RDO_RUNTIME_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- DefineArea
// --------------------------------------------------------------------------------
DefineArea::DefineArea()
{
	IntervalType mType = DomainPart::open(-10e15, 10e15);
	m_domain = Domain(mType);
}

DefineArea::~DefineArea()
{}

DefineArea::DefineArea(const RDOValue& leftRange, const RDOValue& rightRange)
{
	IntervalType mType = DomainPart::closed(leftRange, rightRange);
	m_domain = Domain(mType);
}
DefineArea::DefineArea(const RDOValue& value)
{
	IntervalType mType = DomainPart::closed(value,value);
	m_domain = Domain(mType);
}

// --------------------------------------------------------------------------------
// -------------------- FuzzySet
// --------------------------------------------------------------------------------
RDOValue fun_add (const RDOValue& value1, const RDOValue& value2) { return value1 + value2; }
RDOValue fun_sub (const RDOValue& value1, const RDOValue& value2) { return value1 - value2; }
RDOValue fun_mult(const RDOValue& value1, const RDOValue& value2) { return value1 * value2; }
RDOValue fun_div (const RDOValue& value1, const RDOValue& value2) { return value1 / value2; }

FuzzySet::FuzzySet()
{}

FuzzySet::FuzzySet(const LPDefineArea& pDefineArea)
	: m_defineArea(pDefineArea)
{}

FuzzySet::FuzzySet(const LPFuzzySet& pSet)
	: m_fuzzySet  (pSet->m_fuzzySet  )
	, m_defineArea(pSet->m_defineArea)
{}

FuzzySet::~FuzzySet()
{}

void FuzzySet::setValues(const FuzzySetDefinition& values)
{
	m_fuzzySet = values;
}

LPFuzzySet FuzzySet::append(const RDOValue& rdovalue, double appertain)
{
	std::pair<FuzzySet::FuzzySetDefinition::iterator, bool> checkValue;
	checkValue = m_fuzzySet.insert(std::pair<RDOValue,double>(rdovalue, appertain));
	return LPFuzzySet(this);
}

LPFuzzySet FuzzySet::operator() (const RDOValue& rdovalue, double appertain)
{
	return append(rdovalue, appertain);
}

double& FuzzySet::operator[] (const RDOValue& rdovalue)
{
	return m_fuzzySet[rdovalue];
}

FuzzySet::FuzzySetDefinition::const_iterator FuzzySet::find(const RDOValue& rdovalue) const
{
	return m_fuzzySet.find(rdovalue);
}

FuzzySet::FuzzyItem FuzzySet::findValue(const RDOValue& rdovalue) const
{
	FuzzySetDefinition::const_iterator found = find(rdovalue);
	if (found != end()) return FuzzyItem(found->first, found->second);
	else                return FuzzyItem(rdovalue,     0.0          );
}

FuzzySet::FuzzySetDefinition::const_iterator FuzzySet::begin() const { return m_fuzzySet.begin(); }
FuzzySet::FuzzySetDefinition::const_iterator FuzzySet::end  () const { return m_fuzzySet.end();   }
FuzzySet::FuzzySetDefinition::iterator       FuzzySet::begin()       { return m_fuzzySet.begin(); }
FuzzySet::FuzzySetDefinition::iterator       FuzzySet::end  ()       { return m_fuzzySet.end();   }
bool                                         FuzzySet::empty() const { return m_fuzzySet.empty(); }
bool FuzzySet::inRange (const RDOValue& rdovalue)
{
	return m_fuzzySet.find(rdovalue) != m_fuzzySet.end();
}

LPFuzzySet FuzzySet::operator+ (const LPFuzzySet& pSet) const
{
	LPFuzzySet pThis(const_cast<FuzzySet*>(this));
	return MemberFunctionProperties::ext_binary(fun_add, pThis, pSet);
}
LPFuzzySet FuzzySet::operator- (const LPFuzzySet& pSet) const
{
	LPFuzzySet pThis(const_cast<FuzzySet*>(this));
	return MemberFunctionProperties::ext_binary(fun_sub, pThis, pSet);
}
LPFuzzySet FuzzySet::operator* (const LPFuzzySet& pSet) const
{
	LPFuzzySet pThis(const_cast<FuzzySet*>(this));
	return MemberFunctionProperties::ext_binary(fun_mult, pThis, pSet);
}
LPFuzzySet FuzzySet::operator/ (const LPFuzzySet& pSet) const
{
	LPFuzzySet pThis(const_cast<FuzzySet*>(this));
	return MemberFunctionProperties::ext_binary(fun_div, pThis, pSet);
}

RDOValue fun_u_minus(const RDOValue& rdovalue             ) { return -rdovalue;                                    }
RDOValue fun_u_obr  (const RDOValue& rdovalue             ) { return RDOValue(1)/rdovalue;                         }
RDOValue fun_u_scale(const RDOValue& rdovalue, void* scale) { return rdovalue * (*static_cast<double*>(scale));    }
RDOValue fun_u_log  (const RDOValue& rdovalue             ) { return rdovalue > 0 ? log(rdovalue.getDouble()) : 0; }

LPFuzzySet MemberFunctionProperties::u_minus(const LPFuzzySet& pSet)               { return ext_unary(fun_u_minus,           pSet); }
LPFuzzySet MemberFunctionProperties::u_obr  (const LPFuzzySet& pSet)               { return ext_unary(fun_u_obr,             pSet); }
LPFuzzySet MemberFunctionProperties::u_scale(const LPFuzzySet& pSet, double scale) { return ext_unary(fun_u_scale, &scale, pSet);   }
LPFuzzySet MemberFunctionProperties::u_log  (const LPFuzzySet& pSet)               { return ext_unary(fun_u_log,             pSet); }

std::string FuzzySet::getAsString() const
{
	if (empty())
		return "[empty value]";

	std::string res = "";
	FuzzySetDefinition::const_iterator it = begin();
	while (it != end())
	{
		const bool output = it->second > 0.0;
		if (output)
			res += rdo::format("<%s/%.2lf>", it->first.getAsString().c_str(), it->second);

		++it;

		if (output && it != end())
			res += " ";
	}
	return res;
}

LPFuzzySet FuzzySet::clone() const
{
	return rdo::Factory<FuzzySet>::create(LPFuzzySet(const_cast<FuzzySet*>(this)));
}

LPFuzzySet FuzzySet::operator&& (const LPFuzzySet& pSet) const
{
	LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create();
	ASSERT(pFuzzySetResult);
	// Найдем только пересекающие элементы и выберем минимальную функцию принадлежности
	FuzzySetDefinition::const_iterator it1 = begin();
	while (it1 != end())
	{
		FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet->find(it1->first);
		if (it2 != pSet->end())
		{
			pFuzzySetResult->operator[](it1->first) = (std::min)(it1->second, it2->second);
		}
		++it1;
	}
	return pFuzzySetResult;
}

LPFuzzySet FuzzySet::operator|| (const LPFuzzySet& pSet)const
{
	LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create();
	ASSERT(pFuzzySetResult);
	// Объединим элементы двух множеств
	// Если элемент одновременно принадлежит обоим множествам, то выберем максимальную функцию принадлежности
	FuzzySetDefinition::const_iterator it1 = begin();
	while (it1 != end())
	{
		FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet->find(it1->first);
		if (it2 != pSet->end())
		{
			pFuzzySetResult->operator[](it1->first) = (std::max)(it1->second, it2->second);
		}
		else
		{
			// Не нашли пары
			pFuzzySetResult->operator[](it1->first) = it1->second;
		}
		++it1;
	}
	FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet->begin();
	while (it2 != pSet->end())
	{
		FuzzySetDefinition::const_iterator it1 = find(it2->first);
		if (it1 == end())
		{
			// Не нашли пары
			pFuzzySetResult->operator[](it2->first) = it2->second;
		}
		++it2;
	}
	return pFuzzySetResult;
}

// --------------------------------------------------------------------------------
// -------------------- MemberFunctionProperties
// --------------------------------------------------------------------------------
/// @todo комментарии в *.h
//! Декартово произведение (попарное) элементов двух множест с применением произвольной функции fun
LPFuzzySet MemberFunctionProperties::ext_binary(ExtBinaryFun fun, const LPFuzzySet& pSet1, const LPFuzzySet& pSet2)
{
	FuzzySet::FuzzySetDefinition values;
	FuzzySet::FuzzySetDefinition::const_iterator it1 = pSet1->begin();
	while (it1 != pSet1->end())
	{
		FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet2->begin();
		while (it2 != pSet2->end())
		{
			RDOValue rdo_value = fun(it1->first, it2->first);
			FuzzySet::FuzzySetDefinition::iterator val = values.find(rdo_value);
			if (val == values.end())
			{
				values[rdo_value] = (std::min)(it1->second, it2->second);
			}
			else
			{
				values[rdo_value] = (std::max)(val->second, (std::min)(it1->second, it2->second));
			}
			++it2;
		}
		++it1;
	}

	if (!values.empty())
	{
		LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create();
		ASSERT(pFuzzySetResult);
		pFuzzySetResult->setValues(values);

		return pFuzzySetResult;
	}

	return LPFuzzySet();
}

//! Преобразование элементов через произвольную функцию fun
LPFuzzySet MemberFunctionProperties::ext_unary(ExtUnaryFun fun, const LPFuzzySet& pSet)
{
	FuzzySet::FuzzySetDefinition values;
	FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin();
	while (it != pSet->end())
	{
		RDOValue rdo_value = fun(it->first);
		FuzzySet::FuzzySetDefinition::iterator val = values.find(rdo_value);
		if (val == values.end())
		{
			values[rdo_value] = it->second;
		}
		else
		{
			values[rdo_value] = (std::max)(val->second, it->second);
		}
		++it;
	}

	if (!values.empty())
	{

		LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create();
		ASSERT(pFuzzySetResult);
		pFuzzySetResult->setValues(values);

		return pFuzzySetResult;
	}

	return LPFuzzySet();
}

LPFuzzySet MemberFunctionProperties::ext_unary(ExtUnaryFunP fun, void* pParam, const LPFuzzySet& pSet)
{
	FuzzySet::FuzzySetDefinition values;
	FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin();
	while (it != pSet->end())
	{
		RDOValue rdo_value = fun(it->first, pParam);
		FuzzySet::FuzzySetDefinition::iterator val = values.find(rdo_value);
		if (val == values.end())
		{
			values[rdo_value] = it->second;
		}
		else
		{
			values[rdo_value] = (std::max)(val->second, it->second);
		}
		++it;
	}

	if (!values.empty())
	{

		LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create();
		ASSERT(pFuzzySetResult);
		pFuzzySetResult->setValues(values);
		return pFuzzySetResult;
	}

	return LPFuzzySet();
}

LPFuzzySet MemberFunctionProperties::a_con (const LPFuzzySet& pSet)
{
	return a_pow(pSet, 2.0);
}

LPFuzzySet MemberFunctionProperties::a_dil (const LPFuzzySet& pSet)
{
	return a_pow(pSet, 0.5);
}

LPFuzzySet MemberFunctionProperties::a_mult(const LPFuzzySet& pSet1, const LPFuzzySet& pSet2)
{
	LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create();
	ASSERT(pFuzzySetResult);

	// Найдем только пересекающие элементы и перемножим функции принадлежности
	FuzzySet::FuzzySetDefinition::const_iterator it1 = pSet1->begin();
	for (it1 = pSet1->begin(); it1 != pSet1->end(); ++it1)
	{
		FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet2->find(it1->first);
		if (it2 != pSet2->end())
		{
			pFuzzySetResult->operator[](it1->first) = it1->second * it2->second;
		}
	}
	return pFuzzySetResult;
}

LPFuzzySet MemberFunctionProperties::alpha(const LPFuzzySet& pSet,double appertain)
{
	if (appertain < 0) appertain = 0;
	else if (appertain > 1) appertain = 1;

	LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create();
	ASSERT(pFuzzySetResult);

	FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin();

	// Найдем отсечку
	while (it != pSet->end())
	{
		if (it->second >= appertain)
		{
			pFuzzySetResult->operator[](it->first) = pSet->operator[](it->first);
		}
		++it;
	}
	return pFuzzySetResult;
}

LPFuzzySet MemberFunctionProperties::supplement(const LPFuzzySet& pSet)
{
	LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(pSet);
	ASSERT(pFuzzySetResult);

	FuzzySet::FuzzySetDefinition::iterator it = pFuzzySetResult->begin();
	while (it != pFuzzySetResult->end())
	{
		it->second = 1-(it->second);
		++it;
	}
	return(pFuzzySetResult);
}

LPFuzzySet MemberFunctionProperties::a_pow(LPFuzzySet pSet, double power)
{
	LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(pSet);
	ASSERT(pFuzzySetResult);

	// Возведём в степень
	FuzzySet::FuzzySetDefinition::iterator it = pFuzzySetResult->begin();
	while (it != pFuzzySetResult->end())
	{
		it->second = pow(it->second, power); ///flag
		++it;
	}
	return pFuzzySetResult;
}

LPRDOLingvoVariable MemberFunctionProperties::fuzzyfication(const RDOValue&value, const LPRDOLingvoVariable& variable)
{
	LPRDOLingvoVariable pVariable = rdo::Factory<RDOLingvoVariable>::create(value, variable);
	for (RDOLingvoVariable::TermSet::const_iterator it = variable->begin(); it != variable->end(); ++it)
	{
		LPFuzzySet pSet = rdo::Factory<FuzzySet>::create(it->second);
		FuzzySet::FuzzyItem item = pSet->findValue(value);
		LPFuzzySet newSet = rdo::Factory<FuzzySet>::create();
		newSet->append(item.first, item.second);
		pVariable->append(it->first, newSet);
	}
	return pVariable;
}

RDOValue MemberFunctionProperties::defuzzyfication(const LPFuzzySet& pSet)
{
	FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin();
	if (it == pSet->end())
		return RDOValue();

	FuzzySet::FuzzySetDefinition::const_iterator it_next = it;
	++it_next;
	if (it_next == pSet->end())
		return it->first;

	double g      = 0;
	double f      = 0;
	double x      = it->first.getDouble();
	double x_next = it_next->first.getDouble();
	double a      = it->second;
	double b      = it_next->second;
	double h      = x_next - x;
	for (;;)
	{
		double t = h*(a+b)/2.0;
		g += t*(x_next + x)/2.0;
		f += t;

		++it;
		++it_next;
		if (it_next == pSet->end())
			break;

		x      = x_next;
		a      = b;
		x_next = it_next->first.getDouble();
		b      = it_next->second;
		h      = x_next - x;
	}
	return g / f;
}

// --------------------------------------------------------------------------------
// -------------------- RDOFuzzyTerm
// --------------------------------------------------------------------------------
const LPFuzzySet& RDOFuzzyTerm::getFuzzySetDefinition() const
{
	return (m_term.second);
}
std::string RDOFuzzyTerm::getName() const
{
	return (m_term.first);
}
RDOFuzzyTerm::RDOFuzzyTerm(const termName& pName, const LPFuzzySet& pSet)
{
    m_term = std::make_pair(pName, pSet);
}

RDOFuzzyTerm::~RDOFuzzyTerm()
{}

// --------------------------------------------------------------------------------
// -------------------- RDOLingvoVariable
// --------------------------------------------------------------------------------
RDOLingvoVariable::TermSet::const_iterator RDOLingvoVariable::begin() const     {return m_set.begin();}
RDOLingvoVariable::TermSet::const_iterator RDOLingvoVariable::end  () const     {return m_set.end  ();}
RDOLingvoVariable::RDOLingvoVariable(const LPRDOFuzzyTerm& term, nameOfVariable nameOfVariable)
{
	m_name = nameOfVariable;
	m_set.insert(make_pair(term->getName(), term->getFuzzySetDefinition()));
}

RDOLingvoVariable::RDOLingvoVariable(const RDOValue&pDefineAreaValue, const LPRDOLingvoVariable& variable)
	: m_name("activated")
{
	LPDefineArea   defineArea    = rdo::Factory<DefineArea>::create(pDefineAreaValue);
	LPFuzzySet     setOfVariable = rdo::Factory<FuzzySet>::create(defineArea);
	for (RDOLingvoVariable::TermSet::const_iterator it = variable->begin(); it != variable->end(); it++)
	{
		m_set.insert(std::pair<RDOFuzzyTerm::Term::first_type,LPFuzzySet>(it->first,setOfVariable));
	}
}

RDOLingvoVariable::RDOLingvoVariable(const RDOLingvoVariable& variable)
{
	m_set = variable.m_set;
	m_name  = variable.m_name;
}

RDOLingvoVariable::~RDOLingvoVariable()
{}

void RDOLingvoVariable::setName(nameOfVariable nameVariable)
{
	m_name = nameVariable;
}

LPFuzzySet& RDOLingvoVariable::operator[] (std::string name)
{
	return m_set[name];
}

void RDOLingvoVariable::append(std::string name, const LPFuzzySet& fuzzySet)
{
	operator[](name) = fuzzySet;
}

// --------------------------------------------------------------------------------
// -------------------- Statement
// --------------------------------------------------------------------------------
void Statement::setTerm(LPRDOFuzzyTerm term)
{
	m_term = term;
}

void Statement::setVariable(LPRDOLingvoVariable variable)
{
	m_variable = variable;
}

Statement::Statement()
{}

Statement::~Statement()
{}

CLOSE_RDO_RUNTIME_NAMESPACE


text:
var cssFilesToInject = [
  'styles/main.css'
];
var jsFilesToInject = [
  'js/dependencies/sails.io.js',
  'js/ui.js'
];
var templateFilesToInject = [
  'templates/**/*.html'
];
var tmpPath = '.tmp/public/';
module.exports.cssFilesToInject = cssFilesToInject.map(function(cssPath) {
  if (cssPath[0] === '!') {
    return require('path').join('!.tmp/public/', cssPath.substr(1));
  }
  return require('path').join('.tmp/public/', cssPath);
});
module.exports.jsFilesToInject = jsFilesToInject.map(function(jsPath) {
  if (jsPath[0] === '!') {
    return require('path').join('!.tmp/public/', jsPath.substr(1));
  }
  return require('path').join('.tmp/public/', jsPath);
});
module.exports.templateFilesToInject = templateFilesToInject.map(function(tplPath) {
  if (tplPath[0] === '!') {
    return require('path').join('!assets/', tplPath.substr(1));
  }
  return require('path').join('assets/', tplPath);
});


text:
FROM iojs:onbuild

# File Author
MAINTAINER Andrew Shapro

# Install pm2 for control the process
RUN npm install -g pm2

EXPOSE 3000

# run the app with pm2
CMD [ "pm2", "start", "./bin/www", "--no-daemon" ]


text:
body {
    background: #fff url("../img/music_bg.svg");
}


text:
package pinnacle.api.enums;

import java.util.Arrays;

public enum ROUND_ROBIN_OPTIONS {

	SINGLE_PARLAY("Parlay"),
	BY_2_LEGS("TwoLegRoundRobin"),
	BY_3_LEGS("ThreeLegRoundRobin"),
	BY_4_LEGS("FourLegRoundRobin"),
	BY_5_LEGS("FiveLegRoundRobin"),
	BY_6_LEGS("SixLegRoundRobin"),
	BY_7_LEGS("SevenLegRoundRobin"),
	BY_8_LEGS("EightLegRoundRobin"),
	UNDEFINED("undefined");

	private final String value;

	private ROUND_ROBIN_OPTIONS (final String value) {
		this.value = value;
	}

	public String toAPI () {
		return this.value;
	}

	public static ROUND_ROBIN_OPTIONS fromAPI (String value) {
		return Arrays.stream(ROUND_ROBIN_OPTIONS.values())
		             .filter(e -> e.value.equals(value))
		             .findAny()
		             .orElse(ROUND_ROBIN_OPTIONS.UNDEFINED);
	}
}


text:
<!--

    Licensed to Apereo under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Apereo licenses this file to you under the Apache License,
    Version 2.0 (the "License"); you may not use this file
    except in compliance with the License.  You may obtain a
    copy of the License at the following location:

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

-->
<PersonDirs>
	<!-- An example PersonDirs.xml file which configures a single
		attribute source using directly configured JDBC.
		This file is used for the PersonDirXmlParserTester testcase - this file should
		only be modified in coordination with modifications to that testcase. -->
	<PersonDirInfo>
		<driver>org.hsql.jdbcDriver</driver>
		<url>jdbc:HypersonicSQL:hsql://localhost:8887</url>
		<logonid>username</logonid>
		<logonpassword>password</logonpassword>
		<!-- "SELECT *" is a very bad idea - best practices are to list explicitly the
			columns to be selected.  However this shorter query string is easier to test -->
		<uidquery>select * from schema.table where netid=?</uidquery>
		<attributes>
			<attribute>
				<name>first_last</name>
				<alias>displayName</alias>
			</attribute>
			<attribute>
				<name>last_name</name>
				<alias>sn</alias>
			</attribute>
			<attribute>
				<name>role</name>
				<alias>uPortalAffiliation</alias>
			</attribute>
			<attribute>
				<name>first_name</name>
				<alias>givenName</alias>
			</attribute>
			<attribute>
				<name>email_alias</name>
				<alias>email</alias>
			</attribute>
			<attribute>
				<name>alias</name>
				<alias>alias</alias>
			</attribute>
			<attribute>
				<name>person_type</name>
				<alias>personType</alias>
			</attribute>
			<attribute>
				<name>college</name>
				<alias>YaleCollege</alias>
			</attribute>
			<attribute>
				<name>class_year</name>
				<alias>ClassYear</alias>
			</attribute>
			<attribute>
				<name>student_status</name>
				<alias>StudentStatus</alias>
			</attribute>
			<attribute>
				<name>template</name>
				<alias>uPortalTemplateUserName</alias>
			</attribute>
			<attribute>
				<name>netid</name>
				<alias>netid</alias>
			</attribute>
			<attribute>
				<name>netid</name>
				<alias>eduPersonPrincipalName</alias>
			</attribute>
			<attribute>
				<name>work_phone</name>
				<alias>WorkPhone</alias>
			</attribute>
		</attributes>
	</PersonDirInfo>

	<PersonDirInfo>
		<res-ref-name>PersonDb</res-ref-name>
		<!-- "SELECT *" is a very bad idea - best practices are to list explicitly the
			columns to be selected.  However this shorter query string is easier to test -->
		<uidquery>select * from schema.table where netid=?</uidquery>
		<attributes>
			<attribute>
				<name>first_last</name>
				<alias>displayName</alias>
			</attribute>
			<attribute>
				<name>last_name</name>
				<alias>sn</alias>
			</attribute>
			<attribute>
				<name>role</name>
				<alias>uPortalAffiliation</alias>
			</attribute>
			<attribute>
				<name>first_name</name>
				<alias>givenName</alias>
			</attribute>
			<attribute>
				<name>email_alias</name>
				<alias>email</alias>
			</attribute>
			<attribute>
				<name>alias</name>
				<alias>alias</alias>
			</attribute>
			<attribute>
				<name>person_type</name>
				<alias>personType</alias>
			</attribute>
			<attribute>
				<name>college</name>
				<alias>YaleCollege</alias>
			</attribute>
			<attribute>
				<name>class_year</name>
				<alias>ClassYear</alias>
			</attribute>
			<attribute>
				<name>student_status</name>
				<alias>StudentStatus</alias>
			</attribute>
			<attribute>
				<name>template</name>
				<alias>uPortalTemplateUserName</alias>
			</attribute>
			<attribute>
				<name>netid</name>
				<alias>netid</alias>
			</attribute>
			<attribute>
				<name>netid</name>
				<alias>eduPersonPrincipalName</alias>
			</attribute>
			<attribute>
				<name>work_phone</name>
				<alias>WorkPhone</alias>
			</attribute>
		</attributes>
	</PersonDirInfo>

		<PersonDirInfo>
		<url>ldaps://mrfrumble.its.yale.edu:389/o=yale.edu</url>
		<logonid>someUser</logonid>
		<logonpassword>somePassword</logonpassword>
		<uidquery>(uid={0})</uidquery>
		<usercontext></usercontext>
		<attributes>
			<attribute>
				<name>mail</name>
				<alias>emailfromldap</alias>
			</attribute>
		</attributes>
	</PersonDirInfo>

	<PersonDirInfo>
		<ldap-ref-name>DEFAULT_LDAP_SERVER</ldap-ref-name>
		<uidquery>(cn={0})</uidquery>
		<usercontext>cn=Users</usercontext>
		<attributes>
			<attribute>
				<alias>uPortalTemplateUserName</alias>
				<name>eduPersonPrimaryAffiliation</name>
			</attribute>
			<attribute>
				<alias>eduPersonAffiliation</alias>
				<name>eduPersonAffiliation</name>
			</attribute>
			<attribute>
				<alias>eduPersonNickname</alias>
				<name>eduPersonNickname</name>
			</attribute>
			<attribute>
				<alias>eduPersonOrgDN</alias>
				<name>eduPersonOrgDN</name>
			</attribute>
			<attribute>
				<alias>eduPersonOrgUnitDN</alias>
				<name>eduPersonOrgUnitDN</name>
			</attribute>
			<attribute>
				<alias>eduPersonPrimaryAffiliation</alias>
				<name>eduPersonPrimaryAffiliation</name>
			</attribute>
			<attribute>
				<alias>eduPersonPrincipalName</alias>
				<name>eduPersonPrincipalName</name>
			</attribute>
			<attribute>
				<alias>c</alias>
				<name>c</name>
			</attribute>
			<attribute>
				<alias>cn</alias>
				<name>cn</name>
			</attribute>
			<attribute>
				<alias>description</alias>
				<name>description</name>
			</attribute>
			<attribute>
				<alias>displayName</alias>
				<name>displayName</name>
			</attribute>
			<attribute>
				<alias>facsimileTelephoneNumber</alias>
				<name>facsimileTelephoneNumber</name>
			</attribute>
			<attribute>
				<alias>givenName</alias>
				<name>givenName</name>
			</attribute>
		</attributes>
	</PersonDirInfo>

</PersonDirs>


text:
package com.jayjaylab.lesson.gallery.fragment;

import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.InputEvent;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ClientCertRequest;
import android.webkit.HttpAuthHandler;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.jayjaylab.lesson.gallery.R;
import com.jayjaylab.lesson.gallery.util.LogTag;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;

/**
 * Created by jjkim on 2016. 7. 19..
 */
public class FragmentTab4 extends Fragment {
    public static final String TAG = FragmentTab4.class.getSimpleName();
    @BindView(R.id.webview) WebView webView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.layout_fragment_tab4, container, false);
        init();
        return rootView;
    }

    void init() {
        setWebView();
        testThreadPool();
    }

    void testThreadPool() {
        // 3 : core pool size
        // 5 : maximum pool size
        ExecutorService threadPool = new ThreadPoolExecutor(1, 1, 3, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(100));
        threadPool.submit(new Runnable() {
            @Override
            public void run() {

            }
        });
        threadPool.execute(new Runnable() {
            @Override
            public void run() {

            }
        });
    }

    void setWebView() {
        if(LogTag.DEBUG) Log.d(TAG, "setWebView()");
        webView.loadUrl("http://m.naver.com/");
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
            }

            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                super.onFormResubmission(view, dontResend, resend);
            }

            @Override
            public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
                super.doUpdateVisitedHistory(view, url, isReload);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
            }

            @Override
            public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
                super.onReceivedClientCertRequest(view, request);
            }

            @Override
            public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
                super.onReceivedHttpAuthRequest(view, handler, host, realm);
            }

            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                return super.shouldOverrideKeyEvent(view, event);
            }

            @Override
            public void onUnhandledInputEvent(WebView view, InputEvent event) {
                super.onUnhandledInputEvent(view, event);
            }

            @Override
            public void onScaleChanged(WebView view, float oldScale, float newScale) {
                super.onScaleChanged(view, oldScale, newScale);
            }

            @Override
            public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
                super.onReceivedLoginRequest(view, realm, account, args);
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onCloseWindow(WebView window) {
                super.onCloseWindow(window);
            }

            @Override
            public void onRequestFocus(WebView view) {
                super.onRequestFocus(view);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }

            @Override
            public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
                return super.onJsBeforeUnload(view, url, message, result);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });
    }
}


text:
describe Nanoc::Tilt::Filter do
  it 'supports .erb' do
    item = Nanoc::Core::Item.new('stuff', {}, '/foo.erb')
    item_rep = Nanoc::Core::ItemRep.new(item, :default)

    filter = ::Nanoc::Tilt::Filter.new({ item: item, item_rep: item_rep })

    res = filter.run('<%= "a" * 3 %>')
    expect(res.strip).to eq('aaa')
  end

  it 'supports .erb with options' do
    item = Nanoc::Core::Item.new('stuff', {}, '/foo.erb')
    item_rep = Nanoc::Core::ItemRep.new(item, :default)

    filter = ::Nanoc::Tilt::Filter.new({ item: item, item_rep: item_rep })

    res = filter.run('<%= "&" * 3 %>', args: { escape: false })
    expect(res.strip).to eq('&&&')

    res = filter.run('<%= "&" * 3 %>', args: { escape: true })
    expect(res.strip).to eq('&&&')
  end
end


text:
require "active_xml/version"
require 'active_xml/collection'
require 'active_xml/collection/query'
require 'active_xml/collection/route'
require 'active_xml/object'
require 'nokogiri'
require 'active_support/core_ext/hash/conversions'
require 'pathname'

require 'fileutils'

module ActiveXML
  attr_reader :path

  def initialize(path)
    @path = Pathname.new(path)
    create_file(@path, '<null_tag/>') unless @path.exist?
    set_root!
  end

  def xml
    @xml ||= Nokogiri::XML(@path.read)
  end

  def set_root!
    xml.root.name = root
  end

  def save
    @path.open('w') {|f| f.write(@xml.to_xml) }
  end

  def delete_node(key)
    xml.search(key).remove
  end

  private

  def create_directory(path)
    path.descend do |pathname|
      pathname.dirname.mkdir unless pathname.dirname.exist?
    end
  end

  def fetch_contents(source, key)
    source.css(key.to_s).map(&:content)
  end

  def create_file(path, text)
    create_directory(path)
    path.open('w') {|f| f.write(text)}
  end
end


text:
// Copyright 2012 Mozilla Corporation. All rights reserved.
// This code is governed by the license found in the LICENSE file.

/*---
es5id: 12.2.3_c
description: >
    Tests that Intl.DateTimeFormat provides the required date-time
    format component subsets.
author: Norbert Lindenberg
includes: [testIntl.js]
---*/

var locales = ["de-DE", "en-US", "hi-IN", "id-ID", "ja-JP", "th-TH", "zh-Hans-CN", "zh-Hant-TW", "zxx"];
var subsets = [
    {weekday: "long", year: "numeric", month: "numeric", day: "numeric",
        hour: "numeric", minute: "numeric", second: "numeric"},
    {weekday: "long", year: "numeric", month: "numeric", day: "numeric"},
    {year: "numeric", month: "numeric", day: "numeric"},
    {year: "numeric", month: "numeric"},
    {month: "numeric", day: "numeric"},
    {hour: "numeric", minute: "numeric", second: "numeric"},
    {hour: "numeric", minute: "numeric"}
];

locales.forEach(function (locale) {
    subsets.forEach(function (subset) {
        var format = new Intl.DateTimeFormat([locale], subset);
        var actual = format.resolvedOptions();
        getDateTimeComponents().forEach(function (component) {
            if (actual.hasOwnProperty(component)) {
                if (!subset.hasOwnProperty(component)) {
                    $ERROR("Unrequested component " + component +
                        " added to requested subset " + JSON.stringify(subset) +
                        "; locale " + locale + ".");
                }
                try {
                    testValidDateTimeComponentValue(component, actual[component]);
                } catch (e) {
                    e.message += " (Testing locale " + locale + "; subset " +
                        JSON.stringify(subset) + ")";
                    throw e;
                }
            } else {
                if (subset.hasOwnProperty(component)) {
                    $ERROR("Missing component " + component +
                        " from requested subset " + JSON.stringify(subset) +
                        "; locale " + locale + ".");
                }
            }
        });
    });
});


text:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link href='https://fonts.googleapis.com/css?family=Architects+Daughter' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
    <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen">
    <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">

    <title>Owen002.GitHub.io by owen002</title>

Owen002

ONLINE PAGE

            Follow me on
            GitHub


text:
// Package tide contains a controller for managing a tide pool of PRs. The
// controller will automatically retest PRs in the pool and merge them if they
// pass tests.
package tide

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	githubql "github.com/shurcooL/githubv4"
	"github.com/sirupsen/logrus"

	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/test-infra/prow/config"
	"k8s.io/test-infra/prow/git"
	"k8s.io/test-infra/prow/github"
	"k8s.io/test-infra/prow/kube"
	"k8s.io/test-infra/prow/pjutil"
	"k8s.io/test-infra/prow/tide/blockers"
)

type kubeClient interface {
	ListProwJobs(string) ([]kube.ProwJob, error)
	CreateProwJob(kube.ProwJob) (kube.ProwJob, error)
}

type githubClient interface {
	CreateStatus(string, string, string, github.Status) error
	GetCombinedStatus(org, repo, ref string) (*github.CombinedStatus, error)
	GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error)
	GetRef(string, string, string) (string, error)
	Merge(string, string, int, github.MergeDetails) error
	Query(context.Context, interface{}, map[string]interface{}) error
}

type contextChecker interface {
	// IsOptional tells whether a context is optional.
	IsOptional(string) bool
	// MissingRequiredContexts tells if required contexts are missing from the list of contexts provided.
	MissingRequiredContexts([]string) []string
}

// Controller knows how to sync PRs and PJs.
type Controller struct {
	logger *logrus.Entry
	ca     *config.Agent
	ghc    githubClient
	kc     kubeClient
	gc     *git.Client

	sc *statusController

	m     sync.Mutex
	pools []Pool

	// changedFiles caches the names of files changed by PRs.
	// Cache entries expire if they are not used during a sync loop.
	changedFiles *changedFilesAgent
}

// Action represents what actions the controller can take. It will take
// exactly one action each sync.
type Action string

// Constants for various actions the controller might take
const (
	Wait         Action = "WAIT"
	Trigger             = "TRIGGER"
	TriggerBatch        = "TRIGGER_BATCH"
	Merge               = "MERGE"
	MergeBatch          = "MERGE_BATCH"
	PoolBlocked         = "BLOCKED"
)

// Pool represents information about a tide pool. There is one for every
// org/repo/branch combination that has PRs in the pool.
type Pool struct {
	Org    string
	Repo   string
	Branch string

	// PRs with passing tests, pending tests, and missing or failed tests.
	// Note that these results are rolled up. If all tests for a PR are passing
	// except for one pending, it will be in PendingPRs.
	SuccessPRs []PullRequest
	PendingPRs []PullRequest
	MissingPRs []PullRequest

	// Empty if there is no pending batch.
	BatchPending []PullRequest

	// Which action did we last take, and to what target(s), if any.
	Action   Action
	Target   []PullRequest
	Blockers []blockers.Blocker
}

// Prometheus Metrics
var (
	tideMetrics = struct {
		// Per pool
		pooledPRs  *prometheus.GaugeVec
		updateTime *prometheus.GaugeVec
		merges     *prometheus.HistogramVec

		// Singleton
		syncDuration         prometheus.Gauge
		statusUpdateDuration prometheus.Gauge
	}{
		pooledPRs: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Name: "pooledprs",
			Help: "Number of PRs in each Tide pool.",
		}, []string{
			"org",
			"repo",
			"branch",
		}),
		updateTime: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Name: "updatetime",
			Help: "The last time each subpool was synced. (Used to determine 'pooledprs' freshness.)",
		}, []string{
			"org",
			"repo",
			"branch",
		}),

		merges: prometheus.NewHistogramVec(prometheus.HistogramOpts{
			Name:    "merges",
			Help:    "Histogram of merges where values are the number of PRs merged together.",
			Buckets: []float64{1, 2, 3, 4, 5, 7, 10, 15, 25},
		}, []string{
			"org",
			"repo",
			"branch",
		}),

		syncDuration: prometheus.NewGauge(prometheus.GaugeOpts{
			Name: "syncdur",
			Help: "The duration of the last loop of the sync controller.",
		}),

		statusUpdateDuration: prometheus.NewGauge(prometheus.GaugeOpts{
			Name: "statusupdatedur",
			Help: "The duration of the last loop of the status update controller.",
		}),
	}
)

func init() {
	prometheus.MustRegister(tideMetrics.pooledPRs)
	prometheus.MustRegister(tideMetrics.updateTime)
	prometheus.MustRegister(tideMetrics.merges)
	prometheus.MustRegister(tideMetrics.syncDuration)
	prometheus.MustRegister(tideMetrics.statusUpdateDuration)
}

// NewController makes a Controller out of the given clients.
func NewController(ghcSync, ghcStatus *github.Client, kc *kube.Client, ca *config.Agent, gc *git.Client, logger *logrus.Entry) *Controller {
	if logger == nil {
		logger = logrus.NewEntry(logrus.StandardLogger())
	}
	sc := &statusController{
		logger:         logger.WithField("controller", "status-update"),
		ghc:            ghcStatus,
		ca:             ca,
		newPoolPending: make(chan bool, 1),
		shutDown:       make(chan bool),

		trackedOrgs:  sets.NewString(),
		trackedRepos: sets.NewString(),
	}
	go sc.run()
	return &Controller{
		logger: logger.WithField("controller", "sync"),
		ghc:    ghcSync,
		kc:     kc,
		ca:     ca,
		gc:     gc,
		sc:     sc,
		changedFiles: &changedFilesAgent{
			ghc:             ghcSync,
			nextChangeCache: make(map[changeCacheKey][]string),
		},
	}
}

// Shutdown signals the statusController to stop working and waits for it to
// finish its last update loop before terminating.
// Controller.Sync() should not be used after this function is called.
func (c *Controller) Shutdown() {
	c.sc.shutdown()
}

func prKey(pr *PullRequest) string {
	return fmt.Sprintf("%s#%d", string(pr.Repository.NameWithOwner), int(pr.Number))
}

// org/repo#number -> pr
func byRepoAndNumber(prs []PullRequest) map[string]PullRequest {
	m := make(map[string]PullRequest)
	for _, pr := range prs {
		key := prKey(&pr)
		m[key] = pr
	}
	return m
}

// newExpectedContext creates a Context with Expected state.
func newExpectedContext(c string) Context {
	return Context{
		Context:     githubql.String(c),
		State:       githubql.StatusStateExpected,
		Description: githubql.String(""),
	}
}

// contextsToStrings converts a list Context to a list of string
func contextsToStrings(contexts []Context) []string {
	var names []string
	for _, c := range contexts {
		names = append(names, string(c.Context))
	}
	return names
}

// Sync runs one sync iteration.
func (c *Controller) Sync() error {
	start := time.Now()
	defer func() {
		duration := time.Since(start)
		c.logger.WithField("duration", duration.String()).Info("Synced")
		tideMetrics.syncDuration.Set(duration.Seconds())
	}()
	defer c.changedFiles.prune()

	ctx := context.Background()
	c.logger.Debug("Building tide pool.")
	prs := make(map[string]PullRequest)
	for _, q := range c.ca.Config().Tide.Queries {
		results, err := newSearchExecutor(ctx, c.ghc, c.logger, q.Query()).search()
		if err != nil {
			return err
		}
		for _, pr := range results {
			prs[prKey(&pr)] = pr
		}
	}

	var pjs []kube.ProwJob
	var blocks blockers.Blockers
	var err error
	if len(prs) > 0 {
		pjs, err = c.kc.ListProwJobs(kube.EmptySelector)
		if err != nil {
			return err
		}

		if label := c.ca.Config().Tide.BlockerLabel; label != "" {
			c.logger.Debugf("Searching for blocking issues (label %q).", label)
			orgExcepts, repos := c.ca.Config().Tide.Queries.OrgExceptionsAndRepos()
			orgs := make([]string, 0, len(orgExcepts))
			for org := range orgExcepts {
				orgs = append(orgs, org)
			}
			orgRepoQuery := orgRepoQueryString(orgs, repos.UnsortedList(), orgExcepts)
			blocks, err = blockers.FindAll(c.ghc, c.logger, label, orgRepoQuery)
			if err != nil {
				return err
			}
		}
	}
	// Partition PRs into subpools and filter out non-pool PRs.
	rawPools, err := c.dividePool(prs, pjs)
	if err != nil {
		return err
	}
	filteredPools := c.filterSubpools(c.ca.Config().Tide.MaxGoroutines, rawPools)

	// Notify statusController about the new pool.
	c.sc.Lock()
	c.sc.poolPRs = poolPRMap(filteredPools)
	select {
	case c.sc.newPoolPending <- true:
	default:
	}
	c.sc.Unlock()

	// Sync subpools in parallel.
	poolChan := make(chan Pool, len(filteredPools))
	subpoolsInParallel(
		c.ca.Config().Tide.MaxGoroutines,
		filteredPools,
		func(sp *subpool) {
			spBlocks := blocks.GetApplicable(sp.org, sp.repo, sp.branch)
			if pool, err := c.syncSubpool(*sp, spBlocks); err != nil {
				sp.log.WithError(err).Errorf("Error syncing subpool.")
			} else {
				poolChan <- pool
			}
		},
	)

	close(poolChan)
	pools := make([]Pool, 0, len(poolChan))
	for pool := range poolChan {
		pools = append(pools, pool)
	}
	sortPools(pools)
	c.m.Lock()
	defer c.m.Unlock()
	c.pools = pools
	return nil
}

func (c *Controller) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	c.m.Lock()
	defer c.m.Unlock()
	b, err := json.Marshal(c.pools)
	if err != nil {
		c.logger.WithError(err).Error("Encoding JSON.")
		b = []byte("[]")
	}
	if _, err = w.Write(b); err != nil {
		c.logger.WithError(err).Error("Writing JSON response.")
	}
}

func subpoolsInParallel(goroutines int, sps map[string]*subpool, process func(*subpool)) {
	// Load the subpools into a channel for use as a work queue.
	queue := make(chan *subpool, len(sps))
	for _, sp := range sps {
		queue <- sp
	}
	close(queue)

	if goroutines > len(queue) {
		goroutines = len(queue)
	}
	wg := &sync.WaitGroup{}
	wg.Add(goroutines)
	for i := 0; i < goroutines; i++ {
		go func() {
			defer wg.Done()
			for sp := range queue {
				process(sp)
			}
		}()
	}
	wg.Wait()
}

// filterSubpools filters non-pool PRs out of the initially identified subpools,
// deleting any pools that become empty.
// See filterSubpool for filtering details.
func (c *Controller) filterSubpools(goroutines int, raw map[string]*subpool) map[string]*subpool {
	filtered := make(map[string]*subpool)
	var lock sync.Mutex

	subpoolsInParallel(
		goroutines,
		raw,
		func(sp *subpool) {
			if err := c.initSubpoolData(sp); err != nil {
				sp.log.WithError(err).Error("Error initializing subpool.")
				return
			}
			key := fmt.Sprintf("%s/%s %s", sp.org, sp.repo, sp.branch)
			if spFiltered := filterSubpool(c.ghc, sp); spFiltered != nil {
				sp.log.WithField("key", key).WithField("pool", spFiltered).Debug("filtered sub-pool")

				lock.Lock()
				filtered[key] = spFiltered
				lock.Unlock()
			} else {
				sp.log.WithField("key", key).WithField("pool", spFiltered).Debug("filtering sub-pool removed all PRs")
			}
		},
	)
	return filtered
}

func (c *Controller) initSubpoolData(sp *subpool) error {
	var err error
	sp.presubmitContexts, err = c.presubmitsByPull(sp)
	if err != nil {
		return fmt.Errorf("error determining required presubmit prowjobs: %v", err)
	}
	sp.cc, err = c.ca.Config().GetTideContextPolicy(sp.org, sp.repo, sp.branch)
	if err != nil {
		return fmt.Errorf("error setting up context checker: %v", err)
	}
	return nil
}

// filterSubpool filters PRs from an initially identified subpool, returning the
// filtered subpool.
// If the subpool becomes empty 'nil' is returned to indicate that the subpool
// should be deleted.
func filterSubpool(ghc githubClient, sp *subpool) *subpool {
	var toKeep []PullRequest
	for _, pr := range sp.prs {
		if !filterPR(ghc, sp, &pr) {
			toKeep = append(toKeep, pr)
		}
	}
	if len(toKeep) == 0 {
		return nil
	}
	sp.prs = toKeep
	return sp
}

// filterPR indicates if a PR should be filtered out of the subpool.
// Specifically we filter out PRs that:
// - Have known merge conflicts.
// - Have failing or missing status contexts.
// - Have pending required status contexts that are not associated with a
//   ProwJob. (This ensures that the 'tide' context indicates that the pending
//   status is preventing merge. Required ProwJob statuses are allowed to be
//   'pending' because this prevents kicking PRs from the pool when Tide is
//   retesting them.)
func filterPR(ghc githubClient, sp *subpool, pr *PullRequest) bool {
	log := sp.log.WithFields(pr.logFields())
	// Skip PRs that are known to be unmergeable.
	if pr.Mergeable == githubql.MergeableStateConflicting {
		log.Debug("filtering out PR as it is unmergeable")
		return true
	}
	// Filter out PRs with unsuccessful contexts unless the only unsuccessful
	// contexts are pending required prowjobs.
	contexts, err := headContexts(log, ghc, pr)
	if err != nil {
		log.WithError(err).Error("Getting head contexts.")
		return true
	}
	pjContexts := sp.presubmitContexts[int(pr.Number)]
	for _, ctx := range unsuccessfulContexts(contexts, sp.cc, log) {
		if ctx.State != githubql.StatusStatePending || !pjContexts.Has(string(ctx.Context)) {
			log.WithField("context", ctx.Context).Debug("filtering out PR as unsuccessful context is not a pending Prow-controlled context")
			return true
		}
	}

	return false
}

// poolPRMap collects all subpool PRs into a map containing all pooled PRs.
func poolPRMap(subpoolMap map[string]*subpool) map[string]PullRequest {
	prs := make(map[string]PullRequest)
	for _, sp := range subpoolMap {
		for _, pr := range sp.prs {
			prs[prKey(&pr)] = pr
		}
	}
	return prs
}

type simpleState string

const (
	noneState    simpleState = "none"
	pendingState simpleState = "pending"
	successState simpleState = "success"
)

func toSimpleState(s kube.ProwJobState) simpleState {
	if s == kube.TriggeredState || s == kube.PendingState {
		return pendingState
	} else if s == kube.SuccessState {
		return successState
	}
	return noneState
}

// isPassingTests returns whether or not all contexts set on the PR except for
// the tide pool context are passing.
func isPassingTests(log *logrus.Entry, ghc githubClient, pr PullRequest, cc contextChecker) bool {
	log = log.WithFields(pr.logFields())
	contexts, err := headContexts(log, ghc, &pr)
	if err != nil {
		log.WithError(err).Error("Getting head commit status contexts.")
		// If we can't get the status of the commit, assume that it is failing.
		return false
	}
	unsuccessful := unsuccessfulContexts(contexts, cc, log)
	return len(unsuccessful) == 0
}

// unsuccessfulContexts determines which contexts from the list that we care about are
// failed. For instance, we do not care about our own context.
// If the branchProtection is set to only check for required checks, we will skip
// all non-required tests. If required tests are missing from the list, they will be
// added to the list of failed contexts.
func unsuccessfulContexts(contexts []Context, cc contextChecker, log *logrus.Entry) []Context {
	var failed []Context
	for _, ctx := range contexts {
		if string(ctx.Context) == statusContext {
			continue
		}
		if cc.IsOptional(string(ctx.Context)) {
			continue
		}
		if ctx.State != githubql.StatusStateSuccess {
			failed = append(failed, ctx)
		}
	}
	for _, c := range cc.MissingRequiredContexts(contextsToStrings(contexts)) {
		failed = append(failed, newExpectedContext(c))
	}

	log.Debugf("from %d total contexts (%v) found %d failing contexts: %v", len(contexts), contextsToStrings(contexts), len(failed), contextsToStrings(failed))
	return failed
}

func pickSmallestPassingNumber(log *logrus.Entry, ghc githubClient, prs []PullRequest, cc contextChecker) (bool, PullRequest) {
	smallestNumber := -1
	var smallestPR PullRequest
	for _, pr := range prs {
		if smallestNumber != -1 && int(pr.Number) >= smallestNumber {
			continue
		}
		if len(pr.Commits.Nodes) < 1 {
			continue
		}
		if !isPassingTests(log, ghc, pr, cc) {
			continue
		}
		smallestNumber = int(pr.Number)
		smallestPR = pr
	}
	return smallestNumber > -1, smallestPR
}

// accumulateBatch returns a list of PRs that can be merged after passing batch
// testing, if any exist. It also returns a list of PRs currently being batch
// tested.
func accumulateBatch(presubmits map[int]sets.String, prs []PullRequest, pjs []kube.ProwJob, log *logrus.Entry) ([]PullRequest, []PullRequest) {
	log.Debug("accumulating PRs for batch testing")
	if len(presubmits) == 0 {
		log.Debug("no presubmits configured, no batch can be triggered")
		return nil, nil
	}
	prNums := make(map[int]PullRequest)
	for _, pr := range prs {
		prNums[int(pr.Number)] = pr
	}
	type accState struct {
		prs       []PullRequest
		jobStates map[string]simpleState
		// Are the pull requests in the ref still acceptable? That is, do they
		// still point to the heads of the PRs?
		validPulls bool
	}
	states := make(map[string]*accState)
	for _, pj := range pjs {
		if pj.Spec.Type != kube.BatchJob {
			continue
		}
		// First validate the batch job's refs.
		ref := pj.Spec.Refs.String()
		if _, ok := states[ref]; !ok {
			state := &accState{
				jobStates:  make(map[string]simpleState),
				validPulls: true,
			}
			for _, pull := range pj.Spec.Refs.Pulls {
				if pr, ok := prNums[pull.Number]; ok && string(pr.HeadRefOID) == pull.SHA {
					state.prs = append(state.prs, pr)
				} else if !ok {
					state.validPulls = false
					log.WithField("batch", ref).WithFields(pr.logFields()).Debug("batch job invalid, PR left pool")
					break
				} else {
					state.validPulls = false
					log.WithField("batch", ref).WithFields(pr.logFields()).Debug("batch job invalid, PR HEAD changed")
					break
				}
			}
			states[ref] = state
		}
		if !states[ref].validPulls {
			// The batch contains a PR ref that has changed. Skip it.
			continue
		}

		// Batch job refs are valid. Now accumulate job states by batch ref.
		context := pj.Spec.Context
		jobState := toSimpleState(pj.Status.State)
		// Store the best result for this ref+context.
		if s, ok := states[ref].jobStates[context]; !ok || s == noneState || jobState == successState {
			states[ref].jobStates[context] = jobState
		}
	}
	var pendingBatch, successBatch []PullRequest
	for ref, state := range states {
		if !state.validPulls {
			continue
		}
		requiredPresubmits := sets.NewString()
		for _, pr := range state.prs {
			requiredPresubmits = requiredPresubmits.Union(presubmits[int(pr.Number)])
		}
		overallState := successState
		for _, p := range requiredPresubmits.List() {
			if s, ok := state.jobStates[p]; !ok || s == noneState {
				overallState = noneState
				log.WithField("batch", ref).Debugf("batch invalid, required presubmit %s is not passing", p)
				break
			} else if s == pendingState && overallState == successState {
				overallState = pendingState
			}
		}
		switch overallState {
		// Currently we only consider 1 pending batch and 1 success batch at a time.
		// If more are somehow present they will be ignored.
		case pendingState:
			pendingBatch = state.prs
		case successState:
			successBatch = state.prs
		}
	}
	return successBatch, pendingBatch
}

// accumulate returns the supplied PRs sorted into three buckets based on their
// accumulated state across the presubmits.
func accumulate(presubmits map[int]sets.String, prs []PullRequest, pjs []kube.ProwJob, log *logrus.Entry) (successes, pendings, nones []PullRequest) {
	for _, pr := range prs {
		// Accumulate the best result for each job.
		psStates := make(map[string]simpleState)
		for _, pj := range pjs {
			if pj.Spec.Type != kube.PresubmitJob {
				continue
			}
			if pj.Spec.Refs.Pulls[0].Number != int(pr.Number) {
				continue
			}
			if pj.Spec.Refs.Pulls[0].SHA != string(pr.HeadRefOID) {
				continue
			}

			name := pj.Spec.Context
			oldState := psStates[name]
			newState := toSimpleState(pj.Status.State)
			if oldState == noneState || oldState == "" {
				psStates[name] = newState
			} else if oldState == pendingState && newState == successState {
				psStates[name] = successState
			}
		}
		// The overall result is the worst of the best.
		overallState := successState
		for _, ps := range presubmits[int(pr.Number)].List() {
			if s, ok := psStates[ps]; !ok {
				overallState = noneState
				log.WithFields(pr.logFields()).Debugf("missing presubmit %s", ps)
				break
			} else if s == noneState {
				overallState = noneState
				log.WithFields(pr.logFields()).Debugf("presubmit %s not passing", ps)
				break
			} else if s == pendingState {
				log.WithFields(pr.logFields()).Debugf("presubmit %s pending", ps)
				overallState = pendingState
			}
		}
		if overallState == successState {
			successes = append(successes, pr)
		} else if overallState == pendingState {
			pendings = append(pendings, pr)
		} else {
			nones = append(nones, pr)
		}
	}
	return
}

func prNumbers(prs []PullRequest) []int {
	var nums []int
	for _, pr := range prs {
		nums = append(nums, int(pr.Number))
	}
	return nums
}

func (c *Controller) pickBatch(sp subpool, cc contextChecker) ([]PullRequest, error) {
	// we must choose the oldest PRs for the batch
	sort.Slice(sp.prs, func(i, j int) bool { return sp.prs[i].Number < sp.prs[j].Number })

	var candidates []PullRequest
	for _, pr := range sp.prs {
		if isPassingTests(sp.log, c.ghc, pr, cc) {
			candidates = append(candidates, pr)
		}
	}

	if len(candidates) == 0 {
		sp.log.Debugf("of %d possible PRs, none were passing tests, no batch will be created", len(sp.prs))
		return nil, nil
	}
	sp.log.Debugf("of %d possible PRs, %d are passing tests", len(sp.prs), len(candidates))

	r, err := c.gc.Clone(sp.org + "/" + sp.repo)
	if err != nil {
		return nil, err
	}
	defer r.Clean()
	if err := r.Config("user.name", "prow"); err != nil {
		return nil, err
	}
	if err := r.Config("user.email", "prow@localhost"); err != nil {
		return nil, err
	}
	if err := r.Config("commit.gpgsign", "false"); err != nil {
		sp.log.Warningf("Cannot set gpgsign=false in gitconfig: %v", err)
	}
	if err := r.Checkout(sp.sha); err != nil {
		return nil, err
	}

	var res []PullRequest
	for _, pr := range candidates {
		if ok, err := r.Merge(string(pr.HeadRefOID)); err != nil {
			// we failed to abort the merge and our git client is
			// in a bad state; it must be cleaned before we try again
			return nil, err
		} else if ok {
			res = append(res, pr)
			// TODO: Make this configurable per subpool.
			if len(res) == 5 {
				break
			}
		}
	}
	return res, nil
}

func (c *Controller) mergePRs(sp subpool, prs []PullRequest) error {
	successCount := 0
	defer func() {
		if successCount == 0 {
			return
		}
		tideMetrics.merges.WithLabelValues(sp.org, sp.repo, sp.branch).Observe(float64(successCount))
	}()

	maxRetries := 3
	for i, pr := range prs {
		backoff := time.Second * 4
		log := sp.log.WithFields(pr.logFields())
		mergeMethod := c.ca.Config().Tide.MergeMethod(sp.org, sp.repo)
		if squashLabel := c.ca.Config().Tide.SquashLabel; squashLabel != "" {
			for _, prlabel := range pr.Labels.Nodes {
				if string(prlabel.Name) == squashLabel {
					mergeMethod = github.MergeSquash
					break
				}
			}
		}
		for retry := 0; retry < maxRetries; retry++ {
			if err := c.ghc.Merge(sp.org, sp.repo, int(pr.Number), github.MergeDetails{
				SHA:         string(pr.HeadRefOID),
				MergeMethod: string(mergeMethod),
			}); err != nil {
				if _, ok := err.(github.ModifiedHeadError); ok {
					// This is a possible source of incorrect behavior. If someone
					// modifies their PR as we try to merge it in a batch then we
					// end up in an untested state. This is unlikely to cause any
					// real problems.
					log.WithError(err).Warning("Merge failed: PR was modified.")
					break
				} else if _, ok = err.(github.UnmergablePRBaseChangedError); ok {
					// Github complained that the base branch was modified. This is a
					// strange error because the API doesn't even allow the request to
					// specify the base branch sha, only the head sha.
					// We suspect that github is complaining because we are making the
					// merge requests too rapidly and it cannot recompute mergability
					// in time. https://github.com/kubernetes/test-infra/issues/5171
					// We handle this by sleeping for a few seconds before trying to
					// merge again.
					log.WithError(err).Warning("Merge failed: Base branch was modified.")
					if retry+1 < maxRetries {
						time.Sleep(backoff)
						backoff *= 2
					}
				} else if _, ok = err.(github.UnauthorizedToPushError); ok {
					// Github let us know that the token used cannot push to the branch.
					// Even if the robot is set up to have write access to the repo, an
					// overzealous branch protection setting will not allow the robot to
					// push to a specific branch.
					log.WithError(err).Error("Merge failed: Branch needs to be configured to allow this robot to push.")
					break
				} else if _, ok = err.(github.UnmergablePRError); ok {
					log.WithError(err).Error("Merge failed: PR is unmergable. How did it pass tests?!")
					break
				} else {
					log.WithError(err).Error("Merge failed.")
					return err
				}
			} else {
				log.Info("Merged.")
				successCount++
				// If we have more PRs to merge, sleep to give Github time to recalculate
				// mergeability.
				if i+1 < len(prs) {
					time.Sleep(time.Second * 3)
				}
				break
			}
		}
	}
	return nil
}

func (c *Controller) trigger(sp subpool, presubmitContexts map[int]sets.String, prs []PullRequest) error {
	requiredContexts := sets.NewString()
	for _, pr := range prs {
		requiredContexts = requiredContexts.Union(presubmitContexts[int(pr.Number)])
	}

	// TODO(cjwagner): DRY this out when generalizing triggering code (and code to determine required and to-run jobs).
	for _, ps := range c.ca.Config().Presubmits[sp.org+"/"+sp.repo] {
		if ps.SkipReport || !ps.RunsAgainstBranch(sp.branch) || !requiredContexts.Has(ps.Context) {
			continue
		}

		refs := kube.Refs{
			Org:     sp.org,
			Repo:    sp.repo,
			BaseRef: sp.branch,
			BaseSHA: sp.sha,
		}
		for _, pr := range prs {
			refs.Pulls = append(
				refs.Pulls,
				kube.Pull{
					Number: int(pr.Number),
					Author: string(pr.Author.Login),
					SHA:    string(pr.HeadRefOID),
				},
			)
		}
		var spec kube.ProwJobSpec
		if len(prs) == 1 {
			spec = pjutil.PresubmitSpec(ps, refs)
		} else {
			spec = pjutil.BatchSpec(ps, refs)
		}
		pj := pjutil.NewProwJob(spec, ps.Labels)
		if _, err := c.kc.CreateProwJob(pj); err != nil {
			return err
		}
	}
	return nil
}

func (c *Controller) takeAction(sp subpool, batchPending, successes, pendings, nones, batchMerges []PullRequest) (Action, []PullRequest, error) {
	// Merge the batch!
	if len(batchMerges) > 0 {
		return MergeBatch, batchMerges, c.mergePRs(sp, batchMerges)
	}
	// Do not merge PRs while waiting for a batch to complete. We don't want to
	// invalidate the old batch result.
	if len(successes) > 0 && len(batchPending) == 0 {
		if ok, pr := pickSmallestPassingNumber(sp.log, c.ghc, successes, sp.cc); ok {
			return Merge, []PullRequest{pr}, c.mergePRs(sp, []PullRequest{pr})
		}
	}
	// If no presubmits are configured, just wait.
	if len(sp.presubmitContexts) == 0 {
		return Wait, nil, nil
	}
	// If we have no serial jobs pending or successful, trigger one.
	if len(nones) > 0 && len(pendings) == 0 && len(successes) == 0 {
		if ok, pr := pickSmallestPassingNumber(sp.log, c.ghc, nones, sp.cc); ok {
			return Trigger, []PullRequest{pr}, c.trigger(sp, sp.presubmitContexts, []PullRequest{pr})
		}
	}
	// If we have no batch, trigger one.
	if len(sp.prs) > 1 && len(batchPending) == 0 {
		batch, err := c.pickBatch(sp, sp.cc)
		if err != nil {
			return Wait, nil, err
		}
		if len(batch) > 1 {
			return TriggerBatch, batch, c.trigger(sp, sp.presubmitContexts, batch)
		}
	}
	return Wait, nil, nil
}

// changedFilesAgent queries and caches the names of files changed by PRs.
// Cache entries expire if they are not used during a sync loop.
type changedFilesAgent struct {
	ghc         githubClient
	changeCache map[changeCacheKey][]string
	// nextChangeCache caches file change info that is relevant this sync for use next sync.
	// This becomes the new changeCache when prune() is called at the end of each sync.
	nextChangeCache map[changeCacheKey][]string
	sync.RWMutex
}

type changeCacheKey struct {
	org, repo string
	number    int
	sha       string
}

// prChanges gets the files changed by the PR, either from the cache or by
// querying GitHub.
func (c *changedFilesAgent) prChanges(pr *PullRequest) ([]string, error) {
	cacheKey := changeCacheKey{
		org:    string(pr.Repository.Owner.Login),
		repo:   string(pr.Repository.Name),
		number: int(pr.Number),
		sha:    string(pr.HeadRefOID),
	}

	c.RLock()
	changedFiles, ok := c.changeCache[cacheKey]
	if ok {
		c.RUnlock()
		c.Lock()
		c.nextChangeCache[cacheKey] = changedFiles
		c.Unlock()
		return changedFiles, nil
	}
	if changedFiles, ok = c.nextChangeCache[cacheKey]; ok {
		c.RUnlock()
		return changedFiles, nil
	}
	c.RUnlock()

	// We need to query the changes from GitHub.
	changes, err := c.ghc.GetPullRequestChanges(
		string(pr.Repository.Owner.Login),
		string(pr.Repository.Name),
		int(pr.Number),
	)
	if err != nil {
		return nil, fmt.Errorf("error getting PR changes for #%d: %v", int(pr.Number), err)
	}
	changedFiles = make([]string, 0, len(changes))
	for _, change := range changes {
		changedFiles = append(changedFiles, change.Filename)
	}

	c.Lock()
	c.nextChangeCache[cacheKey] = changedFiles
	c.Unlock()
	return changedFiles, nil
}

// prune removes any cached file changes that were not used since the last prune.
func (c *changedFilesAgent) prune() {
	c.Lock()
	defer c.Unlock()
	c.changeCache = c.nextChangeCache
	c.nextChangeCache = make(map[changeCacheKey][]string)
}

func (c *Controller) presubmitsByPull(sp *subpool) (map[int]sets.String, error) {
	presubmits := make(map[int]sets.String, len(sp.prs))
	record := func(num int, context string) {
		if jobs, ok := presubmits[num]; ok {
			jobs.Insert(context)
		} else {
			presubmits[num] = sets.NewString(context)
		}
	}

	for _, ps := range c.ca.Config().Presubmits[sp.org+"/"+sp.repo] {
		if !ps.ContextRequired() || !ps.RunsAgainstBranch(sp.branch) {
			continue
		}

		if ps.AlwaysRun {
			// Every PR requires this job.
			for _, pr := range sp.prs {
				record(int(pr.Number), ps.Context)
			}
		} else if ps.RunIfChanged != "" {
			// This is a run if changed job so we need to check if each PR requires it.
			for _, pr := range sp.prs {
				changedFiles, err := c.changedFiles.prChanges(&pr)
				if err != nil {
					return nil, err
				}
				if ps.RunsAgainstChanges(changedFiles) {
					record(int(pr.Number), ps.Context)
				}
			}
		}
	}
	return presubmits, nil
}

func (c *Controller) syncSubpool(sp subpool, blocks []blockers.Blocker) (Pool, error) {
	sp.log.Infof("Syncing subpool: %d PRs, %d PJs.", len(sp.prs), len(sp.pjs))
	successes, pendings, nones := accumulate(sp.presubmitContexts, sp.prs, sp.pjs, sp.log)
	batchMerge, batchPending := accumulateBatch(sp.presubmitContexts, sp.prs, sp.pjs, sp.log)
	sp.log.WithFields(logrus.Fields{
		"prs-passing":   prNumbers(successes),
		"prs-pending":   prNumbers(pendings),
		"prs-missing":   prNumbers(nones),
		"batch-passing": prNumbers(batchMerge),
		"batch-pending": prNumbers(batchPending),
	}).Info("Subpool accumulated.")

	var act Action
	var targets []PullRequest
	var err error
	if len(blocks) > 0 {
		act = PoolBlocked
	} else {
		act, targets, err = c.takeAction(sp, batchPending, successes, pendings, nones, batchMerge)
	}

	sp.log.WithFields(logrus.Fields{
		"action":  string(act),
		"targets": prNumbers(targets),
	}).Info("Subpool synced.")
	tideMetrics.pooledPRs.WithLabelValues(sp.org, sp.repo, sp.branch).Set(float64(len(sp.prs)))
	tideMetrics.updateTime.WithLabelValues(sp.org, sp.repo, sp.branch).Set(float64(time.Now().Unix()))
	return Pool{
			Org:    sp.org,
			Repo:   sp.repo,
			Branch: sp.branch,

			SuccessPRs: successes,
			PendingPRs: pendings,
			MissingPRs: nones,

			BatchPending: batchPending,

			Action:   act,
			Target:   targets,
			Blockers: blocks,
		},
		err
}

func sortPools(pools []Pool) {
	sort.Slice(pools, func(i, j int) bool {
		if string(pools[i].Org) != string(pools[j].Org) {
			return string(pools[i].Org) < string(pools[j].Org)
		}
		if string(pools[i].Repo) != string(pools[j].Repo) {
			return string(pools[i].Repo) < string(pools[j].Repo)
		}
		return string(pools[i].Branch) < string(pools[j].Branch)
	})

	sortPRs := func(prs []PullRequest) {
		sort.Slice(prs, func(i, j int) bool { return int(prs[i].Number) < int(prs[j].Number) })
	}
	for i := range pools {
		sortPRs(pools[i].SuccessPRs)
		sortPRs(pools[i].PendingPRs)
		sortPRs(pools[i].MissingPRs)
		sortPRs(pools[i].BatchPending)
	}
}

type subpool struct {
	log    *logrus.Entry
	org    string
	repo   string
	branch string
	sha    string

	pjs []kube.ProwJob
	prs []PullRequest

	cc                contextChecker
	presubmitContexts map[int]sets.String
}

// dividePool splits up the list of pull requests and prow jobs into a group
// per repo and branch. It only keeps ProwJobs that match the latest branch.
func (c *Controller) dividePool(pool map[string]PullRequest, pjs []kube.ProwJob) (map[string]*subpool, error) {
	sps := make(map[string]*subpool)
	for _, pr := range pool {
		org := string(pr.Repository.Owner.Login)
		repo := string(pr.Repository.Name)
		branch := string(pr.BaseRef.Name)
		branchRef := string(pr.BaseRef.Prefix) + string(pr.BaseRef.Name)
		fn := fmt.Sprintf("%s/%s %s", org, repo, branch)
		if sps[fn] == nil {
			sha, err := c.ghc.GetRef(org, repo, strings.TrimPrefix(branchRef, "refs/"))
			if err != nil {
				return nil, err
			}
			sps[fn] = &subpool{
				log: c.logger.WithFields(logrus.Fields{
					"org":      org,
					"repo":     repo,
					"branch":   branch,
					"base-sha": sha,
				}),
				org:    org,
				repo:   repo,
				branch: branch,
				sha:    sha,
			}
		}
		sps[fn].prs = append(sps[fn].prs, pr)
	}
	for _, pj := range pjs {
		if pj.Spec.Type != kube.PresubmitJob && pj.Spec.Type != kube.BatchJob {
			continue
		}
		fn := fmt.Sprintf("%s/%s %s", pj.Spec.Refs.Org, pj.Spec.Refs.Repo, pj.Spec.Refs.BaseRef)
		if sps[fn] == nil || pj.Spec.Refs.BaseSHA != sps[fn].sha {
			continue
		}
		sps[fn].pjs = append(sps[fn].pjs, pj)
	}
	return sps, nil
}

// PullRequest holds graphql data about a PR, including its commits and their contexts.
type PullRequest struct {
	Number githubql.Int
	Author struct {
		Login githubql.String
	}
	BaseRef struct {
		Name   githubql.String
		Prefix githubql.String
	}
	HeadRefName githubql.String `graphql:"headRefName"`
	HeadRefOID  githubql.String `graphql:"headRefOid"`
	Mergeable   githubql.MergeableState
	Repository  struct {
		Name          githubql.String
		NameWithOwner githubql.String
		Owner         struct {
			Login githubql.String
		}
	}
	Commits struct {
		Nodes []struct {
			Commit Commit
		}
		// Request the 'last' 4 commits hoping that one of them is the logically 'last'
		// commit with OID matching HeadRefOID. If we don't find it we have to use an
		// additional API token. (see the 'headContexts' func for details)
		// We can't raise this too much or we could hit the limit of 50,000 nodes
		// per query: https://developer.github.com/v4/guides/resource-limitations/#node-limit
	} `graphql:"commits(last: 4)"`
	Labels struct {
		Nodes []struct {
			Name githubql.String
		}
	} `graphql:"labels(first: 100)"`
	Milestone *struct {
		Title githubql.String
	}
	Title githubql.String
}

// Commit holds graphql data about commits and which contexts they have
type Commit struct {
	Status struct {
		Contexts []Context
	}
	OID githubql.String `graphql:"oid"`
}

// Context holds graphql response data for github contexts.
type Context struct {
	Context     githubql.String
	Description githubql.String
	State       githubql.StatusState
}

type searchQuery struct {
	RateLimit struct {
		Cost      githubql.Int
		Remaining githubql.Int
	}
	Search struct {
		PageInfo struct {
			HasNextPage githubql.Boolean
			EndCursor   githubql.String
		}
		IssueCount githubql.Int
		Nodes      []struct {
			PullRequest PullRequest `graphql:"... on PullRequest"`
		}
	} `graphql:"search(type: ISSUE, first: 100, after: $searchCursor, query: $query)"`
}

func (pr *PullRequest) logFields() logrus.Fields {
	return logrus.Fields{
		"org":  string(pr.Repository.Owner.Login),
		"repo": string(pr.Repository.Name),
		"pr":   int(pr.Number),
		"sha":  string(pr.HeadRefOID),
	}
}

// headContexts gets the status contexts for the commit with OID == pr.HeadRefOID
//
// First, we try to get this value from the commits we got with the PR query.
// Unfortunately the 'last' commit ordering is determined by author date
// not commit date so if commits are reordered non-chronologically on the PR
// branch the 'last' commit isn't necessarily the logically last commit.
// We list multiple commits with the query to increase our chance of success,
// but if we don't find the head commit we have to ask Github for it
// specifically (this costs an API token).
func headContexts(log *logrus.Entry, ghc githubClient, pr *PullRequest) ([]Context, error) {
	for _, node := range pr.Commits.Nodes {
		if node.Commit.OID == pr.HeadRefOID {
			return node.Commit.Status.Contexts, nil
		}
	}
	// We didn't get the head commit from the query (the commits must not be
	// logically ordered) so we need to specifically ask Github for the status
	// and coerce it to a graphql type.
	org := string(pr.Repository.Owner.Login)
	repo := string(pr.Repository.Name)
	// Log this event so we can tune the number of commits we list to minimize this.
	log.Warnf("'last' %d commits didn't contain logical last commit. Querying Github...", len(pr.Commits.Nodes))
	combined, err := ghc.GetCombinedStatus(org, repo, string(pr.HeadRefOID))
	if err != nil {
		return nil, fmt.Errorf("failed to get the combined status: %v", err)
	}
	contexts := make([]Context, 0, len(combined.Statuses))
	for _, status := range combined.Statuses {
		contexts = append(
			contexts,
			Context{
				Context:     githubql.String(status.Context),
				Description: githubql.String(status.Description),
				State:       githubql.StatusState(strings.ToUpper(status.State)),
			},
		)
	}
	// Add a commit with these contexts to pr for future look ups.
	pr.Commits.Nodes = append(pr.Commits.Nodes,
		struct{ Commit Commit }{
			Commit: Commit{
				OID:    pr.HeadRefOID,
				Status: struct{ Contexts []Context }{Contexts: contexts},
			},
		},
	)
	return contexts, nil
}

func orgRepoQueryString(orgs, repos []string, orgExceptions map[string]sets.String) string {
	toks := make([]string, 0, len(orgs))
	for _, o := range orgs {
		toks = append(toks, fmt.Sprintf("org:\"%s\"", o))

		for _, e := range orgExceptions[o].UnsortedList() {
			toks = append(toks, fmt.Sprintf("-repo:\"%s\"", e))
		}
	}
	for _, r := range repos {
		toks = append(toks, fmt.Sprintf("repo:\"%s\"", r))
	}
	return strings.Join(toks, " ")
}


text:
/*
 * File:   Includes.hpp
 * Author: Arthur Lisek-Koper <deathvango@gmail.com>
 *
 * Created on December 28, 2014, 3:50 PM
 *
 * Summary of Code:
 *
 */

#ifndef INCLUDES_HPP
#define	INCLUDES_HPP

//C++ standard libraries
#include <cstdlib>
#include <algorithm>
#include <string>
#include <stack>
#include <unordered_map> //hash map
#include <array>
#include <vector>
#include <map>
#include <list>
#include <fstream>
#include <memory>

//Boost libraries
#include "boost/lexical_cast.hpp"
#include "boost/multi_array.hpp"
#include "boost/regex.hpp"

//SFML libraries
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Window.hpp>

//My libraries
#include "Clock.hpp"
#include "Defines.hpp"
#include "Enums.hpp"
#include "Error.hpp"
#include "IndexList.hpp"
#include "PairList.hpp"
#include "Templates.hpp"
#include "Time.hpp"

#endif	/* INCLUDES_HPP */