text:
/**
 * @author Wang, Hui (huiwang@qlike.com)
 * @repo https://github.com/hui-w/minions-matrix
 * @licence MIT
 *
 * The class Monitor handles the user actions and perform the renderring
 */
function Monitor(width, height) {
  this.width = width;
  this.height = height;

  // The monitor frame
  this.frame = null;

  // Offset is the planet coordinate on the monitor center
  this.offsetX = 0;
  this.offsetY = 0;

  // Painting objects
  this.canvas = null;
  this.context = null;

  // The point on monitor which is selected
  this.selectedPos = null;

  // The point where mouse was down
  this.moveBeginPos = null;

  // From 0000 to 1111 (Keys: left-up-right-bottom)
  this.arrowKeyStatus = 0;
  this.keyboardTimer = null;

  // Callback of redrawing
  this.onRedraw = null;

  // Toolbar
  this.toolbar = null;
}

Monitor.prototype = {
  /* Mouse events */
  handleMouse: function(e, that) {
    switch (e.type) {
      case "mousedown":
        that.touchstartAndMousedown(e);
        break;
      case "mousemove":
        that.touchmoveAndMousemove(e);
        break;
      case "mouseup":
        that.touchcancelAndMouseup(e);
        break;
      case "mouseout":
        that.moveBeginPos = null;
        that.frame.removeClassName("move-cursor");
        break;
      case "mousewheel":
        break;
    }
  },

  /* Touch events */
  handleTouch: function(e, that) {
    e.preventDefault();
    switch (e.type) {
      case "touchstart":
        if (e.touches.length == 1) {
          that.touchstartAndMousedown(e.targetTouches[0]);
        } else if (e.touches.length == 2) {}
        break;
      case "touchend":
        if (e.changedTouches.length == 1) {
          that.touchcancelAndMouseup(e.changedTouches[0]);
        }
        break;
      case "touchmove":
        if (e.changedTouches.length == 1) {
          that.touchmoveAndMousemove(e.changedTouches[0]);
        } else if (e.touches.length == 2) {}
        break;
    }
  },

  touchstartAndMousedown: function(e) {
    this.moveBeginPos = {
      x: e.pageX,
      y: e.pageY
    };

    // Record the selected position on monitor
    this.selectedPos = this.getEventPosition(e);

    // Check if any button in the toolbar is clicked
    this.toolbar.detectToolAction(this.selectedPos.x, this.selectedPos.y);
  },

  touchcancelAndMouseup: function(e) {
    this.moveBeginPos = null;
    if (this.frame.hasClassName("move-cursor")) {
      this.frame.removeClassName("move-cursor");
    }
  },

  touchmoveAndMousemove: function(e) {
    if (this.moveBeginPos == null) {
      return;
    }

    // Set the mouse cursor
    if (!this.frame.hasClassName("move-cursor")) {
      this.frame.addClassName("move-cursor");
    }

    this.offsetX -= e.pageX - this.moveBeginPos.x;
    this.offsetY -= e.pageY - this.moveBeginPos.y;

    this.moveBeginPos = {
      x: e.pageX,
      y: e.pageY
    };

    this.redraw();
  },

  /* Keyboard events */
  handleKey: function(e) {
    var that = this;
    switch (e.type) {
      case "keydown":
        var keyCode = event.keyCode;
        switch (keyCode) {
          case 37:
            this.arrowKeyStatus |= 1;
            break;
          case 38:
            this.arrowKeyStatus |= 1 << 1;
            break;
          case 39:
            this.arrowKeyStatus |= 1 << 2;
            break;
          case 40:
            this.arrowKeyStatus |= 1 << 3;
            break;
        }
        if (this.arrowKeyStatus > 0 && this.keyboardTimer == null) {
          keyboardTimerHandler();
        }

        function keyboardTimerHandler() {
          var changeUnit = Config.Monitor.keyboardChangeUnit;
          if ((that.arrowKeyStatus & 1) > 0) {
            that.offsetX += changeUnit;
          }

          if ((that.arrowKeyStatus & (1 << 1)) > 0) {
            that.offsetY += changeUnit;
          }

          if ((that.arrowKeyStatus & (1 << 2)) > 0) {
            that.offsetX -= changeUnit;
          }

          if ((that.arrowKeyStatus & (1 << 3)) > 0) {
            that.offsetY -= changeUnit;
          }

          if (that.arrowKeyStatus > 0) {
            that.redraw();

            //set-up the timer for next round
            that.keyboardTimer = setTimeout(keyboardTimerHandler, Config.Monitor.keyboardTimerDelay);
          } else {
            that.keyboardTimer = null;
          }

        };
        break;
      case "keyup":
        var keyCode = event.keyCode;
        switch (keyCode) {
          case 37:
            that.arrowKeyStatus &= ~1;
            break;
          case 38:
            that.arrowKeyStatus &= ~(1 << 1);
            break;
          case 39:
            that.arrowKeyStatus &= ~(1 << 2);
            break;
          case 40:
            that.arrowKeyStatus &= ~(1 << 3);
            break;
        }
        if (that.arrowKeyStatus == 0) {
          if (that.keyboardTimer != null) {
            clearTimeout(that.keyboardTimer);
            that.keyboardTimer = null;
          }
        }
        break;
    }
  },

  /* Get the event position on the monitor */
  getEventPosition: function(ev) {
    /*
    return {
    x : ev.offsetX,
    y : ev.offsetY
    };
     */
    return {
      x: ev.pageX - this.canvas.offsetLeft,
      y: ev.pageY - this.canvas.offsetTop
    };
  },

  /* Render into the HTML DOM object */
  renderInto: function(wrapper) {
    var that = this;

    // Render the HTML element
    var cssStyle = "background-color: #FFF; width: {0}px; height: {1}px;".format(this.width, this.height);
    this.frame = wrapper.createChild("div", {
      "id": "monitor-frame",
      "style": cssStyle
    });

    // Handle the mouse events
    this.handleMouseEvent = function(e) {
      that.handleMouse(e, that);
    }
    this.frame.addEventListener("mousedown", this.handleMouseEvent, false);
    this.frame.addEventListener("mousemove", this.handleMouseEvent, false);
    this.frame.addEventListener("mouseup", this.handleMouseEvent, false);
    this.frame.addEventListener("mouseout", this.handleMouseEvent, false);
    this.frame.addEventListener("mousewheel", this.handleMouse, false);

    // Handle the touch events
    this.handleTouchEvent = function(e) {
      that.handleTouch(e, that);
    }
    this.frame.addEventListener("touchstart", this.handleTouchEvent, false);
    this.frame.addEventListener("touchend", this.handleTouchEvent, false);
    this.frame.addEventListener("touchmove", this.handleTouchEvent, false);

    // Handle the key events
    this.handleKeyEvent = function(e) {
      that.handleKey(e, that);
    }
    document.addEventListener("keydown", this.handleKeyEvent, false);
    document.addEventListener("keyup", this.handleKeyEvent, false);

    // Initialize the canvas and the context
    this.canvas = this.frame.createChild("canvas", {
      "id": "monitor-canvas",
      "width": this.width,
      "height": this.height
    });
    if (typeof G_vmlCanvasManager != "undefined") {
      this.canvas = G_vmlCanvasManager.initElement(this.canvas);
    }
    this.context = this.canvas.getContext("2d");

    // Initialize the toolbar
    this.toolbar = new Toolbar(this.context);
    this.toolbar.onChange = function() {
      // Redraw immediately when toolbar is changed
      that.redraw();
    };

    // Setup the timer to update the matrix view
    monitorTimerHandler();

    function monitorTimerHandler() {
      if (that.moveBeginPos == null && that.arrowKeyStatus == 0) {
        that.redraw();
      }

      // Setup the timer for next round
      setTimeout(monitorTimerHandler, Config.Monitor.timerDelay);
    };
  }, // End of renderInto

  /* Resize the monitor */
  resize: function(width, height) {
    this.width = width;
    this.height = height;

    if (this.frame != null) {
      this.frame.style.width = this.width + "px";
      this.frame.style.height = this.height + "px";
    }

    if (this.canvas != null) {
      this.canvas.width = this.width;
      this.canvas.height = this.height;
    }
  },

  /* Clear the canvas and redraw the matrix */
  redraw: function() {
    //clear the existing display
    //this.context.clearRect(10, 10, this.width, this.height);
    this.canvas.width = this.canvas.width;
    this.canvas.height = this.canvas.height;

    // Fill the background
    this.fillBackground();

    // Show the scale
    this.drawScale();

    // Draw labels
    this.drawLabel();

    //console.log("Monitor Redraw {0} - {1}".format(this.offsetX, this.offsetY));
    if (typeof this.onRedraw == "function") {
      this.onRedraw();
    }

    // Draw toolbar
    this.toolbar.redraw();
  },

  // Fill the background
  fillBackground: function() {
    var context = this.context;
    context.save();
    context.fillStyle = "RGBA(255, 255, 255, 1)";
    context.fillRect(0, 0, this.width, this.height);
    context.restore();
  },

  // Render the scale lines and text labels
  drawScale: function() {
    var context = this.context;
    context.save();
    context.beginPath();

    context.font = "{0}px verdana".format(Config.Monitor.fontSize);
    context.textBaseline = "top";
    context.fillStyle = "#000000";

    var unitSize = Config.Monitor.gridSize;

    // Y0 is where the fist horizontal line starts
    var y0 = (Math.round(this.height / 2) - this.offsetY) % unitSize;
    for (var y = y0; y <= this.height; y += unitSize) {
      // Horizontal lines
      var x1 = 0;
      var x2 = this.width;
      context.antiFuzzyLine(x1, y, x2, y);

      var pxPosition = this.monitorToPlanet(0, y);
      context.fillText(pxPosition.y, 0, y);
    }

    // X0 is where the fist vertical line starts
    var x0 = (Math.round(this.width / 2) - this.offsetX) % unitSize;
    for (var x = x0; x <= this.width; x += unitSize) {
      // Vertical lines
      var y1 = 0;
      var y2 = this.height;
      context.antiFuzzyLine(x, y1, x, y2);

      var pxPosition = this.monitorToPlanet(x, 0);
      context.fillText(pxPosition.x, x, 0);
    }

    context.strokeStyle = "RGBA(0, 0, 0, 0.2)";
    context.lineWidth = 1;
    context.stroke();
    context.restore();
  },

  drawLabel: function() {
    // Show offset X and Y
    var context = this.context;
    context.save();
    context.font = "{0}px verdana".format(Config.Monitor.fontSize);
    context.fillStyle = "#333333";
    var lblStr = "Monitor: {0}, {1}, {2}".format(
      padNumber(this.offsetX, 4),
      padNumber(this.offsetY, 4),
      timeNow(5)
    );
    context.fillTextEx(lblStr, this.width, this.height, "right", "bottom");

    context.restore();
  },

  /* Get the position on the planet based on the position on the monitor */
  monitorToPlanet: function(mx, my) {
    return {
      x: mx - Math.round(this.width / 2) + this.offsetX,
      y: my - Math.round(this.height / 2) + this.offsetY
    };
  },

  /* Get the position on the monitor based on the position on the planet */
  planetToMonitor: function(px, py) {
    return {
      x: px + Math.round(this.width / 2) - this.offsetX,
      y: py + Math.round(this.height / 2) - this.offsetY
    };
  }
}

