<commit_before>function GeneralDrawingTest(docTag)
{
	var canvas;
	var scene;
	var camera;

	var dragStartMousePos = {x:-1, y:-1};
	var dragStartCamPos = {x:-1, y:-1};
	var dragOffset = new Vector(0,0);
	var lastMousePos = {x:0, y:0}

	function setup()
	{
		var root = document.getElementById(docTag);

		canvas = document.createElement('canvas');
		canvas.width  = 1200;
		canvas.height = 700;
		canvas.style.border   = "2px solid black";//#99D9EA";
		canvas.style.marginLeft = "auto";
		canvas.style.marginRight = "auto";
		canvas.style.display = "block";
		canvas.addEventListener('mousemove', onMouseMove, false);
		canvas.addEventListener('mousedown', onMouseDown, false);
		canvas.addEventListener('wheel', onMouseWheel, false);

		root.appendChild(canvas);

		scene = new Scene();
		camera = new Camera(canvas);

		scene.addObject(new Grid(new Vector(0,0), 1));
		scene.addObject(new Wall(new Vector(-5,0), new Vector(5,0)));
	}

	function onMouseDown(evt)
	{
		lastMousePos = getMousePos(evt, canvas);

		dragStartMousePos.x = lastMousePos.x;
		dragStartMousePos.y = lastMousePos.y;
		dragStartCamPos.x = camera.getViewPosition().x;
		dragStartCamPos.y = camera.getViewPosition().y;
	}

	function onMouseUp(evt)
	{
	}

	function onMouseMove(evt)
	{
		lastMousePos = getMousePos(evt, canvas);

		if (evt.buttons & 1)
		{
			var delta = div(sub(lastMousePos, dragStartMousePos), new Vector(-camera.getUnitScale(), camera.getUnitScale()));
			var P = add(dragStartCamPos, delta);
			camera.setViewPosition(P.x, P.y);
		}

		draw();
	}

	function onMouseWheel(evt)
	{
		lastMousePos = camera.getMousePos(evt);

		var zoomCenter = lastMousePos;

		var zoomFactor = 1.0 + Math.sign(evt.deltaY) * 0.1;

		var minX = camera.getViewPosition().x - camera.getViewSize().x/2;
		var maxX = camera.getViewPosition().x + camera.getViewSize().x/2;
		var minY = camera.getViewPosition().y - camera.getViewSize().y/2;
		var maxY = camera.getViewPosition().y + camera.getViewSize().y/2;

		minX = zoomCenter.x - (zoomCenter.x - minX) * zoomFactor;
		maxX = zoomCenter.x + (maxX-zoomCenter.x) * zoomFactor;

		minY = zoomCenter.y - (zoomCenter.y - minY) * zoomFactor;
		maxY = zoomCenter.y + (maxY-zoomCenter.y) * zoomFactor;

		camera.setViewPosition((minX+maxX)/2, (minY+maxY)/2);
		camera.setUnitScale( camera.getUnitScale() / zoomFactor);
		draw();
	}

	function draw()
	{
		scene.draw(camera);
	}

	setup();
	draw();
}
<commit_msg>scrolling fixes<commit_after>function GeneralDrawingTest(docTag)
{
	var canvas;
	var scene;
	var camera;

	var dragStartMousePos = {x:-1, y:-1};
	var dragStartCamPos = {x:-1, y:-1};
	var dragOffset = new Vector(0,0);
	var lastMousePos = {x:0, y:0}

	function setup()
	{
		var root = document.getElementById(docTag);

		canvas = document.createElement('canvas');
		canvas.width  = 1200;
		canvas.height = 700;
		canvas.style.border   = "2px solid black";//#99D9EA";
		canvas.style.marginLeft = "auto";
		canvas.style.marginRight = "auto";
		canvas.style.display = "block";
		canvas.addEventListener('mousemove', onMouseMove, false);
		canvas.addEventListener('mousedown', onMouseDown, false);
		document.addEventListener('keydown', onKeyDown, false);
		canvas.onwheel = onMouseWheel;

		root.appendChild(canvas);

		scene = new Scene();
		camera = new Camera(canvas);

		scene.addObject(new Grid(new Vector(0,0), 1));
		scene.addObject(new Wall(new Vector(-5,0), new Vector(5,0)));
	}

	function onKeyDown(evt)
	{

	}

	function onMouseDown(evt)
	{
		lastMousePos = getMousePos(evt, canvas);

		dragStartMousePos.x = lastMousePos.x;
		dragStartMousePos.y = lastMousePos.y;
		dragStartCamPos.x = camera.getViewPosition().x;
		dragStartCamPos.y = camera.getViewPosition().y;
	}

	function onMouseUp(evt)
	{
	}

	function onMouseMove(evt)
	{
		lastMousePos = getMousePos(evt, canvas);

		if (evt.buttons & 1)
		{
			var delta = div(sub(lastMousePos, dragStartMousePos), new Vector(-camera.getUnitScale(), camera.getUnitScale()));
			var P = add(dragStartCamPos, delta);
			camera.setViewPosition(P.x, P.y);
		}

		draw();
	}

	function onMouseWheel(evt)
	{
		lastMousePos = camera.getMousePos(evt);

		var zoomCenter = lastMousePos;

		var zoomFactor = 1.0 + Math.sign(evt.deltaY) * 0.1;

		var minX = camera.getViewPosition().x - camera.getViewSize().x/2;
		var maxX = camera.getViewPosition().x + camera.getViewSize().x/2;
		var minY = camera.getViewPosition().y - camera.getViewSize().y/2;
		var maxY = camera.getViewPosition().y + camera.getViewSize().y/2;

		minX = zoomCenter.x - (zoomCenter.x - minX) * zoomFactor;
		maxX = zoomCenter.x + (maxX-zoomCenter.x) * zoomFactor;

		minY = zoomCenter.y - (zoomCenter.y - minY) * zoomFactor;
		maxY = zoomCenter.y + (maxY-zoomCenter.y) * zoomFactor;

		camera.setViewPosition((minX+maxX)/2, (minY+maxY)/2);
		camera.setUnitScale( camera.getUnitScale() / zoomFactor);
		draw();

		return false;
	}

	function draw()
	{
		scene.draw(camera);
	}

	setup();
	draw();
}
<|endoftext|>


<commit_before>var DIGDAG_CONFIG = {
  url: 'http://localhost:65432/api/',
  td: {
    useTD: false,
    apiV4: 'https://api-console.treasuredata.com/v4',
    connectorUrl: function (connectorName) { return 'https://console.treasuredata.com/connections/data-transfers' },
    queryUrl: function (queryId) { return 'https://console.treasuredata.com/queries/' + queryId },
    jobUrl: function (jobId) { return 'https://console.treasuredata.com/jobs/' + jobId }
  },
  logoutUrl: '/',
  navbar: {
    logo: '/logo.png',
    brand: 'Digdag',
    className: 'navbar-inverse',
    style: {
      backgroundColor: '#2B353F'
    }
  },
  auth: {
    title: 'Authentication',
    items: []
  },
  headers: function (args) {
    return {}
  }
}

window.DIGDAG_CONFIG = DIGDAG_CONFIG
<commit_msg>Update config.js<commit_after>var DIGDAG_CONFIG = {
  url: '/api/',
  td: {
    useTD: false,
    apiV4: 'https://api-console.treasuredata.com/v4',
    connectorUrl: function (connectorName) { return 'https://console.treasuredata.com/connections/data-transfers' },
    queryUrl: function (queryId) { return 'https://console.treasuredata.com/queries/' + queryId },
    jobUrl: function (jobId) { return 'https://console.treasuredata.com/jobs/' + jobId }
  },
  logoutUrl: '/',
  navbar: {
    logo: '/logo.png',
    brand: 'Digdag',
    className: 'navbar-inverse',
    style: {
      backgroundColor: '#2B353F'
    }
  },
  auth: {
    title: 'Authentication',
    items: []
  },
  headers: function (args) {
    return {}
  }
}

window.DIGDAG_CONFIG = DIGDAG_CONFIG
<|endoftext|>


<commit_before>'use strict'

/**
 * @class
 * @param {string} jsonType
 * @param {checkCallback} checkFn
 * @param {toJSONCallback|string} [toJSON]
 */
function Type(jsonType, checkFn, toJSON) {
	var types = ['number', 'string', 'boolean', 'object', 'array', '*', 'raw']

	if (typeof jsonType !== 'string') {
		throw new Error('jsType must be a string')
	} else if (types.indexOf(jsonType) === -1) {
		throw new Error('jsType must be one of: ' + types.join(', '))
	} else if (typeof checkFn !== 'function') {
		throw new Error('checkFn must be a function')
	}

	/** @member {string} */
	this.jsonType = jsonType

	/** @member {Function} */
	this.checkFn = checkFn

	/** @member {?(toJSONCallback|string)} */
	this._toJSON = toJSON
}

module.exports = Type

/**
 * Check if a given value has the right type
 * @param {*} value
 * @param {string} path
 * @param {*} extra
 * @param {Object} options
 * @returns {*} the validated value
 * @throws if invalid
 */
Type.prototype.validate = function (value, path, extra, options) {
	// Call toJSON() if present
	if (this.jsonType !== 'raw' &&
		value !== null &&
		value !== undefined &&
		typeof value.toJSON === 'function') {
		value = value.toJSON()
	}

	var type, ret
	if (Array.isArray(value)) {
		type = 'array'
	} else if (value === null) {
		type = 'null'
	} else if (Number.isNaN(value)) {
		type = 'NaN'
	} else if (value === Infinity || value === -Infinity) {
		type = 'infinity'
	} else {
		type = typeof value
	}
	if (this.jsonType !== '*' &&
		this.jsonType !== 'raw' &&
		this.jsonType !== type) {
		throw 'I was expecting ' + this.jsonType + ' and you gave me ' + type
	}
	ret = this.checkFn(value, extra, options, path)
	return ret === undefined ? value : ret
}

/**
 * @param {*} value
 * @returns {boolean} whether the given value is considered empty
 */
Type.prototype.isEmpty = function (value) {
	return value === undefined ||
		value === null ||
		(this.jsonType === 'string' && value === '')
}

// Lazy loaded require('./index').parse
var parse

/**
 * Function called when stringifying a Field instance
 * Only core types can be precisely stringified
 * Custom types are represented by their parent JSON-type
 * @param {*} extra
 * @returns {*}
 */
