<commit_before>/**
 * Created by aclinton on 11/2/16.
 */
import shortId from 'shortid';
import config from '../config/env';

export default class Server {
    constructor(data) {
        this.id = shortId.generate();
        this.redirect_uri = config.APP_URL + '#/explore/' + this.id;

        //Initialize
        for(let i = 0; i < Server.fillable.length; i++){
            this[Server.fillable[i]] = '';
        }

        //Fill in any that caller says to
        for(let key in data){
            if(Server.fillable.indexOf(key) > -1){
                this[key] = data[key];
            }
        }
    }

    static get fillable() {
        return [
            'name',
            'client_id',
            'client_secret',
            'access_token',
            'auth_endpoint',
            'token_endpoint'
        ];
    }

    static get hidden() {
        return [];
    }

    static create(data) {
        return new Server(data);
    }
}
<commit_msg>force trailing slash<commit_after>/**
 * Created by aclinton on 11/2/16.
 */
import shortId from 'shortid';
import config from '../config/env';

export default class Server {
    constructor(data) {
        this.id = shortId.generate();
        let _url = config.ENV.APP_URL;

        if(_url.substring(-1) !== '/')
            _url += '/';

        this.redirect_uri = _url + '#/explore/' + this.id;

        //Initialize
        for(let i = 0; i < Server.fillable.length; i++){
            this[Server.fillable[i]] = '';
        }

        //Fill in any that caller says to
        for(let key in data){
            if(Server.fillable.indexOf(key) > -1){
                this[key] = data[key];
            }
        }
    }

    static get fillable() {
        return [
            'name',
            'client_id',
            'client_secret',
            'access_token',
            'auth_endpoint',
            'token_endpoint'
        ];
    }

    static get hidden() {
        return [];
    }

    static create(data) {
        return new Server(data);
    }
}
<|endoftext|>


<commit_before>import { FirestoreModel } from 'myfirebase'

class Thread extends FirestoreModel {

    /**
     * Create new Thread.js Instance.
     *
     * @param {object} ref
     */
    constructor (ref) {
        super(ref)
    }

    /**
     * Define required properties.
     *
     * @return array
     */
    required () {
        return []
    }
}

export default Thread;
<commit_msg>Update src/models/Thread.js<commit_after>import { FirestoreModel } from 'myfirebase'

class Thread extends FirestoreModel {

    /**
     * Create new Thread.js Instance.
     *
     * @param {object} ref
     */
    constructor (ref) {
        super(ref)
    }

    /**
     * Define required properties.
     *
     * @return array
     */
    required () {
        return []
    }

    /**
     * Set created_at.
     *
     * @param {*} timestamp
     * @return void
     */
    setCreatedAt (timestamp) {
        this.created_at = timestamp
    }
}

export default Thread;
<|endoftext|>


<commit_before>//requirements
var c     = require("../config/constantes");
var world = require("../world");
var input = require("../controllers/inputs");
var addRenderSystem = require("../modules/render");

var Player = function Player(params)
{
    this.id        = params.id;
    this.playerID  = params.playerID;
    this.gamepad   = input.gamepads[this.playerID];
    this.position  = params.position   || { x : 0, y : 0 };
    this.size      = params.size       || { width : 50, height : 50 };
    this.speed     = params.speed      || 10;
    this.dashSpeed = params.dashSpeed  || 10;

    this.context   = params.context    || world.context;
    this.color     = params.color      || "red";
    this.image     = params.image;

    this.angle     = params.startAngle || 0;

    this.run = function()
    {
        this.rotate();
        this.move();
        this.dash();
        this.shoot();
        this.drawImage();
    }
}

Player.prototype.rotate = function()
{
    var axisX = input.getAxis("RIGHT_HORIZONTAL", this.playerID);
    var axisY = input.getAxis("RIGHT_VERTICAL", this.playerID);

    if ((axisX < -c.ANALOG_DEAD || axisX > c.ANALOG_DEAD) || (axisY < -c.ANALOG_DEAD || axisY > c.ANALOG_DEAD))
    {
        this.angle = Math.atan2(input.getAxis("RIGHT_HORIZONTAL", this.playerID), input.getAxis("RIGHT_VERTICAL", this.playerID)) * -1;
    }
}

Player.prototype.move = function()
{
    var axisX = input.getAxis("LEFT_HORIZONTAL", this.playerID);
    var axisY = input.getAxis("LEFT_VERTICAL", this.playerID);

    if (axisX < -c.ANALOG_DEAD || axisX > c.ANALOG_DEAD)
    {
        //this.position.x += this.speed * ((axisX > 0) ? 1 : -1);
        this.position.x += this.speed * axisX;
    }

    if (axisY < -c.ANALOG_DEAD || axisY > c.ANALOG_DEAD)
    {
        //this.position.y += this.speed * ((axisY > 0) ? 1 : -1);
        this.position.y += this.speed * axisY;
    }
}

Player.prototype.dash = function()
{
    if (input.getKeyDown("LB"))
    {
        this.position.x += - Math.sin(this.angle - Math.PI/2) * this.dashSpeed;
        this.position.y += Math.cos(this.angle - Math.PI/2) * this.dashSpeed;
    }

    if (input.getKeyDown("RB"))
    {
        this.position.x += Math.sin(this.angle - Math.PI/2) * this.dashSpeed;
        this.position.y += - Math.cos(this.angle - Math.PI/2) * this.dashSpeed;
    }
}

addRenderSystem(Player.prototype);

module.exports = Player;<commit_msg>yolo commit de merde<commit_after>//requirements
var c     = require("../config/constantes");
var world = require("../world");
var input = require("../controllers/inputs");
var addRenderSystem = require("../modules/render");

var Player = function Player(params)
{
    this.id        = params.id;
    this.playerID  = params.playerID;
    this.gamepad   = input.gamepads[this.playerID];
    this.position  = params.position   || { x : 0, y : 0 };
    this.size      = params.size       || { width : 50, height : 50 };
    this.speed     = params.speed      || 10;
    this.dashSpeed = params.dashSpeed  || 10;

    this.context   = params.context    || world.context;
    this.color     = params.color      || "red";
    this.image     = params.image;

    this.angle     = params.startAngle || 0;

    this.run = function()
    {
        this.rotate();
        this.move();
        this.dash();
        this.shoot();
        this.drawImage();
    }
}

Player.prototype.rotate = function()
{
    var axisX = input.getAxis("RIGHT_HORIZONTAL", this.playerID);
    var axisY = input.getAxis("RIGHT_VERTICAL", this.playerID);

    if ((axisX < -c.ANALOG_DEAD || axisX > c.ANALOG_DEAD) || (axisY < -c.ANALOG_DEAD || axisY > c.ANALOG_DEAD))
    {
        this.angle = Math.atan2(input.getAxis("RIGHT_HORIZONTAL", this.playerID), input.getAxis("RIGHT_VERTICAL", this.playerID)) * -1;
    }
}

Player.prototype.move = function()
{
    var axisX = input.getAxis("LEFT_HORIZONTAL", this.playerID);
    var axisY = input.getAxis("LEFT_VERTICAL", this.playerID);

    if (axisX < -c.ANALOG_DEAD || axisX > c.ANALOG_DEAD)
    {
        //this.position.x += this.speed * ((axisX > 0) ? 1 : -1);
        this.position.x += this.speed * axisX;
    }

    if (axisY < -c.ANALOG_DEAD || axisY > c.ANALOG_DEAD)
    {
        //this.position.y += this.speed * ((axisY > 0) ? 1 : -1);
        this.position.y += this.speed * axisY;
    }
}

Player.prototype.dash = function()
{
    if (input.getKeyDown("LB"))
    {
        this.position.x += - Math.sin(this.angle - Math.PI/2) * this.dashSpeed;
        this.position.y += Math.cos(this.angle - Math.PI/2) * this.dashSpeed;
    }

    if (input.getKeyDown("RB"))
    {
        this.position.x += Math.sin(this.angle - Math.PI/2) * this.dashSpeed;
        this.position.y += - Math.cos(this.angle - Math.PI/2) * this.dashSpeed;
    }
}

Player.prototype.shoot = function()
{

}

addRenderSystem(Player.prototype);

module.exports = Player;<|endoftext|>


<commit_before>/* @flow */

import * as m                from 'mori'
import { partition, uniqBy } from '../util/mori'

import type { Seq, Seqable, Vector } from 'mori'
import type { Message } from './message'

export type Thread = Seqable<[Message, Thread]>

export {
  buildThread,
  foldThread,
  insertMessage,
  getMessages,
  singleton,
}

function buildThread(messages: Seqable<Message>): Thread {
  return m.reduce(insertMessage, singleton(m.first(messages)), m.rest(messages))
}

function singleton(message: Message): Thread {
  return m.vector([message, m.vector()])
}

function insertMessage(thread: Thread, message: Message): Thread {
  const msgs = uniqBy(
    m => m.messageId,
    m.concat(getMessages(thread), [message])
  )
  let [toplevel, replies] = partition(msg => (
    !m.some(m => ancestorOf(msg, m), msgs)
  ), msgs)
  return m.map(msg => assembleTree(msg, replies), toplevel)
}

function assembleTree(message: Message, messages: Seqable<Message>): [Message, Thread] {
  const descendents = m.filter(msg => msg !== message && ancestorOf(msg, message), messages)
  let [replies, subreplies] = partition(msg => (
    !m.some(m => ancestorOf(msg, m), descendents)
  ), descendents)
  const subthread = m.map(msg => assembleTree(msg, subreplies), replies)
  return [message, sortReplies(subthread)]
}

function getMessages(thread: Thread): Seq<Message> {
  const allMsgs = m.mapcat(([msg, subthread]) => m.cons(msg, getMessages(subthread)))
  return m.sortBy(msg => msg.receivedDate, allMsgs)
}

function parentOf(msg: Message, msg_: Message): boolean {
  return !!msg.inReplyTo && !!m.some(ref => ref === msg_.messageId, msg.inReplyTo)
}

function ancestorOf(msg: Message, msg_: Message): boolean {
  return !!msg.references && !!m.some(ref => ref === msg_.messageId, msg.references)
}

function hasReferences(message: Message): boolean {
  return !!message.references && !m.isEmpty(message.references)
}

function sortReplies(replies: Thread): Thread {
  return m.sortBy(([msg, _]) => msg.receivedDate, replies)
}

function foldThread<T>(reducer: (accum: T, msg: Message) => T, init: T, thread: Thread): T {
  return m.reduce(reducer, init, getMessages(thread))
}
<commit_msg>Add missing collection argument to a `mapcat` call in `getMessages`<commit_after>/* @flow */