/*
8 = 1000
4 = 100
2 = 10

15 & 9 = 9 (1111 & 1001 = 1001)
15 | 9 = 15 (1111 | 1001 = 1111)
15 ^ 9 = 6 (1111 ^ 1001 = 0110)
*/


text:
body{
	font-family:Times New Roman;
	font-size:17px;
	background-color:#A9A9A9;
}
header, h1, nav, ul, li, section, article, p, footer {
	margin:0;
	padding:0;
}
header h1 {
	color:#FAFAD2;
	font-size:2em;
	font-weight:bold;
	text-align:center;
	margin:25px 0px;
}
header {
	text-align: center;
}
footer {
	text-align:center;
	margin:20px 0px;
}
article header h1{
	text-align: left;
	font-size:1.5em;
}
article footer {
	text-align: left;
	font-size:0.9em;
}
article footer a:link, a:visited, a :hover,a:active {
text-decoration:none;
color:#000;
}
nav ul{
list-style:none;
}
nav ul li{
font-weight:bold;
font-size:1.2em;
text-decoration:none;
}
nav a:link{
	text-decoration:none;
	color:#FFF;
}
nav a:visited {
	text-decoration:none;
	color:#FFF;
}
nav a:hover{
	background-color:#D3D3D3;
	text-decoration:none;
	color:#FFF;
}
nav a:active, a.current {
	background-color:#D3D3D3;
	text-decoration:none;
	color:#FFF;
}
li:last-child {
	text-decoration:underline;
	color:#FFF;
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * A simple spell that removes status effects. This is a class
 * that implements the DBSAttack interface.
 *
 * @author Evan Hildreth
 * @version 1.0
 */
public class Esuna implements DBSAttack
{
    /**
     * Gets the name of the attack
     *
     * @return  "Esuna"
     */
    public String Name() { return "Esuna"; }

    /**
     * Returns the type of the attack as given in the
     * DBSTypeHandle class.
     *
     * @return  DBSTypeHandle.WhiteMagic
     */
    public int Type() { return DBSTypeHandle.WhiteMagic; }

    /**
     * Returns relative power of the attack
     *
     * @return  1
     */
    public int Pow() { return 0; }

    /**
     * Returns amount of MP needed to attack
     *
     * @return  3
     */
    public int Draw() { return 3; }

    /**
     * Returns whether or not attack attacks a whole team or just one person
     *
     * @return  false
     */
    public boolean IsTeam() { return false; }

    /**
     * Returns a string representation (the name) of any DBSStatus
     * possibly inflicted by this attack.
     *
     * @return  "None"
     */
    public String Status() { return "None"; }

    /**
     * This is a magic attack, so it returns true
     *
     * @return true
     */
    public boolean IsMagic() { return true;}

    /**
     * Has attacker heal defender. Uses Attacker's GetMagicPow
     * method, since this is a magic-based attack.
     *
     * @param  attacker DBSCharacter healer
     * @param  defender DBSCharacter getting healed
     * @return  amount defender was healed
     */
    public int Exe(DBSCharacter attacker, DBSCharacter defender, DBSBattle battle)
    {
       attacker.ModMP(-3);
       if (defender.Status() == DBSStatusHandle.Normal)
       {
           System.out.println("No Effect.");
           return 0;
       }
       else
       {
           defender.ChangeStatus(DBSStatusHandle.Normal);
           System.out.println(defender + "'s health returned.");
           return defender.Level() * 5;
       }
    }
}


text:
#ifndef _TCOD_COLOR_H
#define _TCOD_COLOR_H

typedef struct {
	uint8 r,g,b;
} TCOD_color_t;

/* constructors */
TCODLIB_API TCOD_color_t TCOD_color_RGB(uint8 r, uint8 g, uint8 b);
TCODLIB_API TCOD_color_t TCOD_color_HSV(float h, float s, float v);
/* basic operations */
TCODLIB_API bool TCOD_color_equals (TCOD_color_t c1, TCOD_color_t c2);
TCODLIB_API TCOD_color_t TCOD_color_add (TCOD_color_t c1, TCOD_color_t c2);
TCODLIB_API TCOD_color_t TCOD_color_subtract (TCOD_color_t c1, TCOD_color_t c2);
TCODLIB_API TCOD_color_t TCOD_color_multiply (TCOD_color_t c1, TCOD_color_t c2);
TCODLIB_API TCOD_color_t TCOD_color_multiply_scalar (TCOD_color_t c1, float value);
TCODLIB_API TCOD_color_t TCOD_color_lerp (TCOD_color_t c1, TCOD_color_t c2, float coef);
/* HSV transformations */
TCODLIB_API void TCOD_color_set_HSV (TCOD_color_t *c,float h, float s, float v);
TCODLIB_API void TCOD_color_get_HSV (TCOD_color_t c,float * h, float * s, float * v);
TCODLIB_API float TCOD_color_get_hue (TCOD_color_t c);
TCODLIB_API void TCOD_color_set_hue (TCOD_color_t *c, float h);
TCODLIB_API float TCOD_color_get_saturation (TCOD_color_t c);
TCODLIB_API void TCOD_color_set_saturation (TCOD_color_t *c, float s);
TCODLIB_API float TCOD_color_get_value (TCOD_color_t c);
TCODLIB_API void TCOD_color_set_value (TCOD_color_t *c, float v);
TCODLIB_API void TCOD_color_shift_hue (TCOD_color_t *c, float hshift);
TCODLIB_API void TCOD_color_scale_HSV (TCOD_color_t *c, float scoef, float vcoef);
/* color map */
TCODLIB_API void TCOD_color_gen_map(TCOD_color_t *map, int nb_key, TCOD_color_t const *key_color, int const *key_index);

/* color names */
enum {
	TCOD_COLOR_RED,
	TCOD_COLOR_FLAME,
	TCOD_COLOR_ORANGE,
	TCOD_COLOR_AMBER,
	TCOD_COLOR_YELLOW,
	TCOD_COLOR_LIME,
	TCOD_COLOR_CHARTREUSE,
	TCOD_COLOR_GREEN,
	TCOD_COLOR_SEA,
	TCOD_COLOR_TURQUOISE,
	TCOD_COLOR_CYAN,
	TCOD_COLOR_SKY,
	TCOD_COLOR_AZURE,
	TCOD_COLOR_BLUE,
	TCOD_COLOR_HAN,
	TCOD_COLOR_VIOLET,
	TCOD_COLOR_PURPLE,
	TCOD_COLOR_FUCHSIA,
	TCOD_COLOR_MAGENTA,
	TCOD_COLOR_PINK,
	TCOD_COLOR_CRIMSON,
	TCOD_COLOR_NB
};

/* color levels */
enum {
	TCOD_COLOR_DESATURATED,
	TCOD_COLOR_LIGHTEST,
	TCOD_COLOR_LIGHTER,
	TCOD_COLOR_LIGHT,
	TCOD_COLOR_NORMAL,
	TCOD_COLOR_DARK,
	TCOD_COLOR_DARKER,
	TCOD_COLOR_DARKEST,
	TCOD_COLOR_LEVELS
};

/* color array */
extern TCODLIB_API const TCOD_color_t  TCOD_colors[TCOD_COLOR_NB][TCOD_COLOR_LEVELS];

/* grey levels */
extern TCODLIB_API const TCOD_color_t TCOD_black;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_grey;
extern TCODLIB_API const TCOD_color_t TCOD_darker_grey;
extern TCODLIB_API const TCOD_color_t TCOD_dark_grey;
extern TCODLIB_API const TCOD_color_t TCOD_grey;
extern TCODLIB_API const TCOD_color_t TCOD_light_grey;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_grey;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_grey;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_gray;
extern TCODLIB_API const TCOD_color_t TCOD_darker_gray;
extern TCODLIB_API const TCOD_color_t TCOD_dark_gray;
extern TCODLIB_API const TCOD_color_t TCOD_gray;
extern TCODLIB_API const TCOD_color_t TCOD_light_gray;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_gray;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_gray;
extern TCODLIB_API const TCOD_color_t TCOD_white;

/* sepia */
extern TCODLIB_API const TCOD_color_t TCOD_darkest_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_darker_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_dark_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_light_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_sepia;

/* standard colors */
extern TCODLIB_API const TCOD_color_t TCOD_red;
extern TCODLIB_API const TCOD_color_t TCOD_flame;
extern TCODLIB_API const TCOD_color_t TCOD_orange;
extern TCODLIB_API const TCOD_color_t TCOD_amber;
extern TCODLIB_API const TCOD_color_t TCOD_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_lime;
extern TCODLIB_API const TCOD_color_t TCOD_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_green;
extern TCODLIB_API const TCOD_color_t TCOD_sea;
extern TCODLIB_API const TCOD_color_t TCOD_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_sky;
extern TCODLIB_API const TCOD_color_t TCOD_azure;
extern TCODLIB_API const TCOD_color_t TCOD_blue;
extern TCODLIB_API const TCOD_color_t TCOD_han;
extern TCODLIB_API const TCOD_color_t TCOD_violet;
extern TCODLIB_API const TCOD_color_t TCOD_purple;
extern TCODLIB_API const TCOD_color_t TCOD_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_pink;
extern TCODLIB_API const TCOD_color_t TCOD_crimson;

/* dark colors */
extern TCODLIB_API const TCOD_color_t TCOD_dark_red;
extern TCODLIB_API const TCOD_color_t TCOD_dark_flame;
extern TCODLIB_API const TCOD_color_t TCOD_dark_orange;
extern TCODLIB_API const TCOD_color_t TCOD_dark_amber;
extern TCODLIB_API const TCOD_color_t TCOD_dark_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_dark_lime;
extern TCODLIB_API const TCOD_color_t TCOD_dark_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_dark_green;
extern TCODLIB_API const TCOD_color_t TCOD_dark_sea;
extern TCODLIB_API const TCOD_color_t TCOD_dark_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_dark_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_dark_sky;
extern TCODLIB_API const TCOD_color_t TCOD_dark_azure;
extern TCODLIB_API const TCOD_color_t TCOD_dark_blue;
extern TCODLIB_API const TCOD_color_t TCOD_dark_han;
extern TCODLIB_API const TCOD_color_t TCOD_dark_violet;
extern TCODLIB_API const TCOD_color_t TCOD_dark_purple;
extern TCODLIB_API const TCOD_color_t TCOD_dark_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_dark_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_dark_pink;
extern TCODLIB_API const TCOD_color_t TCOD_dark_crimson;

/* darker colors */
extern TCODLIB_API const TCOD_color_t TCOD_darker_red;
extern TCODLIB_API const TCOD_color_t TCOD_darker_flame;
extern TCODLIB_API const TCOD_color_t TCOD_darker_orange;
extern TCODLIB_API const TCOD_color_t TCOD_darker_amber;
extern TCODLIB_API const TCOD_color_t TCOD_darker_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_darker_lime;
extern TCODLIB_API const TCOD_color_t TCOD_darker_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_darker_green;
extern TCODLIB_API const TCOD_color_t TCOD_darker_sea;
extern TCODLIB_API const TCOD_color_t TCOD_darker_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_darker_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_darker_sky;
extern TCODLIB_API const TCOD_color_t TCOD_darker_azure;
extern TCODLIB_API const TCOD_color_t TCOD_darker_blue;
extern TCODLIB_API const TCOD_color_t TCOD_darker_han;
extern TCODLIB_API const TCOD_color_t TCOD_darker_violet;
extern TCODLIB_API const TCOD_color_t TCOD_darker_purple;
extern TCODLIB_API const TCOD_color_t TCOD_darker_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_darker_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_darker_pink;
extern TCODLIB_API const TCOD_color_t TCOD_darker_crimson;

/* darkest colors */
extern TCODLIB_API const TCOD_color_t TCOD_darkest_red;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_flame;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_orange;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_amber;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_lime;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_green;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_sea;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_sky;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_azure;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_blue;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_han;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_violet;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_purple;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_pink;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_crimson;

/* light colors */
extern TCODLIB_API const TCOD_color_t TCOD_light_red;
extern TCODLIB_API const TCOD_color_t TCOD_light_flame;
extern TCODLIB_API const TCOD_color_t TCOD_light_orange;
extern TCODLIB_API const TCOD_color_t TCOD_light_amber;
extern TCODLIB_API const TCOD_color_t TCOD_light_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_light_lime;
extern TCODLIB_API const TCOD_color_t TCOD_light_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_light_green;
extern TCODLIB_API const TCOD_color_t TCOD_light_sea;
extern TCODLIB_API const TCOD_color_t TCOD_light_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_light_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_light_sky;
extern TCODLIB_API const TCOD_color_t TCOD_light_azure;
extern TCODLIB_API const TCOD_color_t TCOD_light_blue;
extern TCODLIB_API const TCOD_color_t TCOD_light_han;
extern TCODLIB_API const TCOD_color_t TCOD_light_violet;
extern TCODLIB_API const TCOD_color_t TCOD_light_purple;
extern TCODLIB_API const TCOD_color_t TCOD_light_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_light_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_light_pink;
extern TCODLIB_API const TCOD_color_t TCOD_light_crimson;

/* lighter colors */
extern TCODLIB_API const TCOD_color_t TCOD_lighter_red;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_flame;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_orange;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_amber;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_lime;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_green;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_sea;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_sky;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_azure;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_blue;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_han;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_violet;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_purple;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_pink;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_crimson;

/* lightest colors */
extern TCODLIB_API const TCOD_color_t TCOD_lightest_red;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_flame;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_orange;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_amber;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_lime;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_green;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_sea;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_sky;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_azure;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_blue;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_han;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_violet;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_purple;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_pink;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_crimson;

/* desaturated */
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_red;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_flame;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_orange;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_amber;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_lime;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_green;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_sea;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_sky;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_azure;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_blue;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_han;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_violet;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_purple;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_pink;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_crimson;

/* metallic */
extern TCODLIB_API const TCOD_color_t TCOD_brass;
extern TCODLIB_API const TCOD_color_t TCOD_copper;
extern TCODLIB_API const TCOD_color_t TCOD_gold;
extern TCODLIB_API const TCOD_color_t TCOD_silver;

/* miscellaneous */
extern TCODLIB_API const TCOD_color_t TCOD_celadon;
extern TCODLIB_API const TCOD_color_t TCOD_peach;

#endif


text:
package org.springframework.security.config.annotation.authentication.builders;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityBuilder;
import org.springframework.security.config.annotation.SecurityConfigurer;
import org.springframework.security.config.annotation.authentication.ProviderManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.ldap.LdapAuthenticationProviderConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.JdbcUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.userdetails.UserDetailsAwareConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.Assert;

/**
 * {@link SecurityBuilder} used to create an {@link AuthenticationManager}.
 * Allows for easily building in memory authentication, LDAP authentication,
 * JDBC based authentication, adding {@link UserDetailsService}, and adding
 * {@link AuthenticationProvider}'s.
 *
 * @author Rob Winch
 * @since 3.2
 */
public class AuthenticationManagerBuilder extends AbstractConfiguredSecurityBuilder<AuthenticationManager, AuthenticationManagerBuilder> implements ProviderManagerBuilder<AuthenticationManagerBuilder> {
    private final Log logger = LogFactory.getLog(getClass());

    private AuthenticationManager parentAuthenticationManager;
    private List<AuthenticationProvider> authenticationProviders = new ArrayList<AuthenticationProvider>();
    private UserDetailsService defaultUserDetailsService;
    private Boolean eraseCredentials;
    private AuthenticationEventPublisher eventPublisher;

    /**
     * Creates a new instance
     * @param the {@link ObjectPostProcessor} instance to use.
     */
    public AuthenticationManagerBuilder(ObjectPostProcessor<Object> objectPostProcessor) {
        super(objectPostProcessor,true);
    }

    /**
     * Allows providing a parent {@link AuthenticationManager} that will be
     * tried if this {@link AuthenticationManager} was unable to attempt to
     * authenticate the provided {@link Authentication}.
     *
     * @param authenticationManager
     *            the {@link AuthenticationManager} that should be used if the
     *            current {@link AuthenticationManager} was unable to attempt to
     *            authenticate the provided {@link Authentication}.
     * @return the {@link AuthenticationManagerBuilder} for further adding types
     *         of authentication
     */
    public AuthenticationManagerBuilder parentAuthenticationManager(
            AuthenticationManager authenticationManager) {
        if(authenticationManager instanceof ProviderManager) {
            eraseCredentials(((ProviderManager) authenticationManager).isEraseCredentialsAfterAuthentication());
        }
        this.parentAuthenticationManager = authenticationManager;
        return this;
    }

    /**
     * Sets the {@link AuthenticationEventPublisher}
     *
     * @param eventPublisher
     *            the {@link AuthenticationEventPublisher} to use
     * @return the {@link AuthenticationManagerBuilder} for further
     *         customizations
     */
    public AuthenticationManagerBuilder authenticationEventPublisher(AuthenticationEventPublisher eventPublisher) {
        Assert.notNull(eventPublisher, "AuthenticationEventPublisher cannot be null");
        this.eventPublisher = eventPublisher;
        return this;
    }

    /**
     *
     *
     * @param eraseCredentials
     *            true if {@link AuthenticationManager} should clear the
     *            credentials from the {@link Authentication} object after
     *            authenticating
     * @return the {@link AuthenticationManagerBuilder} for further customizations
     */
    public AuthenticationManagerBuilder eraseCredentials(boolean eraseCredentials) {
        this.eraseCredentials = eraseCredentials;
        return this;
    }

    /**
     * Add in memory authentication to the {@link AuthenticationManagerBuilder}
     * and return a {@link InMemoryUserDetailsManagerConfigurer} to
     * allow customization of the in memory authentication.
     *
     *

     * This method also ensure that a {@link UserDetailsService} is available
     * for the {@link #getDefaultUserDetailsService()} method. Note that
     * additional {@link UserDetailsService}'s may override this
     * {@link UserDetailsService} as the default.
     *

     *
     * @return a {@link InMemoryUserDetailsManagerConfigurer} to allow
     *         customization of the in memory authentication
     * @throws Exception
     *             if an error occurs when adding the in memory authentication
     */
    public InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemoryAuthentication()
            throws Exception {
        return apply(new InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>());
    }

    /**
     * Add JDBC authentication to the {@link AuthenticationManagerBuilder} and
     * return a {@link JdbcUserDetailsManagerConfigurer} to allow customization
     * of the JDBC authentication.
     *
     *

     * When using with a persistent data store, it is best to add users external
     * of configuration using something like Flyway or Liquibase to create the schema and
     * adding users to ensure these steps are only done once and that the
     * optimal SQL is used.
     *

     *
     *

     * This method also ensure that a {@link UserDetailsService} is available
     * for the {@link #getDefaultUserDetailsService()} method. Note that
     * additional {@link UserDetailsService}'s may override this
     * {@link UserDetailsService} as the default. See the User Schema section of the reference for the default schema.
     *

     *
     * @return a {@link JdbcUserDetailsManagerConfigurer} to allow customization
     *         of the JDBC authentication
     * @throws Exception
     *             if an error occurs when adding the JDBC authentication
     */
    public JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcAuthentication()
            throws Exception {
        return apply(new JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder>());
    }

    /**
     * Add authentication based upon the custom {@link UserDetailsService} that
     * is passed in. It then returns a {@link DaoAuthenticationConfigurer} to
     * allow customization of the authentication.
     *
     *

     * This method also ensure that the {@link UserDetailsService} is available
     * for the {@link #getDefaultUserDetailsService()} method. Note that
     * additional {@link UserDetailsService}'s may override this
     * {@link UserDetailsService} as the default.
     *

     *
     * @return a {@link DaoAuthenticationConfigurer} to allow customization
     *         of the DAO authentication
     * @throws Exception
     *             if an error occurs when adding the {@link UserDetailsService}
     *             based authentication
     */
    public <T extends UserDetailsService> DaoAuthenticationConfigurer<AuthenticationManagerBuilder,T> userDetailsService(
            T userDetailsService) throws Exception {
        this.defaultUserDetailsService = userDetailsService;
        return apply(new DaoAuthenticationConfigurer<AuthenticationManagerBuilder,T>(userDetailsService));
    }

    /**
     * Add LDAP authentication to the {@link AuthenticationManagerBuilder} and
     * return a {@link LdapAuthenticationProviderConfigurer} to allow
     * customization of the LDAP authentication.
     *
     *

     * This method does NOT ensure that a {@link UserDetailsService} is
     * available for the {@link #getDefaultUserDetailsService()} method.
     *

     *
     * @return a {@link LdapAuthenticationProviderConfigurer} to allow
     *         customization of the LDAP authentication
     * @throws Exception
     *             if an error occurs when adding the LDAP authentication
     */
    public LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> ldapAuthentication()
            throws Exception {
        return apply(new LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder>());
    }

    /**
     * Add authentication based upon the custom {@link AuthenticationProvider}
     * that is passed in. Since the {@link AuthenticationProvider}
     * implementation is unknown, all customizations must be done externally and
     * the {@link AuthenticationManagerBuilder} is returned immediately.
     *
     *

     * This method does NOT ensure that the {@link UserDetailsService} is
     * available for the {@link #getDefaultUserDetailsService()} method.
     *

     *
     * @return a {@link AuthenticationManagerBuilder} to allow further authentication
     *         to be provided to the {@link AuthenticationManagerBuilder}
     * @throws Exception
     *             if an error occurs when adding the {@link AuthenticationProvider}
     */
    public AuthenticationManagerBuilder authenticationProvider(
            AuthenticationProvider authenticationProvider) {
        this.authenticationProviders.add(authenticationProvider);
        return this;
    }

    @Override
    protected ProviderManager performBuild() throws Exception {
        if(!isConfigured()) {
            logger.debug("No authenticationProviders and no parentAuthenticationManager defined. Returning null.");
            return null;
        }
        ProviderManager providerManager = new ProviderManager(authenticationProviders, parentAuthenticationManager);
        if(eraseCredentials != null) {
            providerManager.setEraseCredentialsAfterAuthentication(eraseCredentials);
        }
        if(eventPublisher != null) {
            providerManager.setAuthenticationEventPublisher(eventPublisher);
        }
        providerManager = postProcess(providerManager);
        return providerManager;
    }

    /**
     * Determines if the {@link AuthenticationManagerBuilder} is configured to
     * build a non null {@link AuthenticationManager}. This means that either a
     * non-null parent is specified or at least one
     * {@link AuthenticationProvider} has been specified.
     *
     *

     * When using {@link SecurityConfigurer} instances, the
     * {@link AuthenticationManagerBuilder} will not be configured until the
     * {@link SecurityConfigurer#configure(SecurityBuilder)} methods. This means
     * a {@link SecurityConfigurer} that is last could check this method and
     * provide a default configuration in the
     * {@link SecurityConfigurer#configure(SecurityBuilder)} method.
     *
     * @return
     */
    public boolean isConfigured() {
        return !authenticationProviders.isEmpty() || parentAuthenticationManager != null;
    }

    /**
     * Gets the default {@link UserDetailsService} for the
     * {@link AuthenticationManagerBuilder}. The result may be null in some
     * circumstances.
     *
     * @return the default {@link UserDetailsService} for the
     * {@link AuthenticationManagerBuilder}
     */
    public UserDetailsService getDefaultUserDetailsService() {
        return this.defaultUserDetailsService;
    }

    /**
     * Captures the {@link UserDetailsService} from any {@link UserDetailsAwareConfigurer}.
     *
     * @param configurer the {@link UserDetailsAwareConfigurer} to capture the {@link UserDetailsService} from.
     * @return the {@link UserDetailsAwareConfigurer} for further customizations
     * @throws Exception if an error occurs
     */
    private <C extends UserDetailsAwareConfigurer<AuthenticationManagerBuilder,? extends UserDetailsService>> C apply(C configurer) throws Exception {
        this.defaultUserDetailsService = configurer.getUserDetailsService();
        return (C) super.apply(configurer);
    }
}


text:
import top

class Trainer(object):
    def __init__(self, sc, dataset):
        self.sc = sc
        self.dataset = dataset
        self.bsize = self.sc.model.batch_size
        self.esize = self.dataset.get_num_examples() / self.bsize

        cost = self.sc.cost()
        self.opt = top.Optimizer(self.sc.model.get_params(), cost,
                input=self.sc.s, method='sgd', learning_rate=0.006)

    def run(self):
        i = 0
        for b in self.dataset.iterator('shuffled_sequential', self.bsize, self.esize):
            i+=1
            print 'Batch #:%d' % i
            self.sc.update_code(b)
            self.opt.run(1,b)


text:
A curated list of browser globals that commonly cause confusion and are not recommended to use without an explicit `window.` qualifier.

## Motivation

Some global variables in browser are likely to be used by people without the intent of using them as globals, such as `status`, `name`, `event`, etc.

For example:

```js
handleClick() { // missing `event` argument
  this.setState({
  	text: event.target.value // uses the `event` global: oops!
  });
}
```

This package exports a list of globals that are often used by mistake. You can feed this list to a static analysis tool like ESLint to prevent their usage without an explicit `window.` qualifier.

## Installation

```sh
npm install --save confusing-browser-globals
```

## Usage

If you use Create React App, you don't need to configure anything, as this rule is already included in the default `eslint-config-react-app` preset.

If you maintain your own ESLint configuration, you can do this:

```js
var restrictedGlobals = require('confusing-browser-globals');

module.exports = {
  rules: {
    'no-restricted-globals': ['error'].concat(restrictedGlobals),
  },
};
```

## License

MIT


text:
from csrv.model import actions
from csrv.model import cost
from csrv.model import errors
from csrv.model import parameters
from csrv.model import timing_phases
from csrv.model.cards import card_info
from csrv.model.cards import resource

class Card01031Cost(cost.BasicActionCost):
  def can_pay(self):
    return (cost.BasicActionCost.can_pay(self) and
            self.player.scored_agendas.size)

  def pay(self, response=None, ignore_clicks=False):
    if not response or not response.agenda:
      raise errors.CostNotSatisfied('You must forfeit an agenda')
    if not response.agenda.location == self.player.scored_agendas:
      raise errors.InvalidResponse('You must forfeit a scored agenda')
    cost.BasicActionCost.pay(
        self, response=response, ignore_clicks=ignore_clicks)
    # TODO(mrroach): This should probably happen automatically when an agenda
    # is removed from the score area. probably via on_enter_*_score_area
    self.player.scored_agendas.remove(response.agenda)
    self.player.agenda_points -= response.agenda.agenda_points

class ForfeitAgenda(actions.Action):
  REQUEST_CLASS = parameters.ForfeitAgendaRequest
  DESCRIPTION = 'Forfeit an agenda, [click]: gain 9 [credits]'
  COST_CLASS = Card01031Cost

  def resolve(self, response=None, ignore_clicks=False, ignore_all_costs=False):
    actions.Action.resolve(
        self, response=response,
        ignore_clicks=ignore_clicks,
        ignore_all_costs=ignore_all_costs)
    self.player.credits.gain(9)

class Card01031(resource.Resource):

  NAME = u'Card01031'
  SET = card_info.CORE
  NUMBER = 31
  SIDE = card_info.RUNNER
  FACTION = card_info.CRIMINAL
  INFLUENCE = 2
  UNIQUE = False
  KEYWORDS = set([
      card_info.CONNECTION,
      card_info.SEEDY,
  ])
  COST = 0
  IMAGE_SRC = '01031.png'

  WHEN_INSTALLED_PROVIDES_CHOICES_FOR = {
      timing_phases.RunnerTurnActions: 'forfeit_agenda_actions',
  }

  def build_actions(self):
    resource.Resource.build_actions(self)
    self._forfeit_agenda = ForfeitAgenda(self.game, self.player, card=self)

  def forfeit_agenda_actions(self):
    return [self._forfeit_agenda]


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

extern "C" {
#include "php.h"
#include "ext/date/php_date.h"
#include "ext/standard/php_string.h"
#include "zend_interfaces.h"
#include "zend_closures.h"
#include "ext/spl/spl_exceptions.h"
#include "zend_exceptions.h"
}

#include "php_v8js_macros.h"
#include "v8js_v8.h"
#include "v8js_exceptions.h"

static void v8js_timer_interrupt_handler(v8::Isolate *isolate, void *data) { /* {{{ */
#ifdef ZTS
	TSRMLS_D = (void ***) data;
#endif

	if (!V8JSG(timer_stack).size()) {
		return;
	}

	v8::Locker locker(isolate);
	v8::HeapStatistics hs;
	isolate->GetHeapStatistics(&hs);

	V8JSG(timer_mutex).lock();

	for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
		 it != V8JSG(timer_stack).end(); it ++) {
		v8js_timer_ctx *timer_ctx = *it;
		v8js_ctx *c = timer_ctx->ctx;

		if(c->isolate != isolate || timer_ctx->killed) {
			continue;
		}

		if (timer_ctx->memory_limit > 0 && hs.used_heap_size() > timer_ctx->memory_limit) {
			timer_ctx->killed = true;
			v8::V8::TerminateExecution(c->isolate);
			c->memory_limit_hit = true;
		}
	}

	V8JSG(timer_mutex).unlock();
}
/* }}} */