Type.prototype.convertToJSON = function (extra) {
	if (this._toJSON) {
		return typeof this._toJSON === 'function' ? this._toJSON(extra) : this._toJSON
	}

	// Lazy loading
	parse = parse || require('./index').parse

	// Aproximated convertion
	return {
		number: '$Number',
		string: '$String',
		boolean: '$Boolean',
		object: '$Object',
		array: '$Array',
		'*': '*',
		raw: '*'
	}[this.jsonType]
}<commit_msg>Remove dead code<commit_after>'use strict'

/**
 * @class
 * @param {string} jsonType
 * @param {checkCallback} checkFn
 * @param {toJSONCallback|string} [toJSON]
 */
function Type(jsonType, checkFn, toJSON) {
	var types = ['number', 'string', 'boolean', 'object', 'array', '*', 'raw']

	if (typeof jsonType !== 'string') {
		throw new Error('jsType must be a string')
	} else if (types.indexOf(jsonType) === -1) {
		throw new Error('jsType must be one of: ' + types.join(', '))
	} else if (typeof checkFn !== 'function') {
		throw new Error('checkFn must be a function')
	}

	/** @member {string} */
	this.jsonType = jsonType

	/** @member {Function} */
	this.checkFn = checkFn

	/** @member {?(toJSONCallback|string)} */
	this._toJSON = toJSON
}

module.exports = Type

/**
 * Check if a given value has the right type
 * @param {*} value
 * @param {string} path
 * @param {*} extra
 * @param {Object} options
 * @returns {*} the validated value
 * @throws if invalid
 */
Type.prototype.validate = function (value, path, extra, options) {
	// Call toJSON() if present
	if (this.jsonType !== 'raw' &&
		value !== null &&
		value !== undefined &&
		typeof value.toJSON === 'function') {
		value = value.toJSON()
	}

	var type, ret
	if (Array.isArray(value)) {
		type = 'array'
	} else if (value === null) {
		type = 'null'
	} else if (Number.isNaN(value)) {
		type = 'NaN'
	} else if (value === Infinity || value === -Infinity) {
		type = 'infinity'
	} else {
		type = typeof value
	}
	if (this.jsonType !== '*' &&
		this.jsonType !== 'raw' &&
		this.jsonType !== type) {
		throw 'I was expecting ' + this.jsonType + ' and you gave me ' + type
	}
	ret = this.checkFn(value, extra, options, path)
	return ret === undefined ? value : ret
}

/**
 * @param {*} value
 * @returns {boolean} whether the given value is considered empty
 */
Type.prototype.isEmpty = function (value) {
	return value === undefined ||
		value === null ||
		(this.jsonType === 'string' && value === '')
}

/**
 * Function called when stringifying a Field instance
 * Only core types can be precisely stringified
 * Custom types are represented by their parent JSON-type
 * @param {*} extra
 * @returns {*}
 */
Type.prototype.convertToJSON = function (extra) {
	if (this._toJSON) {
		return typeof this._toJSON === 'function' ? this._toJSON(extra) : this._toJSON
	}

	// Aproximated convertion
	return {
		number: '$Number',
		string: '$String',
		boolean: '$Boolean',
		object: '$Object',
		array: '$Array',
		'*': '*',
		raw: '*'
	}[this.jsonType]
}<|endoftext|>


<commit_before>

module.exports.uint8ToString = (array, start) => {
  var out, i, len, c;
  var char2, char3;

  out = "";
  len = array.length;
  i = start ? start : 0;
  while(i < len) {
    c = array[i++];
    switch(c >> 4)
    {
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
      // 0xxxxxxx
      out += String.fromCharCode(c);
      break;
      case 12: case 13:
      // 110x xxxx   10xx xxxx
      char2 = array[i++];
      out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
      break;
      case 14:
      // 1110 xxxx  10xx xxxx  10xx xxxx
      char2 = array[i++];
      char3 = array[i++];
      out += String.fromCharCode(((c & 0x0F) << 12) |
      ((char2 & 0x3F) << 6) |
      ((char3 & 0x3F) << 0));
      break;
    }
  }

  return out;
};

module.exports.stringToUint8 = (str) => {
  var arr = new Uint8Array(str.length), i = 0, len = str.length;
  for(; i < len; ++i){
    arr[i] = str.charCodeAt(i);
  }
  return arr;
};

module.exports.makePacket = (type, header, body) => {
  var bdata = null;

  if (body.constructor === Uint8Array) {
    bdata = body;
  } else {
    switch(typeof body) {
      case "string":
      bdata = module.exports.stringToUint8(body);
      break;
      default:
      bdata = module.exports.stringToUint8(JSON.stringify(body));
    }
  }

  var hdata = module.exports.stringToUint8(JSON.stringify(header));
  var msg = new Uint8Array(3 + hdata.length + bdata.length);

  msg[0] = type;
  msg[1] = hdata.length & 0xff;
  msg[2] = (hdata.length >> 0x8) && 0xff;
  msg.set(hdata, 3);
  msg.set(bdata, 3 + hdata.length);

  return msg;
};
<commit_msg>tojson<commit_after>

module.uint8ToJson = (arr) => {

  try {
    var str = module.exports.uint8ToString(arr);
    return JSON.parse(str);

  } catch (err) {
    console.log(err);
  }

  return null;
};

module.exports.uint8ToString = (array, start) => {
  var out, i, len, c;
  var char2, char3;

  out = "";
  len = array.length;
  i = start ? start : 0;
  while(i < len) {
    c = array[i++];
    switch(c >> 4)
    {
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
      // 0xxxxxxx
      out += String.fromCharCode(c);
      break;
      case 12: case 13:
      // 110x xxxx   10xx xxxx
      char2 = array[i++];
      out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
      break;
      case 14:
      // 1110 xxxx  10xx xxxx  10xx xxxx
      char2 = array[i++];
      char3 = array[i++];
      out += String.fromCharCode(((c & 0x0F) << 12) |
      ((char2 & 0x3F) << 6) |
      ((char3 & 0x3F) << 0));
      break;
    }
  }

  return out;
};

module.exports.stringToUint8 = (str) => {
  var arr = new Uint8Array(str.length), i = 0, len = str.length;
  for(; i < len; ++i){
    arr[i] = str.charCodeAt(i);
  }
  return arr;
};

module.exports.makePacket = (type, header, body) => {
  var bdata = null;

  if (body.constructor === Uint8Array) {
    bdata = body;
  } else {
    switch(typeof body) {
      case "string":
      bdata = module.exports.stringToUint8(body);
      break;
      default:
      bdata = module.exports.stringToUint8(JSON.stringify(body));
    }
  }

  var hdata = module.exports.stringToUint8(JSON.stringify(header));
  var msg = new Uint8Array(3 + hdata.length + bdata.length);

  msg[0] = type;
  msg[1] = hdata.length & 0xff;
  msg[2] = (hdata.length >> 0x8) && 0xff;
  msg.set(hdata, 3);
  msg.set(bdata, 3 + hdata.length);

  return msg;
};
<|endoftext|>


<commit_before>/*global ActiveXObject*/

/**
 * @fileOverview Ajax class / require js amd module.
 * @author NathanG
 * @version 0.0.1
 */

(function(root){
  /**
   * Ajax.js. This is an atempt at a nice clean light weight, speedy easy to use
   * interface ontop of the javascript XMLHttpRequest object. It is compatible
   * with require.js, and works as a stand alone vanilla javascript class.
   *
   * @class Ajax
   * @constructor Ajax
   * @param {string} args.url - request url
   * @param {string} [args.method] - HTTP request method. Defaults to GET.
   * Must be valid UPPERCASE http method.
   * @param {object} [args.data] - json request data
   * @param {string} [args.type] - request data content type. default is
   * URLENCODED. available types: JSON (application/json),
   * or URLENCODED(application/x-www-formurlencoded).
   * @param {string} [args.token] - CSRF token. If not provided Ajax will look
   * for a Rails style CSRF token meta tag.
   * @param {onSuccess} [args.onSuccess] - Called after making a successful
   * request.
   * @param {onError} [args.onError] - Called if request throws an error.
   * @param {onStart} [args.onStart] - Always called before other callbacks, at
   * start of request.
   * @param {onFinish} [args.onFinish] - Always called after other callbacks at
   * the end of the request.
   * @param {onTimeout} [args.onTimeout] - Called if request times out.
   * @param {float} [args.timeout] - Set timeout for request in miliseconds.
   * Defaults to no timeout.
   * @param {array} args.headers - Request headers to be set.
   * [{key: 'Key', value: 'Value'}]
   */

  /**
   * @callback onSuccess
   * @param {object} xhr - Called on successful xhr object.
   */

  /**
   * @callback onError
   * @param {object} xhr - Called on unuccessful xhr object.
   */

  /**
   * @callback onStart
   * @param {object} xhr - Called on start of xhr request.
   */

  /**
   * @callback onFinish
   * @param {object} xhr - Called on finish of xhr request.
   */

  /**
   * @callback onTimeout
   * @param {object} xhr - Called on timeout of xhr request.
   */

  'use strict';

  //TODO: Add other common types.
  var CONTENT_TYPES = {
    'URLENCODED': 'application/x-www-form-urlencoded',
    'JSON': 'application/json'
  },

  TYPES = (function(){
    var out = [];
    for(var key in CONTENT_TYPES){
      if(CONTENT_TYPES.hasOwnProperty(key)){
        out.push(key);
      }
    }

    return out;
  })(),

  METHODS = [
    'GET',
    'POST',
    'PUT',
    'HEAD',
    'DELETE',
    'OPTIONS',
    'TRACE',
    'CONNECT'
  ],

  token = function(){
    var el = document.getElementsByName('csrf-token')[0];
    if(typeof el !== 'undefined' && el !== null){return el.content;}
    return null;
  },

  noop = function(){},

  contentType = function(ajax){
    return CONTENT_TYPES[ajax.type];
  },

  createRequest = function(ajax){
    var xhr = null;

    if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();
    }else if(window.ActiveXObject){ // ie <= 9
      try{
        xhr = new ActiveXObject('Msxml2.XMLHTTP');
      }
      catch(e){
        try{
          xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }

        catch(a){}
      }
    }

    if(!xhr){
      throw new Error('Your browser is way too old.');
    }

    xhr.open(ajax.method, ajax.url, true);

    // TODO: why is this in here?
    xhr.timeout = ajax.timeout;

    return xhr;
  },

  bindEvents = function(ajax, xhr){
    xhr.ontimeout = ajax.onTimeout(xhr);

    ajax.onStart(xhr);

    xhr.onreadystatechange = function(){
      if(this.readyState === 4){
        if(this.status === 200){
          ajax.onSuccess(this);
        }else{
          ajax.onError(this);
        }
        ajax.onFinish(this);
      }
    };
  },

  dataToUrlEncoded = function(data){
    var out = [];

    for(var key in data){
      if(data.hasOwnProperty(key)){
        out.push(key + '=' + encodeURIComponent(data[key]));
      }
    }

    return out.join('&');
  },

  parseData = function(ajax){
    if(ajax.type === 'JSON'){
      return JSON.stringify(ajax.data);
    }else{
      // x-www-form-urlencoded
      return dataToUrlEncoded(ajax.data);
    }
  },

  setHeaders = function(ajax, xhr){
    var headers = ajax.headers;
    for(var i=0; i<headers.length; i++){
      var header = headers[i];
      xhr.setRequestHeader(header.key, header.value);
    }
  },

  mergeArgs = function(ajax, args){
    ajax.method = args.method || METHODS[0];
    ajax.url = args.url;
    ajax.data = args.data || {};
    ajax.token = args.token || token();
    ajax.timeout = args.timeout || 0;
    ajax.type = args.type || TYPES[0];
    ajax.headers = args.headers || [];
  },

  mergeCallbacks = function(ajax, args){
    var callbacks = [
      'onSuccess',
      'onError',
      'onStart',
      'onFinish',
      'onTimeout'
    ];

    for(var i=0; i < callbacks.length; i++){
      var callback = callbacks[i];
      ajax[callback] = args[callback] || noop;
    }
  },

  validateUrl = function(url){
    if(typeof url === 'undefined'){
      throw new Error('Ajax requires a url.');
    }
  },

  validateMethod = function(method){
    if(METHODS.indexOf(method) === -1){
      throw new Error('Ajax method must be valid.');
    }
  },

  validateType = function(type){
    if(TYPES.indexOf(type) === -1){
      throw new Error('Ajax content type must be valid.');
    }
  },

  validateAjax = function(ajax){
    validateUrl(ajax.url);
    validateMethod(ajax.method);
    validateType(ajax.type);
  },

  defaultHeaders = function(ajax){
    ajax.headers.push({key: 'Content-Type', value: contentType(ajax)});

    if(ajax.token){
      ajax.headers.push({key:'X-CSRF-Token', value: ajax.token});
    }
  };

  function Ajax(args){
    mergeArgs(this, args);
    mergeCallbacks(this, args);
    validateAjax(this);
    defaultHeaders(this);

    return this;
  }

  /**
   * Constructs, and sends ajax request.
   *
   * @memberOf Ajax
   * @param {object} args - see Ajax constructor.
   */
  Ajax.request = function(args){
    return new Ajax(args).send();
  };

  /**
   * Sends ajax request.
   *
   * @memberOf Ajax
   */
  Ajax.prototype.send = function(){
    var xhr = createRequest(this);

    setHeaders(this, xhr);

    bindEvents(this, xhr);
    xhr.send(parseData(this));

    return this;
  };

  var define = window.define || null;

  if(typeof define === 'function' && define.amd){
    define('ajax', [], function(){return Ajax;}); // amd
  }else{
    root.Ajax = Ajax;
  }
}(this));

