<commit_before>/**
 *
 * Wait for an element (selected by css selector) for the provided amount of
 * milliseconds to be (in)visible. If multiple elements get queryied by given
 * selector, it returns true (or false if reverse flag is set) if at least one
 * element is visible.
 *
 * This function checks for visibility using window.getComputedStyle. An
 * element will be considered invisible if its visibility is 'none', its
 * display is 'hidden', its opacity is 0 or its x/y coordinates are not
 * within the viewport.
 *
 * @param {String}   selector element to wait for
 * @param {Number=}  ms       time in ms (default: 500)
 * @param {Boolean=} reverse  if true it waits for the opposite (default: false)
 *
 * @uses protocol/selectorExecuteAsync, protocol/timeoutsAsyncScript
 * @type utility
 *
 */

import { CommandError } from '../utils/ErrorHandler'

let waitForVisible = function (selector, ms, reverse = false) {
    /*!
     * ensure that ms is set properly
     */
    if (typeof ms !== 'number') {
        ms = this.options.waitforTimeout
    }

    return this.waitUntil(() => {
        return this.isVisible(selector).then((isVisible) => {
            if (!Array.isArray(isVisible)) {
                return isVisible !== reverse
            }

            let result = reverse
            for (let val of isVisible) {
                if (!reverse) {
                    result = result || val
                } else {
                    result = result && val
                }
            }

            return result !== reverse
        })
    }, ms).catch((e) => {
        if (e.message === 'Promise never resolved with an truthy value') {
            let isReversed = reverse ? '' : 'not'
            throw new CommandError(`element (${selector}) still ${isReversed} visible after ${ms}ms`)
        }
        throw e
    })
}

export default waitForVisible
<commit_msg>Correct CSS values in documentation<commit_after>/**
 *
 * Wait for an element (selected by css selector) for the provided amount of
 * milliseconds to be (in)visible. If multiple elements get queryied by given
 * selector, it returns true (or false if reverse flag is set) if at least one
 * element is visible.
 *
 * This function checks for visibility using window.getComputedStyle. An
 * element will be considered invisible if its visibility is 'hidden', its
 * display is 'none', its opacity is 0 or its x/y coordinates are not
 * within the viewport.
 *
 * @param {String}   selector element to wait for
 * @param {Number=}  ms       time in ms (default: 500)
 * @param {Boolean=} reverse  if true it waits for the opposite (default: false)
 *
 * @uses protocol/selectorExecuteAsync, protocol/timeoutsAsyncScript
 * @type utility
 *
 */

import { CommandError } from '../utils/ErrorHandler'

let waitForVisible = function (selector, ms, reverse = false) {
    /*!
     * ensure that ms is set properly
     */
    if (typeof ms !== 'number') {
        ms = this.options.waitforTimeout
    }

    return this.waitUntil(() => {
        return this.isVisible(selector).then((isVisible) => {
            if (!Array.isArray(isVisible)) {
                return isVisible !== reverse
            }

            let result = reverse
            for (let val of isVisible) {
                if (!reverse) {
                    result = result || val
                } else {
                    result = result && val
                }
            }

            return result !== reverse
        })
    }, ms).catch((e) => {
        if (e.message === 'Promise never resolved with an truthy value') {
            let isReversed = reverse ? '' : 'not'
            throw new CommandError(`element (${selector}) still ${isReversed} visible after ${ms}ms`)
        }
        throw e
    })
}

export default waitForVisible
<|endoftext|>


<commit_before>'use strict';

var util = require('./util');
var Response = require('./Response');

module.exports = ExceptionResponse;

/**
 * @private
 * @const
 * @type {object.<number, string>}
 */
var codeToMessageMap = {
  0x01: 'Illegal Function Code: The function code received in the query is not '
    + 'an allowable action for the server (or slave).',
  0x02: 'Illegal Data Address: The data address received in the query is not '
    + 'an allowable address for the server (or slave).',
  0x03: 'Illegal Data Value: A value contained in the query data field is not '
    + 'an allowable value for server (or slave).',
  0x04: 'Slave Device Failure: An unrecoverable error occurred while the '
    + 'server (or slave) was attempting to perform the requested action.',
  0x05: 'Acknowledge: The server (or slave) has accepted the request and is '
    + 'processing it, but a long duration of time will be required to do so.',
  0x06: 'Slave Device Busy: The server (or slave) is engaged in processing '
    + 'a long–duration program command.',
  0x07: 'Negative Acknowledge: The server (or slave) cannot perform the '
    + 'program function received in the query.',
  0x08: 'Memory Parity Error: The server (or slave) attempted to read record '
    + 'file, but detected a parity error in the memory.',
  0x0A: 'Gateway Path Unavailable: Gateway was unable to allocate an internal '
    + 'communication path from the input port to the output port for '
    + 'processing the request.',
  0x0B: 'Gateway Target Device Failed To Respond: No response was obtained '
    + 'from the target device.'
};

/**
 * The exception response (code above 0x80).
 *
 * A binary representation of this response is 2 bytes long and consists of:
 *
 *   - a function code (1 byte),
 *   - an exception code (1 byte).
 *
 * @constructor
 * @extends {Response}
 * @param {number} functionCode A code of the function that resulted in
 * the exception.
 * @param {number} exceptionCode A code of the exception.
 */
function ExceptionResponse(functionCode, exceptionCode)
{
  Response.call(this, functionCode);

  /**
   * A code of the exception.
   *
   * @private
   * @type {number}
   */
  this.exceptionCode = exceptionCode;
}

util.inherits(ExceptionResponse, Response);

/**
 * Creates a new response from the specified `options`.
 *
 * Available options for this response are:
 *
 *   - `functionCode` (number, required) -
 *     A code of the function that resulted in an exception.
 *
 *   - `exceptionCode` (number, required) -
 *     A code of the exception.
 *
 * @param {object} options An options object.
 * @param {number} options.functionCode
 * @param {number} options.exceptionCode
 * @returns {ExceptionResponse} A response created from
 * the specified `options`.
 */
ExceptionResponse.fromOptions = function(options)
{
  return new ExceptionResponse(options.functionCode, options.exceptionCode);
};

/**
 * Creates a new response from its binary representation.
 *
 * @param {Buffer} buffer A binary representation of the response.
 * @returns {ExceptionResponse} A response created from its
 * binary representation.
 * @throws {Error} If the specified buffer is not a valid binary representation
 * of this response.
 */
ExceptionResponse.fromBuffer = function(buffer)
{
  if (buffer[0] <= 0x80)
  {
    throw new Error(util.format(
      "Expected the function code to be above 128, got [%d]",
      buffer[0]
    ));
  }

  return new ExceptionResponse(buffer[0] - 0x80, buffer[1]);
};

/**
 * Returns a binary representation of this response.
 *
 * @returns {Buffer} A binary representation of this response.
 */
ExceptionResponse.prototype.toBuffer = function()
{
  return new Buffer([this.getCode() + 0x80, this.exceptionCode]);
};

/**
 * Returns a string representation of this response.
 *
 * @returns {string} A string representation of this response.
 */
ExceptionResponse.prototype.toString = function ()
{
  var functionCode = '0x';

  if (this.getCode() < 0xF)
  {
    functionCode += '0';
  }

  functionCode += this.getCode().toString(16);

  var message = 'Exception (' + this.exceptionCode + ')';

  if (this.exceptionCode in codeToMessageMap)
  {
    message += ': ' + codeToMessageMap[this.exceptionCode];
  }

  return functionCode + ' (RES) ' + message;
};

/**
 * @returns {number} A code of the exception.
 */
ExceptionResponse.prototype.getExceptionCode = function()
{
  return this.exceptionCode;
};

/**
 * @returns {boolean}
 */
ExceptionResponse.prototype.isException = function()
{
  return true;
};
<commit_msg>Check the buffer's length when creating `ExceptionResponse` from buffer.<commit_after>'use strict';

var util = require('./util');
var Response = require('./Response');

module.exports = ExceptionResponse;

/**
 * @private
 * @const
 * @type {object.<number, string>}
 */
var codeToMessageMap = {
  0x01: 'Illegal Function Code: The function code received in the query is not '
    + 'an allowable action for the server (or slave).',
  0x02: 'Illegal Data Address: The data address received in the query is not '
    + 'an allowable address for the server (or slave).',
  0x03: 'Illegal Data Value: A value contained in the query data field is not '
    + 'an allowable value for server (or slave).',
  0x04: 'Slave Device Failure: An unrecoverable error occurred while the '
    + 'server (or slave) was attempting to perform the requested action.',
  0x05: 'Acknowledge: The server (or slave) has accepted the request and is '
    + 'processing it, but a long duration of time will be required to do so.',
  0x06: 'Slave Device Busy: The server (or slave) is engaged in processing '
    + 'a long–duration program command.',
  0x07: 'Negative Acknowledge: The server (or slave) cannot perform the '
    + 'program function received in the query.',
  0x08: 'Memory Parity Error: The server (or slave) attempted to read record '
    + 'file, but detected a parity error in the memory.',
  0x0A: 'Gateway Path Unavailable: Gateway was unable to allocate an internal '
    + 'communication path from the input port to the output port for '
    + 'processing the request.',
  0x0B: 'Gateway Target Device Failed To Respond: No response was obtained '
    + 'from the target device.'
};

/**
 * The exception response (code above 0x80).
 *
 * A binary representation of this response is 2 bytes long and consists of:
 *
 *   - a function code (1 byte),
 *   - an exception code (1 byte).
 *
 * @constructor
 * @extends {Response}
 * @param {number} functionCode A code of the function that resulted in
 * the exception.
 * @param {number} exceptionCode A code of the exception.
 */
function ExceptionResponse(functionCode, exceptionCode)
{
  Response.call(this, functionCode);

  /**
   * A code of the exception.
   *
   * @private
   * @type {number}
   */
  this.exceptionCode = exceptionCode;
}

util.inherits(ExceptionResponse, Response);

/**
 * Creates a new response from the specified `options`.
 *
 * Available options for this response are:
 *
 *   - `functionCode` (number, required) -
 *     A code of the function that resulted in an exception.
 *
 *   - `exceptionCode` (number, required) -
 *     A code of the exception.
 *
 * @param {object} options An options object.
 * @param {number} options.functionCode
 * @param {number} options.exceptionCode
 * @returns {ExceptionResponse} A response created from
 * the specified `options`.
 */
ExceptionResponse.fromOptions = function(options)
{
  return new ExceptionResponse(options.functionCode, options.exceptionCode);
};

/**
 * Creates a new response from its binary representation.
 *
 * @param {Buffer} buffer A binary representation of the response.
 * @returns {ExceptionResponse} A response created from its
 * binary representation.
 * @throws {Error} If the specified buffer is not a valid binary representation
 * of this response.
 */
ExceptionResponse.fromBuffer = function(buffer)
{
  util.assertBufferLength(buffer, 2);

  if (buffer[0] <= 0x80)
  {
    throw new Error(util.format(
      "Expected the function code to be above 128, got [%d]",
      buffer[0]
    ));
  }

  return new ExceptionResponse(buffer[0] - 0x80, buffer[1]);
};

/**
 * Returns a binary representation of this response.
 *
 * @returns {Buffer} A binary representation of this response.
 */
ExceptionResponse.prototype.toBuffer = function()
{
  return new Buffer([this.getCode() + 0x80, this.exceptionCode]);
};