void v8js_timer_thread(TSRMLS_D) /* {{{ */
{
	while (!V8JSG(timer_stop)) {

		V8JSG(timer_mutex).lock();
		if (V8JSG(timer_stack).size()) {
			v8js_timer_ctx *timer_ctx = V8JSG(timer_stack).front();
			v8js_ctx *c = timer_ctx->ctx;
			std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();

			if(timer_ctx->killed) {
				/* execution already terminated, nothing to check anymore,
				 * but wait for caller to pop this timer context. */
			}
			else if(timer_ctx->time_limit > 0 && now > timer_ctx->time_point) {
				timer_ctx->killed = true;
				v8::V8::TerminateExecution(c->isolate);
				c->time_limit_hit = true;
			}
			else if (timer_ctx->memory_limit > 0) {
				/* If a memory_limit is set, we need to interrupt execution
				 * and check heap size within the callback.  We must *not*
				 * directly call GetHeapStatistics here, since we don't have
				 * a v8::Locker on the isolate, but are expected to hold one,
				 * and cannot aquire it as v8 is executing the script ... */
				void *data = NULL;
#ifdef ZTS
				data = (void *) TSRMLS_C;
#endif
				c->isolate->RequestInterrupt(v8js_timer_interrupt_handler, data);
			}
		}
		V8JSG(timer_mutex).unlock();

		// Sleep for 10ms
#ifdef _WIN32
		concurrency::wait(10);
#else
		std::chrono::milliseconds duration(10);
		std::this_thread::sleep_for(duration);
#endif
	}
}
/* }}} */