import * as m                from 'mori'
import { partition, uniqBy } from '../util/mori'

import type { Seq, Seqable, Vector } from 'mori'
import type { Message } from './message'

export type Thread = Seqable<[Message, Thread]>

export {
  buildThread,
  foldThread,
  insertMessage,
  getMessages,
  singleton,
}

function buildThread(messages: Seqable<Message>): Thread {
  return m.reduce(insertMessage, singleton(m.first(messages)), m.rest(messages))
}

function singleton(message: Message): Thread {
  return m.vector([message, m.vector()])
}

function insertMessage(thread: Thread, message: Message): Thread {
  const msgs = uniqBy(
    m => m.messageId,
    m.concat(getMessages(thread), [message])
  )
  let [toplevel, replies] = partition(msg => (
    !m.some(m => ancestorOf(msg, m), msgs)
  ), msgs)
  return m.map(msg => assembleTree(msg, replies), toplevel)
}

function assembleTree(message: Message, messages: Seqable<Message>): [Message, Thread] {
  const descendents = m.filter(msg => msg !== message && ancestorOf(msg, message), messages)
  let [replies, subreplies] = partition(msg => (
    !m.some(m => ancestorOf(msg, m), descendents)
  ), descendents)
  const subthread = m.map(msg => assembleTree(msg, subreplies), replies)
  return [message, sortReplies(subthread)]
}

function getMessages(thread: Thread): Seq<Message> {
  const allMsgs = m.mapcat(([msg, subthread]) => m.cons(msg, getMessages(subthread)), thread)
  return m.sortBy(msg => msg.receivedDate, allMsgs)
}

function parentOf(msg: Message, msg_: Message): boolean {
  return !!msg.inReplyTo && !!m.some(ref => ref === msg_.messageId, msg.inReplyTo)
}

function ancestorOf(msg: Message, msg_: Message): boolean {
  return !!msg.references && !!m.some(ref => ref === msg_.messageId, msg.references)
}

function hasReferences(message: Message): boolean {
  return !!message.references && !m.isEmpty(message.references)
}

function sortReplies(replies: Thread): Thread {
  return m.sortBy(([msg, _]) => msg.receivedDate, replies)
}

function foldThread<T>(reducer: (accum: T, msg: Message) => T, init: T, thread: Thread): T {
  return m.reduce(reducer, init, getMessages(thread))
}
<|endoftext|>


<commit_before>// index.js
// ========

/* Copyright  2014 Yahoo Inc.
 * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
 */

require([
  'core/utils',
  'API/API'
], function(utils, API) {
  // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, and plain browser loading
  if (typeof define === 'function' && define.amd) {
    define([], function() {
      return API;
    });
  } else if (typeof exports !== 'undefined') {
    module.exports = API;
  } else {
    window.gifshot = API;
  }
});<commit_msg>Removed index.js utils dependency<commit_after>// index.js
// ========

/* Copyright  2014 Yahoo Inc.
 * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
 */

require([
  'API/API'
], function(API) {
  // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, and plain browser loading
  if (typeof define === 'function' && define.amd) {
    define([], function() {
      return API;
    });
  } else if (typeof exports !== 'undefined') {
    module.exports = API;
  } else {
    window.gifshot = API;
  }
});<|endoftext|>


<commit_before>// gifshot.js
define(['util', 'videoStream'], function(util, videoStream) {
	videoStream.startVideoStreaming(function(cameraStream, videoElement, width, height) {

		var canvas = document.createElement("canvas");

		if(!util.isCanvasSupported()){
				if(isConsoleSupported()){
						console.log("ERROR: Canvas not supported");
				}
				return;
		}

		videoElement.onclick = snapShot;
		document.body.appendChild(videoElement);

		function snapShot(){

			if (cameraStream) {
				canvas.width = video.videoWidth;
				canvas.height = video.videoHeight;
				ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
				images.push(canvas.toDataURL('image/gif'));
			}

		}

	});
});
<commit_msg>util -> utils<commit_after>// gifshot.js
define(['utils', 'videoStream'], function(util, videoStream) {
	videoStream.startVideoStreaming(function(cameraStream, videoElement, width, height) {

		var canvas = document.createElement("canvas");

		if(!util.isCanvasSupported()){
				if(isConsoleSupported()){
						console.log("ERROR: Canvas not supported");
				}
				return;
		}

		videoElement.onclick = snapShot;
		document.body.appendChild(videoElement);

		function snapShot(){

			if (cameraStream) {
				canvas.width = video.videoWidth;
				canvas.height = video.videoHeight;
				ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
				images.push(canvas.toDataURL('image/gif'));
			}

		}

	});
});
<|endoftext|>


<commit_before>var syn = require('./synthetic');
require('./mouse');

if (!document.body) {
	syn.schedule(function () {
		checkSupport(syn);
	}, 1);
} else {
	window.__synthTest = function () {
		syn.support.linkHrefJS = true;
	};

	var div = document.createElement("div"),
		checkbox, submit, form, select;

	div.innerHTML = "<form id='outer'>" + "<input name='checkbox' type='checkbox'/>" + "<input name='radio' type='radio' />" + "<input type='submit' name='submitter'/>" + "<input type='input' name='inputter'/>" + "<input name='one'>" + "<input name='two'/>" + "" + "<select><option></option></select>" + "</form>";
	document.documentElement.appendChild(div);
	form = div.firstChild;
	checkbox = form.childNodes[0];
	submit = form.childNodes[2];
	select = form.getElementsByTagName('select')[0];

	//trigger click for linkHrefJS support, childNodes[6] === anchor
	syn.trigger(form.childNodes[6], 'click', {});

	checkbox.checked = false;
	checkbox.onchange = function () {
		syn.support.clickChanges = true;
	};

	syn.trigger(checkbox, "click", {});
	syn.support.clickChecks = checkbox.checked;

	checkbox.checked = false;

	syn.trigger(checkbox, "change", {});

	syn.support.changeChecks = checkbox.checked;

	form.onsubmit = function (ev) {
		if (ev.preventDefault) {
			ev.preventDefault();
		}
		syn.support.clickSubmits = true;
		return false;
	};
	syn.trigger(submit, "click", {});

	form.childNodes[1].onchange = function () {
		syn.support.radioClickChanges = true;
	};
	syn.trigger(form.childNodes[1], "click", {});

	syn.bind(div, 'click', function onclick() {
		syn.support.optionClickBubbles = true;
		syn.unbind(div, 'click', onclick);
	});
	syn.trigger(select.firstChild, "click", {});

	syn.support.changeBubbles = syn.eventSupported('change');

	//test if mousedown followed by mouseup causes click (opera), make sure there are no clicks after this
	div.onclick = function () {
		syn.support.mouseDownUpClicks = true;
	};
	syn.trigger(div, "mousedown", {});
	syn.trigger(div, "mouseup", {});

	document.documentElement.removeChild(div);

	//check stuff
	syn.support.ready++;
}

<commit_msg>mouse.support.js: Fix scheduled execution in case of no document.body.<commit_after>var syn = require('./synthetic');
require('./mouse');

(function checkSupport() {
	if (!document.body) {
		return syn.schedule(checkSupport, 1);
	}
	window.__synthTest = function () {
		syn.support.linkHrefJS = true;
	};

	var div = document.createElement("div"),
		checkbox, submit, form, select;

	div.innerHTML = "<form id='outer'>" + "<input name='checkbox' type='checkbox'/>" + "<input name='radio' type='radio' />" + "<input type='submit' name='submitter'/>" + "<input type='input' name='inputter'/>" + "<input name='one'>" + "<input name='two'/>" + "" + "<select><option></option></select>" + "</form>";
	document.documentElement.appendChild(div);
	form = div.firstChild;
	checkbox = form.childNodes[0];
	submit = form.childNodes[2];
	select = form.getElementsByTagName('select')[0];

	//trigger click for linkHrefJS support, childNodes[6] === anchor
	syn.trigger(form.childNodes[6], 'click', {});

	checkbox.checked = false;
	checkbox.onchange = function () {
		syn.support.clickChanges = true;
	};

	syn.trigger(checkbox, "click", {});
	syn.support.clickChecks = checkbox.checked;

	checkbox.checked = false;

	syn.trigger(checkbox, "change", {});

	syn.support.changeChecks = checkbox.checked;

	form.onsubmit = function (ev) {
		if (ev.preventDefault) {
			ev.preventDefault();
		}
		syn.support.clickSubmits = true;
		return false;
	};
	syn.trigger(submit, "click", {});

	form.childNodes[1].onchange = function () {
		syn.support.radioClickChanges = true;
	};
	syn.trigger(form.childNodes[1], "click", {});

	syn.bind(div, 'click', function onclick() {
		syn.support.optionClickBubbles = true;
		syn.unbind(div, 'click', onclick);
	});
	syn.trigger(select.firstChild, "click", {});

	syn.support.changeBubbles = syn.eventSupported('change');

	//test if mousedown followed by mouseup causes click (opera), make sure there are no clicks after this
	div.onclick = function () {
		syn.support.mouseDownUpClicks = true;
	};
	syn.trigger(div, "mousedown", {});
	syn.trigger(div, "mouseup", {});

	document.documentElement.removeChild(div);

	//check stuff
	syn.support.ready++;
}());

<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

const util = require('util');
const Stream = require('stream');
const ResponseBase = require('../response-base');
const { mixin } = require('../utils');

/**
 * Expose `Response`.
 */

module.exports = Response;

/**
 * Initialize a new `Response` with the given `xhr`.
 *
 *  - set flags (.ok, .error, etc)
 *  - parse header
 *
 * @param {Request} req
 * @param {Object} options
 * @constructor
 * @extends {Stream}
 * @implements {ReadableStream}
 * @api private
 */

function Response(request) {
  Stream.call(this);
  this.res = request.res;
  const { res } = this;
  this.request = request;
  this.req = request.req;
  this.text = res.text;
  this.body = res.body === undefined ? {} : res.body;
  this.files = res.files || {};
  this.buffered = request._resBuffered;
  this.headers = res.headers;
  this.header = this.headers;
  this._setStatusProperties(res.statusCode);
  this._setHeaderProperties(this.header);
  this.setEncoding = res.setEncoding.bind(res);
  res.on('data', this.emit.bind(this, 'data'));
  res.on('end', this.emit.bind(this, 'end'));
  res.on('close', this.emit.bind(this, 'close'));
  res.on('error', this.emit.bind(this, 'error'));
}

/**
 * Inherit from `Stream`.
 */

util.inherits(Response, Stream);

mixin(Response.prototype, ResponseBase.prototype);

/**
 * Implements methods of a `ReadableStream`
 */

Response.prototype.destroy = function (error) {
  this.res.destroy(error);
};