/**
 * Returns a string representation of this response.
 *
 * @returns {string} A string representation of this response.
 */
ExceptionResponse.prototype.toString = function ()
{
  var functionCode = '0x';

  if (this.getCode() < 0xF)
  {
    functionCode += '0';
  }

  functionCode += this.getCode().toString(16);

  var message = 'Exception (' + this.exceptionCode + ')';

  if (this.exceptionCode in codeToMessageMap)
  {
    message += ': ' + codeToMessageMap[this.exceptionCode];
  }

  return functionCode + ' (RES) ' + message;
};

/**
 * @returns {number} A code of the exception.
 */
ExceptionResponse.prototype.getExceptionCode = function()
{
  return this.exceptionCode;
};

/**
 * @returns {boolean}
 */
ExceptionResponse.prototype.isException = function()
{
  return true;
};
<|endoftext|>


<commit_before>import { compact, merge } from 'lodash'
import sampleData from './sampleData.json'
import formatData from './formatData'
import personalizeData from './personalizeData'
import {
  defaultTimeRange,
  getPostsAndComments,
  getRecipients,
  shouldSendData
} from './util'

const templateId = 'tem_eCnLj6q75A7Ruu9zsLgppN'

const timePeriod = type => {
  switch (type) {
    case 'daily': return 'yesterday'
    case 'weekly': return 'last week'
  }
}

export const prepareDigestData = (id, type, opts = {}) => {
  let startTime = opts.startTime
  let endTime = opts.endTime
  if (!opts.startTime) {
    const range = defaultTimeRange(type)
    startTime = range[0]
    endTime = range[1]
  }
  return Community.find(id).then(c =>
    getPostsAndComments(c, startTime, endTime)
    .then(formatData(c))
    .then(data => merge({
      community_id: c.id,
      community_name: c.get('name'),
      community_avatar_url: c.get('avatar_url'),
      community_url: Frontend.Route.community(c) + '?ctt=digest_email',
      time_period: timePeriod(type)
    }, data)))
}

const sendToUser = (user, data, opts = {}) =>
  personalizeData(user, data, opts).then(data =>
    opts.dryRun || Email.sendSimpleEmail(user.get('email'), templateId, data))

export const sendDigestToUser = (id, userId, type, opts = {}) =>
  prepareDigestData(id, type, opts).then(data =>
    shouldSendData(data) && User.find(userId).then(user =>
      sendToUser(user, data, opts)))

export const sendDigest = (id, type, opts) =>
  prepareDigestData(id, type, opts).then(data =>
    shouldSendData(data) && getRecipients(id, type)
    .then(users => Promise.each(users, user => sendToUser(user, data, opts)))
    .then(users => users.length))

export const sendAllDigests = (type, opts) =>
  Community.where('daily_digest', true).query().pluck('id')
  .then(ids => Promise.map(ids, id =>
    sendDigest(id, type, opts).then(count => count && [id, count]))
  .then(compact))

export const sendSampleData = address =>
  Email.sendSimpleEmail(address, templateId, sampleData)
<commit_msg>digest sent from community name<commit_after>import { compact, merge } from 'lodash'
import sampleData from './sampleData.json'
import formatData from './formatData'
import personalizeData from './personalizeData'
import {
  defaultTimeRange,
  getPostsAndComments,
  getRecipients,
  shouldSendData
} from './util'

const templateId = 'tem_eCnLj6q75A7Ruu9zsLgppN'

const timePeriod = type => {
  switch (type) {
    case 'daily': return 'yesterday'
    case 'weekly': return 'last week'
  }
}

export const prepareDigestData = (id, type, opts = {}) => {
  let startTime = opts.startTime
  let endTime = opts.endTime
  if (!opts.startTime) {
    const range = defaultTimeRange(type)
    startTime = range[0]
    endTime = range[1]
  }
  return Community.find(id).then(c =>
    getPostsAndComments(c, startTime, endTime)
    .then(formatData(c))
    .then(data => merge({
      community_id: c.id,
      community_name: c.get('name'),
      community_avatar_url: c.get('avatar_url'),
      community_url: Frontend.Route.community(c) + '?ctt=digest_email',
      time_period: timePeriod(type)
    }, data)))
}

const sendToUser = (user, data, opts = {}) =>
  personalizeData(user, data, opts).then(data =>
    opts.dryRun ||
    Email.sendSimpleEmail(user.get('email'), templateId, data, {
      sender: {
        name: data.community_name || 'Hylo',
        address: process.env.EMAIL_SENDER
      }
    }))

export const sendDigestToUser = (id, userId, type, opts = {}) =>
  prepareDigestData(id, type, opts).then(data =>
    shouldSendData(data) && User.find(userId).then(user =>
      sendToUser(user, data, opts)))

export const sendDigest = (id, type, opts) =>
  prepareDigestData(id, type, opts).then(data =>
    shouldSendData(data) && getRecipients(id, type)
    .then(users => Promise.each(users, user => sendToUser(user, data, opts)))
    .then(users => users.length))

export const sendAllDigests = (type, opts) =>
  Community.where('daily_digest', true).query().pluck('id')
  .then(ids => Promise.map(ids, id =>
    sendDigest(id, type, opts).then(count => count && [id, count]))
  .then(compact))

export const sendSampleData = address =>
  Email.sendSimpleEmail(address, templateId, sampleData)
<|endoftext|>


<commit_before>var smylie = [];

var Bbcode = (function(){
  function isLetter(state){
    var i = state.s.charCodeAt(state.i);
    return i >= 97 && i <= 122;
  }

  function controleString(c, obj){
    var buffer = "";
    for(var i=0;i<c.length;i++){
      if(c.charAt(i) == "\n" && obj.lineBreak){
        buffer += "
";
      }else{
        buffer += c.charAt(i);
      }
    }
    return buffer;
  }

  function getCode(state){
    var buffer = "";
    while(isLetter(state)){
      buffer += state.s.charAt(state.i);
      state.i++;
    }

    return buffer;
  }

  function parseBlock(state){
    state.i++;
    var code = { code : getCode(state)};
    if(state.s.charAt(state.i) == "="){
       code.attribute = "";
       for(state.i++;state.i<state.s.length;state.i++){
          if(state.s.charAt(state.i) == "]"){
            break;
          }
          code.attribute += state.s.charAt(state.i);
       }
    }
    if(state.s.charAt(state.i) !== "]"){
      return null;
    }

    return code;
  }

  function evulatebb(state, obj){
    //if this is a [/tag] just return here.
    if(state.s.charAt(state.i+1) == "/"){
      return "[";
    }
    var i=state.i;
    var start = parseBlock(state);
    if(start === null || typeof obj.bbcode[start.code] === "undefined"){
      return state.s.substr(i, (state.i-i)+1);
    }

    var buffer = "";
    for(state.i++;state.i<state.s.length;state.i++){
      if(state.s.charAt(state.i) == "["){
        if(state.s.charAt(state.i+1) == "/"){
          state.i++;
          var end = parseBlock(state);
          if(end != null && end.code == start.code){
            return obj.bbcode[start.code](start.attribute, buffer);
          }
          buffer += "[/"+end.code+"]";
        }else{
          buffer += evulatebb(state, obj);
        }
      }else{
        buffer += controleString(state.s.charAt(state.i), obj);
      }
    }

    return "["+start.code+(typeof start.attribute === "undefined" ? "" : "="+start.attribute)+"]"+buffer;
  }

  function renderString(state, obj){
     var buffer = "";
     for(;state.i<state.s.length;state.i++){
       if(state.s.charAt(state.i) == "["){
         buffer += evulatebb(state, obj);
         continue;
       }
       buffer += controleString(state.s.charAt(state.i), obj);
     }
     return buffer;
  }

  function Bbcode(){
    this.lineBreak = false;
    this.bbcode = {};
    this.pushCode("url", function(attribute, str){
       return ""+str+"";
    });

    this.pushCode("color", function(attribute, str){
       return ""+str+"";
    });
  }

  Bbcode.prototype.pushCode = function(name, func){
    this.bbcode[name] = func;
  };

  Bbcode.prototype.render = function(str){
    return renderString({
       s : str,
       i : 0
    }, this);
  };

  return new Bbcode();
})();

function bbcode(str){
  if(typeof str === "undefined"){
    return "";
  }
  for(var i=0;i<smylie.length;i++){
    while(str.indexOf(smylie[i].tag) !== -1){
      str = str.replace(smylie[i].tag, "");
    }
  }
  return Bbcode.render(str);
}
<commit_msg>Delete bbcode.js<commit_after><|endoftext|>


<commit_before>/* Demo ruleset #3 */

var ruleset = server.getRuleset();
ruleset = new Ruleset(server);

ruleset.properties.botsPerTeam = 5;

ruleset.properties.bots = {
	'angleStep': 0.1,
	'speed': 2,
	'radius': 15,
	'radiusMargin': 0,
	'colors': [ "#1eabb1", "#e27ef0" ]
};

ruleset.properties.weapons.bullet.speed = 15;
ruleset.properties.weapons.bullet.strength = 3;
ruleset.properties.weapons.bullet.waitTime = 5;
ruleset.properties.weapons.bullet.numAllowed = 8;

ruleset.generateObstacles = function() {
	// Simpler obstacle generation for now
	var obstacles = [
		{ "x": 50, "y": 50, "width": 100, "height": 100 },
		{ "x": 350, "y": 350, "width": 100, "height": 100 },
		{ "x": 550, "y": 150, "width": 100, "height": 100 },
		{ "x": 750, "y": 250, "width": 100, "height": 100 },
		{ "x": 100, "y": 450, "width": 50, "height": 50 },
		{ "x": 850, "y": 500, "width": 50, "height": 50 },
		{ "x": 850, "y": 20, "width": 50, "height": 50 },
	];

	return obstacles;
};

// Replace the grid with background circles
ruleset.draw.gridItems = [];
for (var x=0; x<280; x++) {
	ruleset.draw.gridItems.push({ 'x': Math.random() * ruleset.draw.width, 'y': Math.random() * ruleset.draw.height, 'radius': Math.random() * 2 });
}

ruleset.draw.grid = function() {
	this.c.beginPath();

	for (i in this.gridItems) {
		var item = this.gridItems[i];

		this.c.arc(item.x, item.y, item.radius, 0, Math.PI * 2, true);
	}

	this.c.fillStyle = "rgba(255, 255, 255, 0.15)";
	this.c.fill();
};

ruleset.draw.obstacle = function(obstacle) {
	this.c.strokeStyle = "#024";
	this.c.lineWidth = 2;
	this.c.fillStyle = "#013";

	this.c.beginPath();
	this.c.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
	this.c.strokeRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
}

ruleset.draw.bot = function(x, y, angle, color, radius, health) {
	this.c.save();
	this.c.translate(x, y);
	this.c.rotate(angle);

	this.c.lineWidth = 2;

	var healthValue = parseInt(health * (255 / 100)); // hardcoded for now
	this.c.strokeStyle = "rgba(255, " + healthValue + ", " + healthValue + ", 1.0)";
	this.c.fillStyle = color;

	// Draw triangle
	var halfRadius = radius / 2;
	this.c.beginPath();
	this.c.moveTo(-radius, -halfRadius);
	this.c.lineTo(-radius + (halfRadius / 2), 0);
	this.c.lineTo(-radius, halfRadius);
	this.c.lineTo(radius, 0);
	this.c.lineTo(-radius, -halfRadius);
	this.c.closePath();
	this.c.fill();
	this.c.stroke();

	this.c.restore();
};