void v8js_timer_push(long time_limit, long memory_limit, v8js_ctx *c TSRMLS_DC) /* {{{ */
{
	V8JSG(timer_mutex).lock();

	// Create context for this timer
	v8js_timer_ctx *timer_ctx = (v8js_timer_ctx *)emalloc(sizeof(v8js_timer_ctx));

	// Calculate the time point when the time limit is exceeded
	std::chrono::milliseconds duration(time_limit);
	std::chrono::time_point<std::chrono::high_resolution_clock> from = std::chrono::high_resolution_clock::now();

	// Push the timer context
	timer_ctx->time_limit = time_limit;
	timer_ctx->memory_limit = memory_limit;
	timer_ctx->time_point = from + duration;
	timer_ctx->ctx = c;
	timer_ctx->killed = false;
	V8JSG(timer_stack).push_front(timer_ctx);

	V8JSG(timer_mutex).unlock();
}
/* }}} */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Tagging;
using PowerShellTools.Common.Logging;

namespace PowerShellTools.Classification
{
    /// <summary>
    /// Provides matching for regions.
    /// </summary>
    internal class PowerShellOutliningTagger : ITagger<IOutliningRegionTag>, INotifyTagsChanged
    {
	public event EventHandler<SnapshotSpanEventArgs> TagsChanged;