<commit_msg>ie8 fixes<commit_after>/*global ActiveXObject*/

/**
 * @fileOverview Ajax class / require js amd module.
 * @author NathanG
 * @version 0.0.1
 */

(function(root){
  /**
   * Ajax.js. This is an atempt at a nice clean light weight, speedy easy to use
   * interface ontop of the javascript XMLHttpRequest object. It is compatible
   * with require.js, and works as a stand alone vanilla javascript class.
   *
   * @class Ajax
   * @constructor Ajax
   * @param {string} args.url - request url
   * @param {string} [args.method] - HTTP request method. Defaults to GET.
   * Must be valid UPPERCASE http method.
   * @param {object} [args.data] - json request data
   * @param {string} [args.type] - request data content type. default is
   * URLENCODED. available types: JSON (application/json),
   * or URLENCODED(application/x-www-formurlencoded).
   * @param {string} [args.token] - CSRF token. If not provided Ajax will look
   * for a Rails style CSRF token meta tag.
   * @param {onSuccess} [args.onSuccess] - Called after making a successful
   * request.
   * @param {onError} [args.onError] - Called if request throws an error.
   * @param {onStart} [args.onStart] - Always called before other callbacks, at
   * start of request.
   * @param {onFinish} [args.onFinish] - Always called after other callbacks at
   * the end of the request.
   * @param {onTimeout} [args.onTimeout] - Called if request times out.
   * @param {float} [args.timeout] - Set timeout for request in miliseconds.
   * Defaults to no timeout.
   * @param {array} args.headers - Request headers to be set.
   * [{key: 'Key', value: 'Value'}]
   */

  /**
   * @callback onSuccess
   * @param {object} xhr - Called on successful xhr object.
   */

  /**
   * @callback onError
   * @param {object} xhr - Called on unuccessful xhr object.
   */

  /**
   * @callback onStart
   * @param {object} xhr - Called on start of xhr request.
   */

  /**
   * @callback onFinish
   * @param {object} xhr - Called on finish of xhr request.
   */

  /**
   * @callback onTimeout
   * @param {object} xhr - Called on timeout of xhr request.
   */

  'use strict';

  //TODO: Add other common types.
  var CONTENT_TYPES = {
    'URLENCODED': 'application/x-www-form-urlencoded',
    'JSON': 'application/json'
  },

  TYPES = (function(){
    var out = [];
    for(var key in CONTENT_TYPES){
      if(CONTENT_TYPES.hasOwnProperty(key)){
        out.push(key);
      }
    }

    return out;
  })(),

  METHODS = [
    'GET',
    'POST',
    'PUT',
    'HEAD',
    'DELETE',
    'OPTIONS',
    'TRACE',
    'CONNECT'
  ],

  token = function(){
    var el = document.getElementsByName('csrf-token')[0];
    if(typeof el !== 'undefined' && el !== null){return el.content;}
    return null;
  },

  noop = function(){},

  contentType = function(ajax){
    return CONTENT_TYPES[ajax.type];
  },

  createRequest = function(ajax){
    var xhr = null;

    if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();
    }else if(window.ActiveXObject){ // ie <= 9
      try{
        xhr = new ActiveXObject('Msxml2.XMLHTTP');
      }
      catch(e){
        try{
          xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }

        catch(a){}
      }
    }

    if(!xhr){
      throw new Error('Your browser is way too old.');
    }

    xhr.open(ajax.method, ajax.url, true);
    xhr.timeout = ajax.timeout;

    return xhr;
  },

  bindEvents = function(ajax, xhr){
    if(xhr.onTimeout){ xhr.ontimeout = ajax.onTimeout(xhr); }

    ajax.onStart(xhr);

    xhr.onreadystatechange = function(){
      if(this.readyState === 4){
        if(this.status === 200){
          ajax.onSuccess(this);
        }else{
          ajax.onError(this);
        }
        ajax.onFinish(this);
      }
    };
  },

  dataToUrlEncoded = function(data){
    var out = [];

    for(var key in data){
      if(data.hasOwnProperty(key)){
        out.push(key + '=' + encodeURIComponent(data[key]));
      }
    }

    return out.join('&');
  },

  parseData = function(ajax){
    if(ajax.type === 'JSON'){
      return JSON.stringify(ajax.data);
    }else{
      // x-www-form-urlencoded
      return dataToUrlEncoded(ajax.data);
    }
  },

  setHeaders = function(ajax, xhr){
    var headers = ajax.headers;
    for(var i=0; i<headers.length; i++){
      var header = headers[i];
      xhr.setRequestHeader(header.key, header.value);
    }
  },

  mergeArgs = function(ajax, args){
    ajax.method = args.method || METHODS[0];
    ajax.url = args.url;
    ajax.data = args.data || {};
    ajax.token = args.token || token();
    ajax.timeout = args.timeout || 0;
    ajax.type = args.type || TYPES[0];
    ajax.headers = args.headers || [];
  },

  mergeCallbacks = function(ajax, args){
    var callbacks = [
      'onSuccess',
      'onError',
      'onStart',
      'onFinish',
      'onTimeout'
    ];

    for(var i=0; i < callbacks.length; i++){
      var callback = callbacks[i];
      ajax[callback] = args[callback] || noop;
    }
  },

  validateUrl = function(url){
    if(typeof url === 'undefined'){
      throw new Error('Ajax requires a url.');
    }
  },

  inArray = function(arr, value){
    // ie <= 8 dosent support Array.prototype.indexOf :(
    for(var i = 0; i < arr.length; i++){
      if(arr[i] === value){ return true; }
    }
    return false;
  },

  validateMethod = function(method){

    if(!inArray(METHODS, method)){
      throw new Error('Ajax method must be valid.');
    }
  },

  validateType = function(type){
    if(!inArray(TYPES, type)){
      throw new Error('Ajax content type must be valid.');
    }
  },

  validateAjax = function(ajax){
    validateUrl(ajax.url);
    validateMethod(ajax.method);
    validateType(ajax.type);
  },

  defaultHeaders = function(ajax){
    ajax.headers.push({key: 'Content-Type', value: contentType(ajax)});

    if(ajax.token){
      ajax.headers.push({key:'X-CSRF-Token', value: ajax.token});
    }
  };

  function Ajax(args){
    mergeArgs(this, args);
    mergeCallbacks(this, args);
    validateAjax(this);
    defaultHeaders(this);

    return this;
  }

  /**
   * Constructs, and sends ajax request.
   *
   * @memberOf Ajax
   * @param {object} args - see Ajax constructor.
   */
  Ajax.request = function(args){
    return new Ajax(args).send();
  };

  /**
   * Sends ajax request.
   *
   * @memberOf Ajax
   */
  Ajax.prototype.send = function(){
    var xhr = createRequest(this);

    setHeaders(this, xhr);

    bindEvents(this, xhr);
    xhr.send(parseData(this));

    return this;
  };

  var define = window.define || null;

  if(typeof define === 'function' && define.amd){
    define('ajax', [], function(){return Ajax;}); // amd
  }else{
    root.Ajax = Ajax;
  }
}(this));

<|endoftext|>


<commit_before>// Copyright (c) 2013 Marco Biasini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

function BackboneTrace() {
  this._trace = [];
}

BackboneTrace.prototype.push = function(residue) {
  this._trace.push(residue);
};

BackboneTrace.prototype.length = function() {
  return this._trace.length;
};

BackboneTrace.prototype.residueAt = function(index) {
  return this._trace[index];
};

BackboneTrace.prototype.posAt = function(out, index) {
   vec3.copy(out, this._trace[index].atom('CA').pos());
   return out;
};

BackboneTrace.prototype.normalAt = function(out, index) {
   vec3.sub(out, this._trace[index].atom('O').pos(),
            this._trace[index].atom('C').pos());
   vec3.normalize(out, out);
   return out;
};