server.setRuleset(ruleset);

$("body").css("background", "#050505");

// 3D transform
$("#main").css("-webkit-perspective", "300px");

$("#main .container").css({
	"-webkit-transform": "rotateX(5deg) rotateY(2deg)",
	"-webkit-transition": "all 1s ease-in-out",
	"-webkit-animation": "pulse 1000ms infinite",
});

document.styleSheets[0].insertRule("@-webkit-keyframes pulse { 0% { -webkit-transform: rotateX(5deg) rotateY(2deg); } 50% { -webkit-transform: rotateX(-5deg) rotateY(-2deg); } 100% { -webkit-transform: rotateX(5deg) rotateY(2deg); } }");
<commit_msg>Updated demo3<commit_after>/* Demo ruleset #3 */

var ruleset = server.getRuleset();
ruleset = new Ruleset(server);

ruleset.properties.botsPerTeam = 5;

ruleset.properties.bots = {
	'angleStep': 0.1,
	'speed': 2,
	'radius': 15,
	'radiusMargin': 0,
	'colors': [ "#1eabb1", "#e27ef0" ]
};

ruleset.properties.weapons.bullet.speed = 15;
ruleset.properties.weapons.bullet.strength = 3;
ruleset.properties.weapons.bullet.waitTime = 5;
ruleset.properties.weapons.bullet.numAllowed = 8;

ruleset.generateObstacles = function() {
	// Simpler obstacle generation for now
	var obstacles = [
		{ "x": 50, "y": 50, "width": 100, "height": 100 },
		{ "x": 350, "y": 350, "width": 100, "height": 100 },
		{ "x": 550, "y": 150, "width": 100, "height": 100 },
		{ "x": 750, "y": 250, "width": 100, "height": 100 },
		{ "x": 100, "y": 450, "width": 50, "height": 50 },
		{ "x": 850, "y": 500, "width": 50, "height": 50 },
		{ "x": 850, "y": 20, "width": 50, "height": 50 },
	];

	return obstacles;
};

// Replace the grid with background circles
ruleset.draw.gridItems = [];
for (var x=0; x<280; x++) {
	ruleset.draw.gridItems.push({ 'x': Math.random() * ruleset.draw.width, 'y': Math.random() * ruleset.draw.height, 'radius': Math.random() * 2 });
}

ruleset.draw.grid = function() {
	this.c.beginPath();

	for (i in this.gridItems) {
		var item = this.gridItems[i];

		this.c.arc(item.x, item.y, item.radius, 0, Math.PI * 2, true);
	}

	this.c.fillStyle = "rgba(255, 255, 255, 0.15)";
	this.c.fill();
};

ruleset.draw.obstacle = function(obstacle) {
	this.c.strokeStyle = "#024";
	this.c.lineWidth = 2;
	this.c.fillStyle = "#013";

	this.c.beginPath();
	this.c.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
	this.c.strokeRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
}

ruleset.draw.bot = function(x, y, angle, color, radius, health) {
	this.c.save();
	this.c.translate(x, y);
	this.c.rotate(angle);

	this.c.lineWidth = 2;

	var healthValue = parseInt(health * (255 / 100)); // hardcoded for now
	this.c.strokeStyle = "rgba(255, " + healthValue + ", " + healthValue + ", 1.0)";
	this.c.fillStyle = color;

	// Draw triangle
	var halfRadius = radius / 2;
	this.c.beginPath();
	this.c.moveTo(-radius, -halfRadius);
	this.c.lineTo(-radius + (halfRadius / 2), 0);
	this.c.lineTo(-radius, halfRadius);
	this.c.lineTo(radius, 0);
	this.c.lineTo(-radius, -halfRadius);
	this.c.closePath();
	this.c.fill();
	this.c.stroke();

	this.c.restore();
};

server.setRuleset(ruleset);

$("body").css("background", "#050505");

// 3D transform
$("#main").css("-webkit-perspective", "300px");

$("#main .container").css({
	"-webkit-transform": "rotateX(5deg) rotateY(2deg)",
	"-webkit-transition": "all 1s ease-in-out",
	"-webkit-animation": "pulse 5000ms infinite",
});

document.styleSheets[0].insertRule("@-webkit-keyframes pulse { 0% { -webkit-transform: rotateX(5deg) rotateY(2deg); } 50% { -webkit-transform: rotateX(-5deg) rotateY(-2deg); } 100% { -webkit-transform: rotateX(5deg) rotateY(2deg); } }");
<|endoftext|>


<commit_before>module.exports = {
  up: (queryInterface, Sequelize) =>
    queryInterface.createTable('cjtest', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV1,
        primaryKey: true,
      },
      idCj: {
        type: Sequelize.STRING(255),
        allowNull: false,
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
    }),

  down: queryInterface => queryInterface.dropTable('cjtest'),
};
<commit_msg>add problemId field for cjtest migration<commit_after>module.exports = {
  up: (queryInterface, Sequelize) =>
    queryInterface.createTable('cjtest', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV1,
        primaryKey: true,
      },
      idCj: {
        type: Sequelize.STRING(255),
        allowNull: false,
      },
      problemId: {
        type: Sequelize.STRING(255),
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
    }),

  down: queryInterface => queryInterface.dropTable('cjtest'),
};
<|endoftext|>


<commit_before>(function() {

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "caissa-invariant") {
      checkVersion(design, name, value);
  }
}

var findPiece = function(design, board, player, type) {
  var positions = design.allPositions();
  for (var i = 0; i < positions.length; i++) {
       var piece = board.getPiece(positions[i]);
       if ((piece !== null) && (piece.type == type) && (piece.player == player)) {
           return positions[i];
       }
  }
  return null;
}

var checkDirection = function(design, board, player, pos, dir, riders) {
  var hole = design.getPieceType("Hole");
  var p = design.navigate(player, pos, dir);
  if (p === null) return false;
  var piece = board.getPiece(p);
  while ((piece === null) || (piece.type == hole)) {
      p = design.navigate(player, p, dir);
      if (p === null) return false;
      piece = board.getPiece(p);
  }
  if (piece.player == player) return false;
  return _.indexOf(riders, piece.type) >= 0;
}

var checkLeap = function(design, board, player, pos, o, d, leaper) {
  var p = design.navigate(player, pos, o);
  if (p === null) return false;
  p = design.navigate(player, p, d);
  if (p === null) return false;
  var piece = board.getPiece(p);
  if (piece === null) return false;
  return (piece.player != player) && (piece.type == leaper);
}

var isAttacked = function(design, board, pos, player) {
  var design = Dagaz.Model.design;
  var queen  = design.getPieceType("Queen");
  var rook   = design.getPieceType("Rook");
  var bishop = design.getPieceType("Bishop");
  var knight = design.getPieceType("Knight");
  var n  = design.getDirection("n");  var w  = design.getDirection("w");
  var s  = design.getDirection("s");  var e  = design.getDirection("e");
  var nw = design.getDirection("nw"); var sw = design.getDirection("sw");
  var ne = design.getDirection("ne"); var se = design.getDirection("se");
  if (checkDirection(design, board, player, pos, n,  [rook, queen])) return true;
  if (checkDirection(design, board, player, pos, s,  [rook, queen])) return true;
  if (checkDirection(design, board, player, pos, w,  [rook, queen])) return true;
  if (checkDirection(design, board, player, pos, e,  [rook, queen])) return true;
  if (checkDirection(design, board, player, pos, nw, [bishop, queen])) return true;
  if (checkDirection(design, board, player, pos, ne, [bishop, queen])) return true;
  if (checkDirection(design, board, player, pos, sw, [bishop, queen])) return true;
  if (checkDirection(design, board, player, pos, se, [bishop, queen])) return true;
  if (checkLeap(design, board, player, pos, n, nw, knight)) return true;
  if (checkLeap(design, board, player, pos, n, ne, knight)) return true;
  if (checkLeap(design, board, player, pos, s, sw, knight)) return true;
  if (checkLeap(design, board, player, pos, s, se, knight)) return true;
  if (checkLeap(design, board, player, pos, w, nw, knight)) return true;
  if (checkLeap(design, board, player, pos, w, sw, knight)) return true;
  if (checkLeap(design, board, player, pos, e, ne, knight)) return true;
   if (checkLeap(design, board, player, pos, e, se, knight)) return true;
  return false;
}

var CheckInvariants = Dagaz.Model.CheckInvariants;

Dagaz.Model.CheckInvariants = function(board) {
  var design = Dagaz.Model.design;
  var queen  = design.getPieceType("Queen");
  _.each(board.moves, function(move) {
      if ((move.actions.length > 0) && (move.actions[0][0] !== null) && (move.actions[0][1] !== null)) {
          var pos = move.actions[0][0][0];
          var piece = board.getPiece(pos);
          if ((piece !== null) && (piece.type == queen) && (move.mode == 1)) {
               if (isAttacked(design, board, pos, board.player)) {
                   move.failed = true;
                   return;
               }
          }
          var b = board.apply(move);
          pos = findPiece(design, b, board.player, queen);
          if ((pos === null) || isAttacked(design, b, pos, board.player)) {
              move.failed = true;
              return;
          }
          // TODO: Check Coherence

      }
  });
  CheckInvariants(board);
}

})();
<commit_msg>Caissa (completed)<commit_after>(function() {

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "caissa-invariant") {
      checkVersion(design, name, value);
  }
}

var findPiece = function(design, board, player, type) {
  var positions = design.allPositions();
  for (var i = 0; i < positions.length; i++) {
       var piece = board.getPiece(positions[i]);
       if ((piece !== null) && (piece.type == type) && (piece.player == player)) {
           return positions[i];
       }
  }
  return null;
}

var checkDirection = function(design, board, player, pos, dir, riders) {
  var hole = design.getPieceType("Hole");
  var p = design.navigate(player, pos, dir);
  if (p === null) return false;
  var piece = board.getPiece(p);
  while ((piece === null) || (piece.type == hole)) {
      p = design.navigate(player, p, dir);
      if (p === null) return false;
      piece = board.getPiece(p);
  }
  if (piece.player == player) return false;
  return _.indexOf(riders, piece.type) >= 0;
}

var checkLeap = function(design, board, player, pos, o, d, leaper) {
  var p = design.navigate(player, pos, o);
  if (p === null) return false;
  p = design.navigate(player, p, d);
  if (p === null) return false;
  var piece = board.getPiece(p);
  if (piece === null) return false;
  return (piece.player != player) && (piece.type == leaper);
}