	private static readonly ILog Log = LogManager.GetLogger(typeof(PowerShellOutliningTagger));
	private ITextBuffer _textBuffer { get; set; }

	internal PowerShellOutliningTagger(ITextBuffer sourceBuffer)
	{
	    _textBuffer = sourceBuffer;
	    _textBuffer.Properties.AddProperty(typeof(PowerShellOutliningTagger).Name, this);
	    _textBuffer.ContentTypeChanged += Buffer_ContentTypeChanged;
	}

	public IEnumerable<ITagSpan<IOutliningRegionTag>> GetTags(NormalizedSnapshotSpanCollection spans)
	{
	    Log.Debug("GetTags");
	    List<ITagSpan<IOutliningRegionTag>> regionTagSpans;
	    if (_textBuffer.Properties.TryGetProperty(BufferProperties.RegionTags, out regionTagSpans) && regionTagSpans != null)
	    {
		Log.Debug("Returning existing tag spans.");
		return regionTagSpans;
	    }

	    List<TagInformation<IOutliningRegionTag>> regionTagInformation;
	    regionTagSpans = new List<ITagSpan<IOutliningRegionTag>>();
	    if (_textBuffer.Properties.TryGetProperty<List<TagInformation<IOutliningRegionTag>>>(BufferProperties.Regions, out regionTagInformation) &&
		regionTagInformation != null)
	    {
		var currentSnapshot = _textBuffer.CurrentSnapshot;
		regionTagSpans.AddRange(regionTagInformation.Select(current => current.GetTagSpan(currentSnapshot)).Where(tagSpan => tagSpan != null));

		Log.Debug("Updating with new tag spans.");
		if (!_textBuffer.Properties.ContainsProperty(BufferProperties.RegionTags))
		{
		    _textBuffer.Properties.AddProperty(BufferProperties.RegionTags, regionTagSpans);
		}
	    }

	    return regionTagSpans;
	}