// nothing needs to be done for the backbone trace.
BackboneTrace.prototype.smoothPosAt = BackboneTrace.prototype.posAt;
BackboneTrace.prototype.smoothNormalAt = BackboneTrace.prototype.normalAt;

BackboneTrace.prototype.centralAtomAt = function(index) {
  return this._trace[index].atom('CA');
};

BackboneTrace.prototype.tangentAt = (function() {
  var posBefore = vec3.create();
  var posAfter = vec3.create();
  return function(out, index) {
    if (index > 0) {
      this.posAt(posBefore, index-1);
    } else {
      this.posAt(posBefore, index);
    }
    if (index < this._trace.length-1) {
      this.posAt(posAfter, index+1);
    } else {
      this.posAt(posAfter, index);
    }
    vec3.sub(out, posAfter, posBefore);
  };
})();

BackboneTrace.prototype.fullTraceIndex = function(index) { return index; };

BackboneTrace.prototype.subsets = function(residues) {
  // we assume that the residue list is ordered from N- to C-
  // terminus and we can traverse it in one go.
  var fullTraceIdx = 0, listIdx = 0;
  var subsets = [];
  while (listIdx < residues.length && fullTraceIdx < this._trace.length) {
    // increase pointer until we residue indices match.
    var residueIndex = residues[listIdx].full().index();
    while (this._trace.length > fullTraceIdx &&
           this._trace[fullTraceIdx].index() < residueIndex) {
      ++fullTraceIdx;
    }
    if (fullTraceIdx >= this._trace.length) {
      break;
    }
    var traceIndex = this._trace[fullTraceIdx].index();
    while (residues.length > listIdx &&
           residues[listIdx].full().index() < traceIndex) {
      ++listIdx;
    }
    if (listIdx >= residues.length) {
      break;
    }
    var fullTraceBegin = fullTraceIdx;
    var residueListBegin = listIdx;
    while (residues.length > listIdx &&
           this._trace.length > fullTraceIdx &&
           residues[listIdx].full().index() === this._trace[fullTraceIdx].index()) {
      ++listIdx;
      ++fullTraceIdx;
    }
    var residueListEnd = listIdx;
    var fullTraceEnd = fullTraceIdx;
    subsets.push(new TraceSubset(this, fullTraceBegin, fullTraceEnd,
                                 residues.slice(residueListBegin,
                                                residueListEnd)));

  }
  return subsets;
};

// a trace subset, e.g. the part of a trace contained in a view. End regions
// are handled automatically depending on whether the beginning/end of the
// trace subset coincides with the C- and N-terminus of the full trace.
function TraceSubset(fullTrace, fullTraceBegin, fullTraceEnd, trace) {
  this._fullTrace = fullTrace;
  this._fullTraceBegin = fullTraceBegin;
  this._fullTraceEnd = fullTraceEnd;
  this._trace = trace;
  this._isNTerminal = this._fullTraceBegin === 0;
  this._isCTerminal = this._fullTrace.length() === this._fullTraceEnd;
  var length = this._fullTraceEnd - this._fullTraceBegin;
  if (!this._isCTerminal) {
    ++length;
  }
  if (!this._isNTerminal) {
    ++length;
    this._fullTraceBegin -= 1;
  }
  this._length = length;
}

TraceSubset.prototype.length = function() {
  return this._length;
};

TraceSubset.prototype.residueAt = function(index) {
  return this._fullTrace.residueAt(this._fullTraceBegin+index);
};

TraceSubset.prototype._interpolate = (function() {
  var posOne = vec3.create();
  var tangentOne = vec3.create();
  var tangentTwo = vec3.create();
  return function(out, indexOne, indexTwo, strength) {
      this.tangentAt(tangentOne, indexOne);
      this.tangentAt(tangentTwo, indexTwo);
      vec3.scale(tangentOne, tangentOne, strength);
      vec3.scale(tangentTwo, tangentTwo, strength);
      geom.cubicHermiteInterpolate(out,
                                   this.centralAtomAt(indexOne).pos(),
                                   tangentOne,
                                   this.centralAtomAt(indexTwo).pos(),
                                   tangentTwo, 0.5, 0);
      return out;
  };
})();

// like posAt, but interpolates the position for the ends with a Catmull-Rom
// spline.
TraceSubset.prototype.smoothPosAt = (function() {
  var posOne = vec3.create();
  var tangentOne = vec3.create();
  var tangentTwo = vec3.create();
  return function(out, index, strength) {
    if (index === 0 && !this._isNTerminal) {
      return this._interpolate(out, index, index+1, strength);
    }
    if (index === this._length-1 && !this._isCTerminal) {
      return this._interpolate(out, index-1, index, strength);
    }
    var atom = this.centralAtomAt(index);
    vec3.copy(out, atom.pos());
    return out;
  };
})();

TraceSubset.prototype.smoothNormalAt = (function() {
  return function(out, index, strength) {
    /*
    if (index === 0 && !this._isNTerminal) {
      return this._interpolate(out, index, index+1, strength);
    }
    if (index === this._length-1 && !this._isCTerminal) {
      return this._interpolate(out, index-1, index, strength);
    }
    */
    this._fullTrace.normalAt(out, index+this._fullTraceBegin);
    return out;
  };
})();

TraceSubset.prototype.posAt = function(out, index) {
  var atom = this.centralAtomAt(index);
  var atom2 = null;
  vec3.copy(out, atom.pos());
  if (index === 0 && !this._isNTerminal) {
    atom2 = this.centralAtomAt(index+1);
    vec3.add(out, out, atom2.pos());
    vec3.scale(out, out, 0.5);
  }
  if (index === this._length-1 && !this._isCTerminal) {
    atom2 = this.centralAtomAt(index-1);
    vec3.add(out, out, atom2.pos());
    vec3.scale(out, out, 0.5);
  }
  return out;
};

TraceSubset.prototype.centralAtomAt = function(index) {
  return this.residueAt(index).atom('CA');
};

TraceSubset.prototype.fullTraceIndex = function(index) {
  return this._fullTraceBegin+index;
};
TraceSubset.prototype.tangentAt =  function(out, index) {
  return this._fullTrace.tangentAt(out, index+this._fullTraceBegin);
};
<commit_msg>remove unused code<commit_after>// Copyright (c) 2013 Marco Biasini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

function BackboneTrace() {
  this._trace = [];
}

BackboneTrace.prototype.push = function(residue) {
  this._trace.push(residue);
};

BackboneTrace.prototype.length = function() {
  return this._trace.length;
};

BackboneTrace.prototype.residueAt = function(index) {
  return this._trace[index];
};

BackboneTrace.prototype.posAt = function(out, index) {
   vec3.copy(out, this._trace[index].atom('CA').pos());
   return out;
};

BackboneTrace.prototype.normalAt = function(out, index) {
   vec3.sub(out, this._trace[index].atom('O').pos(),
            this._trace[index].atom('C').pos());
   vec3.normalize(out, out);
   return out;
};

// nothing needs to be done for the backbone trace.
BackboneTrace.prototype.smoothPosAt = BackboneTrace.prototype.posAt;
BackboneTrace.prototype.smoothNormalAt = BackboneTrace.prototype.normalAt;

BackboneTrace.prototype.centralAtomAt = function(index) {
  return this._trace[index].atom('CA');
};

BackboneTrace.prototype.tangentAt = (function() {
  var posBefore = vec3.create();
  var posAfter = vec3.create();
  return function(out, index) {
    if (index > 0) {
      this.posAt(posBefore, index-1);
    } else {
      this.posAt(posBefore, index);
    }
    if (index < this._trace.length-1) {
      this.posAt(posAfter, index+1);
    } else {
      this.posAt(posAfter, index);
    }
    vec3.sub(out, posAfter, posBefore);
  };
})();

BackboneTrace.prototype.fullTraceIndex = function(index) { return index; };

BackboneTrace.prototype.subsets = function(residues) {
  // we assume that the residue list is ordered from N- to C-
  // terminus and we can traverse it in one go.
  var fullTraceIdx = 0, listIdx = 0;
  var subsets = [];
  while (listIdx < residues.length && fullTraceIdx < this._trace.length) {
    // increase pointer until we residue indices match.
    var residueIndex = residues[listIdx].full().index();
    while (this._trace.length > fullTraceIdx &&
           this._trace[fullTraceIdx].index() < residueIndex) {
      ++fullTraceIdx;
    }
    if (fullTraceIdx >= this._trace.length) {
      break;
    }
    var traceIndex = this._trace[fullTraceIdx].index();
    while (residues.length > listIdx &&
           residues[listIdx].full().index() < traceIndex) {
      ++listIdx;
    }
    if (listIdx >= residues.length) {
      break;
    }
    var fullTraceBegin = fullTraceIdx;
    var residueListBegin = listIdx;
    while (residues.length > listIdx &&
           this._trace.length > fullTraceIdx &&
           residues[listIdx].full().index() === this._trace[fullTraceIdx].index()) {
      ++listIdx;
      ++fullTraceIdx;
    }
    var residueListEnd = listIdx;
    var fullTraceEnd = fullTraceIdx;
    subsets.push(new TraceSubset(this, fullTraceBegin, fullTraceEnd,
                                 residues.slice(residueListBegin,
                                                residueListEnd)));

  }
  return subsets;
};

// a trace subset, e.g. the part of a trace contained in a view. End regions
// are handled automatically depending on whether the beginning/end of the
// trace subset coincides with the C- and N-terminus of the full trace.
function TraceSubset(fullTrace, fullTraceBegin, fullTraceEnd, trace) {
  this._fullTrace = fullTrace;
  this._fullTraceBegin = fullTraceBegin;
  this._fullTraceEnd = fullTraceEnd;
  this._trace = trace;
  this._isNTerminal = this._fullTraceBegin === 0;
  this._isCTerminal = this._fullTrace.length() === this._fullTraceEnd;
  var length = this._fullTraceEnd - this._fullTraceBegin;
  if (!this._isCTerminal) {
    ++length;
  }
  if (!this._isNTerminal) {
    ++length;
    this._fullTraceBegin -= 1;
  }
  this._length = length;
}

TraceSubset.prototype.length = function() {
  return this._length;
};

TraceSubset.prototype.residueAt = function(index) {
  return this._fullTrace.residueAt(this._fullTraceBegin+index);
};