var isAttacked = function(design, board, pos, player) {
  var design = Dagaz.Model.design;
  var queen  = design.getPieceType("Queen");
  var rook   = design.getPieceType("Rook");
  var bishop = design.getPieceType("Bishop");
  var knight = design.getPieceType("Knight");
  var n  = design.getDirection("n");  var w  = design.getDirection("w");
  var s  = design.getDirection("s");  var e  = design.getDirection("e");
  var nw = design.getDirection("nw"); var sw = design.getDirection("sw");
  var ne = design.getDirection("ne"); var se = design.getDirection("se");
  if (checkDirection(design, board, player, pos, n,  [rook, queen])) return true;
  if (checkDirection(design, board, player, pos, s,  [rook, queen])) return true;
  if (checkDirection(design, board, player, pos, w,  [rook, queen])) return true;
  if (checkDirection(design, board, player, pos, e,  [rook, queen])) return true;
  if (checkDirection(design, board, player, pos, nw, [bishop, queen])) return true;
  if (checkDirection(design, board, player, pos, ne, [bishop, queen])) return true;
  if (checkDirection(design, board, player, pos, sw, [bishop, queen])) return true;
  if (checkDirection(design, board, player, pos, se, [bishop, queen])) return true;
  if (checkLeap(design, board, player, pos, n, nw, knight)) return true;
  if (checkLeap(design, board, player, pos, n, ne, knight)) return true;
  if (checkLeap(design, board, player, pos, s, sw, knight)) return true;
  if (checkLeap(design, board, player, pos, s, se, knight)) return true;
  if (checkLeap(design, board, player, pos, w, nw, knight)) return true;
  if (checkLeap(design, board, player, pos, w, sw, knight)) return true;
  if (checkLeap(design, board, player, pos, e, ne, knight)) return true;
  if (checkLeap(design, board, player, pos, e, se, knight)) return true;
  return false;
}

var noCoherence = function(design, board) {
  var hole  = design.getPieceType("Hole");
  var group = [];
  for (var pos = 0; pos < design.positions.length; pos++) {
       var piece = board.getPiece(pos);
       if ((piece === null) || (piece.type != hole)) {
           if ((group.length > 0) && (_.indexOf(group, pos) < 0)) return true;
           group.push(pos);
           for (var i = 0; i < group.length; i++) {
                _.each(design.allDirections(), function(dir) {
                     var pos = design.navigate(board.player, group[i], dir);
                     if ((pos !== null) && (_.indexOf(group, pos) < 0)) {
                          var piece = board.getPiece(pos);
                          if ((piece === null) || (piece.type != hole)) {
                              group.push(pos);
                          }
                     }
                });
           }
       }
  }
  return false;
}

var CheckInvariants = Dagaz.Model.CheckInvariants;

Dagaz.Model.CheckInvariants = function(board) {
  var design = Dagaz.Model.design;
  var queen  = design.getPieceType("Queen");
  _.each(board.moves, function(move) {
      if ((move.actions.length > 0) && (move.actions[0][0] !== null) && (move.actions[0][1] !== null)) {
          var pos = move.actions[0][0][0];
          var piece = board.getPiece(pos);
          if ((piece !== null) && (piece.type == queen) && (move.mode == 1)) {
               if (isAttacked(design, board, pos, board.player)) {
                   move.failed = true;
                   return;
               }
          }
          var b = board.apply(move);
          pos = findPiece(design, b, board.player, queen);
          if ((pos === null) || isAttacked(design, b, pos, board.player)) {
              move.failed = true;
              return;
          }
          if (noCoherence(design, b)) {
              move.failed = true;
          }
      }
  });
  CheckInvariants(board);
}

})();
<|endoftext|>


<commit_before>/*jshint node:true*/
var async = require('async'),
    path = require('path'),
    utils = require('../lib/utils'),
    EventEmitter = require('events').EventEmitter,
    logger = require('winston').loggers.get('mimik'),
    stepFileProcessor = require('./StepFileProcessor'),
    Mocha = require('mocha'),
    Yadda = require('yadda'),
    English = Yadda.localisation.English,
    chai = require('chai');

var Session = function(config) {
    var me = this;
    this.id = config.id;
    this.driver = config.driver;
    this.featureFile = config.featureFile;
    this.profile = config.profile;
    this.testRunner = null;
    this.feature = null;
    this.options = config.options;
    this.context = {};
    me.init();
};
// Make Session an Observable
utils.extend(Session, EventEmitter);

Session.prototype.init = function (args) {
    var me = this,
        testRunner = new Mocha({
            ui: 'bdd',
            //reporter: 'base',
            reporter: 'spec',
            useInlineDiffs: true,
            //asyncOnly: true,
            timeout: me.options.timeout,
            bail: me.options.bail,
            slow: me.options.slow
        });
    me.testRunner = testRunner;
    // workaround to export describe, before, after handlers globally
    testRunner.suite.emit('pre-require', me.context, null, testRunner);

    Yadda.plugins.mocha.AsyncStepLevelPlugin.init({
        container: me.context
    });
}

Session.prototype.loadFeature = function(featureFile, cb) {
    var me = this;
    try {
        me.context.featureFile(me.featureFile, function(feature) {
            me.feature = feature;
            feature.file = me.featureFile;
            var data = {
                feature: feature,
                suite: me.testRunner.suite.suites[0],
                driver: me.driver,
                profile: me.profile
            };
            me.emit('feature', data);
            //var libraries = me.getFeatureRequires(feature);
            cb(null, feature);
        });
    } catch(err) {
        logger.debug('[session] %s in %s', err.message, featureFile);
        console.error('[session] %s in %s', err.message, featureFile);
        cb(err);
    }
}
Session.prototype.start = function(cb) {
    var me = this;
    logger.debug('[session] Processing ' + me.featureFile + ' on ' + me.profile.desiredCapabilities.browserName);
    logger.debug('[session] Client Session Id', me.id);
    // execute features after the browser is launched
    me.executeFeature(function(err) {
        if(!err) {
            logger.debug('[session] Done processing file ', me.featureFile);
        }
        if(typeof cb === 'function') {
            cb(err, me);
        }
    });

};
Session.prototype.stop = function(){

};
Session.prototype.executeFeature = function(callback) {
    var me = this;
    async.series([
        function(cb) {
            me.parseFeature(me.testRunner, cb);
        }
        ],
        function(err, results) {
            if(err) {
                callback(err);
                return;
            }
            var feature = results[0];
            var runner = me.testRunner.run(function(failures) {
                var suite = me.testRunner.suite.suites[0];
                var data = {
                    feature: feature,
                    suite: suite,
                    failures: failures
                };
                me.emit('feature end', data);
                callback(null, data);
            });
            runner.on('suite', function(suite) { me.emit('suite', suite); });
            runner.on('suite end', function(suite) { me.emit('suite end', suite); });
            runner.on('test', function(test) { me.emit('test', test); });
            runner.on('test end', function(test) { me.emit('test end', test); });
            runner.on('pass', function(test) { me.emit('pass', test); });
            runner.on('fail', function(test, err) { me.emit('fail', test, err); });
            runner.on('pending', function(test) { me.emit('pending', test); });
        }
    );
};

Session.prototype.parseFeature = function(testRunner, cb) {
    var me = this;
    try {
        me.context.featureFile(me.featureFile, function(feature) {
            var suite = testRunner.suite.suites[0];
            suite.feature = feature;
            //feature.suite = suite; // cross-reference
            me.feature = feature;
            feature.file = me.featureFile;
            var data = {
                feature: feature,
                suite: suite,
                driver: me.driver,
                profile: me.profile
            };
            me.emit('feature', data);
            var stepFile = me.getStepFile(me.featureFile);
            //var libraries = me.getFeatureRequires(feature);
            if(!stepFile) {
                var err = new Error('No corresponding step definitions were found for feature "' +  path.basename(me.featureFile) + '"');
                logger.debug('[session] %s', err.message);
                console.error('[session] %s', err.message);
                cb(err);
                return;
            }

            stepFileProcessor.processFile(stepFile, function(err, file) {
                if(err) {
                    logger.debug('[session] %s', err.message);
                    console.error('[session] %s', err.message);
                    cb(err);
                    return;
                }
                // TODO enable language support
                var dictionary = new Yadda.Dictionary().define('NUM', /(\d+)/),
                    library = English.library(dictionary);
                file.execute(library, chai, me.driver, stepFileProcessor);
                var yadda = new Yadda.Yadda(library);

                me.context.scenarios(feature.scenarios, function(scenario) {
                    //yadda.yadda(scenario.steps);
                    me.context.steps(scenario.steps, function(step, done) {
                        yadda.yadda(step, done);
                    });
                });
                cb(null, feature);
            });
        });
    } catch(err) {
        logger.debug('[session] %s', err.message);
        console.error('[session] %s', err.message);
        cb(err);
    }
};
// TODO enable support for feature import "@GivenFeature"
/*
Session.prototype.getFeatureRequires = function(feature) {
    var GivenFeature = feature.annotations.GivenFeature;
    return GivenFeature ? GivenFeature.split(',').reduce(this.loadFile, []) : [];
};
*/
Session.prototype.getStepFile = function(file) {
    var basename = path.basename(file, '.feature'),
        re = new RegExp('^' + basename + '(Steps?|-steps?|_steps?)'),
        stepFile;
    this.options.stepFiles.every(function(file) {
        var name = path.basename(file);
        if(re.test(name)) {
            stepFile = file;
            return false;
        }
        return true;
    });
    return stepFile;
};

module.exports = Session;
<commit_msg>Fixed jshint violation<commit_after>/*jshint node:true*/
var async = require('async'),
    path = require('path'),
    utils = require('../lib/utils'),
    EventEmitter = require('events').EventEmitter,
    logger = require('winston').loggers.get('mimik'),
    stepFileProcessor = require('./StepFileProcessor'),
    Mocha = require('mocha'),
    Yadda = require('yadda'),
    English = Yadda.localisation.English,
    chai = require('chai');

var Session = function(config) {
    var me = this;
    this.id = config.id;
    this.driver = config.driver;
    this.featureFile = config.featureFile;
    this.profile = config.profile;
    this.testRunner = null;
    this.feature = null;
    this.options = config.options;
    this.context = {};
    me.init();
};
// Make Session an Observable
utils.extend(Session, EventEmitter);

Session.prototype.init = function () {
    var me = this,
        testRunner = new Mocha({
            ui: 'bdd',
            //reporter: 'base',
            reporter: 'spec',
            useInlineDiffs: true,
            //asyncOnly: true,
            timeout: me.options.timeout,
            bail: me.options.bail,
            slow: me.options.slow
        });
    me.testRunner = testRunner;
    // workaround to export describe, before, after handlers globally
    testRunner.suite.emit('pre-require', me.context, null, testRunner);

    Yadda.plugins.mocha.AsyncStepLevelPlugin.init({
        container: me.context
    });
};

Session.prototype.loadFeature = function(featureFile, cb) {
    var me = this;
    try {
        me.context.featureFile(me.featureFile, function(feature) {
            me.feature = feature;
            feature.file = me.featureFile;
            var data = {
                feature: feature,
                suite: me.testRunner.suite.suites[0],
                driver: me.driver,
                profile: me.profile
            };
            me.emit('feature', data);
            //var libraries = me.getFeatureRequires(feature);
            cb(null, feature);
        });
    } catch(err) {
        logger.debug('[session] %s in %s', err.message, featureFile);
        console.error('[session] %s in %s', err.message, featureFile);
        cb(err);
    }
};

Session.prototype.start = function(cb) {
    var me = this;
    logger.debug('[session] Processing ' + me.featureFile + ' on ' + me.profile.desiredCapabilities.browserName);
    logger.debug('[session] Client Session Id', me.id);
    // execute features after the browser is launched
    me.executeFeature(function(err) {
        if(!err) {
            logger.debug('[session] Done processing file ', me.featureFile);
        }
        if(typeof cb === 'function') {
            cb(err, me);
        }
    });

};
Session.prototype.stop = function(){

};
Session.prototype.executeFeature = function(callback) {
    var me = this;
    async.series([
        function(cb) {
            me.parseFeature(me.testRunner, cb);
        }
        ],
        function(err, results) {
            if(err) {
                callback(err);
                return;
            }
            var feature = results[0];
            var runner = me.testRunner.run(function(failures) {
                var suite = me.testRunner.suite.suites[0];
                var data = {
                    feature: feature,
                    suite: suite,
                    failures: failures
                };
                me.emit('feature end', data);
                callback(null, data);
            });
            runner.on('suite', function(suite) { me.emit('suite', suite); });
            runner.on('suite end', function(suite) { me.emit('suite end', suite); });
            runner.on('test', function(test) { me.emit('test', test); });
            runner.on('test end', function(test) { me.emit('test end', test); });
            runner.on('pass', function(test) { me.emit('pass', test); });
            runner.on('fail', function(test, err) { me.emit('fail', test, err); });
            runner.on('pending', function(test) { me.emit('pending', test); });
        }
    );
};