	public void OnTagsChanged(SnapshotSpan span)
	{
	    Log.Debug("OnTagsChanged");
	    if (TagsChanged != null)
	    {
		TagsChanged(this, new SnapshotSpanEventArgs(span));
	    }
	}

	private void Buffer_ContentTypeChanged(object sender, ContentTypeChangedEventArgs e)
	{
	    _textBuffer.ContentTypeChanged -= Buffer_ContentTypeChanged;
	    _textBuffer.Properties.RemoveProperty(typeof(PowerShellOutliningTagger).Name);
	}
    }
}


text:
module Spree
  class CreditCard < Spree::Base
    belongs_to :payment_method
    has_many :payments, as: :source

    before_create :set_missing_info

    attr_accessor :number, :verification_value, :encrypted_data

    validates :month, :year, numericality: { only_integer: true }, if: :require_card_numbers?, on: :create
    validates :number, presence: true, if: :require_card_numbers?, on: :create
    validates :name, presence: true, if: :require_card_numbers?, on: :create
    validates :verification_value, presence: true, if: :require_card_numbers?, on: :create

    validate :expiry_not_in_the_past

    scope :with_payment_profile, -> { where('gateway_customer_profile_id IS NOT NULL') }

    # needed for some of the ActiveMerchant gateways (eg. SagePay)
    alias_attribute :brand, :cc_type

    CARD_TYPES = {
      visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
      master: /(^5[1-5][0-9]{14}$)|(^6759[0-9]{2}([0-9]{10})$)|(^6759[0-9]{2}([0-9]{12})$)|(^6759[0-9]{2}([0-9]{13})$)/,
      diners_club: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,
      american_express: /^3[47][0-9]{13}$/,
      discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,
      jcb: /^(?:2131|1800|35\d{3})\d{11}$/
    }

    def expiry=(expiry)
      return unless expiry.present?

      self[:month], self[:year] =
      if expiry.match(/\d\s?\/\s?\d/) # will match mm/yy and mm / yyyy
        expiry.delete(' ').split('/')
      elsif match = expiry.match(/(\d{2})(\d{2,4})/) # will match mmyy and mmyyyy
        [match[1], match[2]]
      end
      if self[:year]
        self[:year] = "20" + self[:year] if self[:year].length == 2
        self[:year] = self[:year].to_i
      end
      self[:month] = self[:month].to_i
    end

    def number=(num)
      @number = num.gsub(/[^0-9]/, '') rescue nil
    end

    # cc_type is set by jquery.payment, which helpfully provides different
    # types from Active Merchant. Converting them is necessary.
    def cc_type=(type)
      self[:cc_type] = case type
      when 'mastercard', 'maestro' then 'master'
      when 'amex' then 'american_express'
      when 'dinersclub' then 'diners_club'
      when '' then try_type_from_number
      else type
      end
    end

    def try_type_from_number
      numbers = number.delete(' ') if number
      CARD_TYPES.find{|type, pattern| return type.to_s if numbers =~ pattern}.to_s
    end

    def verification_value?
      verification_value.present?
    end

    # Show the card number, with all but last 4 numbers replace with "X". (XXXX-XXXX-XXXX-4338)
    def display_number
      "XXXX-XXXX-XXXX-#{last_digits}"
    end

    def actions
      %w{capture void credit}
    end

    # Indicates whether its possible to capture the payment
    def can_capture?(payment)
      payment.pending? || payment.checkout?
    end

    # Indicates whether its possible to void the payment.
    def can_void?(payment)
      !payment.void?
    end

    # Indicates whether its possible to credit the payment.  Note that most gateways require that the
    # payment be settled first which generally happens within 12-24 hours of the transaction.
    def can_credit?(payment)
      payment.completed? && payment.credit_allowed > 0
    end

    def has_payment_profile?
      gateway_customer_profile_id.present? || gateway_payment_profile_id.present?
    end

    # ActiveMerchant needs first_name/last_name because we pass it a Spree::CreditCard and it calls those methods on it.
    # Looking at the ActiveMerchant source code we should probably be calling #to_active_merchant before passing
    # the object to ActiveMerchant but this should do for now.
    def first_name
      name.to_s.split(/[[:space:]]/, 2)[0]
    end

    def last_name
      name.to_s.split(/[[:space:]]/, 2)[1]
    end

    def to_active_merchant
      ActiveMerchant::Billing::CreditCard.new(
        :number => number,
        :month => month,
        :year => year,
        :verification_value => verification_value,
        :first_name => first_name,
        :last_name => last_name,
      )
    end

    private

    def expiry_not_in_the_past
      if year.present? && month.present?
        if month.to_i < 1 || month.to_i > 12
          errors.add(:base, :expiry_invalid)
        else
          time = Time.zone.parse("#{year}-#{month}-1")
          if time < Time.zone.now.to_time.beginning_of_month
            errors.add(:base, :card_expired)
          end
        end
      end
    end

    def require_card_numbers?
      !self.encrypted_data.present? && !self.has_payment_profile?
    end

    def set_last_digits
      number.to_s.gsub!(/\s/,'')
      verification_value.to_s.gsub!(/\s/,'')
      self.last_digits ||= number.to_s.length <= 4 ? number : number.to_s.slice(-4..-1)
    end

    def set_missing_info
      set_last_digits
      if has_payment_profile?
        if matching_card = self.class.where(gateway_customer_profile_id: self.gateway_customer_profile_id, gateway_payment_profile_id: self.gateway_payment_profile_id).first
          self.cc_type     = matching_card.cc_type
          self.last_digits = matching_card.last_digits
          self.month       = matching_card.month
          self.name        = matching_card.name
          self.year        = matching_card.year
        end
      end
    end

  end