/**
 * Pause.
 */

Response.prototype.pause = function () {
  this.res.pause();
};

/**
 * Resume.
 */

Response.prototype.resume = function () {
  this.res.resume();
};

/**
 * Return an `Error` representative of this response.
 *
 * @return {Error}
 * @api public
 */

Response.prototype.toError = function () {
  const { req } = this;
  const { method } = req;
  const { path } = req;

  const message = `cannot ${method} ${path} (${this.status})`;
  const error = new Error(message);
  error.status = this.status;
  error.text = this.text;
  error.method = method;
  error.path = path;

  return error;
};

Response.prototype.setStatusProperties = function (status) {
  console.warn('In superagent 2.x setStatusProperties is a private method');
  return this._setStatusProperties(status);
};

/**
 * To json.
 *
 * @return {Object}
 * @api public
 */

Response.prototype.toJSON = function () {
  return {
    req: this.request.toJSON(),
    header: this.header,
    status: this.status,
    text: this.text
  };
};
<commit_msg>lazy access body (#1634)<commit_after>/**
 * Module dependencies.
 */

const util = require('util');
const Stream = require('stream');
const ResponseBase = require('../response-base');
const { mixin } = require('../utils');

/**
 * Expose `Response`.
 */

module.exports = Response;

/**
 * Initialize a new `Response` with the given `xhr`.
 *
 *  - set flags (.ok, .error, etc)
 *  - parse header
 *
 * @param {Request} req
 * @param {Object} options
 * @constructor
 * @extends {Stream}
 * @implements {ReadableStream}
 * @api private
 */

function Response(request) {
  Stream.call(this);
  this.res = request.res;
  const { res } = this;
  this.request = request;
  this.req = request.req;
  this.text = res.text;
  this.files = res.files || {};
  this.buffered = request._resBuffered;
  this.headers = res.headers;
  this.header = this.headers;
  this._setStatusProperties(res.statusCode);
  this._setHeaderProperties(this.header);
  this.setEncoding = res.setEncoding.bind(res);
  res.on('data', this.emit.bind(this, 'data'));
  res.on('end', this.emit.bind(this, 'end'));
  res.on('close', this.emit.bind(this, 'close'));
  res.on('error', this.emit.bind(this, 'error'));
}

// Lazy access res.body.
// https://github.com/nodejs/node/pull/39520#issuecomment-889697136
Object.defineProperty(Response.prototype, 'body', {
  get () {
    return this._body !== undefined
      ? this._body
      : this.res.body !== undefined
        ? this.res.body
        : {};
  },
  set (value) {
    this._body = value;
  }
});

/**
 * Inherit from `Stream`.
 */

util.inherits(Response, Stream);

mixin(Response.prototype, ResponseBase.prototype);

/**
 * Implements methods of a `ReadableStream`
 */

Response.prototype.destroy = function (error) {
  this.res.destroy(error);
};

/**
 * Pause.
 */

Response.prototype.pause = function () {
  this.res.pause();
};

/**
 * Resume.
 */

Response.prototype.resume = function () {
  this.res.resume();
};

/**
 * Return an `Error` representative of this response.
 *
 * @return {Error}
 * @api public
 */

Response.prototype.toError = function () {
  const { req } = this;
  const { method } = req;
  const { path } = req;

  const message = `cannot ${method} ${path} (${this.status})`;
  const error = new Error(message);
  error.status = this.status;
  error.text = this.text;
  error.method = method;
  error.path = path;

  return error;
};

Response.prototype.setStatusProperties = function (status) {
  console.warn('In superagent 2.x setStatusProperties is a private method');
  return this._setStatusProperties(status);
};

/**
 * To json.
 *
 * @return {Object}
 * @api public
 */

Response.prototype.toJSON = function () {
  return {
    req: this.request.toJSON(),
    header: this.header,
    status: this.status,
    text: this.text
  };
};
<|endoftext|>


<commit_before>// adopted from: <https://github.com/jonschlinkert/assign-value>
// Copyright (c) 2015, Jon Schlinkert. (MIT)

var isObject = require('../lang/isObject')
var extend = require('./extend')
var get = require('./get')
var set = require('./set')

function assignValue (obj, prop, value) {
  if (!isObject(obj)) {
    throw new TypeError('assignValue expects first arg to be an object')
  }

  if (typeof prop === 'undefined' && typeof value === 'undefined') {
    return obj
  }

  if (typeof value === 'undefined' && isObject(prop)) {
    return extend(obj, prop)
  }

  set(obj, prop, extend({}, get(obj, prop), value))

  return obj
}

module.exports = assignValue
<commit_msg>source file object/assign.js<commit_after>// adopted from: sindresorhus/object-assign
// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) (MIT)

var toObject = require('../lang/toObject')

var propIsEnumerable = Object.prototype.propertyIsEnumerable

function ownEnumerableKeys (obj) {
  var keys = Object.getOwnPropertyNames(obj)
  if (Object.getOwnPropertySymbols) {
    keys = keys.concat(Object.getOwnPropertySymbols(obj))
  }

  return keys.filter(function (key) {
    return propIsEnumerable.call(obj, key)
  })
}

function assign (target, source) {
  var from
  var keys
  var to = toObject(target)
  var s = 0
  var len = arguments.length

  while (++s < len) {
    from = arguments[s]
    keys = ownEnumerableKeys(Object(from))

    for (var i = 0; i < keys.length; i++) {
      to[keys[i]] = from[keys[i]]
    }
  }
  return to
}

module.exports = Object.assign || assign
<|endoftext|>


<commit_before>
/**
 * An implementation of Google Maps' MVCArray.
 * @see https://developers.google.com/maps/documentation/javascript/reference
 */

goog.provide('ol.Collection');
goog.provide('ol.CollectionEvent');
goog.provide('ol.CollectionEventType');

goog.require('goog.array');
goog.require('goog.events.Event');
goog.require('ol.Object');

/**
 * @enum {string}
 */
ol.CollectionEventType = {
  ADD: 'add',
  REMOVE: 'remove'
};

/**
 * @constructor
 * @extends {goog.events.Event}
 * @param {ol.CollectionEventType} type Type.
 * @param {*=} opt_elem Element.
 * @param {Object=} opt_target Target.
 */
ol.CollectionEvent = function(type, opt_elem, opt_target) {

  goog.base(this, type, opt_target);

  /**
   * @private
   * @type {*}
   */
  this.elem_ = opt_elem;

};
goog.inherits(ol.CollectionEvent, goog.events.Event);

/**
 * @return {*} The element to which this event pertains.
 */
ol.CollectionEvent.prototype.getElement = function() {
  return this.elem_;
};

/**
 * @enum {string}
 */
ol.CollectionProperty = {
  LENGTH: 'length'
};

/**
 * A mutable MVC Array.
 * @constructor
 * @extends {ol.Object}
 * @param {Array=} opt_array Array.
 * @todo stability experimental
 * @todo observable length {number} readonly the length of the array
 */
ol.Collection = function(opt_array) {

  goog.base(this);

  /**
   * @private
   * @type {Array.<*>}
   */
  this.array_ = opt_array || [];

  this.updateLength_();

};
goog.inherits(ol.Collection, ol.Object);

/**
 * Remove all elements from the collection.
 * @todo stability experimental
 */
ol.Collection.prototype.clear = function() {
  while (this.getLength() > 0) {
    this.pop();
  }
};

/**
 * @param {Array} arr Array.
 * @return {ol.Collection} This collection.
 * @todo stability experimental
 */
ol.Collection.prototype.extend = function(arr) {
  var i, ii;
  for (i = 0, ii = arr.length; i < ii; ++i) {
    this.push(arr[i]);
  }
  return this;
};

/**
 * Iterate over each element, calling the provided callback.
 * @param {function(this: S, T, number, Array.<T>): *} f The function to call
 *     for every element. This function takes 3 arguments (the element, the
 *     index and the array). The return value is ignored.
 * @param {S=} opt_obj The object to be used as the value of 'this' within f.
 * @template T,S
 * @todo stability experimental
 */
ol.Collection.prototype.forEach = function(f, opt_obj) {
  goog.array.forEach(this.array_, f, opt_obj);
};

/**
 * Get a reference to the underlying Array object. Warning: if the array
 * is mutated, no events will be dispatched by the collection, and the
 * collection's "length" property won't be in sync with the actual length
 * of the array.
 * @return {Array} Array.
 * @todo stability experimental
 */
ol.Collection.prototype.getArray = function() {
  return this.array_;
};

/**
 * Get the element at the provided index.
 * @param {number} index Index.
 * @return {*} Element.
 * @todo stability experimental
 */
ol.Collection.prototype.getAt = function(index) {
  return this.array_[index];
};

/**
 * Get the length of this collection.
 * @return {number} Length.
 * @todo stability experimental
 */
ol.Collection.prototype.getLength = function() {
  return /** @type {number} */ (this.get(ol.CollectionProperty.LENGTH));
};

/**
 * Insert an element at the provided index.
 * @param {number} index Index.
 * @param {*} elem Element.
 * @todo stability experimental
 */
ol.Collection.prototype.insertAt = function(index, elem) {
  goog.array.insertAt(this.array_, elem, index);
  this.updateLength_();
  this.dispatchEvent(
      new ol.CollectionEvent(ol.CollectionEventType.ADD, elem, this));
};

/**
 * Remove the last element of the collection.
 * @return {*} Element.
 * @todo stability experimental
 */
ol.Collection.prototype.pop = function() {
  return this.removeAt(this.getLength() - 1);
};

/**
 * Insert the provided element at the end of the collection.
 * @param {*} elem Element.
 * @return {number} Length.
 * @todo stability experimental
 */
ol.Collection.prototype.push = function(elem) {
  var n = this.array_.length;
  this.insertAt(n, elem);
  return n;
};

/**
 * Removes the first occurence of elem from the collection.
 * @param {*} elem Element.
 * @return {*} The removed element or undefined if elem was not found.
 * @todo stability experimental
 */
ol.Collection.prototype.remove = function(elem) {
  var arr = this.array_;
  var i, ii;
  for (i = 0, ii = arr.length; i < ii; ++i) {
    if (arr[i] === elem) {
      return this.removeAt(i);
    }
  }
  return undefined;
};

/**
 * Remove the element at the provided index.
 * @param {number} index Index.
 * @return {*} Value.
 * @todo stability experimental
 */
ol.Collection.prototype.removeAt = function(index) {
  var prev = this.array_[index];
  goog.array.removeAt(this.array_, index);
  this.updateLength_();
  this.dispatchEvent(
      new ol.CollectionEvent(ol.CollectionEventType.REMOVE, prev, this));
  return prev;
};

/**
 * Set the element at the provided index.
 * @param {number} index Index.
 * @param {*} elem Element.
 * @todo stability experimental
 */
ol.Collection.prototype.setAt = function(index, elem) {
  var n = this.getLength();
  if (index < n) {
    var prev = this.array_[index];
    this.array_[index] = elem;
    this.dispatchEvent(
        new ol.CollectionEvent(ol.CollectionEventType.REMOVE, prev, this));
    this.dispatchEvent(
        new ol.CollectionEvent(ol.CollectionEventType.ADD, elem, this));
  } else {
    var j;
    for (j = n; j < index; ++j) {
      this.insertAt(j, undefined);
    }
    this.insertAt(index, elem);
  }
};

/**
 * @private
 */
ol.Collection.prototype.updateLength_ = function() {
  this.set(ol.CollectionProperty.LENGTH, this.array_.length);
};
<commit_msg>Use opt_this instead of opt_obj in ol.Collection<commit_after>
/**
 * An implementation of Google Maps' MVCArray.
 * @see https://developers.google.com/maps/documentation/javascript/reference
 */

goog.provide('ol.Collection');
goog.provide('ol.CollectionEvent');
goog.provide('ol.CollectionEventType');

goog.require('goog.array');
goog.require('goog.events.Event');
goog.require('ol.Object');

/**
 * @enum {string}
 */
ol.CollectionEventType = {
  ADD: 'add',
  REMOVE: 'remove'
};

/**
 * @constructor
 * @extends {goog.events.Event}
 * @param {ol.CollectionEventType} type Type.
 * @param {*=} opt_elem Element.
 * @param {Object=} opt_target Target.
 */
ol.CollectionEvent = function(type, opt_elem, opt_target) {

  goog.base(this, type, opt_target);

  /**
   * @private
   * @type {*}
   */
  this.elem_ = opt_elem;

};
goog.inherits(ol.CollectionEvent, goog.events.Event);

/**
 * @return {*} The element to which this event pertains.
 */
ol.CollectionEvent.prototype.getElement = function() {
  return this.elem_;
};

/**
 * @enum {string}
 */
ol.CollectionProperty = {
  LENGTH: 'length'
};

/**
 * A mutable MVC Array.
 * @constructor
 * @extends {ol.Object}
 * @param {Array=} opt_array Array.
 * @todo stability experimental
 * @todo observable length {number} readonly the length of the array
 */
ol.Collection = function(opt_array) {

  goog.base(this);

  /**
   * @private
   * @type {Array.<*>}
   */
  this.array_ = opt_array || [];

  this.updateLength_();

};
goog.inherits(ol.Collection, ol.Object);

/**
 * Remove all elements from the collection.
 * @todo stability experimental
 */
ol.Collection.prototype.clear = function() {
  while (this.getLength() > 0) {
    this.pop();
  }
};

/**
 * @param {Array} arr Array.
 * @return {ol.Collection} This collection.
 * @todo stability experimental
 */
ol.Collection.prototype.extend = function(arr) {
  var i, ii;
  for (i = 0, ii = arr.length; i < ii; ++i) {
    this.push(arr[i]);
  }
  return this;
};

/**
 * Iterate over each element, calling the provided callback.
 * @param {function(this: S, T, number, Array.<T>): *} f The function to call
 *     for every element. This function takes 3 arguments (the element, the
 *     index and the array). The return value is ignored.
 * @param {S=} opt_this The object to use as `this` in `f`.
 * @template T,S
 * @todo stability experimental
 */
ol.Collection.prototype.forEach = function(f, opt_this) {
  goog.array.forEach(this.array_, f, opt_this);
};

/**
 * Get a reference to the underlying Array object. Warning: if the array
 * is mutated, no events will be dispatched by the collection, and the
 * collection's "length" property won't be in sync with the actual length
 * of the array.
 * @return {Array} Array.
 * @todo stability experimental
 */
ol.Collection.prototype.getArray = function() {
  return this.array_;
};

/**
 * Get the element at the provided index.
 * @param {number} index Index.
 * @return {*} Element.
 * @todo stability experimental
 */
ol.Collection.prototype.getAt = function(index) {
  return this.array_[index];
};

/**
 * Get the length of this collection.
 * @return {number} Length.
 * @todo stability experimental
 */
ol.Collection.prototype.getLength = function() {
  return /** @type {number} */ (this.get(ol.CollectionProperty.LENGTH));
};

/**
 * Insert an element at the provided index.
 * @param {number} index Index.
 * @param {*} elem Element.
 * @todo stability experimental
 */
ol.Collection.prototype.insertAt = function(index, elem) {
  goog.array.insertAt(this.array_, elem, index);
  this.updateLength_();
  this.dispatchEvent(
      new ol.CollectionEvent(ol.CollectionEventType.ADD, elem, this));
};

/**
 * Remove the last element of the collection.
 * @return {*} Element.
 * @todo stability experimental
 */
ol.Collection.prototype.pop = function() {
  return this.removeAt(this.getLength() - 1);
};

/**
 * Insert the provided element at the end of the collection.
 * @param {*} elem Element.
 * @return {number} Length.
 * @todo stability experimental
 */
ol.Collection.prototype.push = function(elem) {
  var n = this.array_.length;
  this.insertAt(n, elem);
  return n;
};

/**
 * Removes the first occurence of elem from the collection.
 * @param {*} elem Element.
 * @return {*} The removed element or undefined if elem was not found.
 * @todo stability experimental
 */
ol.Collection.prototype.remove = function(elem) {
  var arr = this.array_;
  var i, ii;
  for (i = 0, ii = arr.length; i < ii; ++i) {
    if (arr[i] === elem) {
      return this.removeAt(i);
    }
  }
  return undefined;
};

/**
 * Remove the element at the provided index.
 * @param {number} index Index.
 * @return {*} Value.
 * @todo stability experimental
 */
ol.Collection.prototype.removeAt = function(index) {
  var prev = this.array_[index];
  goog.array.removeAt(this.array_, index);
  this.updateLength_();
  this.dispatchEvent(
      new ol.CollectionEvent(ol.CollectionEventType.REMOVE, prev, this));
  return prev;
};

/**
 * Set the element at the provided index.
 * @param {number} index Index.
 * @param {*} elem Element.
 * @todo stability experimental
 */
ol.Collection.prototype.setAt = function(index, elem) {
  var n = this.getLength();
  if (index < n) {
    var prev = this.array_[index];
    this.array_[index] = elem;
    this.dispatchEvent(
        new ol.CollectionEvent(ol.CollectionEventType.REMOVE, prev, this));
    this.dispatchEvent(
        new ol.CollectionEvent(ol.CollectionEventType.ADD, elem, this));
  } else {
    var j;
    for (j = n; j < index; ++j) {
      this.insertAt(j, undefined);
    }
    this.insertAt(index, elem);
  }
};

/**
 * @private
 */
ol.Collection.prototype.updateLength_ = function() {
  this.set(ol.CollectionProperty.LENGTH, this.array_.length);
};
<|endoftext|>


<commit_before>// Plany - ZUT Online Parsing Script

var nextTerm = JSON.parse(sessionStorage["nextTerm"] || false);
var isPrevious = JSON.parse(sessionStorage["isPrevious"] || false);
var nextData = sessionStorage["nextData"] || null;
var goBack = JSON.parse(sessionStorage["goBack"] || false);

function browserGoBack() {
    window.history.back();
}

function loadPrevious() {
    var previousButton = document.getElementById("ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_butP");
    previousButton.checked = true;
    previousButton.click();
}

function parseContent(){
    var location = window.location.href;

    var user = document.getElementsByClassName("who_is_logged_in")[0];

    if (user != null){
        window.webkit.messageHandlers.canStartLoading.postMessage("");

        if (location.includes("PodzGodz")) {

            if (goBack) {
                sessionStorage["goBack"] = false;
            }

            var term = document.getElementById('ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_rbJak_2');
            var termValue = term.getAttribute('checked');

            if (termValue){

                var scheduleTable = document.getElementById("ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_dgDane");

                if (scheduleTable) {

                    if (nextTerm) {
                        if (window.webkit.messageHandlers.hasOwnProperty("preprintReport")) {
                            window.webkit.messageHandlers.preprintReport.postMessage(document.documentElement.outerHTML);

                        }

                        if (!isPrevious) {
                            if (scheduleTable.getElementsByTagName("tr").length < 30) {
                                sessionStorage["goBack"] = true;
                            }

                        }

                        var printButton = document.getElementById('ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_btDrukuj');
                        var click = printButton.getAttribute('onclick');
                        var beginLocationIndex = click.indexOf('\'');
                        var endLocationIndex = click.lastIndexOf('\'');
                        var printUrl = click.substring(beginLocationIndex + 1,endLocationIndex);
                        window.location.href = printUrl;

                    } else {

                        sessionStorage["nextTerm"] = true;
                        var nextButton = document.getElementById("ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_butN");
                        nextButton.checked = true;
                        nextButton.click();
                    }

                } else {

                    if (nextTerm) {
                        sessionStorage["isPrevious"] = true;
                        loadPrevious();

                    } else {
                        window.webkit.messageHandlers.noData.postMessage("");
                    }
                }
            }else {

                term.checked = true;
                term.onclick();

            }
        }else {
                window.location.href = 'https://edziekanat.zut.edu.pl/WU/PodzGodzin.aspx';
        }
    }else {

        if (location.includes("PodzGodzDruk")){

            var table = document.getElementsByTagName("table")[0];
            var tbody = table.getElementsByTagName("tbody")[0];
            var rows = tbody.getElementsByTagName("tr");
            rows[0].remove();
            var currentElement = {};
            var currentLessons = [];
            var collectedElements = [];
            for(var i = 0; i < rows.length; i++) {
                var currentRow = rows[i];
                var ths = currentRow.getElementsByTagName("th");
                if (ths.length > 0) {
                    if (currentElement.hasOwnProperty("date")) {

                        currentElement["lessons"] = currentLessons;
                        currentLessons = [];
                        collectedElements.push(currentElement);
                        currentElement = {};
                    }
                    var th = ths[0];
                    var keyValues = th.textContent.split(",");
                    keyValues = keyValues.map(function (element) {
                                              return element.trim();
                                              });
                    if (keyValues.length === 2) {
                        currentElement["date"] = keyValues[0];
                        currentElement["dayName"] = keyValues[1];
                    }
                } else {
                    if (currentElement.hasOwnProperty("date")) {
                        var tds = [].slice.call(currentRow.getElementsByTagName("td"));
                        var currentLesson = {};
                        tds.forEach(function (element, index) {
                                    var content = element.textContent;
                                    switch (index) {
                                    case 2:
                                    currentLesson["fromHour"] = content; break;
                                    case 3:
                                    currentLesson["tillHour"] = content; break;
                                    case 4:
                                    currentLesson["subject"] = content; break;
                                    case 5:
                                    currentLesson["teacher"] = content; break;
                                    case 6:
                                    currentLesson["classroom"] = content; break;
                                    case 8:
                                    currentLesson["type"] = content; break;
                                    default:
                                    break;

                                    }
                        });
                        currentLessons.push(currentLesson);

                    }

                }
            }
            // last day
            if (currentElement.hasOwnProperty("date") && currentLessons.length !== 0) {
                currentElement["lessons"] = currentLessons;
                currentLessons = [];
                collectedElements.push(currentElement);
                currentElement = {};
            }

            if (nextData) {
                let next = JSON.parse(nextData);
                for( key in next) {
                    collectedElements.push(next[key]);
                }

            }
            let data = JSON.stringify(collectedElements);

            if (goBack) {
                sessionStorage["nextData"] = data;
                sessionStorage["isPrevious"] = true;
                browserGoBack();
                return;
            }

            if (window.webkit.messageHandlers.hasOwnProperty("passDataMessageAndReport")) {
                var prepare = {
                    "raw": document.documentElement.outerHTML,
                    "data": data
                };
                var str = JSON.stringify(prepare);
                window.webkit.messageHandlers.passDataMessageAndReport.postMessage(str);
            } else {
                window.webkit.messageHandlers.passDataMessage.postMessage(data);
            }

        }
    }

}

window.onload = function(){
    parseContent();
}
<commit_msg>Update online_parser.js<commit_after>// Plany - ZUT Online Parsing Script

var nextTerm = JSON.parse(sessionStorage["nextTerm"] || false);
var isPrevious = JSON.parse(sessionStorage["isPrevious"] || false);
var nextData = sessionStorage["nextData"] || null;
var goBack = JSON.parse(sessionStorage["goBack"] || false);
var validationFlag = JSON.parse(sessionStorage["validation"] || false);
var onlyLoginFlag = JSON.parse(sessionStorage["onlyLogin"] || false);

function browserGoBack() {
    window.history.back();
}

function loadPrevious() {
    var previousButton = document.getElementById("ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_butP");
    previousButton.checked = true;
    previousButton.click();
}

function parseContent(){

    var location = window.location.href;

    var userElement = document.getElementsByClassName("who_is_logged_in");

    if (userElement.length > 0){
        if (onlyLoginFlag) {
            if (window.webkit.messageHandlers.hasOwnProperty("didFinishLogin")) {
                window.webkit.messageHandlers.didFinishLogin.postMessage("");
            }
            return;
        }
        sessionStorage["validation"] = false;
        window.webkit.messageHandlers.canStartLoading.postMessage("");

        if (location.includes("PodzGodz")) {

            if (goBack) {
                sessionStorage["goBack"] = false;
            }

            var term = document.getElementById('ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_rbJak_2');
            var termValue = term.getAttribute('checked');

            if (termValue){

                var scheduleTable = document.getElementById("ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_dgDane");

                if (scheduleTable) {

                    if (nextTerm) {
                        if (window.webkit.messageHandlers.hasOwnProperty("preprintReport")) {
                            window.webkit.messageHandlers.preprintReport.postMessage(document.documentElement.outerHTML);

                        }

                        if (!isPrevious) {
                            if (scheduleTable.getElementsByTagName("tr").length < 30) {
                                sessionStorage["goBack"] = true;
                            }

                        }

                        var printButton = document.getElementById('ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_btDrukuj');
                        var click = printButton.getAttribute('onclick');
                        var beginLocationIndex = click.indexOf('\'');
                        var endLocationIndex = click.lastIndexOf('\'');
                        var printUrl = click.substring(beginLocationIndex + 1,endLocationIndex);
                        window.location.href = printUrl;

                    } else {

                        sessionStorage["nextTerm"] = true;
                        var nextButton = document.getElementById("ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_butN");
                        nextButton.checked = true;
                        nextButton.click();
                    }

                } else {

                    if (nextTerm) {
                        sessionStorage["isPrevious"] = true;
                        loadPrevious();

                    } else {
                        window.webkit.messageHandlers.noData.postMessage("");
                    }
                }
            }else {

                term.checked = true;
                term.onclick();

            }
        }else {
                window.location.href = 'https://edziekanat.zut.edu.pl/WU/PodzGodzin.aspx';
        }
    } else {
        if (location.includes("PodzGodzDruk")){
            if (onlyLoginFlag) {
                return;
            }
            var table = document.getElementsByTagName("table")[0];
            var tbody = table.getElementsByTagName("tbody")[0];
            var rows = tbody.getElementsByTagName("tr");
            rows[0].remove();
            var currentElement = {};
            var currentLessons = [];
            var collectedElements = [];
            for(var i = 0; i < rows.length; i++) {
                var currentRow = rows[i];
                var ths = currentRow.getElementsByTagName("th");
                if (ths.length > 0) {
                    if (currentElement.hasOwnProperty("date")) {

                        currentElement["lessons"] = currentLessons;
                        currentLessons = [];
                        collectedElements.push(currentElement);
                        currentElement = {};
                    }
                    var th = ths[0];
                    var keyValues = th.textContent.split(",");
                    keyValues = keyValues.map(function (element) {
                                              return element.trim();
                                              });
                    if (keyValues.length === 2) {
                        currentElement["date"] = keyValues[0];
                        currentElement["dayName"] = keyValues[1];
                    }
                } else {
                    if (currentElement.hasOwnProperty("date")) {
                        var tds = [].slice.call(currentRow.getElementsByTagName("td"));
                        var currentLesson = {};
                        tds.forEach(function (element, index) {
                                    var content = element.textContent;
                                    switch (index) {
                                    case 2:
                                    currentLesson["fromHour"] = content; break;
                                    case 3:
                                    currentLesson["tillHour"] = content; break;
                                    case 4:
                                    currentLesson["subject"] = content; break;
                                    case 5:
                                    currentLesson["teacher"] = content; break;
                                    case 6:
                                    currentLesson["classroom"] = content; break;
                                    case 8:
                                    currentLesson["type"] = content; break;
                                    default:
                                    break;

                                    }
                        });
                        currentLessons.push(currentLesson);

                    }

                }
            }
             // last day
            if (currentElement.hasOwnProperty("date") && currentLessons.length !== 0) {
                currentElement["lessons"] = currentLessons;
                currentLessons = [];
                collectedElements.push(currentElement);
                currentElement = {};
            }

            if (nextData) {
                let next = JSON.parse(nextData);
                for( key in next) {
                    collectedElements.push(next[key]);
                }

            }
            let data = JSON.stringify(collectedElements);

            if (goBack) {
                sessionStorage["nextData"] = data;
                sessionStorage["isPrevious"] = true;
                browserGoBack();
                return;
            }

            if (window.webkit.messageHandlers.hasOwnProperty("passDataMessageAndReport")) {
                var prepare = {
                    "raw": document.documentElement.outerHTML,
                    "data": data
                };
                var str = JSON.stringify(prepare);
                window.webkit.messageHandlers.passDataMessageAndReport.postMessage(str);
            } else {
                window.webkit.messageHandlers.passDataMessage.postMessage(data);
            }

        } else {
            if (validationFlag) {
                let loginRes = document.getElementById("ctl00_ctl00_ContentPlaceHolder_MiddleContentPlaceHolder_lblMessage");
                var message = null;
                if (loginRes) {
                    if (window.getComputedStyle(loginRes).display !== "none") {
                        message = "failed";
                    }
                } else {
                    message = "error";
                }
                if (window.webkit.messageHandlers.hasOwnProperty("loginFailure")) {
                    window.webkit.messageHandlers.loginFailure.postMessage(message);
                }
            }
        }
    }

}
function online_loginUser(login, password, onlyLogin) {
    // try login fields
    let loginInput = document.getElementById("ctl00_ctl00_ContentPlaceHolder_MiddleContentPlaceHolder_txtIdent");
    let passInput =  document.getElementById("ctl00_ctl00_ContentPlaceHolder_MiddleContentPlaceHolder_txtHaslo");
    let loginBtn = document.getElementById("ctl00_ctl00_ContentPlaceHolder_MiddleContentPlaceHolder_butLoguj");
    if (loginInput && passInput && loginBtn) {
        loginInput.value = login;
        passInput.value = password;
        sessionStorage["validation"] = true;
        loginBtn.click();
    }
    sessionStorage["onlyLogin"] = onlyLogin === 0 ? false : true;
}
window.onload = function(){
    parseContent();
}
<|endoftext|>


<commit_before>process.env.NODE_ENV = 'test';

const chai = require('chai');
const moment = require('moment');

const should = chai.should();
const chaiHttp = require('chai-http');

var datetime = moment().unix();

chai.use(chaiHttp);

const confFile = './config/config.json';
// load the config file
const nconf = require('nconf');

const passportStub = require('passport-stub');
var server = require('../app');
const db = require('../knex/knex.js');
// This needs to be sorted out, use a different config file when testing?

passportStub.install(server);

nconf.file({ file: confFile });
nconf.load();
// set required settings in config file

beforeEach(() => db.migrate.rollback().then(() => db.migrate.latest().then(() => db.seed.run())));
afterEach(() => db.migrate.rollback().then(() => passportStub.logout()));

describe('POST /api/messages', () => {
        it('should POST new message', done => {
                chai.request(server)
                        .post('/api/messages')
                        .set({
                                'X-Requested-With': 'XMLHttpRequest',
                                'User-Agent': 'CI-Test',
                                apikey: 'reallylongkeythatneedstobechanged',
                        })
                        .send({
                                address: '000000',
                                message: '!@#$%^& (This is a test message. 1a2b3c4d5e6e7f) !@#$%^&',
                                datetime,
                                source: 'CI-Test',
                        })
                        .end((err, res) => {
                                should.not.exist(err);
                                res.status.should.eql(200);
                                res.type.should.eql('text/html');
                                res.text.should.be.eql('6');
                                done();
                        });
        });
});

describe('GET /api/messages', () => {
        it('should return message id 5', done => {
                nconf.set('messages:HideCapcode', false);
                nconf.save();
                chai.request(server)
                    .get('/api/messages/5')
                    .end((err, res) => {
                                should.not.exist(err);
                                res.status.should.eql(200);
                                res.type.should.eql('application/json');
                                res.body.should.be.a('array');
                                (res.body[0]).should.have.property('id').eql(5);
                                (res.body[0]).should.have.property('address').eql('1234570');
                                (res.body[0]).should.have.property('message').eql('This is a Test Message to Address 1234570');
                                (res.body[0]).should.have.property('source').eql('Client 4');
                                done();
                    });
        });
        it('should not show capcode in hidecapcode mode if not logged in ', done => {
                nconf.set('messages:HideCapcode', true);
                nconf.save();
                chai.request(server)
                        .get('/api/messages/5')
                        .end((err, res) => {
                                    should.not.exist(err);
                                    res.status.should.eql(200);
                                    res.type.should.eql('application/json');
                                    res.body.should.be.a('array');
                                    (res.body[0]).should.have.property('id').eql(5);
                                    (res.body[0]).should.have.property('message').eql('This is a Test Message to Address 1234570');
                                    (res.body[0]).should.have.property('source').eql('Client 4');
                                    (res.body[0]).should.not.have.property('address');
                                    done();
                        });
            });

});<commit_msg>Checks<commit_after>process.env.NODE_ENV = 'test';

const chai = require('chai');
const moment = require('moment');

const should = chai.should();
const chaiHttp = require('chai-http');

var datetime = moment().unix();

chai.use(chaiHttp);

const confFile = './config/config.json';
// load the config file
const nconf = require('nconf');
nconf.file({ file: confFile });;
nconf.load();

//Force someconfigs back to default
nconf.set('messages:HideCapcode', false);
nconf.set('messages:HideSource', false);
nconf.set('messages:apiSecurity', false);
nconf.save();

const passportStub = require('passport-stub');
var server = require('../app');
const db = require('../knex/knex.js');
// This needs to be sorted out, use a different config file when testing?

passportStub.install(server);
// set required settings in config file

beforeEach(() => db.migrate.rollback().then(() => db.migrate.latest().then(() => db.seed.run())));
afterEach(() => db.migrate.rollback().then(() => passportStub.logout()));

describe('POST /api/messages', () => {
        it('should POST new message', done => {
                chai.request(server)
                        .post('/api/messages')
                        .set({
                                'X-Requested-With': 'XMLHttpRequest',
                                'User-Agent': 'CI-Test',
                                apikey: 'reallylongkeythatneedstobechanged',
                        })
                        .send({
                                address: '000000',
                                message: '!@#$%^& (This is a test message. 1a2b3c4d5e6e7f) !@#$%^&',
                                datetime,
                                source: 'CI-Test',
                        })
                        .end((err, res) => {
                                should.not.exist(err);
                                res.status.should.eql(200);
                                res.type.should.eql('text/html');
                                res.text.should.be.eql('6');
                                done();
                        });
        });
});

describe('GET /api/messages', () => {
        it('should return message id 5', done => {
               chai.request(server)
                    .get('/api/messages/5')
                    .end((err, res) => {
                                should.not.exist(err);
                                res.status.should.eql(200);
                                res.type.should.eql('application/json');
                                res.body.should.be.a('array');
                                (res.body[0]).should.have.property('id').eql(5);
                                (res.body[0]).should.have.property('address').eql('1234570');
                                (res.body[0]).should.have.property('message').eql('This is a Test Message to Address 1234570');
                                (res.body[0]).should.have.property('source').eql('Client 4');
                                done();
                    });
        });
        it('should not show capcode in hidecapcode mode if not logged in ', done => {
                nconf.set('messages:HideCapcode', true);
                nconf.save();
                chai.request(server)
                        .get('/api/messages/5')
                        .end((err, res) => {
                                    should.not.exist(err);
                                    res.status.should.eql(200);
                                    res.type.should.eql('application/json');
                                    res.body.should.be.a('array');
                                    (res.body[0]).should.have.property('id').eql(5);
                                    (res.body[0]).should.have.property('message').eql('This is a Test Message to Address 1234570');
                                    (res.body[0]).should.have.property('source').eql('Client 4');
                                    (res.body[0]).should.not.have.property('address');
                                    done();
                        });
            });

});<|endoftext|>


<commit_before>// dependencies
//
import React from 'react';
import classnames from 'classnames';
import uniqueId from 'lodash/uniqueId';
import isRegExp from 'lodash/isRegExp';
import isFunction from 'lodash/isFunction';

// @TODO pattern = function which returns true if value passes
// @TODO add different validation error messages for failing different rules
// @TODO horizontal form - label & input element widths
// @TODO permitted characters regex
// @TODO parse & format functions for onFocus & onBlur handling of values

/**
 * The TextInput component
 *
 */
class TextInput extends React.Component {
    /**
     * Construct the component instance
     * @param  {Object} props The component props
     */
    constructor(props) {
        super(props);

        // initialize the state for the component
        //
        this.state = {
            value:   props.value,
            isValid: true,
        };

        this.id = uniqueId('form-textinput-');

        // intialize the validation message for the component
        //
        this.validationMessage = props.validationMessage
            || `${this.props.description} is required`;

        // bind `this` to the component event handlers
        //
        this.onBlur = this.onBlur.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    componentWillMount() {
        // call the `onChildValidationEvent` handler once with no error message,
        // just to ensure that the parent knows about this child
        //
        this.context.onChildValidationEvent(this.id, null);
    }

    /**
     * Handle the blur event for the input element
     * @param  {Object} event The event object
     */
    onBlur(event) {
        // get the new value
        //
        const value = event.target.value;

        // determine if it's valid
        //
        const isValid = this.validate(value);

        // set the `isValid` state
        //
        this.setState({ isValid });

        // call the `onChildValidationEvent` handler
        //
        this.context.onChildValidationEvent(this.id, isValid ? null : this.validationMessage);
    }

    /**
     * Handle the change event for the input element
     * @param  {Object} event The event object
     */
    onChange(event) {
        const value = event.target.value;

        this.setState({ value });

        if (this.props.onChange) {
            this.props.onChange(value);
        }
    }

    validate(value) {
        let isValid = true;

        if (this.props.pattern) {
            if (isRegExp(this.props.pattern)) {
                isValid = isValid && this.props.pattern.test(`${value}`);
            } else if (isFunction(this.props.pattern)) {
                isValid = isValid && this.props.pattern(value);
            }
        }

        return isValid && (!this.props.required || value);
    }

    /**
     * Render the component
     * @return {React.Element} The React element describing the component
     */
    render() {
        return (

                {this.props.label ? {this.props.label} : ''}
                <input
                    type="text"
                    id={this.id}
                    value={this.state.value}
                    className="form-control"
                    onBlur={this.onBlur}
                    onChange={this.onChange}
                />
                {!this.state.isValid
                    ? {this.validationMessage}
                    : null
                }

        );
    }
}

// set the property types for the component
// @TODO placeholder
//
TextInput.propTypes = {
    required:               React.PropTypes.bool,
    value:                  React.PropTypes.string,
    label:                  React.PropTypes.string,
    description:            React.PropTypes.string,
    validationMessage:      React.PropTypes.string,
    pattern:                (props, propName, componentName) => {
        if (props.pattern && !isRegExp(props.pattern) && !isFunction(props.pattern)) {
            return new Error(
                `Invalid prop ${propName} supplied to ${componentName}` +
                ' - should be a regular expression'
            );
        }
        return null;
    },
    onChange:               React.PropTypes.func,
    validationKey:          React.PropTypes.string,
    onChildValidationEvent: React.PropTypes.func,
};

TextInput.contextTypes = {
    onChildValidationEvent: React.PropTypes.func,
};

export default TextInput;
<commit_msg>comment cleanup<commit_after>// dependencies
//
import React from 'react';
import classnames from 'classnames';
import uniqueId from 'lodash/uniqueId';
import isRegExp from 'lodash/isRegExp';
import isFunction from 'lodash/isFunction';

// @TODO pattern = function which returns true if value passes
// @TODO add different validation error messages for failing different rules
// @TODO horizontal form - label & input element widths
// @TODO permitted characters regex
// @TODO parse & format functions for onFocus & onBlur handling of values
// @TODO placeholder

/**
 * The TextInput component
 *
 */
class TextInput extends React.Component {
    /**
     * Construct the component instance
     * @param  {Object} props The component props
     */
    constructor(props) {
        super(props);

        // initialize the state for the component
        //
        this.state = {
            value:   props.value,
            isValid: true,
        };

        // generate a unique ID for this component instance
        //
        this.id = uniqueId('form-textinput-');

        // intialize the validation message for the component
        //
        this.validationMessage = props.validationMessage
            || `${this.props.description} is required`;

        // bind `this` to the component event handlers
        //
        this.onBlur = this.onBlur.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    /**
     * Handle the "component is about to mount" event
     */
    componentWillMount() {
        // call the `onChildValidationEvent` handler once with no error message,
        // just to ensure that the parent knows about this child
        //
        this.context.onChildValidationEvent(this.id, null);
    }

    /**
     * Handle the blur event for the input element
     * @param  {Object} event The event object
     */
    onBlur(event) {
        // get the new value
        //
        const value = event.target.value;

        // determine if it's valid
        //
        const isValid = this.validate(value);

        // set the `isValid` state
        //
        this.setState({ isValid });

        // call the `onChildValidationEvent` handler
        //
        this.context.onChildValidationEvent(this.id, isValid ? null : this.validationMessage);
    }

    /**
     * Handle the change event for the input element
     * @param  {Object} event The event object
     */
    onChange(event) {
        // get the value from the event object
        //
        const value = event.target.value;

        // update the component state
        //
        this.setState({ value });

        // do we have an `onChange` handler? if so call it with the new value
        //
        if (this.props.onChange) {
            this.props.onChange(value);
        }
    }

    /**
     * Validate a value
     * @param  {String} value The value to validate
     * @return {Boolean}      True if the value is valid, false otherwise
     */
    validate(value) {
        // declare a variable to hold the result
        //
        let isValid = true;

        // do we have a pattern prop?
        //
        if (this.props.pattern) {
            // is the pattern a regex? is it a function?
            //
            if (isRegExp(this.props.pattern)) {
                // the pattern is a regex. Test the value against it
                //
                isValid = isValid && this.props.pattern.test(`${value}`);
            } else if (isFunction(this.props.pattern)) {
                // the pattern is a function. Pass the value to the function
                //
                isValid = isValid && this.props.pattern(value);
            }
        }

        return isValid && (!this.props.required || value);
    }

    /**
     * Render the component
     * @return {React.Element} The React element describing the component
     */
    render() {
        return (

                {this.props.label ? {this.props.label} : ''}
                <input
                    type="text"
                    id={this.id}
                    value={this.state.value}
                    className="form-control"
                    onBlur={this.onBlur}
                    onChange={this.onChange}
                />
                {!this.state.isValid
                    ? {this.validationMessage}
                    : null
                }

        );
    }
}

// set the property types for the component
//
TextInput.propTypes = {
    required:               React.PropTypes.bool,
    value:                  React.PropTypes.string,
    label:                  React.PropTypes.string,
    description:            React.PropTypes.string,
    validationMessage:      React.PropTypes.string,
    pattern:                (props, propName, componentName) => {
        if (props.pattern && !isRegExp(props.pattern) && !isFunction(props.pattern)) {
            return new Error(
                `Invalid prop ${propName} supplied to ${componentName}` +
                ' - should be a regular expression'
            );
        }
        return null;
    },
    onChange:               React.PropTypes.func,
    validationKey:          React.PropTypes.string,
    onChildValidationEvent: React.PropTypes.func,
};

TextInput.contextTypes = {
    onChildValidationEvent: React.PropTypes.func,
};

export default TextInput;
<|endoftext|>


<commit_before>
var mongo = require('mongodb');
var config = require('../conf');
var sntApi = require('sentiment');

    var mongoClient = mongo.MongoClient;

    var tweetsWithCoordinates = {};

    var getCoordinateViaTimeZone = false;

    var TDataObj = function (date,type,sentiment,tweet){
                        this.date = date;
                        this.type = type;
                        this.sentiment = sentiment;
                        this.tweet = tweet;
                    };

    var Coordinates = function (lat,lng){
        this.lat = lat
        this.lng = lng;
    }
    var MiniTData = function (lat, lng, topic){
        this.coordinates = new Coordinates(lat,lng);
        this.tweetCount = 0;
        this.averageSentiment = 0;
        this.topic = topic;
    }

    var startReadingStream = function (){

        // Connect to the db //strat mango db before trying to connect.
        mongoClient.connect("mongodb://"+config.ip+":27017/wardolph", function(err, db) {
          if(!err) {
            console.log("tread: We are connected to mongo db");
            var collection = db.collection(config.peer.list_name);//try feminismCoordinate for smaller set
            var timezoneCol = db.collection('timezone');
            var readyToDraw = db.collection(config.peer.list_name+'_readyToDraw');
            readyToDraw.drop();
            var timezone = null;
            var keywordDataMap = {};
            var dataCoordinateMappedSentiment = {};

            //start debugging section;
            var totalTweetCount = 1;
            collection.count(function(err, countRet) {
              totalTweetCount = countRet;
                console.log('total collections elements: '+totalTweetCount);
            });
            var currentStreamCount = 0;
            var printCompletionPercentageIntervalId = 0;
            var readyToSave = false;
            var printCompletionPercentage = function(){
              var percentage = (currentStreamCount/totalTweetCount*100);
              console.log('completed percentage % : '+ percentage);
              if(percentage >= 100 && readyToSave){
                clearInterval(printCompletionPercentageIntervalId);

                console.log("saving data");
                var size = 0;
                for(topic in keywordDataMap){
                    for(latlng in keywordDataMap[topic]){
                        var data = keywordDataMap[topic][latlng];
                        data.averageSentiment = data.averageSentiment / data.tweetCount;
                        readyToDraw.insert(data, { w: 1 }, function(err, result) { if(err)console.log("err: "+err);});
                        size++;
                    }
                }
                /*for (key in dataCoordinateMappedSentiment) {
                    var data = dataCoordinateMappedSentiment[key];
                    data.averageSentiment = data.averageSentiment / data.tweetCount;
                    //console.log(JSON.stringify(data, null, 1));
                    //TODO save data here
                    readyToDraw.insert(data, { w: 1 }, function(err, result) { if(err)console.log("err: "+err);});
                    size++;
                }*/
                console.log("data saved: "+size);
              }
            }
            printCompletionPercentageIntervalId = setInterval(printCompletionPercentage, 30000);//print percentage every 30 sec
            //end debugging section;

            var getTimeZone = function(tweet){
                var timezoneFound = null;
                for(var i=0; i<timezone.length; i++){
                    if(typeof(tweet.user.time_zone) != 'undefined' && tweet.user.time_zone!=null && tweet.user.time_zone == timezone[i].name){
                        timezoneFound = timezone[i];
                        break;
                    }
                }
                return timezoneFound;
            }

            var storeInLatLongMap = function(lat, lng, sentiment, topic){

                var latlng = lat+','+lng;
                if(typeof(keywordDataMap[topic]) == 'undefined'){
                    keywordDataMap[topic] = {};
                }
                if(typeof(keywordDataMap[topic][latlng]) == 'undefined'){
                    var miniData = new MiniTData(lat, lng, topic);
                    keywordDataMap[topic][latlng] = miniData;
                }
                var miniData = keywordDataMap[topic][latlng];
                miniData.tweetCount++;
                miniData.averageSentiment = miniData.averageSentiment + sentiment.score;
                //console.log('storing: '+topic+' '+lat+' '+lng);

                if(topic != 'all'){
                    storeInLatLongMap(lat, lng, sentiment, 'all');
                }
            }

            var filterData = config.client.filterData[config.peer.list_name];
            console.log('classifying data on: '+JSON.stringify(filterData, null, 1));
            var findTopic = function(tweet){
                var text = tweet.text;
                for (key in filterData) {
                    var filterArr = filterData[key];
                    for (var i = 0; i < filterArr.length; i++) {
                        var match = text.match(new RegExp(filterArr[i], "i"));
                        if(match) {
                            return key;
                        }
                    };
                }
                if(tweet.entities.urls.length > 0){

                    var url = tweet.entities.urls[0].expanded_url;
                    console.log("found url: "+url);
                    for (key in filterData) {
                        var filterArr = filterData[key];
                        for (var i = 0; i < filterArr.length; i++) {
                            var match = url.match(new RegExp(filterArr[i], "i"));
                            if(match) {
                                console.log("url topic: "+key);
                                return key;
                            }
                        };
                    }
                }
                return 'all';
            }

            var initStream = function(){
                var stream = collection.find().stream();

                var firststream = true;
                stream.on("data", function(item) {

                    //for (key in item) {

                      //  if (key!='_id' && item.hasOwnProperty(key)) {
                            //var sentiment = item[key].sentiment;
                            //var item2 = item;//item[key];
                        if(typeof(item.tweet)!='undefined' && typeof(item.tweet.text)!='undefined'){
                            var tweet = item.tweet;
                            var sentiment = sntApi(item.tweet.text);
                            var topic = findTopic(item.tweet);
                            if(tweet!=null && typeof(tweet)!='undefined' && sentiment.words.length>0){
                                if( tweet.coordinates!=null && typeof(tweet.coordinates) != 'undefined'){
                                    var lat = tweet.coordinates.coordinates[1];
                                    var lng = tweet.coordinates.coordinates[0];

                                    storeInLatLongMap(lat,lng,sentiment,topic);
                                    //console.log('jzTest1 sentiment: '+sentiment.score+' tweet:  '+tweet.text);
                                }
                                else{
                                    var timezoneFound = getTimeZone(tweet);
                                    if(timezoneFound!=null){
                                        var lat = timezoneFound.lat;
                                        var lng = timezoneFound.lng;

                                        storeInLatLongMap(lat,lng,sentiment,topic);
                                        //console.log('jzTest1 sentiment: '+sentiment.score+' tweet:  '+tweet.text);
                                    }
                                }
                            }
                        }
                        //}
                    //}//end for loop

                    currentStreamCount++;//only for debugging

                });

                stream.on("end", function() {//check if all processing complete before storing.
                    readyToSave = true;

                });
            }

            timezoneCol.find().toArray(function(err, items) {
                //console.log(items);
                timezone = items;
                initStream();
            });

            /*collection.find().toArray(function(err, items) {
                //console.log(items);
                tweetsWithCoordinates = items;
            });*/

            //to decript json date object
            // var jsonDate = "2011-05-26T07:56:00.123Z";
            // var then = new Date(jsonDate);

          }
          else{
              console.log("mongodb error connecting: "+err);
          }
        });

    };

    startReadingStream();

<commit_msg>commented debug print url<commit_after>
var mongo = require('mongodb');
var config = require('../conf');
var sntApi = require('sentiment');

    var mongoClient = mongo.MongoClient;

    var tweetsWithCoordinates = {};

    var getCoordinateViaTimeZone = false;

    var TDataObj = function (date,type,sentiment,tweet){
                        this.date = date;
                        this.type = type;
                        this.sentiment = sentiment;
                        this.tweet = tweet;
                    };

    var Coordinates = function (lat,lng){
        this.lat = lat
        this.lng = lng;
    }
    var MiniTData = function (lat, lng, topic){
        this.coordinates = new Coordinates(lat,lng);
        this.tweetCount = 0;
        this.averageSentiment = 0;
        this.topic = topic;
    }

    var startReadingStream = function (){

        // Connect to the db //strat mango db before trying to connect.
        mongoClient.connect("mongodb://"+config.ip+":27017/wardolph", function(err, db) {
          if(!err) {
            console.log("tread: We are connected to mongo db");
            var collection = db.collection(config.peer.list_name);//try feminismCoordinate for smaller set
            var timezoneCol = db.collection('timezone');
            var readyToDraw = db.collection(config.peer.list_name+'_readyToDraw');
            readyToDraw.drop();
            var timezone = null;
            var keywordDataMap = {};
            var dataCoordinateMappedSentiment = {};

            //start debugging section;
            var totalTweetCount = 1;
            collection.count(function(err, countRet) {
              totalTweetCount = countRet;
                console.log('total collections elements: '+totalTweetCount);
            });
            var currentStreamCount = 0;
            var printCompletionPercentageIntervalId = 0;
            var readyToSave = false;
            var printCompletionPercentage = function(){
              var percentage = (currentStreamCount/totalTweetCount*100);
              console.log('completed percentage % : '+ percentage);
              if(percentage >= 100 && readyToSave){
                clearInterval(printCompletionPercentageIntervalId);

                console.log("saving data");
                var size = 0;
                for(topic in keywordDataMap){
                    for(latlng in keywordDataMap[topic]){
                        var data = keywordDataMap[topic][latlng];
                        data.averageSentiment = data.averageSentiment / data.tweetCount;
                        readyToDraw.insert(data, { w: 1 }, function(err, result) { if(err)console.log("err: "+err);});
                        size++;
                    }
                }
                /*for (key in dataCoordinateMappedSentiment) {
                    var data = dataCoordinateMappedSentiment[key];
                    data.averageSentiment = data.averageSentiment / data.tweetCount;
                    //console.log(JSON.stringify(data, null, 1));
                    //TODO save data here
                    readyToDraw.insert(data, { w: 1 }, function(err, result) { if(err)console.log("err: "+err);});
                    size++;
                }*/
                console.log("data saved: "+size);
              }
            }
            printCompletionPercentageIntervalId = setInterval(printCompletionPercentage, 30000);//print percentage every 30 sec
            //end debugging section;

            var getTimeZone = function(tweet){
                var timezoneFound = null;
                for(var i=0; i<timezone.length; i++){
                    if(typeof(tweet.user.time_zone) != 'undefined' && tweet.user.time_zone!=null && tweet.user.time_zone == timezone[i].name){
                        timezoneFound = timezone[i];
                        break;
                    }
                }
                return timezoneFound;
            }

            var storeInLatLongMap = function(lat, lng, sentiment, topic){

                var latlng = lat+','+lng;
                if(typeof(keywordDataMap[topic]) == 'undefined'){
                    keywordDataMap[topic] = {};
                }
                if(typeof(keywordDataMap[topic][latlng]) == 'undefined'){
                    var miniData = new MiniTData(lat, lng, topic);
                    keywordDataMap[topic][latlng] = miniData;
                }
                var miniData = keywordDataMap[topic][latlng];
                miniData.tweetCount++;
                miniData.averageSentiment = miniData.averageSentiment + sentiment.score;
                //console.log('storing: '+topic+' '+lat+' '+lng);

                if(topic != 'all'){
                    storeInLatLongMap(lat, lng, sentiment, 'all');
                }
            }

            var filterData = config.client.filterData[config.peer.list_name];
            console.log('classifying data on: '+JSON.stringify(filterData, null, 1));
            var findTopic = function(tweet){
                var text = tweet.text;
                for (key in filterData) {
                    var filterArr = filterData[key];
                    for (var i = 0; i < filterArr.length; i++) {
                        var match = text.match(new RegExp(filterArr[i], "i"));
                        if(match) {
                            return key;
                        }
                    };
                }
                if(tweet.entities.urls.length > 0){

                    var url = tweet.entities.urls[0].expanded_url;
                    //console.log("found url: "+url);
                    for (key in filterData) {
                        var filterArr = filterData[key];
                        for (var i = 0; i < filterArr.length; i++) {
                            var match = url.match(new RegExp(filterArr[i], "i"));
                            if(match) {
                                console.log("url topic: "+key);
                                return key;
                            }
                        };
                    }
                }
                return 'all';
            }

            var initStream = function(){
                var stream = collection.find().stream();

                var firststream = true;
                stream.on("data", function(item) {

                    //for (key in item) {

                      //  if (key!='_id' && item.hasOwnProperty(key)) {
                            //var sentiment = item[key].sentiment;
                            //var item2 = item;//item[key];
                        if(typeof(item.tweet)!='undefined' && typeof(item.tweet.text)!='undefined'){
                            var tweet = item.tweet;
                            var sentiment = sntApi(item.tweet.text);
                            var topic = findTopic(item.tweet);
                            if(tweet!=null && typeof(tweet)!='undefined' && sentiment.words.length>0){
                                if( tweet.coordinates!=null && typeof(tweet.coordinates) != 'undefined'){
                                    var lat = tweet.coordinates.coordinates[1];
                                    var lng = tweet.coordinates.coordinates[0];

                                    storeInLatLongMap(lat,lng,sentiment,topic);
                                    //console.log('jzTest1 sentiment: '+sentiment.score+' tweet:  '+tweet.text);
                                }
                                else{
                                    var timezoneFound = getTimeZone(tweet);
                                    if(timezoneFound!=null){
                                        var lat = timezoneFound.lat;
                                        var lng = timezoneFound.lng;

                                        storeInLatLongMap(lat,lng,sentiment,topic);
                                        //console.log('jzTest1 sentiment: '+sentiment.score+' tweet:  '+tweet.text);
                                    }
                                }
                            }
                        }
                        //}
                    //}//end for loop

                    currentStreamCount++;//only for debugging

                });

                stream.on("end", function() {//check if all processing complete before storing.
                    readyToSave = true;

                });
            }

            timezoneCol.find().toArray(function(err, items) {
                //console.log(items);
                timezone = items;
                initStream();
            });

            /*collection.find().toArray(function(err, items) {
                //console.log(items);
                tweetsWithCoordinates = items;
            });*/

            //to decript json date object
            // var jsonDate = "2011-05-26T07:56:00.123Z";
            // var then = new Date(jsonDate);

          }
          else{
              console.log("mongodb error connecting: "+err);
          }
        });

    };

    startReadingStream();

<|endoftext|>


<commit_before>// ─────────────────────────────────────────────────────────────────────────────
// import
// ─────────────────────────────────────────────────────────────────────────────

import React from 'react';
import { string, number, func } from 'prop-types';

import styled, { css } from 'styled-components';

import { animation } from '~utils';

// ─────────────────────────────────────────────────────────────────────────────
// helpers
// ─────────────────────────────────────────────────────────────────────────────

const spinnerAnimation = animation({
  to: { transform: 'rotate(360deg)' },
  properties: '1s infinite',
});

export const Picture = styled.picture`
  --loader-hsl: var(--hsl-primary);

  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;

  &::before {
    content: '';

    display: block;
    padding-bottom: ${({ ratio }) => ratio * 100}%;
  }

  ${({ isLoaded }) => {
    if (!isLoaded) {
      return css`
        &::after {
          content: '';

          z-index: 1;
          width: 1em;
          height: 1em;

          border: 0.125em solid hsla(var(--loader-hsl), 0.1);
          border-top-color: hsla(var(--loader-hsl), 1);
          border-radius: 50%;

          animation: ${spinnerAnimation};
        }
      `;
    }
    return null;
  }}
`;

Picture.defaultProps = {
  as: 'picture',
  overflow: 'hidden',
};

export const StyledImg = styled.img`
  user-drag: none;

  position: absolute;
  display: block;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;

  object-fit: cover;
  background-color: hsla(var(--hsl-text), 0.1);

  ${({ zoom }) => {
    if (zoom) {
      return css`
        transition: transform 250ms;

        &:hover {
          transform: scale(${zoom});
          z-index: var(--z-index-modal);
        }
      `;
    }
    return null;
  }}
`;

// ─────────────────────────────────────────────────────────────────────────────
// component
// ─────────────────────────────────────────────────────────────────────────────

export default function Img({ ratio, zoom, onLoad, onError, onMouseMove, ...rest }) {
  const [isLoaded, setIsLoaded] = React.useState(false);

  const handlers = {
    onLoad: (event) => {
      setIsLoaded(true);
      onLoad(event);
    },
    onError: (event) => {
      const { target } = event;
      target.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E"; // use a transparent svg as a default image
      setIsLoaded(true);
      onError(event);
    },
    onMouseMove: (event) => {
      if (zoom) {
        const { offsetX, offsetY, target } = event?.nativeEvent;
        const x = (offsetX / target.offsetWidth) * 100;
        const y = (offsetY / target.offsetHeight) * 100;
        target.style.transformOrigin = `${x}% ${y}%`;
      }
      onMouseMove(event);
    },
  };

  return (
    <Picture ratio={ratio} isLoaded={isLoaded}>
      <StyledImg {...rest} zoom={zoom} {...handlers} />
    </Picture>
  );
}

Img.propTypes = {
  ratio: number,
  src: string.isRequired,
  alt: string.isRequired,
  zoom: number,
  onLoad: func,
  onError: func,
  onMouseMove: func,
};

Img.defaultProps = {
  ratio: 1,
  zoom: undefined,
  onLoad: () => {},
  onError: () => {},
  onMouseMove: () => {},
};
<commit_msg>allow img ratio prop to be nullable<commit_after>// ─────────────────────────────────────────────────────────────────────────────
// import
// ─────────────────────────────────────────────────────────────────────────────

import React from 'react';
import { string, number, func } from 'prop-types';

import styled, { css } from 'styled-components';

import { animation } from '~utils';

// ─────────────────────────────────────────────────────────────────────────────
// helpers
// ─────────────────────────────────────────────────────────────────────────────

const spinnerAnimation = animation({
  to: { transform: 'rotate(360deg)' },
  properties: '1s infinite',
});

export const Picture = styled.picture`
  --loader-hsl: var(--hsl-primary);

  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;

  ${({ ratio }) => {
    if (ratio) {
      return css`
        &::before {
          content: '';

          display: block;
          padding-bottom: ${ratio * 100}%;
        }
      `;
    }
    return null;
  }}

  ${({ isLoaded }) => {
    if (!isLoaded) {
      return css`
        &::after {
          content: '';

          z-index: 1;
          width: 1em;
          height: 1em;

          border: 0.125em solid hsla(var(--loader-hsl), 0.1);
          border-top-color: hsla(var(--loader-hsl), 1);
          border-radius: 50%;

          animation: ${spinnerAnimation};
        }
      `;
    }
    return null;
  }}
`;

Picture.defaultProps = {
  as: 'picture',
  overflow: 'hidden',
};

export const StyledImg = styled.img`
  user-drag: none;

  position: absolute;
  display: block;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;

  object-fit: cover;
  background-color: hsla(var(--hsl-text), 0.1);

  ${({ zoom }) => {
    if (zoom) {
      return css`
        transition: transform 250ms;

        &:hover {
          transform: scale(${zoom});
          z-index: var(--z-index-modal);
        }
      `;
    }
    return null;
  }}
`;

// ─────────────────────────────────────────────────────────────────────────────
// component
// ─────────────────────────────────────────────────────────────────────────────

export default function Img({
  pictureProps,
  ratio,
  fit,
  zoom,
  onLoad,
  onError,
  onMouseMove,
  ...rest
}) {
  const [isLoaded, setIsLoaded] = React.useState(false);

  const handlers = {
    onLoad: (event) => {
      setIsLoaded(true);
      onLoad(event);
    },
    onError: (event) => {
      const { target } = event;
      target.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E"; // use a transparent svg as a default image
      setIsLoaded(true);
      onError(event);
    },
    onMouseMove: (event) => {
      if (zoom) {
        const { offsetX, offsetY, target } = event?.nativeEvent;
        const x = (offsetX / target.offsetWidth) * 100;
        const y = (offsetY / target.offsetHeight) * 100;
        target.style.transformOrigin = `${x}% ${y}%`;
      }
      onMouseMove(event);
    },
  };

  return (
    <Picture {...pictureProps} ratio={ratio} isLoaded={isLoaded}>
      <StyledImg {...rest} zoom={zoom} {...handlers} />
    </Picture>
  );
}

Img.propTypes = {
  ratio: number,
  src: string.isRequired,
  alt: string.isRequired,
  zoom: number,
  onLoad: func,
  onError: func,
  onMouseMove: func,
};

Img.defaultProps = {
  ratio: 1,
  zoom: undefined,
  onLoad: () => {},
  onError: () => {},
  onMouseMove: () => {},
};
<|endoftext|>