TraceSubset.prototype._interpolate = (function() {
  var posOne = vec3.create();
  var tangentOne = vec3.create();
  var tangentTwo = vec3.create();
  return function(out, indexOne, indexTwo, strength) {
      this.tangentAt(tangentOne, indexOne);
      this.tangentAt(tangentTwo, indexTwo);
      vec3.scale(tangentOne, tangentOne, strength);
      vec3.scale(tangentTwo, tangentTwo, strength);
      geom.cubicHermiteInterpolate(out,
                                   this.centralAtomAt(indexOne).pos(),
                                   tangentOne,
                                   this.centralAtomAt(indexTwo).pos(),
                                   tangentTwo, 0.5, 0);
      return out;
  };
})();

// like posAt, but interpolates the position for the ends with a Catmull-Rom
// spline.
TraceSubset.prototype.smoothPosAt = (function() {
  var posOne = vec3.create();
  var tangentOne = vec3.create();
  var tangentTwo = vec3.create();
  return function(out, index, strength) {
    if (index === 0 && !this._isNTerminal) {
      return this._interpolate(out, index, index+1, strength);
    }
    if (index === this._length-1 && !this._isCTerminal) {
      return this._interpolate(out, index-1, index, strength);
    }
    var atom = this.centralAtomAt(index);
    vec3.copy(out, atom.pos());
    return out;
  };
})();

TraceSubset.prototype.smoothNormalAt = (function() {
  return function(out, index, strength) {
    this._fullTrace.normalAt(out, index+this._fullTraceBegin);
    return out;
  };
})();

TraceSubset.prototype.posAt = function(out, index) {
  var atom = this.centralAtomAt(index);
  var atom2 = null;
  vec3.copy(out, atom.pos());
  if (index === 0 && !this._isNTerminal) {
    atom2 = this.centralAtomAt(index+1);
    vec3.add(out, out, atom2.pos());
    vec3.scale(out, out, 0.5);
  }
  if (index === this._length-1 && !this._isCTerminal) {
    atom2 = this.centralAtomAt(index-1);
    vec3.add(out, out, atom2.pos());
    vec3.scale(out, out, 0.5);
  }
  return out;
};

TraceSubset.prototype.centralAtomAt = function(index) {
  return this.residueAt(index).atom('CA');
};

TraceSubset.prototype.fullTraceIndex = function(index) {
  return this._fullTraceBegin+index;
};
TraceSubset.prototype.tangentAt =  function(out, index) {
  return this._fullTrace.tangentAt(out, index+this._fullTraceBegin);
};
<|endoftext|>


<commit_before>// required for IE11
import 'core-js/features/promise';
// JS's startsWith() -- support for IE and old Opera
import 'core-js/features/string/starts-with';
// JS's findIndex() -- support for IE and old Opera
import 'core-js/features/array/find-index';
// JS's includes -- support for old browsers
import 'core-js/features/array/includes';
// Object.assign -- support for old browsers
import 'core-js/features/object/assign';
// array forEach -- support for old browsers
import 'core-js/features/array/for-each';
// array isArray -- support for old browser
import 'core-js/features/array/is-array';
import 'core-js/features/array/from';
// vue.js Object.values
import 'core-js/features/object/values';

import './store';
// import './components/dropdown.js';
import './components/scrolltop.js';
import './components/breadcrumb.js';
import './components/navbar-toggle.js';
import './components/state.js';
import './libs/timeago.js';
import './components/vcard.js';
import './components/popover.js';
import './components/flag.js';
import './plugins/sociale.js';
import './plugins/geo-ip';
import './bootstrap';

import Config from './libs/config';
import { default as setToken } from './libs/csrf';
import Router from './libs/router';
import Prism from 'prismjs';

Prism.highlightAll();

$(function () {
  'use strict';

  setToken(Config.csrfToken());

  let r = new Router();

  r.on('/User', () => {
    require.ensure([], require => require('./pages/user'), 'user');
  })
  .on('/Praca/Application/*', () => {
    require.ensure([], require => require('./pages/job/application'), 'application');
  })
  .on('/Praca/Payment/*', () => {
    require.ensure([], require => require('./pages/job/payment'), 'payment');
  })
  .on('/Praca/Oferta', () => {
    require.ensure([], require => require('./pages/job/business'), 'business');
  })
  .on(['/Praca', '/Praca/Miasto/*', '/Praca/Technologia/*', '/Praca/Zdalna', '/Praca/Firma/*'], () => {
    require('./pages/job/homepage');
  })
  .on('/Praca/\\d+\\-*', () => {
    require('./pages/job/offer');
  })
  .on('/Adm/Firewall/*', () => {
    require.ensure(['flatpickr', 'flatpickr/dist/l10n/pl'], require => {
      require('flatpickr');
      const Polish = require('flatpickr/dist/l10n/pl.js').pl;

      $('#expire-at').flatpickr({
        allowInput: true,
        locale: Polish
      });
    });
  })
  .on('/Adm/Mailing', () => {
    require('./libs/tinymce').default();
  })
  .on(['/User/Pm/Submit', '/User/Pm/Show/*', '/User/Pm'], () => {
    require('./pages/pm');
  });

  r.resolve();
});
<commit_msg>polyfill<commit_after>// required for IE11
import 'core-js/features/promise';
// JS's startsWith() -- support for IE and old Opera
import 'core-js/features/string/starts-with';
// JS's findIndex() -- support for IE and old Opera
import 'core-js/features/array/find-index';
import 'core-js/features/array/find';
// JS's includes -- support for old browsers
import 'core-js/features/array/includes';
// Object.assign -- support for old browsers
import 'core-js/features/object/assign';
// array forEach -- support for old browsers
import 'core-js/features/array/for-each';
// array isArray -- support for old browser
import 'core-js/features/array/is-array';
import 'core-js/features/array/from';
// vue.js Object.values
import 'core-js/features/object/values';

import './store';
// import './components/dropdown.js';
import './components/scrolltop.js';
import './components/breadcrumb.js';
import './components/navbar-toggle.js';
import './components/state.js';
import './libs/timeago.js';
import './components/vcard.js';
import './components/popover.js';
import './components/flag.js';
import './plugins/sociale.js';
import './plugins/geo-ip';
import './bootstrap';

import Config from './libs/config';
import { default as setToken } from './libs/csrf';
import Router from './libs/router';
import Prism from 'prismjs';

Prism.highlightAll();

$(function () {
  'use strict';

  setToken(Config.csrfToken());

  let r = new Router();

  r.on('/User', () => {
    require.ensure([], require => require('./pages/user'), 'user');
  })
  .on('/Praca/Application/*', () => {
    require.ensure([], require => require('./pages/job/application'), 'application');
  })
  .on('/Praca/Payment/*', () => {
    require.ensure([], require => require('./pages/job/payment'), 'payment');
  })
  .on('/Praca/Oferta', () => {
    require.ensure([], require => require('./pages/job/business'), 'business');
  })
  .on(['/Praca', '/Praca/Miasto/*', '/Praca/Technologia/*', '/Praca/Zdalna', '/Praca/Firma/*'], () => {
    require('./pages/job/homepage');
  })
  .on('/Praca/\\d+\\-*', () => {
    require('./pages/job/offer');
  })
  .on('/Adm/Firewall/*', () => {
    require.ensure(['flatpickr', 'flatpickr/dist/l10n/pl'], require => {
      require('flatpickr');
      const Polish = require('flatpickr/dist/l10n/pl.js').pl;

      $('#expire-at').flatpickr({
        allowInput: true,
        locale: Polish
      });
    });
  })
  .on('/Adm/Mailing', () => {
    require('./libs/tinymce').default();
  })
  .on(['/User/Pm/Submit', '/User/Pm/Show/*', '/User/Pm'], () => {
    require('./pages/pm');
  });

  r.resolve();
});
<|endoftext|>


<commit_before>import md from 'components/md'

const ServerSideRendering = () => md`
  ## Server Side Rendering | v2

  styled-components supports concurrent server side rendering, with stylesheet rehydration.
  The basic idea is that everytime you render your app on the server, you can create
  a \`ServerStyleSheet\` and add a provider to your React tree, that accepts styles
  via a context API.

  This doesn't interfere with global styles, such as \`keyframes\` or \`injectGlobal\` and
  allows you to use styled-components with React DOM's SSR, or even Rapscallion.

  The basic API goes as follows:

  \`\`\`jsx
  import { renderToString } from 'react-dom/server'
  import { ServerStyleSheet } from 'styled-components'

  const sheet = new ServerStyleSheet()
  const html = renderToString(sheet.collectStyles(<YourApp />))
  const styleTags = sheet.getStyleTags() // or sheet.getStyleElement()
  \`\`\`

  The \`collectStyles\` method wraps your element in a provider. Optionally you can use
  the \`StyleSheetManager\` provider directly, instead of this method. Just make sure not to
  use it on the client-side.

  \`\`\`jsx
  import { renderToString } from 'react-dom/server'
  import { ServerStyleSheet, StyleSheetManager } from 'styled-components'

  const sheet = new ServerStyleSheet()
  const html = renderToString(

  )

  const styleTags = sheet.getStyleTags() // or sheet.getStyleElement()
  \`\`\`

  The \`sheet.getStyleTags()\` returns a string of multiple \`<style>\` tags.
  You need to take this into account when adding the CSS string to your HTML output.

  Alternatively the \`ServerStyleSheet\` instance also has a \`getStyleElement()\` method
  that returns an array of React elements.

  > \`sheet.getStyleTags()\` and \`sheet.getStyleElement()\` can only be called after your element is rendered. As a result, components from \`sheet.getStyleElement()\` cannot be combined with \`<YourApp />\` into a larger component.

  You might need to install and use our babel plugin with its `ssr` option turned on.
  This prevents checksum mismatches by adding a deterministic ID to each styled component.
  Refer to the [tooling documentation](/docs/tooling#serverside-rendering) for more information.

  ### Next.js

  Basically you need to add a custom \`pages/_document.js\` (if you don't have one). Then
  [copy the logic](https://github.com/zeit/next.js/tree/master/examples/with-styled-components/pages/_document.js)
  for styled-components to inject the server side rendered styles into the \`<head>\`.

  Refer to [our example](https://github.com/zeit/next.js/tree/master/examples/with-styled-components) in the Next.js repo for an up-to-date usage example.
  ### Streaming Rendering

  styled-components offers a streaming API for use with [ReactDOMServer.renderToNodeStream()](https://reactjs.org/docs/react-dom-server.html#rendertonodestream). There are two parts to a streaming implementation:

  _On the server:_

  \`ReactDOMServer.renderToNodeStream\` emits a "readable" stream that styled-components wraps. As whole chunks of HTML are pushed onto the stream, if any corresponding styles are ready to be rendered, a style block is prepended to React's HTML and forwarded on to the client browser.

  \`\`\`js
  import { renderToNodeStream } from 'react-dom/server'
  import styled, { ServerStyleSheet } from 'styled-components'

  // if you're using express.js, you'd have access to the response object "res"

  // typically you'd want to write some preliminary HTML, since React doesn't handle this
  res.write('<title>Test</title>')

  const Heading = styled.h1\`
    color: red;
  \`

  const sheet = new ServerStyleSheet()
  const jsx = sheet.collectStyles(<Heading>Hello SSR!</Heading>)
  const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx))

  // you'd then pipe the stream into the response object until it's done
  stream.pipe(res, { end: false })

  // and finalize the response with closing HTML
  stream.on('end', () => res.end(''))
  \`\`\`

  _On the client:_

  Before calling \`ReactDOM.hydrate\` to allow client-side React to take over, the \`consolidateStreamedStyles\` API must be called from styled-components to relocate the style blocks that will be intersperced throughout the rendered HTML. Otherwise, the checksum between server and client will be violated and result in an inconsistent page since \`interleaveWithNodeStream\` injected HTML that React wasn't expecting.

  \`\`\`js
  import { hydrate } from 'react-dom'
  import { consolidateStreamedStyles } from 'styled-components'

  consolidateStreamedStyles()

  hydrate(
    // your client-side react implementation
  )
  \`\`\`

  After client-side rehydration is complete, styled-components will take over as usual and inject any further dynamic styles after the relocated streaming ones.
`