end


text:
The purpose of this tiny header-only library is to provide a type called SafeAny::Any which can hold any
type, just like std::any or boost::any.
But it has few importants features:

- It has small object optimization for objects smaller than two words (16 bytes on a 64bits platform), thanks to this 3rdparty implementation [thelink2012/any](https://github.com/thelink2012/any).

- it is less pedantic than usual when an arithmetic value (integer, floating point, enum, etc.) is casted into another one. The library will check for narrowing, signedness conversions and numerical cancellation.

## Example

```c++
using SafeAny::Any;

{
  Any val( int(-1000) );

  int    int_val = val.cast<int>(); //OK
  double real_val = val.cast<double>(); //OK
  double long_val = val.cast<long>(); //OK

  int8_t small_val      = val.cast<uint8_t>(); // throws exception
  uint16_t unsigned_val = val.cast<uint16_t>(); // throws exception
}

{
  Any val( float(3.1) );

  float  f_val = val.cast<float>(); //OK
  double d_val = val.cast<double>(); //OK

  int i_val = val.cast<int>(); // throws exception.
}
```

## Implementation

SafeAny extends std::any with few ideas from [Poco::DynamicAny](http://pocoproject.org/docs-1.4.6/Poco.DynamicAny.html).

The main drawback of Poco::DynamicAny is that it requires heap allocation, something that is slow and not very cache-friendly.


text:
package main

import (
	"io"
	"testing"

	"github.com/spf13/cobra"

	"k8s.io/helm/pkg/helm"
	"k8s.io/helm/pkg/proto/hapi/release"
)

func TestDelete(t *testing.T) {

	tests := []releaseCase{
		{
			name:     "basic delete",
			args:     []string{"aeneas"},
			flags:    []string{},
			expected: "", // Output of a delete is an empty string and exit 0.
			resp:     helm.ReleaseMock(&helm.MockReleaseOptions{Name: "aeneas"}),
			rels:     []*release.Release{helm.ReleaseMock(&helm.MockReleaseOptions{Name: "aeneas"})},
		},
		{
			name:     "delete with timeout",
			args:     []string{"aeneas"},
			flags:    []string{"--timeout", "120"},
			expected: "",
			resp:     helm.ReleaseMock(&helm.MockReleaseOptions{Name: "aeneas"}),
			rels:     []*release.Release{helm.ReleaseMock(&helm.MockReleaseOptions{Name: "aeneas"})},
		},
		{
			name:     "delete without hooks",
			args:     []string{"aeneas"},
			flags:    []string{"--no-hooks"},
			expected: "",
			resp:     helm.ReleaseMock(&helm.MockReleaseOptions{Name: "aeneas"}),
			rels:     []*release.Release{helm.ReleaseMock(&helm.MockReleaseOptions{Name: "aeneas"})},
		},
		{
			name:     "purge",
			args:     []string{"aeneas"},
			flags:    []string{"--purge"},
			expected: "",
			resp:     helm.ReleaseMock(&helm.MockReleaseOptions{Name: "aeneas"}),
			rels:     []*release.Release{helm.ReleaseMock(&helm.MockReleaseOptions{Name: "aeneas"})},
		},
		{
			name:     "delete with description",
			args:     []string{"aeneas"},
			flags:    []string{"--description", "foo"},
			expected: "",
			resp:     helm.ReleaseMock(&helm.MockReleaseOptions{Name: "aeneas"}),
			rels:     []*release.Release{helm.ReleaseMock(&helm.MockReleaseOptions{Name: "aeneas"})},
		},
		{
			name: "delete without release",
			args: []string{},
			err:  true,
		},
	}
	runReleaseCases(t, tests, func(c *helm.FakeClient, out io.Writer) *cobra.Command {
		return newDeleteCmd(c, out)
	})
}


text:
package cbedoy.cblibrary.services;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cbedoy.cblibrary.business.InjectionManager;

/**
 * Created by Carlos Bedoy on 12/15/14.
 */
public class ImageCacheService
{
    private static ImageCacheService imageCacheService;
    private final String folderStorage;
    private final String cacheStorage;
    private final String TAG = ImageCacheService.class.getSimpleName();

    private String cachePath;
    private String imagesPath;

    public static ImageCacheService getInstance(){
        if(imageCacheService == null)
            imageCacheService = new ImageCacheService();
        return imageCacheService;
    }

    public ImageCacheService()
    {
        File external_files_dir = ApplicationLoader.mainContext.getExternalFilesDir(null);
        if(external_files_dir != null && this.isExternalStorageWritable())
        {
            this.folderStorage  = external_files_dir.getAbsolutePath() + File.separator + "bills" + File.separator + "images" + File.separator;
            this.cacheStorage   = external_files_dir.getAbsolutePath() + File.separator + "bills" + File.separator + "cache" + File.separator;
        }
        else
        {
            this.folderStorage  = ApplicationLoader.mainContext.getFilesDir().getAbsolutePath() + File.separator + "bills" + File.separator + "images" + File.separator;
            this.cacheStorage   = ApplicationLoader.mainContext.getFilesDir().getAbsolutePath() + File.separator + "bills" + File.separator + "cache" + File.separator;
        }
        new File(this.folderStorage).mkdirs();
        new File(this.cacheStorage).mkdirs();
        cachePath   = InjectionManager.getInstance().isProduction() ? "production/cache"   : "develop/cache";
        imagesPath  = "images";
        saveAssetsToSDCard();
        saveCacheBinaryToSDCard();
    }

    private void saveCacheBinaryToSDCard() {
        AssetManager assetManager = ApplicationLoader.mainContext.getAssets();
        try {
            String[] files = assetManager.list(cachePath);
            for(String filename : files)
            {
                File file = new File(this.cacheStorage + filename);
                if(!file.exists())
                {
                    String pathAsset = cachePath + File.separator + filename;
                    InputStream in = assetManager.open(pathAsset);
                    OutputStream out = new FileOutputStream(file);
                    copyFile(in, out);
                    in.close();
                    out.flush();
                    out.close();
                    LogService.e("Cache: "+ filename + " saved.");
                }
                else
                {
                    LogService.e("Cache: " + filename + " has been saved.");
                }
            }
        } catch (IOException e)
        {
            LogService.e(e.getMessage());
            System.gc();
        }
    }

    @SuppressWarnings("unchecked")
    public void downloadImagesFrom(Object images_info)
    {
        ArrayList<String> images_list = new ArrayList<String>();
        this.processObject(images_info, images_list);

        if(images_list.size() == 0)
            return;
        DownloadImagesAsyncTask asyncTask = new DownloadImagesAsyncTask();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, images_list);
        else
            asyncTask.execute(images_list);
    }

    private void saveAssetsToSDCard() {
        AssetManager assetManager = ApplicationLoader.mainContext.getAssets();
        try {
            String[] files = assetManager.list(imagesPath);
            for(String filename : files)
            {
                File file = new File(this.folderStorage + filename);
                if(!file.exists())
                {
                    String pathAsset = imagesPath + File.separator + filename;
                    InputStream in = assetManager.open(pathAsset);
                    OutputStream out = new FileOutputStream(file);
                    copyFile(in, out);
                    in.close();
                    out.flush();
                    out.close();
                    LogService.e("Image: "+ filename + " saved.");
                    System.gc();
                }

            }
        } catch (IOException e)
        {
            LogService.e(e.getMessage());
        }
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
            out.write(buffer, 0, read);
        }
    }

    public Bitmap getBitmapFromFile(String file)
    {
        BitmapFactory.Options opts=new BitmapFactory.Options();
        opts.inDither=false;                     //Disable Dithering mode
        opts.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
        opts.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
        opts.inTempStorage=new byte[32 * 1024];
        Bitmap bmp = BitmapFactory.decodeFile(this.folderStorage + file, opts);
        System.gc();
        return bmp;
    }

    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }

    private void processObject(Object images_info, ArrayList<String> images_list) {
        if (images_info == null)
            return;

        if (images_info instanceof List) {
            for (Object object : (List) images_info)
                this.processObject(object, images_list);
            return;
        }

        if (images_info instanceof Map) {
            for (Object o : ((Map) images_info).entrySet()) {
                Map.Entry pair = (Map.Entry) o;
                Object value = pair.getValue();
                this.processObject(value, images_list);
            }
            return;
        }

        if (images_info instanceof String && images_info.toString().toLowerCase(Locale.getDefault()).contains(".png")) {
            File file = new File(this.folderStorage + images_info.toString());
            if (!file.exists())
                images_list.add(images_info.toString());
        }
    }

    @SuppressWarnings({"unchecked", "deprecated"})
    public void parseImagesToDownload(HashMap<String, Object> response)
    {
        ArrayList<HashMap<String, Object>> services = (ArrayList<HashMap<String, Object>>) response.get("servicios");
        ArrayList<HashMap<String, Object>> categories = (ArrayList<HashMap<String, Object>>) response.get("categories");
        ArrayList<String> images = new ArrayList<String>();

        for(HashMap<String, Object> category : categories)
        {
            images.add(category.get("imagen").toString());
        }
        for(HashMap<String, Object> service : services)
        {
            images.add(service.get("imagen_portada").toString());
            images.add(service.get("imagen_parallax").toString());
            if(service.containsKey("imagenes_ayuda"))
            {
                ArrayList<String> helpImages = (ArrayList<String>) service.get("imagenes_ayuda");
                for(String imgURL : helpImages)
                    images.add(imgURL);
            }

        }
        downloadImagesFrom(images);
    }

    private class DownloadImagesAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {
        private int index = 0;
        protected Void doInBackground(ArrayList<String>... urls) {
            for (ArrayList<String> list : urls)
                for (String link : list)
                    this.getBitmapFromURL(link);
            return null;
        }

        private void getBitmapFromURL(String link) {
            try {
                String url_path = ApplicationLoader.urlProject + link;
                URL url = new URL(url_path);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap bmp   = BitmapFactory.decodeStream(input);
                this.saveImage(bmp, link);
            } catch (Exception ignored) {
            }
        }

        private void saveImage(Bitmap bmp, String link) {
            try {
                FileOutputStream fos;
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.PNG, 100, bytes);
                File file = new File(folderStorage + link);
                if (!file.exists())
                    file.createNewFile();
                fos = new FileOutputStream(file);
                fos.write(bytes.toByteArray());
                fos.close();
            } catch (Exception ignored) {
            }
            LogService.e("Image save "+(index++));
            System.gc();
        }
    }

    public String getFolderStorage() {
        return folderStorage;
    }
}


text:
require 'simplecov'
require 'test/unit'
require 'shoulda'
require 'mocha/setup'
require 'ostruct'

SimpleCov.start do
  add_filter 'specs/ruby/1.9.1/gems/'
  add_filter '/test/'
  add_filter '/config/'
end

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
Mocha::Configuration.prevent(:stubbing_non_existent_method)

require 'flatfoot'