Session.prototype.parseFeature = function(testRunner, cb) {
    var me = this;
    try {
        me.context.featureFile(me.featureFile, function(feature) {
            var suite = testRunner.suite.suites[0];
            suite.feature = feature;
            //feature.suite = suite; // cross-reference
            me.feature = feature;
            feature.file = me.featureFile;
            var data = {
                feature: feature,
                suite: suite,
                driver: me.driver,
                profile: me.profile
            };
            me.emit('feature', data);
            var stepFile = me.getStepFile(me.featureFile);
            //var libraries = me.getFeatureRequires(feature);
            if(!stepFile) {
                var err = new Error('No corresponding step definitions were found for feature "' +  path.basename(me.featureFile) + '"');
                logger.debug('[session] %s', err.message);
                console.error('[session] %s', err.message);
                cb(err);
                return;
            }

            stepFileProcessor.processFile(stepFile, function(err, file) {
                if(err) {
                    logger.debug('[session] %s', err.message);
                    console.error('[session] %s', err.message);
                    cb(err);
                    return;
                }
                // TODO enable language support
                var dictionary = new Yadda.Dictionary().define('NUM', /(\d+)/),
                    library = English.library(dictionary);
                file.execute(library, chai, me.driver, stepFileProcessor);
                var yadda = new Yadda.Yadda(library);

                me.context.scenarios(feature.scenarios, function(scenario) {
                    //yadda.yadda(scenario.steps);
                    me.context.steps(scenario.steps, function(step, done) {
                        yadda.yadda(step, done);
                    });
                });
                cb(null, feature);
            });
        });
    } catch(err) {
        logger.debug('[session] %s', err.message);
        console.error('[session] %s', err.message);
        cb(err);
    }
};
// TODO enable support for feature import "@GivenFeature"
/*
Session.prototype.getFeatureRequires = function(feature) {
    var GivenFeature = feature.annotations.GivenFeature;
    return GivenFeature ? GivenFeature.split(',').reduce(this.loadFile, []) : [];
};
*/
Session.prototype.getStepFile = function(file) {
    var basename = path.basename(file, '.feature'),
        re = new RegExp('^' + basename + '(Steps?|-steps?|_steps?)'),
        stepFile;
    this.options.stepFiles.every(function(file) {
        var name = path.basename(file);
        if(re.test(name)) {
            stepFile = file;
            return false;
        }
        return true;
    });
    return stepFile;
};

module.exports = Session;
<|endoftext|>


<commit_before>const utils = require('../lib/modelUtils');

const methodSets = [
  require('./systems'),
  require('./issuers'),
  require('./programs'),
  require('./badges'),
  require('./claimCodes'),
  //require('./issuing'),
  require('./assessment'),
];

exports = module.exports = methodSets.reduce(function(methods, set) {
  Object.keys(set).forEach(function(method) {
    methods[method] = set[method];
  });
  return methods;
}, {});
<commit_msg>Adding a TODO comment<commit_after>const utils = require('../lib/modelUtils');

const methodSets = [
  require('./systems'),
  require('./issuers'),
  require('./programs'),
  require('./badges'),
  require('./claimCodes'),
  //require('./issuing'),  // TODO: Don't do this
  require('./assessment'),
];

exports = module.exports = methodSets.reduce(function(methods, set) {
  Object.keys(set).forEach(function(method) {
    methods[method] = set[method];
  });
  return methods;
}, {});
<|endoftext|>


<commit_before>import forEach from 'lodash.foreach';
import hoistStatics from 'hoist-non-react-statics';
import invariant from 'invariant';
import isEqual from 'lodash.isequal';
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';

import getVariables from '../helpers/get-variables';
import removeConnector from '../actions/remove-connector';
import {generateConnectorId} from '../helpers/connectors-ids';

// getBundle is a function which receives the component props
// and retrieves a configuration set by the user
// e.g
// (props) => ({
//   fragments: {
//     pages: {
//       _id: 1,
//       title: 1
//     },
//     page: {
//       _id: 1,
//       title: 1,
//       user: {
//         _id: 1,
//         username: 1
//       }
//     }
//   },
//   variablesTypes: {
//     pages: {
//       order: 'String!',
//       sort: 'String!'
//     }
//   },
//   initialVariables: {
//     pages: {
//       order: 'asc',
//       sort: 'date'
//     }
//   },
//   mutations: {
//     addPage: [
//       {
//         type: 'APPEND', // INCREMENT || DECREMENT || APPEND || PREPEND
//         field: 'pages'
//       },
//       {
//         type: 'INCREMENT',
//         field: 'pagesCount'
//       },
//       {
//         type: 'INCREMENT',
//         field: ['pages', 'pagesCount']
//       }
//     ]
//   }
// })
export default function dataConnect (...args) {
  invariant(args.length, 'Relate: a dataConnect does not have arguments specified');

  const getReduxState = args.length > 1 && args[0];
  const getReduxDispatches = args.length > 2 && args[1];
  const getBundle = args[args.length - 1];

  return function wrapWithDataConnect (WrappedComponent) {
    class ConnectData extends Component {
      static propTypes = {
        relateConnectorData: PropTypes.object,
        CONNECTOR_ID: PropTypes.string.isRequired
      };

      static contextTypes = {
        fetchData: PropTypes.func.isRequired,
        store: PropTypes.any.isRequired,
        relate_ssr: PropTypes.func
      };

      static defaultProps = {
        relateConnectorData: {}
      };

      static relateIdentifier = 'DATA_CONNECT';

      constructor (props, context) {
        super(props, context);

        const initialBundle = getBundle && getBundle(this.props);

        // Relate connector info
        this.variablesTypes = initialBundle && initialBundle.variablesTypes || {};
        this.relate = {
          setVariables: ::this.setVariables,
          refresh: ::this.refresh,
          loadMore: ::this.loadMore,
          variables: initialBundle && initialBundle.initialVariables,
          hasMore: true
        };

        if (!props.relateConnectorData || Object.keys(props.relateConnectorData).length === 0) {
          // Fetch data
          const hasDataToFetch = initialBundle && this.hasDataToFetch(initialBundle.fragments) && true;
          if (hasDataToFetch) {
            this.fetchData({
              fragments: initialBundle.fragments,
              variables: initialBundle.initialVariables,
              mutations: initialBundle.mutations
            });
          }

          // Set initial state
          this.state = {
            loading: hasDataToFetch,
            error: false
          };
        } else {
          this.state = {
            loading: false,
            error: false
          };
        }
      }

      shouldComponentUpdate (nextProps, nextState) {
        return (
          !this.state.loading ||
          this.state.loading && !nextState.loading ||
          this.state.error !== nextState.error
        );
      }

      componentWillUnmount () {
        this.context.store.dispatch(removeConnector(this.props.CONNECTOR_ID));
      }

      setVariables (variables) {
        const bundle = getBundle && getBundle(this.props);
        this.relate.variables = variables;

        // Fetch data
        if (bundle) {
          this.setState({
            loading: true
          }, () => {
            this.fetchData({
              fragments: bundle.fragments,
              variables,
              mutations: bundle.mutations
            });
          });
        }
      }

      loadMore (variables, loadMore, expected) {
        const bundle = getBundle && getBundle(this.props);
        this.relate.variables = variables;

        // Fetch data
        if (bundle) {
          this.setState({
            loading: true,
            loadingMore: true,
            loadingMoreProperty: loadMore,
            loadingMoreExpects: expected
          }, () => {
            this.fetchData({
              fragments: bundle.fragments,
              variables,
              mutations: bundle.mutations,
              loadMore
            });
          });
        }
      }

      refresh (props = this.props) {
        const bundle = getBundle && getBundle(props);

        // Fetch data
        if (bundle) {
          this.setState({
            loading: true
          }, () => {
            this.fetchData({
              fragments: bundle.fragments,
              variables: bundle.initialVariables,
              mutations: bundle.mutations
            });
          });
        }
      }

      hasDataToFetch (fragments) {
        return typeof fragments === 'object' && Object.keys(fragments).length > 0;
      }

      fetchData ({fragments, variables, mutations, loadMore = false}) {
        const {fetchData} = this.context;

        if (fetchData && this.hasDataToFetch(fragments)) {
          const fetchOptions = {
            fragments,
            variables: getVariables({
              variables,
              variablesTypes: this.variablesTypes,
              fragments,
              displayName: typeof WrappedComponent !== 'undefined' && WrappedComponent.displayName
            }),
            ID: this.props.CONNECTOR_ID,
            mutations,
            loadMore
          };
          if (this.context.relate_ssr) {
            fetchData(fetchOptions);
          } else {
            fetchData(fetchOptions)
              .then((data) => {
                const {loadingMore, loadingMoreExpects, loadingMoreProperty} = this.state;
                let hasMore = true;

                if (loadingMore && loadingMoreExpects && data[loadingMoreProperty]) {
                  hasMore = data[loadingMoreProperty].length >= loadingMoreExpects;
                }

                this.relate.hasMore = hasMore;

                this.setState({
                  loading: false,
                  loadingMore: false,
                  error: false,
                  loadingMoreProperty: null,
                  loadingMoreExpects: null
                });
              })
              .catch(() => {
                this.setState({
                  loading: false,
                  loadingMore: false,
                  error: true,
                  loadingMoreProperty: null,
                  loadingMoreExpects: null
                });
              });
          }
        } else {
          if (!this.context.relate_ssr) {
            this.setState({
              loading: false,
              loadingMore: false,
              error: false,
              loadingMoreProperty: null,
              loadingMoreExpects: null
            });
          }
        }
      }

      render () {
        const {relateConnectorData, ...otherProps} = this.props;
        const {loading, loadingMore} = this.state;
        return (
          <WrappedComponent
            {...otherProps}
            {...relateConnectorData}
            relate={this.relate}
            loading={loading && !loadingMore}
            loadingMore={loadingMore}
          />
        );
      }
    }

    const Connected = connect(
      () => function map (state, props) {
        if (!this.CONNECTOR_ID) {
          if (state.relateReducer.server) {
            const finalProps = Object.assign({}, props, getReduxState && getReduxState(state, props));
            const initialBundle = getBundle(finalProps);
            const thisCompare = {
              fragments: initialBundle.fragments,
              variables: getVariables({
                variables: initialBundle.initialVariables,
                variablesTypes: initialBundle.variablesTypes,
                fragments: initialBundle.fragments
              })
            };

            forEach(state.relateReducer.server, (compare, id) => {
              if (isEqual(compare, thisCompare)) {
                this.CONNECTOR_ID = id;
                return false;
              }
              return true;
            });

            if (!this.CONNECTOR_ID) {
              this.CONNECTOR_ID = generateConnectorId();
            }
          } else {
            this.CONNECTOR_ID = generateConnectorId();
          }
        }

        return Object.assign(
          getReduxState && getReduxState(state, props) || {},
          {
            relateConnectorData: state.relateReducer[this.CONNECTOR_ID],
            CONNECTOR_ID: this.CONNECTOR_ID
          }
        );
      },
      (dispatch) => Object.assign(
        getReduxDispatches && getReduxDispatches(dispatch) || {},
        {
          removeConnector: dispatch(removeConnector)
        }
      )
    )(ConnectData);

    return hoistStatics(Connected, WrappedComponent, {
      relateIdentifier: true
    });
  };
}
<commit_msg>calculate bundle on set variables and load more<commit_after>import forEach from 'lodash.foreach';
import hoistStatics from 'hoist-non-react-statics';
import invariant from 'invariant';
import isEqual from 'lodash.isequal';
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';