export default ServerSideRendering
<commit_msg>Add back missing whiteline.<commit_after>import md from 'components/md'

const ServerSideRendering = () => md`
  ## Server Side Rendering | v2

  styled-components supports concurrent server side rendering, with stylesheet rehydration.
  The basic idea is that everytime you render your app on the server, you can create
  a \`ServerStyleSheet\` and add a provider to your React tree, that accepts styles
  via a context API.

  This doesn't interfere with global styles, such as \`keyframes\` or \`injectGlobal\` and
  allows you to use styled-components with React DOM's SSR, or even Rapscallion.

  The basic API goes as follows:

  \`\`\`jsx
  import { renderToString } from 'react-dom/server'
  import { ServerStyleSheet } from 'styled-components'

  const sheet = new ServerStyleSheet()
  const html = renderToString(sheet.collectStyles(<YourApp />))
  const styleTags = sheet.getStyleTags() // or sheet.getStyleElement()
  \`\`\`

  The \`collectStyles\` method wraps your element in a provider. Optionally you can use
  the \`StyleSheetManager\` provider directly, instead of this method. Just make sure not to
  use it on the client-side.

  \`\`\`jsx
  import { renderToString } from 'react-dom/server'
  import { ServerStyleSheet, StyleSheetManager } from 'styled-components'

  const sheet = new ServerStyleSheet()
  const html = renderToString(

  )

  const styleTags = sheet.getStyleTags() // or sheet.getStyleElement()
  \`\`\`

  The \`sheet.getStyleTags()\` returns a string of multiple \`<style>\` tags.
  You need to take this into account when adding the CSS string to your HTML output.

  Alternatively the \`ServerStyleSheet\` instance also has a \`getStyleElement()\` method
  that returns an array of React elements.

  > \`sheet.getStyleTags()\` and \`sheet.getStyleElement()\` can only be called after your element is rendered. As a result, components from \`sheet.getStyleElement()\` cannot be combined with \`<YourApp />\` into a larger component.

  You might need to install and use our babel plugin with its `ssr` option turned on.
  This prevents checksum mismatches by adding a deterministic ID to each styled component.
  Refer to the [tooling documentation](/docs/tooling#serverside-rendering) for more information.

  ### Next.js

  Basically you need to add a custom \`pages/_document.js\` (if you don't have one). Then
  [copy the logic](https://github.com/zeit/next.js/tree/master/examples/with-styled-components/pages/_document.js)
  for styled-components to inject the server side rendered styles into the \`<head>\`.

  Refer to [our example](https://github.com/zeit/next.js/tree/master/examples/with-styled-components) in the Next.js repo for an up-to-date usage example.

  ### Streaming Rendering

  styled-components offers a streaming API for use with [ReactDOMServer.renderToNodeStream()](https://reactjs.org/docs/react-dom-server.html#rendertonodestream). There are two parts to a streaming implementation:

  _On the server:_

  \`ReactDOMServer.renderToNodeStream\` emits a "readable" stream that styled-components wraps. As whole chunks of HTML are pushed onto the stream, if any corresponding styles are ready to be rendered, a style block is prepended to React's HTML and forwarded on to the client browser.

  \`\`\`js
  import { renderToNodeStream } from 'react-dom/server'
  import styled, { ServerStyleSheet } from 'styled-components'

  // if you're using express.js, you'd have access to the response object "res"

  // typically you'd want to write some preliminary HTML, since React doesn't handle this
  res.write('<title>Test</title>')

  const Heading = styled.h1\`
    color: red;
  \`

  const sheet = new ServerStyleSheet()
  const jsx = sheet.collectStyles(<Heading>Hello SSR!</Heading>)
  const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx))

  // you'd then pipe the stream into the response object until it's done
  stream.pipe(res, { end: false })

  // and finalize the response with closing HTML
  stream.on('end', () => res.end(''))
  \`\`\`

  _On the client:_

  Before calling \`ReactDOM.hydrate\` to allow client-side React to take over, the \`consolidateStreamedStyles\` API must be called from styled-components to relocate the style blocks that will be intersperced throughout the rendered HTML. Otherwise, the checksum between server and client will be violated and result in an inconsistent page since \`interleaveWithNodeStream\` injected HTML that React wasn't expecting.

  \`\`\`js
  import { hydrate } from 'react-dom'
  import { consolidateStreamedStyles } from 'styled-components'

  consolidateStreamedStyles()

  hydrate(
    // your client-side react implementation
  )
  \`\`\`

  After client-side rehydration is complete, styled-components will take over as usual and inject any further dynamic styles after the relocated streaming ones.
`

export default ServerSideRendering
<|endoftext|>


<commit_before>var jenkinsapi = require('jenkins-api');
var Promise = require('bluebird')
var cache = require('./cache.js').getCache()
var async = require('async')
var dateFormat = require('dateformat');
var slackmsg = require('./slackMsgs.js')

// config
var username = process.env.JENKINS_USERNAME;
var jenkins_url = process.env.JENKINS_URL
var url = process.env.JENKINS_URL.split('//');
var uri = url[1]
var protocol = url[0];
var df = "dd/mm/yyyy, hh:MM TT"