import getVariables from '../helpers/get-variables';
import removeConnector from '../actions/remove-connector';
import {generateConnectorId} from '../helpers/connectors-ids';

// getBundle is a function which receives the component props
// and retrieves a configuration set by the user
// e.g
// (props) => ({
//   fragments: {
//     pages: {
//       _id: 1,
//       title: 1
//     },
//     page: {
//       _id: 1,
//       title: 1,
//       user: {
//         _id: 1,
//         username: 1
//       }
//     }
//   },
//   variablesTypes: {
//     pages: {
//       order: 'String!',
//       sort: 'String!'
//     }
//   },
//   initialVariables: {
//     pages: {
//       order: 'asc',
//       sort: 'date'
//     }
//   },
//   mutations: {
//     addPage: [
//       {
//         type: 'APPEND', // INCREMENT || DECREMENT || APPEND || PREPEND
//         field: 'pages'
//       },
//       {
//         type: 'INCREMENT',
//         field: 'pagesCount'
//       },
//       {
//         type: 'INCREMENT',
//         field: ['pages', 'pagesCount']
//       }
//     ]
//   }
// })
export default function dataConnect (...args) {
  invariant(args.length, 'Relate: a dataConnect does not have arguments specified');

  const getReduxState = args.length > 1 && args[0];
  const getReduxDispatches = args.length > 2 && args[1];
  const getBundle = args[args.length - 1];

  return function wrapWithDataConnect (WrappedComponent) {
    class ConnectData extends Component {
      static propTypes = {
        relateConnectorData: PropTypes.object,
        CONNECTOR_ID: PropTypes.string.isRequired
      };

      static contextTypes = {
        fetchData: PropTypes.func.isRequired,
        store: PropTypes.any.isRequired,
        relate_ssr: PropTypes.func
      };

      static defaultProps = {
        relateConnectorData: {}
      };

      static relateIdentifier = 'DATA_CONNECT';

      constructor (props, context) {
        super(props, context);

        // Relate connector info
        this.relate = {
          setVariables: ::this.setVariables,
          refresh: ::this.refresh,
          loadMore: ::this.loadMore,
          variables: {},
          hasMore: true
        };

        // get bundle
        const initialBundle = this.processBundle(this.props);

        if (!props.relateConnectorData || Object.keys(props.relateConnectorData).length === 0) {
          // Fetch data
          const hasDataToFetch = initialBundle && this.hasDataToFetch(initialBundle.fragments) && true;
          if (hasDataToFetch) {
            this.fetchData({
              fragments: initialBundle.fragments,
              variables: initialBundle.initialVariables,
              mutations: initialBundle.mutations
            });
          }

          // Set initial state
          this.state = {
            loading: hasDataToFetch,
            error: false
          };
        } else {
          this.state = {
            loading: false,
            error: false
          };
        }
      }

      shouldComponentUpdate (nextProps, nextState) {
        return (
          !this.state.loading ||
          this.state.loading && !nextState.loading ||
          this.state.error !== nextState.error
        );
      }

      componentWillUnmount () {
        this.context.store.dispatch(removeConnector(this.props.CONNECTOR_ID));
      }

      setVariables (variables) {
        const bundle = this.processBundle(this.props, variables);

        // Fetch data
        if (bundle) {
          this.setState({
            loading: true
          }, () => {
            this.fetchData({
              fragments: bundle.fragments,
              variables,
              mutations: bundle.mutations
            });
          });
        }
      }

      processBundle (props, variables) {
        const bundle = getBundle && getBundle(this.props);

        this.variablesTypes = bundle && bundle.variablesTypes || {};
        this.relate.variables = variables || bundle && bundle.initialVariables || {};

        return bundle;
      }

      loadMore (variables, loadMore, expected) {
        const bundle = this.processBundle(this.props, variables);

        // Fetch data
        if (bundle) {
          this.setState({
            loading: true,
            loadingMore: true,
            loadingMoreProperty: loadMore,
            loadingMoreExpects: expected
          }, () => {
            this.fetchData({
              fragments: bundle.fragments,
              variables,
              mutations: bundle.mutations,
              loadMore
            });
          });
        }
      }

      refresh (props = this.props) {
        const bundle = this.processBundle(props);

        // Fetch data
        if (bundle) {
          this.setState({
            loading: true
          }, () => {
            this.fetchData({
              fragments: bundle.fragments,
              variables: bundle.initialVariables,
              mutations: bundle.mutations
            });
          });
        }
      }

      hasDataToFetch (fragments) {
        return typeof fragments === 'object' && Object.keys(fragments).length > 0;
      }

      fetchData ({fragments, variables, mutations, loadMore = false}) {
        const {fetchData} = this.context;

        if (fetchData && this.hasDataToFetch(fragments)) {
          const fetchOptions = {
            fragments,
            variables: getVariables({
              variables,
              variablesTypes: this.variablesTypes,
              fragments,
              displayName: typeof WrappedComponent !== 'undefined' && WrappedComponent.displayName
            }),
            ID: this.props.CONNECTOR_ID,
            mutations,
            loadMore
          };
          if (this.context.relate_ssr) {
            fetchData(fetchOptions);
          } else {
            fetchData(fetchOptions)
              .then((data) => {
                const {loadingMore, loadingMoreExpects, loadingMoreProperty} = this.state;
                let hasMore = true;

                if (loadingMore && loadingMoreExpects && data[loadingMoreProperty]) {
                  hasMore = data[loadingMoreProperty].length >= loadingMoreExpects;
                }

                this.relate.hasMore = hasMore;

                this.setState({
                  loading: false,
                  loadingMore: false,
                  error: false,
                  loadingMoreProperty: null,
                  loadingMoreExpects: null
                });
              })
              .catch(() => {
                this.setState({
                  loading: false,
                  loadingMore: false,
                  error: true,
                  loadingMoreProperty: null,
                  loadingMoreExpects: null
                });
              });
          }
        } else {
          if (!this.context.relate_ssr) {
            this.setState({
              loading: false,
              loadingMore: false,
              error: false,
              loadingMoreProperty: null,
              loadingMoreExpects: null
            });
          }
        }
      }

      render () {
        const {relateConnectorData, ...otherProps} = this.props;
        const {loading, loadingMore} = this.state;
        return (
          <WrappedComponent
            {...otherProps}
            {...relateConnectorData}
            relate={this.relate}
            loading={loading && !loadingMore}
            loadingMore={loadingMore}
          />
        );
      }
    }

    const Connected = connect(
      () => function map (state, props) {
        if (!this.CONNECTOR_ID) {
          if (state.relateReducer.server) {
            const finalProps = Object.assign({}, props, getReduxState && getReduxState(state, props));
            const initialBundle = getBundle(finalProps);
            const thisCompare = {
              fragments: initialBundle.fragments,
              variables: getVariables({
                variables: initialBundle.initialVariables,
                variablesTypes: initialBundle.variablesTypes,
                fragments: initialBundle.fragments
              })
            };

            forEach(state.relateReducer.server, (compare, id) => {
              if (isEqual(compare, thisCompare)) {
                this.CONNECTOR_ID = id;
                return false;
              }
              return true;
            });

            if (!this.CONNECTOR_ID) {
              this.CONNECTOR_ID = generateConnectorId();
            }
          } else {
            this.CONNECTOR_ID = generateConnectorId();
          }
        }

        return Object.assign(
          getReduxState && getReduxState(state, props) || {},
          {
            relateConnectorData: state.relateReducer[this.CONNECTOR_ID],
            CONNECTOR_ID: this.CONNECTOR_ID
          }
        );
      },
      (dispatch) => Object.assign(
        getReduxDispatches && getReduxDispatches(dispatch) || {},
        {
          removeConnector: dispatch(removeConnector)
        }
      )
    )(ConnectData);

    return hoistStatics(Connected, WrappedComponent, {
      relateIdentifier: true
    });
  };
}
<|endoftext|>


<commit_before>const {htmlTransform, jsTransform} = require('polymer-build');
const {getRequestFilePath} = require('@web/dev-server-core');
const {browserCapabilities} = require('browser-capabilities');
const {getCompileTarget} = require('polyserve/lib/get-compile-target.js');

exports.compileJSPlugin = () => {
  let rootDir = undefined;

  return {
    name: 'compile-js-plugin',

    async serverStart(args) {
      rootDir = args.config.rootDir;
    },

    // `@web/test-runner` reuses the same server across multiple browser
    // launchers (e.g. when we test on Sauce Labs). This cache key determines if
    // the result of `transform()` below can be reused for later requests to the
    // same path. Without it, all `transform()` results are permanently cached,
    // which is a problem when different browsers require different transforms.
    async transformCacheKey(context) {
      if (context.path.includes(`/node_modules/@webcomponents/`)) {
        return;
      }

      const capabilities = browserCapabilities(context.headers['user-agent']);
      const compileTarget = getCompileTarget(capabilities, 'auto');

      return JSON.stringify({
        compile: compileTarget,
        transformModulesToAmd: !capabilities.has('modules'),
        filePath: getRequestFilePath(context, rootDir),
      });
    },

    async transform(context) {
      if (context.path.includes(`/node_modules/@webcomponents/`)) {
        return;
      }

      const capabilities = browserCapabilities(context.headers['user-agent']);
      const compileTarget = getCompileTarget(capabilities, 'auto');

      const jsOptions = {
        compile: compileTarget,
        moduleResolution: 'node',
        transformModulesToAmd: !capabilities.has('modules'),
        filePath: getRequestFilePath(context, rootDir),
      };
      const htmlOptions = {
        js: jsOptions,
        injectAmdLoader: jsOptions.transformModulesToAmd,
      };

      if (context.response.is('html')) {
        context.body = htmlTransform(context.body, htmlOptions);
      } else if (context.response.is('js')) {
        context.body = jsTransform(context.body, jsOptions);
      }
    },
  };
};
<commit_msg>Extract a function that generates the options for `polymer-build`'s transforms.<commit_after>const {htmlTransform, jsTransform} = require('polymer-build');
const {getRequestFilePath} = require('@web/dev-server-core');
const {browserCapabilities} = require('browser-capabilities');
const {getCompileTarget} = require('polyserve/lib/get-compile-target.js');

/**
 * This `@web/dev-server` plugin is used to roughly mimic the automatic JS
 * compilation behavior of WCT's test server (`polyserve`) as is assumed by many
 * of the tests.
 */
exports.compileJSPlugin = () => {
  let rootDir = undefined;

  /**
   * Compute the settings that should be passed to `polymer-build`'s
   * `htmlTransform` given a Koa `Context`.[^1] (The options for `jsTransform`
   * are embedded as the `js` property.)
   *
   * [^1]: https://github.com/modernweb-dev/web/blob/3f671e732201f141d910b59c60666f31df9c6126/packages/dev-server-core/src/plugins/Plugin.ts#L35
   */
  const getHTMLTransformOptions = (context) => {
    const capabilities = browserCapabilities(context.headers['user-agent']);
    const compileTarget = getCompileTarget(capabilities, 'auto');

    const jsOptions = {
      compile: compileTarget,
      moduleResolution: 'node',
      transformModulesToAmd: !capabilities.has('modules'),
      filePath: getRequestFilePath(context, rootDir),
    };
    const htmlOptions = {
      js: jsOptions,
      injectAmdLoader: jsOptions.transformModulesToAmd,
    };

    return htmlOptions;
  };

  return {
    name: 'compile-js-plugin',

    async serverStart(args) {
      rootDir = args.config.rootDir;
    },

    // `@web/test-runner` reuses the same server across multiple browser
    // launchers (e.g. when we test on Sauce Labs). This cache key determines if
    // the result of `transform()` below can be reused for later requests to the
    // same path. Without it, all `transform()` results are permanently cached,
    // which is a problem when different browsers require different transforms.
    async transformCacheKey(context) {
      if (context.path.includes(`/node_modules/@webcomponents/`)) {
        return;
      }

      return JSON.stringify(getHTMLTransformOptions(context));
    },

    async transform(context) {
      if (context.path.includes(`/node_modules/@webcomponents/`)) {
        return;
      }

      const htmlOptions = getHTMLTransformOptions(context);
      const jsOptions = htmlOptions.js;

      if (context.response.is('html')) {
        context.body = htmlTransform(context.body, htmlOptions);
      } else if (context.response.is('js')) {
        context.body = jsTransform(context.body, jsOptions);
      }
    },
  };
};
<|endoftext|>


<commit_before>'use strict';

var Utils = require('../../utils')
  , AbstractQuery = require('../abstract/query')
  , DataTypes = require('../../data-types')
  , hstore = require('./hstore')
  , QueryTypes = require('../../query-types')
  , Promise = require('../../promise')
  , sequelizeErrors = require('../../errors.js');

// Parses hstore fields if the model has any hstore fields.
// This cannot be done in the 'pg' lib because hstore is a UDT.
var parseHstoreFields = function(model, row) {
  Utils._.forEach(row, function(value, key) {
    if(value === null) return row[key] = null;

    if (model._isHstoreAttribute(key)) {
      row[key] = hstore.parse(value);
    }else if(model.attributes[key] && model.attributes[key].type === DataTypes.ARRAY(DataTypes.HSTORE)) {
      var array = JSON.parse('[' + value.slice(1).slice(0,-1) + ']');
      row[key] = Utils._.map(array, function(v){return hstore.parse(v);});
    }else{
      row[key] = value;
    }
  });
};