module.exports = function (robot) {

    /*************************************************************************
     *                               BUILDS
     */

    function build(jobName) {
        jenkins.build(jobName, function (err, data) {
            if (err) throw err;
            console.log(data)
        });
    }

    function stopBuild(jobName, buildNum) {
        jenkins.stop_build(jobName, buildNum, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getConsoleOutput(jobName, buildNum) {
        jenkins.console_output(jobName, buildNum, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data.body)
        });
    }

    function getBuildInfo(res) {
        var userid = res.message.user.id
        var jobName = res.match[2]
        var buildNum = res.match[1]

        console.log('j: ', jobName)
        console.log('b: ', buildNum)

        var jenkins = login(res)
        if (!jenkins) return
        else console.log('ok')
        jenkins.build_infoAsync(jobName, buildNum, {})
            .then(item => {
                console.log(item)
                var msg = { attachments: [] }
                var att = slackmsg.attachment()

                // title: Build #num (timestamp)
                var date = new Date(item.timestamp)
                att.title = `<${item.url}|Build #${item.id}>`
                    + ` (${dateFormat(date, df)})`

                // fallback
                att.fallback = att.title

                // text: Result: <result> | Duration: #.### s
                att.text = `Result: ${item.result} | Duration: ${item.duration / 1000} s`

                // color
                if (item.result == 'SUCCESS') {
                    att.color = 'good'
                } else if (att.color.includes('FAIL')) {
                    att.color = 'danger'
                } else {
                    att.color = 'warning'
                }

                // description

                //changes
                if (item.changeSet.items) {
                    console.log('\n', item.changeSet.items)

                    console.log('\n', item.changeSet.items[0])
                }

                msg.attachments.push(att)
                return msg
            })
            .then(msg => { robot.messageRoom(userid, msg) })
            .catch(err => { console.log(err) })
    }

    function getLastBuildInfo(res) {
        var userid = res.message.user.id
        var jobName = res.match[1]

        var jenkins = login(res)
        if (!jenkins) return
        jenkins.last_build_infoAsync(jobName, {})
            .then(item => {
                var msg = { attachments: [] }
                var att = slackmsg.attachment()
                var date = new Date(item.timestamp)
                att.title = `<${item.url}|Build #${item.id}>`
                    + ` (${dateFormat(date, df)})`
                att.fallback = att.title
                att.text = `Result: ${item.result} | Duration: ${item.duration / 1000} s`
                if (item.result == 'SUCCESS') {
                    att.color = 'good'
                } else if (att.color.includes('FAIL')) {
                    att.color = 'danger'
                } else {
                    att.color = 'warning'
                }
                msg.attachments.push(att)
                return msg
            })
            .then(msg => { robot.messageRoom(userid, msg) })
            .catch(err => { console.log(err) })
    }

    function getLastCompletedBuildInfo(jobName) {
        jenkins.last_completed_build_info(jobName, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getAllBuilds(res) {
        var username, token
        var userid = res.message.user.id
        var jobName = res.match[1]

        var jenkins = login(res)
        if (!jenkins) return

        jenkins.all_buildsAsync(jobName, {})
            .then(data => {
                var msg = { attachments: [] }
                data.forEach(function (item) {
                    var att = slackmsg.attachment()
                    var date = new Date(item.timestamp)
                    att.title = `<${jenkins_url}/job/${jobName}/${item.id}|Build #${item.id}>`
                        + ` (${dateFormat(date, df)})`
                    att.fallback = att.title
                    att.text = `Result: ${item.result} | Duration: ${item.duration / 1000} s`
                    if (item.result == 'SUCCESS') {
                        att.color = 'good'
                    } else if (att.color.includes('FAIL')) {
                        att.color = 'danger'
                    } else {
                        att.color = 'warning'
                    }
                    msg.attachments.push(att)
                })
                return msg

            })
            .then(msg => { robot.messageRoom(userid, msg) })
            .catch(err => { console.log(err) })
    }

    function getTestResult(jobName, buildNum) {
        jenkins.test_result(jobName, buildNum, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function deleteBuildData(jobName, buildNum) {
        jenkins.delete_build(jobName, buildNum, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    /*************************************************************************
     *                               JOBS
     */

    function getAllJobs() {
        jenkins.all_jobs({}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getJobConfigXML(jobName) {

        jenkins.get_config_xml(jobName, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getJobInfo(jobName) {
        jenkins.job_info(jobName, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getJobsLastSuccessBuild(jobName) {
        jenkins.last_success(jobName, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getJobsLastResult(jobName) {
        jenkins.last_result(jobName, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    /*
        NOT IMPLEMENTED:
        update
        create
        copy
        delete
        enable
        disaple
    */

    /*************************************************************************
     *                               VIEWS
     */

    function getAllViews() {
        jenkins.all_views({}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    /*************************************************************************
     *                           robot instance
     */

    robot.respond(/jenkins builds of job (.*)/i, function (res) {
        getAllBuilds(res)
    })

    robot.respond(/jenkins last build report of job (.*)/i, function (res) {
        getLastBuildInfo(res)
    })

    robot.respond(/jenkins build (.*) info of job (.*)/i, function (res) {
        getBuildInfo(res)
    })

    function login(res) {
        var userid = res.message.user.id

        try {
            var token = cache.get(userid).jenkins_token
            var username = cache.get(userid).jenkins_username
            if (!token || !username) throw error // catch the case where username or token are null/undefined
        } catch (error) {
            robot.emit('jenkinsLogin', {}, res)
            return false
        }
        var jenkins = jenkinsapi.init(`https://${username}:${token}@c349f31c.ngrok.io`)
        return Promise.promisifyAll(jenkins);
    }

}<commit_msg>jenkins-integration.js<commit_after>var jenkinsapi = require('jenkins-api');
var Promise = require('bluebird')
var cache = require('./cache.js').getCache()
var async = require('async')
var dateFormat = require('dateformat');
var slackmsg = require('./slackMsgs.js')

// config
var username = process.env.JENKINS_USERNAME;
var jenkins_url = process.env.JENKINS_URL
var url = process.env.JENKINS_URL.split('//');
var uri = url[1]
var protocol = url[0];
var df = "dd/mm/yyyy, hh:MM TT"

module.exports = function (robot) {

    /*************************************************************************
     *                               BUILDS
     */

    function build(jobName) {
        jenkins.build(jobName, function (err, data) {
            if (err) throw err;
            console.log(data)
        });
    }

    function stopBuild(jobName, buildNum) {
        jenkins.stop_build(jobName, buildNum, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getConsoleOutput(jobName, buildNum) {
        jenkins.console_output(jobName, buildNum, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data.body)
        });
    }

    function getBuildInfo(res) {
        var userid = res.message.user.id
        var jobName = res.match[2]
        var buildNum = res.match[1]

        console.log('j: ', jobName)
        console.log('b: ', buildNum)

        var jenkins = login(res)
        if (!jenkins) return
        else console.log('ok')
        jenkins.build_infoAsync(jobName, buildNum, {})
            .then(item => {
                console.log(item)
                var msg = { attachments: [] }
                var att = slackmsg.attachment()

                // title: Build #num (timestamp)
                var date = new Date(item.timestamp)
                att.title = `<${item.url}|Build #${item.id}>`
                    + ` (${dateFormat(date, df)})`

                // fallback
                att.fallback = att.title

                // text: Result: <result> | Duration: #.### s
                att.text = `Result: ${item.result} | Duration: ${item.duration / 1000} s`

                // color
                if (item.result == 'SUCCESS') {
                    att.color = 'good'
                } else if (att.color.includes('FAIL')) {
                    att.color = 'danger'
                } else {
                    att.color = 'warning'
                }

                // description

                //changes
                if (item.changeSet.items) {
                    console.log('\n', item.changeSet.items)
                    console.log('\n', item.changeSet.items[0])
                }

                msg.attachments.push(att)
                return msg
            })
            .then(msg => { robot.messageRoom(userid, msg) })
            .catch(err => { console.log(err) })
    }

    function getLastBuildInfo(res) {
        var userid = res.message.user.id
        var jobName = res.match[1]

        var jenkins = login(res)
        if (!jenkins) return
        jenkins.last_build_infoAsync(jobName, {})
            .then(item => {
                var msg = { attachments: [] }
                var att = slackmsg.attachment()
                var date = new Date(item.timestamp)
                att.title = `<${item.url}|Build #${item.id}>`
                    + ` (${dateFormat(date, df)})`
                att.fallback = att.title
                att.text = `Result: ${item.result} | Duration: ${item.duration / 1000} s`
                if (item.result == 'SUCCESS') {
                    att.color = 'good'
                } else if (att.color.includes('FAIL')) {
                    att.color = 'danger'
                } else {
                    att.color = 'warning'
                }
                msg.attachments.push(att)
                return msg
            })
            .then(msg => { robot.messageRoom(userid, msg) })
            .catch(err => { console.log(err) })
    }

    function getLastCompletedBuildInfo(jobName) {
        jenkins.last_completed_build_info(jobName, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getAllBuilds(res) {
        var username, token
        var userid = res.message.user.id
        var jobName = res.match[1]

        var jenkins = login(res)
        if (!jenkins) return

        jenkins.all_buildsAsync(jobName, {})
            .then(data => {
                var msg = { attachments: [] }
                data.forEach(function (item) {
                    var att = slackmsg.attachment()
                    var date = new Date(item.timestamp)
                    att.title = `<${jenkins_url}/job/${jobName}/${item.id}|Build #${item.id}>`
                        + ` (${dateFormat(date, df)})`
                    att.fallback = att.title
                    att.text = `Result: ${item.result} | Duration: ${item.duration / 1000} s`
                    if (item.result == 'SUCCESS') {
                        att.color = 'good'
                    } else if (att.color.includes('FAIL')) {
                        att.color = 'danger'
                    } else {
                        att.color = 'warning'
                    }
                    msg.attachments.push(att)
                })
                return msg

            })
            .then(msg => { robot.messageRoom(userid, msg) })
            .catch(err => { console.log(err) })
    }

    function getTestResult(jobName, buildNum) {
        jenkins.test_result(jobName, buildNum, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function deleteBuildData(jobName, buildNum) {
        jenkins.delete_build(jobName, buildNum, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    /*************************************************************************
     *                               JOBS
     */

    function getAllJobs() {
        jenkins.all_jobs({}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getJobConfigXML(jobName) {

        jenkins.get_config_xml(jobName, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getJobInfo(jobName) {
        jenkins.job_info(jobName, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getJobsLastSuccessBuild(jobName) {
        jenkins.last_success(jobName, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    function getJobsLastResult(jobName) {
        jenkins.last_result(jobName, {}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    /*
        NOT IMPLEMENTED:
        update
        create
        copy
        delete
        enable
        disaple
    */

    /*************************************************************************
     *                               VIEWS
     */

    function getAllViews() {
        jenkins.all_views({}, function (err, data) {
            if (err) { return console.log(err); }
            console.log(data)
        });
    }

    /*************************************************************************
     *                           robot instance
     */

    robot.respond(/jenkins builds of job (.*)/i, function (res) {
        getAllBuilds(res)
    })

    robot.respond(/jenkins last build report of job (.*)/i, function (res) {
        getLastBuildInfo(res)
    })

    robot.respond(/jenkins build (.*) info of job (.*)/i, function (res) {
        getBuildInfo(res)
    })

    function login(res) {
        var userid = res.message.user.id

        try {
            var token = cache.get(userid).jenkins_token
            var username = cache.get(userid).jenkins_username
            if (!token || !username) throw error // catch the case where username or token are null/undefined
        } catch (error) {
            robot.emit('jenkinsLogin', {}, res)
            return false
        }
        var jenkins = jenkinsapi.init(`https://${username}:${token}@c349f31c.ngrok.io`)
        return Promise.promisifyAll(jenkins);
    }

}<|endoftext|>


<commit_before>import App from "../app";
import { pubsub } from "../helpers/subscriptionManager.js";
import uuid from "uuid";

App.on("chargePhaserBeam", ({ id, beamId }) => {
  const sys = App.systems.find(s => s.id === id);
  sys.updateBeamState(beamId, "charging");
  //sys.updateBeamCharge(beamId, 1);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("dischargePhaserBeam", ({ id, beamId }) => {
  const sys = App.systems.find(s => s.id === id);
  sys.updateBeamState(beamId, "discharging");
  //sys.updateBeamCharge(beamId, 0);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("firePhaserBeam", ({ id, beamId }) => {
  const sys = App.systems.find(s => s.id === id);
  sys.fireBeam(beamId);
  pubsub.publish("notify", {
    id: uuid.v4(),
    simulatorId: sys.simulatorId,
    station: "Core",
    title: `Phasers Firing`,
    body: "",
    color: "info"
  });
  App.handleEvent(
    {
      simulatorId: sys.simulatorId,
      title: `Phasers Firing`,
      component: "PhaserCore",
      body: null,
      color: "danger"
    },
    "addCoreFeed"
  );
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("stopPhaserBeams", ({ id }) => {
  const sys = App.systems.find(s => s.id === id);
  sys.stopBeams();
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("phaserArc", ({ id, beamId, arc }) => {
  App.systems.find(s => s.id === id).updateArc(arc);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("setPhaserBeamCharge", ({ id, beamId, charge }) => {
  App.systems.find(s => s.id === id).updateBeamCharge(beamId, charge);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("setPhaserBeamHeat", ({ id, beamId, heat }) => {
  App.systems.find(s => s.id === id).updateBeamHeat(beamId, heat);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("coolPhaserBeam", ({ id, beamId }) => {
  App.systems.find(s => s.id === id).coolBeam(beamId);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("applyPhaserCoolant", ({ id, beamId }) => {
  const phaser = App.systems.find(s => s.id === id);
  const beam = phaser.beams.find(b => b.id === beamId);
  phaser.setCoolant(Math.min(1, Math.max(0, phaser.coolant - 0.005)));
  beam.setHeat(Math.min(1, Math.max(0, beam.heat - 0.01)));
  if (phaser.coolant === 0 || beam.heat === 0) phaser.coolBeam(null);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("setPhaserBeamCount", ({ id, beamCount }) => {
  App.systems.find(s => s.id === id).setBeams(beamCount);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
<commit_msg>Improves handling of phaser beams. Closes #537<commit_after>import App from "../app";
import { pubsub } from "../helpers/subscriptionManager.js";
import uuid from "uuid";

App.on("chargePhaserBeam", ({ id, beamId }) => {
  const sys = App.systems.find(s => s.id === id);
  sys.updateBeamState(beamId, "charging");
  //sys.updateBeamCharge(beamId, 1);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("dischargePhaserBeam", ({ id, beamId }) => {
  const sys = App.systems.find(s => s.id === id);
  sys.updateBeamState(beamId, "discharging");
  //sys.updateBeamCharge(beamId, 0);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("firePhaserBeam", ({ id, beamId }) => {
  const sys = App.systems.find(s => s.id === id);
  sys.fireBeam(beamId);
  pubsub.publish("notify", {
    id: uuid.v4(),
    simulatorId: sys.simulatorId,
    station: "Core",
    title: `Phasers Firing`,
    body: "",
    color: "info"
  });
  App.handleEvent(
    {
      simulatorId: sys.simulatorId,
      title: `Phasers Firing`,
      component: "PhaserCore",
      body: null,
      color: "danger"
    },
    "addCoreFeed"
  );
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("stopPhaserBeams", ({ id }) => {
  const sys = App.systems.find(s => s.id === id);
  sys && sys.stopBeams();
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("phaserArc", ({ id, beamId, arc }) => {
  App.systems.find(s => s.id === id).updateArc(arc);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("setPhaserBeamCharge", ({ id, beamId, charge }) => {
  App.systems.find(s => s.id === id).updateBeamCharge(beamId, charge);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("setPhaserBeamHeat", ({ id, beamId, heat }) => {
  App.systems.find(s => s.id === id).updateBeamHeat(beamId, heat);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("coolPhaserBeam", ({ id, beamId }) => {
  const sys = App.systems.find(s => s.id === id);
  sys && sys.coolBeam(beamId);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("applyPhaserCoolant", ({ id, beamId }) => {
  const phaser = App.systems.find(s => s.id === id);
  const beam = phaser.beams.find(b => b.id === beamId);
  phaser.setCoolant(Math.min(1, Math.max(0, phaser.coolant - 0.005)));
  beam.setHeat(Math.min(1, Math.max(0, beam.heat - 0.01)));
  if (phaser.coolant === 0 || beam.heat === 0) phaser.coolBeam(null);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
App.on("setPhaserBeamCount", ({ id, beamCount }) => {
  App.systems.find(s => s.id === id).setBeams(beamCount);
  pubsub.publish(
    "phasersUpdate",
    App.systems.filter(s => s.type === "Phasers")
  );
});
<|endoftext|>


<commit_before>export const up = knex => {
  const unit_price = knex.raw('(o.line_total / o.quantity)::float as unit_price')
  const quantity_received = knex
    .select(knex.raw('o.quantity - coalesce(sum(r.quantity), 0)::integer'))
    .from('shipment_line_items as r')
    .whereRaw('o.id = r.order_line_item_id')
    .as('quantity_remaining')
  const columns = [
    'o.id',
    'o.order_id',
    'o.sku',
    'o.quantity',
    'o.description',
    'o.line_total',
    'o.is_closed',
    unit_price,
    quantity_received
  ]
  const view = knex
    .select(columns)
    .from('order_line_items as o')
    .leftJoin('shipment_line_items as r', 'o.id', 'r.order_line_item_id')
  return knex.raw(`create view "order_line_items_view" as ${view}`)
}

export const down = ({ raw }) =>
  raw('drop view "order_line_items_view"')
<commit_msg>Fixes table alias in order_line_items_view.<commit_after>export const up = knex => {
  const unit_price = knex.raw('(o.line_total / o.quantity)::float as unit_price')
  const quantity_received = knex
    .select(knex.raw('o.quantity - coalesce(sum(s.quantity), 0)::integer'))
    .from('shipment_line_items as s')
    .whereRaw('o.id = s.order_line_item_id')
    .as('quantity_remaining')
  const columns = [
    'o.id',
    'o.order_id',
    'o.sku',
    'o.quantity',
    'o.description',
    'o.line_total',
    'o.is_closed',
    unit_price,
    quantity_received
  ]
  const view = knex
    .select(columns)
    .from('order_line_items as o')
    .leftJoin('shipment_line_items as s', 'o.id', 's.order_line_item_id')
  return knex.raw(`create view "order_line_items_view" as ${view}`)
}

export const down = ({ raw }) =>
  raw('drop view "order_line_items_view"')
<|endoftext|>


<commit_before>/* Copyright 2016 Streampunk Media Ltd.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

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

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

// Run a demonstration node

var NodeAPI = require('../api/NodeAPI.js');
var NodeRAMStore = require('../api/NodeRAMStore.js');
var Node = require('../model/Node.js');
var Device = require('../model/Device.js');
var Source = require('../model/Source.js');
var Flow = require('../model/Flow.js');
var Sender = require('../model/Sender.js');
var Receiver = require('../model/Receiver.js');
var formats = require('../model/Formats.js');
var transports = require('../model/Transports.js');

var node = new Node(null, null, "Punkd Up Node", "http://tereshkova.local:3000",
  "tereshkova");
var store = new NodeRAMStore(node);

var nodeAPI = new NodeAPI(3000, store);

nodeAPI.init().start();

var device = new Device(null, null, "Dat Punking Ting", null, node.id);
function regDev() {
  nodeAPI.putResource(device, function (e, d, s) {
    if (e) console.error(e);
    else {
      nodeAPI.setStore(s);
      regVideoSource();
    }
  });
}

var videoSource = new Source(null, null, "Noisy Punk", "Will you turn it down!!",
  formats.video, null, null, device.id);
function regVideoSource() {
  nodeAPI.putResource(videoSource, function (e, d, s) {
    if (e) console.error(e);
    else nodeAPI.setStore(s);
    regAudioSource();
  });
}

var audioSource = new Source(null, null, "Garish Punk", "What do you look like!!",
  formats.audio, null, null, device.id);
function regAudioSource() {
  nodeAPI.putResource(audioSource, function (e, d, s) {
    if (e) console.error(e);
    else nodeAPI.setStore(s);
    regAudioFlow();
  });
}

var audioFlow = new Flow(null, null, "Funk Punk", "Blasting at you, punk!",
  formats.audio, null, audioSource.id);
function regAudioFlow() {
  nodeAPI.putResource(audioFlow, function (e, d, s) {
    if (e) console.error(e);
    else nodeAPI.setStore(s);
    regVideoFlow();
  });
}

var videoFlow = new Flow(null, null, "Junk Punk", "You looking at me, punk?",
  formats.video, null, videoSource.id);
function regVideoFlow() {
  nodeAPI.putResource(videoFlow, function (e, d, s) {
    if (e) console.error(e);
    else nodeAPI.setStore(s);
    regAudioSender();
  });
}

var audioSender = new Sender(null, null, "Listen Up Punk",
  "Should have listened to your Mother!", audioFlow.id,
  transports.rtp_mcast, device.id, "http://tereshkova.local/audio.sdp");
function regAudioSender() {
  nodeAPI.putResource(audioSender, function (e, d, s) {
    if (e) console.error(e);
    else nodeAPI.setStore(s);
    regVideoSender();
  });
}

var videoSender = new Sender(null, null, "In Ya Face Punk",
  "What do you look like?", videoFlow.id,
  transports.rtp_mcast, device.id, "http://tereshkova.local/video.sdp");
function regVideoSender() {
  nodeAPI.putResource(videoSender, function (e, d, s) {
    if (e) console.error(e);
    else nodeAPI.setStore(s);
    regAudioReceiver();
  });
}

var audioReceiver = new Receiver(null, null, "Say It Punk?",
  "You talking to me?", formats.audio, null, null, device.id,
  transports.rtp_mcast);
function regAudioReceiver() {
  nodeAPI.putResource(audioReceiver, function (e, d, s) {
    if (e) console.error(e);
    else nodeAPI.setStore(s);
    regVideoReceiver();
  });
}

var videoReceiver = new Receiver(null, null, "Watching da Punks",
  "Looking hot, punk!", formats.video, null, null, device.id,
  transports.rtp_mcast);
function regVideoReceiver() {
  nodeAPI.putResource(videoReceiver, function (e, d, s) {
    if (e) console.error(e);
    else nodeAPI.setStore(s);
    console.log('Demo registration complete.');
  //  console.log(JSON.stringify(s));
  });
}

regDev();
<commit_msg>Changed the smoke test of the Node API to use promises.<commit_after>/* Copyright 2016 Streampunk Media Ltd.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

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

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

// Run a demonstration node

var NodeAPI = require('../api/NodeAPI.js');
var NodeRAMStore = require('../api/NodeRAMStore.js');
var Node = require('../model/Node.js');
var Device = require('../model/Device.js');
var Source = require('../model/Source.js');
var Flow = require('../model/Flow.js');
var Sender = require('../model/Sender.js');
var Receiver = require('../model/Receiver.js');
var formats = require('../model/Formats.js');
var transports = require('../model/Transports.js');

var node = new Node(null, null, "Punkd Up Node", "http://tereshkova.local:3000",
  "tereshkova");
var store = new NodeRAMStore(node);

var nodeAPI = new NodeAPI(3000, store);

nodeAPI.init().start();

var device = new Device(null, null, "Dat Punking Ting", null, node.id);

var videoSource = new Source(null, null, "Noisy Punk", "Will you turn it down!!",
  formats.video, null, null, device.id);

var audioSource = new Source(null, null, "Garish Punk", "What do you look like!!",
  formats.audio, null, null, device.id);

var audioFlow = new Flow(null, null, "Funk Punk", "Blasting at you, punk!",
  formats.audio, null, audioSource.id);

var videoFlow = new Flow(null, null, "Junk Punk", "You looking at me, punk?",
  formats.video, null, videoSource.id);

var audioSender = new Sender(null, null, "Listen Up Punk",
  "Should have listened to your Mother!", audioFlow.id,
  transports.rtp_mcast, device.id, "http://tereshkova.local/audio.sdp");

var videoSender = new Sender(null, null, "In Ya Face Punk",
  "What do you look like?", videoFlow.id,
  transports.rtp_mcast, device.id, "http://tereshkova.local/video.sdp");

var audioReceiver = new Receiver(null, null, "Say It Punk?",
  "You talking to me?", formats.audio, null, null, device.id,
  transports.rtp_mcast);

var videoReceiver = new Receiver(null, null, "Watching da Punks",
  "Looking hot, punk!", formats.video, null, null, device.id,
  transports.rtp_mcast);

function putRes(res) {
  return function () { return nodeAPI.putResource(res); };
}

nodeAPI.putResource(device)
.then(putRes(videoSource))
.then(putRes(audioSource))
.then(putRes(videoFlow))
.then(putRes(audioFlow))
.then(putRes(videoSender))
.then(putRes(audioSender))
.then(putRes(videoReceiver))
.then(putRes(audioSender))
.catch(console.error.bind(null, 'Failed to register resources:'))
.done(function() { console.log('Demo registration complete.'); });
<|endoftext|>