module.exports = (function() {
  var Query = function(client, sequelize, callee, options) {
    this.client = client;
    this.sequelize = sequelize;
    this.callee = callee;
    this.options = Utils._.extend({
      logging: console.log,
      plain: false,
      raw: false
    }, options || {});

    this.checkLoggingOption();
  };
  Utils.inherit(Query, AbstractQuery);

  Query.prototype.run = function(sql) {
    /* jshint -W027 */
    this.sql = sql;

    var self = this
      , receivedError = false
      , query = this.client.query(sql)
      , rows = [];

    this.sequelize.log('Executing (' + (this.client.uuid || 'default') + '): ' + this.sql, this.options);

    var promise = new Promise(function(resolve, reject) {
      query.on('row', function(row) {
        rows.push(row);
      });

      query.on('error', function(err) {
        receivedError = true;
        err.sql = sql;
        promise.emit('sql', sql, self.client.uuid);
        reject(self.formatError(err));
      });

      query.on('end', function(result) {
        if (receivedError) {
          return;
        }

        promise.emit('sql', self.sql, self.client.uuid);
        resolve([rows, sql, result]);
      });
    }).spread(function(rows, sql, result) {
      var results = rows
        , isTableNameQuery = (sql.indexOf('SELECT table_name FROM information_schema.tables') === 0)
        , isRelNameQuery = (sql.indexOf('SELECT relname FROM pg_class WHERE oid IN') === 0);

      if (isTableNameQuery || isRelNameQuery) {
        if (isRelNameQuery) {
          results = rows.map(function(row) {
            return {
              name: row.relname,
              tableName: row.relname.split('_')[0]
            };
          });
        } else {
          results = rows.map(function(row) { return Utils._.values(row); });
        }
        return results;
      }

      if (rows[0] && rows[0].sequelize_caught_exception) {
        throw new self.formatError({
          code: '23505',
          detail: rows[0].sequelize_caught_exception
        });
      }

      if (self.isShowIndexesQuery()) {
        results.forEach(function (result) {
          var attributes = /ON .*? (?:USING .*?\s)?\((.*)\)/gi.exec(result.definition)[1].split(',')
            , field
            , attribute
            , columns;

          // Map column index in table to column name
          columns = Utils._.zipObject(
            result.column_indexes,
            self.sequelize.queryInterface.QueryGenerator.fromArray(result.column_names)
          );
          delete result.column_indexes;
          delete result.column_names;

          // Indkey is the order of attributes in the index, specified by a string of attribute indexes
          result.fields = result.indkey.split(' ').map(function (indKey, index) {
            field = columns[indKey];
            attribute = attributes[index];
            return {
              attribute: field,
              collate: attribute.match(/COLLATE "(.*?)"/) ? /COLLATE "(.*?)"/.exec(attribute)[1] : undefined,
              order: attribute.indexOf('DESC') !== -1 ? 'DESC' : attribute.indexOf('ASC') !== -1 ? 'ASC': undefined,
              length: undefined,
            };
          });
          delete result.columns;
        });
        return results;
      } else if (self.isForeignKeysQuery()) {
        result = [];
        rows.forEach(function(row) {
          var defParts;
          if (row.condef !== undefined && (defParts = row.condef.match(/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)( ON (UPDATE|DELETE) (CASCADE|RESTRICT))?( ON (UPDATE|DELETE) (CASCADE|RESTRICT))?/))) {
            row.id = row.constraint_name;
            row.table = defParts[2];
            row.from = defParts[1];
            row.to = defParts[3];
            var i;
            for (i=5;i<=8;i+=3) {
              if (/(UPDATE|DELETE)/.test(defParts[i])) {
                row['on_'+defParts[i].toLowerCase()] = defParts[i+1];
              }
            }
          }
          result.push(row);
        });
        return result;
      } else if (self.isSelectQuery()) {
        if (self.sql.toLowerCase().indexOf('select c.column_name') === 0) {
          result = {};

          rows.forEach(function(_result) {
            result[_result.Field] = {
              type: _result.Type.toUpperCase(),
              allowNull: (_result.Null === 'YES'),
              defaultValue: _result.Default,
              special: (!!_result.special ? self.sequelize.queryInterface.QueryGenerator.fromArray(_result.special) : [])
            };

            if (result[_result.Field].type === 'BOOLEAN') {
              result[_result.Field].defaultValue = { 'false': false, 'true': true }[result[_result.Field].defaultValue];

              if (result[_result.Field].defaultValue === undefined) {
                result[_result.Field].defaultValue = null;
              }
            }

            if (typeof result[_result.Field].defaultValue === 'string') {
              result[_result.Field].defaultValue = result[_result.Field].defaultValue.replace(/'/g, '');

              if (result[_result.Field].defaultValue.indexOf('::') > -1) {
                var split = result[_result.Field].defaultValue.split('::');
                if (split[1].toLowerCase() !== 'regclass)') {
                  result[_result.Field].defaultValue = split[0];
                }
              }
            }
          });

          return result;
        } else {
          // Postgres will treat tables as case-insensitive, so fix the case
          // of the returned values to match attributes
          if (self.options.raw === false && self.sequelize.options.quoteIdentifiers === false) {
            var attrsMap = Utils._.reduce(self.callee.attributes, function(m, v, k) { m[k.toLowerCase()] = k; return m; }, {});
            rows.forEach(function(row) {
              Utils._.keys(row).forEach(function(key) {
                var targetAttr = attrsMap[key];
                if (targetAttr !== key) {
                  row[targetAttr] = row[key];
                  delete row[key];
                }
              });
            });
          }

          if (!!self.callee && !!self.callee._hasHstoreAttributes) {
            rows.forEach(function(row) {
              parseHstoreFields(self.callee, row);
            });
          }

          return self.handleSelectQuery(rows);
        }
      } else if (self.isShowOrDescribeQuery()) {
        return results;
      } else if (QueryTypes.BULKUPDATE === self.options.type) {
        if (!self.options.returning) {
          return result.rowCount;
        }

        if (!!self.callee && !!self.callee._hasHstoreAttributes) {
          rows.forEach(function(row) {
            parseHstoreFields(self.callee, row);
          });
        }

        return self.handleSelectQuery(rows);
      } else if (QueryTypes.BULKDELETE === self.options.type) {
        return result.rowCount;
      } else if (self.isUpsertQuery()) {
        return rows[0].sequelize_upsert;
      } else if (self.isInsertQuery() || self.isUpdateQuery()) {
        if (!!self.callee && self.callee.dataValues) {
          if (!!self.callee.Model && !!self.callee.Model._hasHstoreAttributes) {
            parseHstoreFields(self.callee.Model, rows[0]);
          }

          for (var key in rows[0]) {
            if (rows[0].hasOwnProperty(key)) {
              var record = rows[0][key];

              var attr = Utils._.find(self.callee.Model.rawAttributes, function (attribute) {
                return attribute.fieldName === key || attribute.field === key;
              });

              self.callee.dataValues[attr && attr.fieldName || key] = record;
            }
          }
        }

        return self.callee || (rows && ((self.options.plain && rows[0]) || rows)) || undefined;
      } else if (self.isVersionQuery()) {
        return results[0].version;
      } else {
        return results;
      }
    });

    return promise;
  };

  Query.prototype.formatError = function (err) {
    var match
      , table
      , index;

    var code = err.code || err.sqlState
      , errMessage = err.message || err.messagePrimary
      , errDetail = err.detail || err.messageDetail;

    switch (code) {
      case '23503':
        index = errMessage.match(/violates foreign key constraint \"(.+?)\"/)[1];
        table = errMessage.match(/on table \"(.+?)\"/)[1];

        return new sequelizeErrors.ForeignKeyConstraintError({
          fields: null,
          index: index,
          table: table,
          parent: err
        });
      case '23505':
        // there are multiple different formats of error messages for this error code
        // this regex should check at least two
        match = errDetail.match(/Key \((.*?)\)=\((.*?)\)/);

        if (match) {
          var fields = Utils._.zipObject(match[1].split(', '), match[2].split(', '))
            , errors = []
            , message = 'Validation error';

          Utils._.forOwn(fields, function(value, field) {
            errors.push(new sequelizeErrors.ValidationErrorItem(
              field + ' must be unique', 'unique violation', field, value));
          });

          if (this.callee && this.callee.__options && this.callee.__options.uniqueKeys) {
            Utils._.forOwn(this.callee.__options.uniqueKeys, function(constraint) {
              if (Utils._.isEqual(constraint.fields, Object.keys(fields)) && !!constraint.msg) {
                message = constraint.msg;
                return false;
              }
            });
          }

          return new sequelizeErrors.UniqueConstraintError({
            message: message,
            errors: errors,
            parent: err,
            fields: fields
          });
        } else {
          return new sequelizeErrors.UniqueConstraintError({
            message: errMessage,
            parent: err
          });
        }

        break;
      default:
        return new sequelizeErrors.DatabaseError(err);
    }
  };

  Query.prototype.isForeignKeysQuery = function() {
    return /SELECT conname as constraint_name, pg_catalog\.pg_get_constraintdef\(r\.oid, true\) as condef FROM pg_catalog\.pg_constraint r WHERE r\.conrelid = \(SELECT oid FROM pg_class WHERE relname = '.*' LIMIT 1\) AND r\.contype = 'f' ORDER BY 1;/.test(this.sql);
  };

  Query.prototype.getInsertIdField = function() {
    return 'id';
  };

  return Query;
})();
<commit_msg>Update `rowCount` to always return an integer<commit_after>'use strict';

var Utils = require('../../utils')
  , AbstractQuery = require('../abstract/query')
  , DataTypes = require('../../data-types')
  , hstore = require('./hstore')
  , QueryTypes = require('../../query-types')
  , Promise = require('../../promise')
  , sequelizeErrors = require('../../errors.js');

// Parses hstore fields if the model has any hstore fields.
// This cannot be done in the 'pg' lib because hstore is a UDT.
var parseHstoreFields = function(model, row) {
  Utils._.forEach(row, function(value, key) {
    if(value === null) return row[key] = null;

    if (model._isHstoreAttribute(key)) {
      row[key] = hstore.parse(value);
    }else if(model.attributes[key] && model.attributes[key].type === DataTypes.ARRAY(DataTypes.HSTORE)) {
      var array = JSON.parse('[' + value.slice(1).slice(0,-1) + ']');
      row[key] = Utils._.map(array, function(v){return hstore.parse(v);});
    }else{
      row[key] = value;
    }
  });
};

module.exports = (function() {
  var Query = function(client, sequelize, callee, options) {
    this.client = client;
    this.sequelize = sequelize;
    this.callee = callee;
    this.options = Utils._.extend({
      logging: console.log,
      plain: false,
      raw: false
    }, options || {});

    this.checkLoggingOption();
  };
  Utils.inherit(Query, AbstractQuery);

  Query.prototype.run = function(sql) {
    /* jshint -W027 */
    this.sql = sql;

    var self = this
      , receivedError = false
      , query = this.client.query(sql)
      , rows = [];

    this.sequelize.log('Executing (' + (this.client.uuid || 'default') + '): ' + this.sql, this.options);

    var promise = new Promise(function(resolve, reject) {
      query.on('row', function(row) {
        rows.push(row);
      });

      query.on('error', function(err) {
        receivedError = true;
        err.sql = sql;
        promise.emit('sql', sql, self.client.uuid);
        reject(self.formatError(err));
      });

      query.on('end', function(result) {
        if (receivedError) {
          return;
        }

        promise.emit('sql', self.sql, self.client.uuid);
        resolve([rows, sql, result]);
      });
    }).spread(function(rows, sql, result) {
      var results = rows
        , isTableNameQuery = (sql.indexOf('SELECT table_name FROM information_schema.tables') === 0)
        , isRelNameQuery = (sql.indexOf('SELECT relname FROM pg_class WHERE oid IN') === 0);

      if (isTableNameQuery || isRelNameQuery) {
        if (isRelNameQuery) {
          results = rows.map(function(row) {
            return {
              name: row.relname,
              tableName: row.relname.split('_')[0]
            };
          });
        } else {
          results = rows.map(function(row) { return Utils._.values(row); });
        }
        return results;
      }

      if (rows[0] && rows[0].sequelize_caught_exception) {
        throw new self.formatError({
          code: '23505',
          detail: rows[0].sequelize_caught_exception
        });
      }

      if (self.isShowIndexesQuery()) {
        results.forEach(function (result) {
          var attributes = /ON .*? (?:USING .*?\s)?\((.*)\)/gi.exec(result.definition)[1].split(',')
            , field
            , attribute
            , columns;

          // Map column index in table to column name
          columns = Utils._.zipObject(
            result.column_indexes,
            self.sequelize.queryInterface.QueryGenerator.fromArray(result.column_names)
          );
          delete result.column_indexes;
          delete result.column_names;

          // Indkey is the order of attributes in the index, specified by a string of attribute indexes
          result.fields = result.indkey.split(' ').map(function (indKey, index) {
            field = columns[indKey];
            attribute = attributes[index];
            return {
              attribute: field,
              collate: attribute.match(/COLLATE "(.*?)"/) ? /COLLATE "(.*?)"/.exec(attribute)[1] : undefined,
              order: attribute.indexOf('DESC') !== -1 ? 'DESC' : attribute.indexOf('ASC') !== -1 ? 'ASC': undefined,
              length: undefined,
            };
          });
          delete result.columns;
        });
        return results;
      } else if (self.isForeignKeysQuery()) {
        result = [];
        rows.forEach(function(row) {
          var defParts;
          if (row.condef !== undefined && (defParts = row.condef.match(/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)( ON (UPDATE|DELETE) (CASCADE|RESTRICT))?( ON (UPDATE|DELETE) (CASCADE|RESTRICT))?/))) {
            row.id = row.constraint_name;
            row.table = defParts[2];
            row.from = defParts[1];
            row.to = defParts[3];
            var i;
            for (i=5;i<=8;i+=3) {
              if (/(UPDATE|DELETE)/.test(defParts[i])) {
                row['on_'+defParts[i].toLowerCase()] = defParts[i+1];
              }
            }
          }
          result.push(row);
        });
        return result;
      } else if (self.isSelectQuery()) {
        if (self.sql.toLowerCase().indexOf('select c.column_name') === 0) {
          result = {};

          rows.forEach(function(_result) {
            result[_result.Field] = {
              type: _result.Type.toUpperCase(),
              allowNull: (_result.Null === 'YES'),
              defaultValue: _result.Default,
              special: (!!_result.special ? self.sequelize.queryInterface.QueryGenerator.fromArray(_result.special) : [])
            };

            if (result[_result.Field].type === 'BOOLEAN') {
              result[_result.Field].defaultValue = { 'false': false, 'true': true }[result[_result.Field].defaultValue];

              if (result[_result.Field].defaultValue === undefined) {
                result[_result.Field].defaultValue = null;
              }
            }

            if (typeof result[_result.Field].defaultValue === 'string') {
              result[_result.Field].defaultValue = result[_result.Field].defaultValue.replace(/'/g, '');

              if (result[_result.Field].defaultValue.indexOf('::') > -1) {
                var split = result[_result.Field].defaultValue.split('::');
                if (split[1].toLowerCase() !== 'regclass)') {
                  result[_result.Field].defaultValue = split[0];
                }
              }
            }
          });

          return result;
        } else {
          // Postgres will treat tables as case-insensitive, so fix the case
          // of the returned values to match attributes
          if (self.options.raw === false && self.sequelize.options.quoteIdentifiers === false) {
            var attrsMap = Utils._.reduce(self.callee.attributes, function(m, v, k) { m[k.toLowerCase()] = k; return m; }, {});
            rows.forEach(function(row) {
              Utils._.keys(row).forEach(function(key) {
                var targetAttr = attrsMap[key];
                if (targetAttr !== key) {
                  row[targetAttr] = row[key];
                  delete row[key];
                }
              });
            });
          }

          if (!!self.callee && !!self.callee._hasHstoreAttributes) {
            rows.forEach(function(row) {
              parseHstoreFields(self.callee, row);
            });
          }

          return self.handleSelectQuery(rows);
        }
      } else if (self.isShowOrDescribeQuery()) {
        return results;
      } else if (QueryTypes.BULKUPDATE === self.options.type) {
        if (!self.options.returning) {
          return parseInt(result.rowCount, 10);
        }

        if (!!self.callee && !!self.callee._hasHstoreAttributes) {
          rows.forEach(function(row) {
            parseHstoreFields(self.callee, row);
          });
        }

        return self.handleSelectQuery(rows);
      } else if (QueryTypes.BULKDELETE === self.options.type) {
        return parseInt(result.rowCount, 10);
      } else if (self.isUpsertQuery()) {
        return rows[0].sequelize_upsert;
      } else if (self.isInsertQuery() || self.isUpdateQuery()) {
        if (!!self.callee && self.callee.dataValues) {
          if (!!self.callee.Model && !!self.callee.Model._hasHstoreAttributes) {
            parseHstoreFields(self.callee.Model, rows[0]);
          }

          for (var key in rows[0]) {
            if (rows[0].hasOwnProperty(key)) {
              var record = rows[0][key];

              var attr = Utils._.find(self.callee.Model.rawAttributes, function (attribute) {
                return attribute.fieldName === key || attribute.field === key;
              });

              self.callee.dataValues[attr && attr.fieldName || key] = record;
            }
          }
        }

        return self.callee || (rows && ((self.options.plain && rows[0]) || rows)) || undefined;
      } else if (self.isVersionQuery()) {
        return results[0].version;
      } else {
        return results;
      }
    });

    return promise;
  };

  Query.prototype.formatError = function (err) {
    var match
      , table
      , index;

    var code = err.code || err.sqlState
      , errMessage = err.message || err.messagePrimary
      , errDetail = err.detail || err.messageDetail;

    switch (code) {
      case '23503':
        index = errMessage.match(/violates foreign key constraint \"(.+?)\"/)[1];
        table = errMessage.match(/on table \"(.+?)\"/)[1];

        return new sequelizeErrors.ForeignKeyConstraintError({
          fields: null,
          index: index,
          table: table,
          parent: err
        });
      case '23505':
        // there are multiple different formats of error messages for this error code
        // this regex should check at least two
        match = errDetail.match(/Key \((.*?)\)=\((.*?)\)/);

        if (match) {
          var fields = Utils._.zipObject(match[1].split(', '), match[2].split(', '))
            , errors = []
            , message = 'Validation error';

          Utils._.forOwn(fields, function(value, field) {
            errors.push(new sequelizeErrors.ValidationErrorItem(
              field + ' must be unique', 'unique violation', field, value));
          });

          if (this.callee && this.callee.__options && this.callee.__options.uniqueKeys) {
            Utils._.forOwn(this.callee.__options.uniqueKeys, function(constraint) {
              if (Utils._.isEqual(constraint.fields, Object.keys(fields)) && !!constraint.msg) {
                message = constraint.msg;
                return false;
              }
            });
          }

          return new sequelizeErrors.UniqueConstraintError({
            message: message,
            errors: errors,
            parent: err,
            fields: fields
          });
        } else {
          return new sequelizeErrors.UniqueConstraintError({
            message: errMessage,
            parent: err
          });
        }

        break;
      default:
        return new sequelizeErrors.DatabaseError(err);
    }
  };

  Query.prototype.isForeignKeysQuery = function() {
    return /SELECT conname as constraint_name, pg_catalog\.pg_get_constraintdef\(r\.oid, true\) as condef FROM pg_catalog\.pg_constraint r WHERE r\.conrelid = \(SELECT oid FROM pg_class WHERE relname = '.*' LIMIT 1\) AND r\.contype = 'f' ORDER BY 1;/.test(this.sql);
  };

  Query.prototype.getInsertIdField = function() {
    return 'id';
  };

  return Query;
})();
<|endoftext|>