<commit_before>const {send_json, send_csv} = require('./file_manager')
const {no_box, please_send_id} = require('./messages')

/**
 * Converts the presence nodejs buffer to a single bit 1 or 0 to represent booleans
 */
function fix_format(data){

    if(data[0].Presence !== undefined){
        // for each text row
        for(let row=0; row<data.length; row++){
            data[row].Presence = String(data[row].Presence[0])
            data[row].Time_received = fix_timestamp(data[row].Time_received)
            data[row].Time_sent = fix_timestamp(data[row].Time_sent)

            // let clean_dust = clean_data(data[row].pm10, data[row].pm2_5)
            // data[row].pm10 = clean_dust.PM10
            // data[row].pm2_5 = clean_dust.PM2_5
        }
    }

   return data
}

// var dust_cleaner = require("../dust_cleaner/dustCleanerClient.js")

// below two timestampfunctions were retrieved from https://stackoverflow.com/a/5133807/6142189

function fix_timestamp(data){

    return data.getFullYear() + "-" + (data.getMonth() + 1) + "-" + data.getDate() + " " + data.getHours() + ":" + data.getMinutes() + ":" + data.getSeconds();

}

var connection = null

const {config_db, extract, has} = require('./lib')

function resolve_db(){

    if(connection === null){
        try{
            connection = config_db()
        }
        catch(error){
            console.error(error)
            console.error("DB not running or not accessible")
            connection = null
        }
        return connection
    }
    else{
        return connection
    }

}

// to stream use AND ROWNUM <= 3 AND ROWNUM > ....
// so that we only get x number of rows will have to calculate chunks

function get_box(id, resp, format){

    // check to make sure that they give a ID value, that it is a valid number and not the value all or a _ seperated list
    resolve_db()

    // check if it is a valid number if it is we carry on without issues
    if(isNaN(id) && id !== "all" ){
        id = String(id)
    }
    else if(id == null){
        resp.send(please_send_id)
        return
    }

    let query = 'SELECT * from box' + id

    // todo fix later
    // if(id !== "all"){
    //     id = String(id)
    //     if(id.indexOf('_') > -1){
    //         query += ' where Box_ID in (' + id.replace('_', ',') + ')'
    //     }else{
    //         query += ' where Box_ID = ' + id
    //     }
    // }

    connection.query(query, (err, results , fields)=>{
        if(results != null){
            if(results.length !== 0){
                if(format === 'json'){
                    send_json(results, resp)
                }else{
                    send_csv('skomobo.csv', fix_format(results), resp)
                }
            }
        }
        else{
            resp.send(no_box(id))
        }
    })
}

async function store(response, database_name, values){

    // restructure db to have seperate table for each box

    // list of boxes in database gets stored in box_info, if a box is not in that list
    // we insert it into said list and then create its table
    // if it does exist we insert the data into its correct table
    // each table should be like box1, box2, box3 etc to denote what ID it maps to

    // the box info table is used to track the meta data about each box

    if(!has(values, null)){

        box_exists(values["Box_ID"], (exists)=>{
            if(exists){
                // insert into new table now
                connection.query('INSERT INTO ' + database_name + ' set ?' , values)
                // tell the client everything is ok
                response.writeHead(200, {"Content-Type": "text/HTML"})
                response.end()
            }
            else{
                connection.query('CREATE TABLE ' + database_name + ' LIKE box_data')

                // insert into box2
    // select * from arduino where box_id = 2
    // something like this to migrate across old data first?
    // need a way to fix the primary key index and sort by time received maybe in migrate proc??
                // connection.query('')

                // copy this query structure to migrate data and index correctly
                // create table box2 like box_data;
// alter table box2 auto_increment = 1;
// insert into box2(`Time_received`, `Box_ID`, `Time_sent`,  `Dust1`,  `Dust2_5`,  `Dust10`,  `Presence`,  `Temperature`,  `Humidity`,  `CO2`)
	// select `Time_received`, `Box_ID`, `Time_sent`,  `Dust1`,  `Dust2_5`,  `Dust10`,  `Presence`,  `Temperature`,  `Humidity`,  `CO2`
	// from arduino where box_id = "2";

                connection.query('INSERT INTO ' + database_name + ' set ?' , values)

                // update box metadata
                let box_meta =  {"ID": values["Box_ID"], "processor": "arduino"}
                connection.query('INSERT INTO box_info set ?' , box_meta)
                response.writeHead(200, {"Content-Type": "text/HTML"})
                response.end()
            }
        })
    }
    else{
        response.writeHead(400, {"Content-Type": "text/HTML"})
        response.end()
    }
}

const {validate_data} = require('./validator')
function store_arduino(req, resp){
    resolve_db()

    let url = req.url.slice(1)

    validate_data(url, (data)=>{
        let values = extract(url)
        store(resp, "box" + values["Box_ID"], values)
    },()=>{
        resp.send("Invalid data")
    })
}

function get_connection(){
    return connection
}

function set_connection(value){
    connection = value
}

// make a get_data
function get_info(id, cols, callback){
    resolve_db()
    if(id != null){

        cols = cols.join(', ')
        connection.query("select " + cols + " from box_info where id = '" + String(id) + "'", (err, results , fields)=>{

            if(err != null){
                console.error(err)
            }

            if(results != null){
                if(results.length !== 0){
                    callback(true, results)
                }
                else{
                    callback(false)
                }
            }
            else{
                callback(false)
            }

        })
    }
}

function box_exists(id, callback){
    get_info(id, ['id'], (has_result)=>{
        callback(has_result)
    })
}

function box_processor(id, callback){
    get_info(id, ['processor'], (has_result, result)=>{
        has_result ?callback(has_result, result[0]['processor']): callback(has_result)
    })
}

function latest(id, format, resp){
    // check to make sure that they give a ID value, that it is a valid number and not the value all or a _ seperated list
    resolve_db()

    // check if it is a valid number if it is we carry on without issues
    if(isNaN(id) && id !== "all" ){
        id = String(id)
    }
    else if(id == null){
        resp.send(please_send_id)
        return
    }

    let query = 'SELECT * from box' + id + ' order by Time_received DESC limit 1'

    connection.query(query, (err, results , fields)=>{

        if(err != null){
            console.error(err)
        }

        if(results != null){
            if(results.length !== 0){
                if(format === 'json'){
                    send_json(results, resp)
                }else{
                    // finish this
                    let values = fix_format(results)[0]
                    console.log(values)
                    let msg = "box " + id + " received at
" + values["Time_received"]
                    + "

stats:
temperature: " + values['Temperature']
                    +"
humidity: " + values["Humidity"] + "
CO2: " + values['CO2']
                    +"
presence: " + values["Presence"] + "

Dust: "
                    + "
Pm1: " + values["Dust1"] + "
Pm2.5: " + values["Dust2_5"]
                    + "
Pm10: " + values["Dust10"]

                    resp.send(msg)
                }
            }
        }
        else{
            resp.send(no_box(id))
        }
    })
}

const {export_functs} = require('./lib')

module.exports = export_functs(latest, box_processor,set_connection, get_connection, get_box, store_arduino, resolve_db, fix_format, fix_timestamp, box_exists)<commit_msg>Finished db migration code<commit_after>const {send_json, send_csv} = require('./file_manager')
const {no_box, please_send_id} = require('./messages')

/**
 * Converts the presence nodejs buffer to a single bit 1 or 0 to represent booleans
 */
function fix_format(data){

    if(data[0].Presence !== undefined){
        // for each text row
        for(let row=0; row<data.length; row++){
            data[row].Presence = String(data[row].Presence[0])
            data[row].Time_received = fix_timestamp(data[row].Time_received)
            data[row].Time_sent = fix_timestamp(data[row].Time_sent)

            // let clean_dust = clean_data(data[row].pm10, data[row].pm2_5)
            // data[row].pm10 = clean_dust.PM10
            // data[row].pm2_5 = clean_dust.PM2_5
        }
    }

   return data
}

// var dust_cleaner = require("../dust_cleaner/dustCleanerClient.js")

// below two timestampfunctions were retrieved from https://stackoverflow.com/a/5133807/6142189

function fix_timestamp(data){

    return data.getFullYear() + "-" + (data.getMonth() + 1) + "-" + data.getDate() + " " + data.getHours() + ":" + data.getMinutes() + ":" + data.getSeconds();

}

var connection = null

const {config_db, extract, has} = require('./lib')

function resolve_db(){

    if(connection === null){
        try{
            connection = config_db()
        }
        catch(error){
            console.error(error)
            console.error("DB not running or not accessible")
            connection = null
        }
        return connection
    }
    else{
        return connection
    }

}

/**
 * This function creates our tables and database if it doesn't already exist
 *
 */
function setup_db(){
    //todo put code in here to do above
    //run on startup, then setup docker container with mariadb to unit test against
    // / just add services:mariadb to travis file and make sure to include delete statements
    // fix db_manager so that it checks results of functions and tests real db not mock stuff
}

// to stream use AND ROWNUM <= 3 AND ROWNUM > ....
// so that we only get x number of rows will have to calculate chunks

function get_box(id, resp, format){

    // check to make sure that they give a ID value, that it is a valid number and not the value all or a _ seperated list
    resolve_db()

    // check if it is a valid number if it is we carry on without issues
    if(isNaN(id) && id !== "all" ){
        id = String(id)
    }
    else if(id == null){
        resp.send(please_send_id)
        return
    }

    let query = 'SELECT * from box' + id

    // todo fix later
    // if(id !== "all"){
    //     id = String(id)
    //     if(id.indexOf('_') > -1){
    //         query += ' where Box_ID in (' + id.replace('_', ',') + ')'
    //     }else{
    //         query += ' where Box_ID = ' + id
    //     }
    // }

    connection.query(query, (err, results , fields)=>{
        if(results != null){
            if(results.length !== 0){
                if(format === 'json'){
                    send_json(results, resp)
                }else{
                    send_csv('skomobo.csv', fix_format(results), resp)
                }
            }
        }
        else{
            resp.send(no_box(id))
        }
    })
}

async function store(response, database_name, values){

    // restructure db to have seperate table for each box

    // list of boxes in database gets stored in box_info, if a box is not in that list
    // we insert it into said list and then create its table
    // if it does exist we insert the data into its correct table
    // each table should be like box1, box2, box3 etc to denote what ID it maps to

    // the box info table is used to track the meta data about each box

    if(!has(values, null)){

        box_exists(values["Box_ID"], (exists)=>{
            if(exists){
                // insert into new table now
                connection.query('INSERT INTO ' + database_name + ' set ?' , values)
                // tell the client everything is ok
                response.writeHead(200, {"Content-Type": "text/HTML"})
                response.end()
            }
            else{
                connection.query('CREATE TABLE ' + database_name + ' LIKE box_data')
                connection.query('ALTER TABLE ' + database_name + ' AUTO_INCREMENT = 1')
                // copy this query structure to migrate data and index correctly

                let old_data = connection.query('SELECT `Time_received`, `Box_ID`, `Time_sent`,  `Dust1`,' +
                 ' `Dust2_5`,  `Dust10`,  `Presence`,  `Temperature`,  `Humidity`,  `CO2` from arduino' +
                 "where Box_ID = '" + values["Box_ID"] + "'")

                connection.query('Insert into ' + database_name + ' set ?', old_data)

                // from arduino where box_id = "2";')
// insert into box2(`Time_received`, `Box_ID`, `Time_sent`,  `Dust1`,  `Dust2_5`,  `Dust10`,  `Presence`,  `Temperature`,  `Humidity`,  `CO2`)
	// select `Time_received`, `Box_ID`, `Time_sent`,  `Dust1`,  `Dust2_5`,  `Dust10`,  `Presence`,  `Temperature`,  `Humidity`,  `CO2`
	// from arduino where box_id = "2";

                // insert new data
                connection.query('INSERT INTO ' + database_name + ' set ?' , values)

                // update box metadata
                let box_meta =  {"ID": values["Box_ID"], "processor": "arduino"}
                connection.query('INSERT INTO box_info set ?' , box_meta)
                response.writeHead(200, {"Content-Type": "text/HTML"})
                response.end()
            }
        })
    }
    else{
        response.writeHead(400, {"Content-Type": "text/HTML"})
        response.end()
    }
}

const {validate_data} = require('./validator')
function store_arduino(req, resp){
    resolve_db()

    let url = req.url.slice(1)

    validate_data(url, (data)=>{
        let values = extract(url)
        store(resp, "box" + values["Box_ID"], values)
    },()=>{
        resp.send("Invalid data")
    })
}

function get_connection(){
    return connection
}

function set_connection(value){
    connection = value
}

// make a get_data
function get_info(id, cols, callback){
    resolve_db()
    if(id != null){

        cols = cols.join(', ')
        connection.query("select " + cols + " from box_info where id = '" + String(id) + "'", (err, results , fields)=>{

            if(err != null){
                console.error(err)
            }

            if(results != null){
                if(results.length !== 0){
                    callback(true, results)
                }
                else{
                    callback(false)
                }
            }
            else{
                callback(false)
            }

        })
    }
}

function box_exists(id, callback){
    get_info(id, ['id'], (has_result)=>{
        callback(has_result)
    })
}

function box_processor(id, callback){
    get_info(id, ['processor'], (has_result, result)=>{
        has_result ?callback(has_result, result[0]['processor']): callback(has_result)
    })
}

function latest(id, format, resp){
    // check to make sure that they give a ID value, that it is a valid number and not the value all or a _ seperated list
    resolve_db()

    // check if it is a valid number if it is we carry on without issues
    if(isNaN(id) && id !== "all" ){
        id = String(id)
    }
    else if(id == null){
        resp.send(please_send_id)
        return
    }

    let query = 'SELECT * from box' + id + ' order by Time_received DESC limit 1'

    connection.query(query, (err, results , fields)=>{

        if(err != null){
            console.error(err)
        }

        if(results != null){
            if(results.length !== 0){
                if(format === 'json'){
                    send_json(results, resp)
                }else{
                    // finish this
                    let values = fix_format(results)[0]
                    console.log(values)
                    let msg = "box " + id + " received at
" + values["Time_received"]
                    + "

stats:
temperature: " + values['Temperature']
                    +"
humidity: " + values["Humidity"] + "
CO2: " + values['CO2']
                    +"
presence: " + values["Presence"] + "

Dust: "
                    + "
Pm1: " + values["Dust1"] + "
Pm2.5: " + values["Dust2_5"]
                    + "
Pm10: " + values["Dust10"]

                    resp.send(msg)
                }
            }
        }
        else{
            resp.send(no_box(id))
        }
    })
}

const {export_functs} = require('./lib')

module.exports = export_functs(latest, box_processor,set_connection, get_connection, get_box, store_arduino, resolve_db, fix_format, fix_timestamp, box_exists)<|endoftext|>


<commit_before>!function(r){if("object"==typeof exports)module.exports=r();else if("function"==typeof define&&define.amd)define(r);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.find=r()}}(function(){return function r(e,n,t){function o(f,u){if(!n[f]){if(!e[f]){var a="function"==typeof require&&require;if(!u&&a)return a(f,!0);if(i)return i(f,!0);throw new Error("Cannot find module '"+f+"'")}var l=n[f]={exports:{}};e[f][0].call(l.exports,function(r){var n=e[f][1][r];return o(n?n:r)},l,l.exports,r,e,n,t)}return n[f].exports}for(var i="function"==typeof require&&require,f=0;f<t.length;f++)o(t[f]);return o}({1:[function(r,e,n){r("array-from"),e["export"].find=function(r,e){return Array.from(r.querySelectorAll(e))}},{"array-from":2}],2:[function(r,e,n){e.exports="function"==typeof Array.from?Array.from:r("./polyfill")},{"./polyfill":3}],3:[function(r,e,n){e.exports=function(){var r=function(r){return"function"==typeof r},e=function(r){var e=Number(r);return isNaN(e)?0:0!==e&&isFinite(e)?(e>0?1:-1)*Math.floor(Math.abs(e)):e},n=Math.pow(2,53)-1,t=function(r){var t=e(r);return Math.min(Math.max(t,0),n)},o=function(r){if(null!=r){if("undefined"!=typeof Symbol&&"iterator"in Symbol&&Symbol.iterator in r)return Symbol.iterator;if("@@iterator"in r)return"@@iterator"}},i=function(e,n){if(null!=e&&null!=n){var t=e[n];if(null==t)return;if(!r(t))throw new TypeError(t+" is not a function");return t}},f=function(r){var e=r.next(),n=Boolean(e.done);return n?!1:e};return function(e){"use strict";var n,u=this,a=arguments.length>1?arguments[1]:void 0;if("undefined"!=typeof a){if(!r(a))throw new TypeError("Array.from: when provided, the second argument must be a function");arguments.length>2&&(n=arguments[2])}var l,c,y=i(e,o(e));if(void 0!==y){l=r(u)?Object(new u):[];var d=y.call(e);if(null==d)throw new TypeError("Array.from requires an array-like or iterable object");c=0;for(var p,s;;){if(p=f(d),!p)return l.length=c,l;s=p.value,a?l[c]=a.call(n,s,c):l[c]=s,c++}}else{var m=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object - not null or undefined");var v=t(m.length);l=r(u)?Object(new u(v)):new Array(v),c=0;for(var h;v>c;)h=m[c],a?l[c]=a.call(n,h,c):l[c]=h,c++;l.length=v}return l}}()},{}]},{},[1])(1)});<commit_msg>1.0.1<commit_after>!function(r){if("object"==typeof exports)module.exports=r();else if("function"==typeof define&&define.amd)define(r);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.find=r()}}(function(){return function r(e,n,t){function o(f,u){if(!n[f]){if(!e[f]){var a="function"==typeof require&&require;if(!u&&a)return a(f,!0);if(i)return i(f,!0);throw new Error("Cannot find module '"+f+"'")}var l=n[f]={exports:{}};e[f][0].call(l.exports,function(r){var n=e[f][1][r];return o(n?n:r)},l,l.exports,r,e,n,t)}return n[f].exports}for(var i="function"==typeof require&&require,f=0;f<t.length;f++)o(t[f]);return o}({1:[function(r,e,n){r("array-from"),e.exports.find=function(r,e){return Array.from(r.querySelectorAll(e))}},{"array-from":2}],2:[function(r,e,n){e.exports="function"==typeof Array.from?Array.from:r("./polyfill")},{"./polyfill":3}],3:[function(r,e,n){e.exports=function(){var r=function(r){return"function"==typeof r},e=function(r){var e=Number(r);return isNaN(e)?0:0!==e&&isFinite(e)?(e>0?1:-1)*Math.floor(Math.abs(e)):e},n=Math.pow(2,53)-1,t=function(r){var t=e(r);return Math.min(Math.max(t,0),n)},o=function(r){if(null!=r){if("undefined"!=typeof Symbol&&"iterator"in Symbol&&Symbol.iterator in r)return Symbol.iterator;if("@@iterator"in r)return"@@iterator"}},i=function(e,n){if(null!=e&&null!=n){var t=e[n];if(null==t)return;if(!r(t))throw new TypeError(t+" is not a function");return t}},f=function(r){var e=r.next(),n=Boolean(e.done);return n?!1:e};return function(e){"use strict";var n,u=this,a=arguments.length>1?arguments[1]:void 0;if("undefined"!=typeof a){if(!r(a))throw new TypeError("Array.from: when provided, the second argument must be a function");arguments.length>2&&(n=arguments[2])}var l,c,y=i(e,o(e));if(void 0!==y){l=r(u)?Object(new u):[];var d=y.call(e);if(null==d)throw new TypeError("Array.from requires an array-like or iterable object");c=0;for(var s,p;;){if(s=f(d),!s)return l.length=c,l;p=s.value,a?l[c]=a.call(n,p,c):l[c]=p,c++}}else{var m=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object - not null or undefined");var v=t(m.length);l=r(u)?Object(new u(v)):new Array(v),c=0;for(var h;v>c;)h=m[c],a?l[c]=a.call(n,h,c):l[c]=h,c++;l.length=v}return l}}()},{}]},{},[1])(1)});<|endoftext|>


<commit_before>angular.module('videosharing-embed', []);

angular.module('videosharing-embed').service('PlayerConfig', function () {
	'use strict';
    this.createInstance = function (init) {
        var PlayerConfig = function (init) {
            this.playerRegExp = init.playerRegExp;
            this.whitelist = init.whitelist;
            this.config = {
                playerID: init.playerID,
                options: init.options
            };
            this.isPlayerFromURL = function (url) {
                return (url.match(this.playerRegExp) != null);
            }
        };
        return new PlayerConfig(init);
    }
});

angular.module('videosharing-embed').factory('RegisteredPlayers', [ 'PlayerConfig', function (PlayerConfig) {
	'use strict';
    var configurations = {
        youtube: {
            options: {
                autoplay: 0,
                controls: 1,
                loop: 0,
            },
            whitelist: ['autoplay', 'controls', 'loop', 'playlist', 'rel'],
            playerID: 'www.youtube.com/embed/',
            protocol: 'http://',
            playerRegExp: /(http:|https:)?\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)(\w*)(&(amp;)?[\w\?=]*)?/
        },
        youtubeNoCookie: {
            options: {
                autoplay: 0,
                controls: 1,
                loop: 0,
            },
            whitelist: ['autoplay', 'controls', 'loop', 'playlist', 'rel'],
            playerID: 'www.youtube-nocookie.com/embed/',
            protocol: 'http://',
            playerRegExp: /(http:|https:)?\/\/(www\.youtube\-nocookie\.com)\/watch\?v=([A-Za-z0-9\-\_]+)/
        },
        vimeo: {
            options: {
                autoplay: 0,
                loop: 0,
            },
            whitelist: ['autoplay', 'color', 'loop'],
            playerID: 'player.vimeo.com/video/',
            protocol: 'http://',
            playerRegExp: /(http:|https:)?\/\/vimeo\.com\/([A-Za-z0-9]+)/
        },
        dailymotion: {
            options: {
                autoPlay: 0,
                logo: 0,
            },
            whitelist: ['autoPlay', 'logo', 'forceQuality'],
            playerID: 'www.dailymotion.com/embed/video/',
            protocol: 'http://',
            playerRegExp: /(http:|https:)?\/\/www\.dailymotion\.com\/video\/([A-Za-z0-9]+)/
        }
    };
    var players = [];
    angular.forEach(configurations, function (value) {
        players.push(PlayerConfig.createInstance(value));
    });
    return players;
}]);
<commit_msg>youtube video ID can contain dashes, courtesy of Thomas Devol<commit_after>angular.module('videosharing-embed', []);

angular.module('videosharing-embed').service('PlayerConfig', function () {
	'use strict';
    this.createInstance = function (init) {
        var PlayerConfig = function (init) {
            this.playerRegExp = init.playerRegExp;
            this.whitelist = init.whitelist;
            this.config = {
                playerID: init.playerID,
                options: init.options
            };
            this.isPlayerFromURL = function (url) {
                return (url.match(this.playerRegExp) != null);
            }
        };
        return new PlayerConfig(init);
    }
});

angular.module('videosharing-embed').factory('RegisteredPlayers', [ 'PlayerConfig', function (PlayerConfig) {
	'use strict';
    var configurations = {
        youtube: {
            options: {
                autoplay: 0,
                controls: 1,
                loop: 0,
            },
            whitelist: ['autoplay', 'controls', 'loop', 'playlist', 'rel'],
            playerID: 'www.youtube.com/embed/',
            protocol: 'http://',
            playerRegExp: /(http:|https:)?\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w-]*)(&(amp;)?[\w\?=]*)?/
        },
        youtubeNoCookie: {
            options: {
                autoplay: 0,
                controls: 1,
                loop: 0,
            },
            whitelist: ['autoplay', 'controls', 'loop', 'playlist', 'rel'],
            playerID: 'www.youtube-nocookie.com/embed/',
            protocol: 'http://',
            playerRegExp: /(http:|https:)?\/\/(www\.youtube\-nocookie\.com)\/watch\?v=([A-Za-z0-9\-\_]+)/
        },
        vimeo: {
            options: {
                autoplay: 0,
                loop: 0,
            },
            whitelist: ['autoplay', 'color', 'loop'],
            playerID: 'player.vimeo.com/video/',
            protocol: 'http://',
            playerRegExp: /(http:|https:)?\/\/vimeo\.com\/([A-Za-z0-9]+)/
        },
        dailymotion: {
            options: {
                autoPlay: 0,
                logo: 0,
            },
            whitelist: ['autoPlay', 'logo', 'forceQuality'],
            playerID: 'www.dailymotion.com/embed/video/',
            protocol: 'http://',
            playerRegExp: /(http:|https:)?\/\/www\.dailymotion\.com\/video\/([A-Za-z0-9]+)/
        }
    };
    var players = [];
    angular.forEach(configurations, function (value) {
        players.push(PlayerConfig.createInstance(value));
    });
    return players;
}]);
<|endoftext|>


<commit_before>'use strict';

let instance = new sigma({
  renderer: {
    container: 'graph-container',
    type: 'canvas',
    skipErrors: true,
    labelThreshold: -2,
    labelSize: 'proportional'
  }
});

(function(instance) {
  const $ = id => document.getElementById(id);

  function createFilter(instance) {
    // Initialize the Filter API
    const filter = new sigma.plugins.filter(instance);

    const maximumDegree = setupPane(instance.graph, filter);

    function applyMinDegreeFilter(value) {
      if (typeof value === 'object') {
        value = value.target.value;
      }

      $('min-degree').value = value;
      $('min-degree-val').textContent = value;

      console.log(value);

      filter
        .undo('min-degree')
        .nodesBy(node => instance.graph.degree(node.id) >= value, 'min-degree')
        .apply();
    }

    function applyGroupFilter(element) {
      let group = element.target[element.target.selectedIndex].value;
      if (group.length > 0) {
        filter
          .undo('node-group')
          .nodesBy(node => node.group === group, 'node-group')
          .apply();
      }
    }

    // for Chrome and FF
    $('min-degree').addEventListener('input', applyMinDegreeFilter);
    // for IE10+, that sucks
    $('min-degree').addEventListener('change', applyMinDegreeFilter);
    $('node-group').addEventListener('change', applyGroupFilter);

    // Start by filtering out some of the nodes
    applyMinDegreeFilter(Math.trunc(maximumDegree / 8));
  }

  function setupPane(graph, filter) {
    let maximumDegree = 0, categories = {};

    // Collect the maximum degree and categories.
    graph.nodes().forEach(node => {
      maximumDegree = Math.max(maximumDegree, graph.degree(node.id));
      categories[node.group] = true;
    })

    // Set the slider values.
    $('min-degree').max = maximumDegree;
    $('max-degree-value').textContent = maximumDegree;

    // Set up the node group combo box.
    const nodeGroup = $('node-group');
    Object.keys(categories).forEach(function(group) {
      if (group.length === 0) return;
      let option = document.createElement('option');
      option.text = group;
      nodeGroup.add(option);
    });

    return maximumDegree;
  }

  sigma.parsers.json('graph.json', instance, () => {
    instance.refresh();
    instance.startForceAtlas2({
      worker: true,
      barnesHutOptimize: true,
      adjustSizes: true,
      slowDown: 20,
      strongGravityMode: true
    });
    createFilter(instance);
  });

  const drag = sigma.plugins.dragNodes(instance, instance.renderers[0]);
  drag.bind('startdrag', event => {
    if (instance.isForceAtlas2Running()) {
      instance.killForceAtlas2()
    }
  });

})(instance);
<commit_msg>Fixed bug for showing all groups<commit_after>'use strict';

let instance = new sigma({
  renderer: {
    container: 'graph-container',
    type: 'canvas',
    skipErrors: true,
    labelThreshold: -2,
    labelSize: 'proportional'
  }
});

(function(instance) {
  const $ = id => document.getElementById(id);

  function createFilter(instance) {
    // Initialize the Filter API
    const filter = new sigma.plugins.filter(instance);

    const maximumDegree = setupPane(instance.graph, filter);

    function applyMinDegreeFilter(value) {
      if (typeof value === 'object') {
        value = value.target.value;
      }

      $('min-degree').value = value;
      $('min-degree-val').textContent = value;

      filter
        .undo('min-degree')
        .nodesBy(node => instance.graph.degree(node.id) >= value, 'min-degree')
        .apply();
    }

    function applyGroupFilter(element) {
      let group = element.target[element.target.selectedIndex].value;
      filter
        .undo('node-group')
        .nodesBy(node => !group || node.group === group, 'node-group')
        .apply();
    }

    // for Chrome and FF
    $('min-degree').addEventListener('input', applyMinDegreeFilter);
    // for IE10+, that sucks
    $('min-degree').addEventListener('change', applyMinDegreeFilter);
    $('node-group').addEventListener('change', applyGroupFilter);

    // Start by filtering out some of the nodes
    applyMinDegreeFilter(Math.trunc(maximumDegree / 8));
  }

  function setupPane(graph, filter) {
    let maximumDegree = 0, categories = {};

    // Collect the maximum degree and categories.
    graph.nodes().forEach(node => {
      maximumDegree = Math.max(maximumDegree, graph.degree(node.id));
      categories[node.group] = true;
    })

    // Set the slider values.
    $('min-degree').max = maximumDegree;
    $('max-degree-value').textContent = maximumDegree;

    // Set up the node group combo box.
    const nodeGroup = $('node-group');
    Object.keys(categories).forEach(function(group) {
      if (group.length === 0) return;
      let option = document.createElement('option');
      option.text = group;
      nodeGroup.add(option);
    });

    return maximumDegree;
  }

  sigma.parsers.json('graph.json', instance, () => {
    instance.refresh();
    instance.startForceAtlas2({
      worker: true,
      barnesHutOptimize: true,
      adjustSizes: true,
      slowDown: 20,
      strongGravityMode: true
    });
    createFilter(instance);
  });

  const drag = sigma.plugins.dragNodes(instance, instance.renderers[0]);
  drag.bind('startdrag', event => {
    if (instance.isForceAtlas2Running()) {
      instance.killForceAtlas2()
    }
  });

})(instance);
<|endoftext|>


<commit_before>module.exports = (client, message, args) => {

    { let numArray = args.map(n=> parseInt(n));  let total = numArray.reduce( (p,c) => p/c);
        if (c != 0){
        message.channel.sendMessage(total);  }
        else
        {
            message.reply("Não existe divisão por 0.");
        }}

  };<commit_msg><commit_after>module.exports = (client, message, args) => {

    { let numArray = args.map(n=> parseInt(n));  let total = numArray.reduce( (p,c) => p/c); message.channel.sendMessage(total);  }

  };<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 gm9
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */

(function(){
    // import
    var igt = gm9.IngressGlyphTools;
    var Glyph = igt.Glyph;
    var Dictionary = igt.Dictionary;
    var DictionaryEntry = igt.DictionaryEntry;

    // ref: http://glyphtionary.com/
    // ref: https://plus.google.com/u/1/+Ingress/posts/6Ey9jT3mhsD
    // ref: https://plus.google.com/u/1/+NianticProject/posts/LSnjYR3YKCW
    // ref: https://plus.google.com/+NianticProject/posts/1b1aEfxWW4w
    var DIC =
            [
                "1634486a8a", ["Abandon"]
                ,"587a8a", ["Adapt"]
                ,"0949", ["Advance"]
                ,"1216276a7a", ["After"]
                ,"49676a898a", ["Again", "Repeat"]
                ,"010512233445", ["All"]
                ,"67697a", ["Answer"]
                ,"06092649", ["Attack", "War"]
                ,"05061617", ["Avoid"] //"Struggle"
                ,"0a277a", ["Barrier", "Obstacle"]
                ,"4548598a9a", ["Before"]
                ,"083738", ["Begin"]
                ,"3738676989", ["Being", "Human"]
                ,"696a9a", ["Body", "Shell"]
                ,"16596a9a", ["Breathe","Live"]
                ,"099a", ["Call"] //ref: http://glyphtionary.com/ http://decodeingress.me/2014/09/16/passcode-decoding-walkthrough-012/ https://plus.google.com/u/0/+SteinLightman/posts/V84nKXZmVrh
                ,"1734487a8a", ["Capture"]
                ,"373a8a", ["Change","Modify"]
                ,"01051638456a8a", ["Chaos","Disorder"]
                ,"0a3a", ["Clear"]
                ,"01050a1223343a45", ["Close All", "Clear All", "Clearall"]
                ,"698a9a", ["Complex"]
                ,"2649677889", ["Conflict"]
                ,"27597889", ["Consequence"]
                ,"011223386a899a", ["Contemplate"]
                ,"497889", ["Courage"]
                ,"16486a8a", ["Create","Creation"]
                ,"1216274548597a9a", ["Creativity","Idea","Thought"]//, "Mind"
                ,"393a9a", ["Creativity"]
                ,"093a9a", ["Danger"]
                ,"06386a8a", ["Data","Signal"]//"Message"
                ,"17373858", ["Defend"]
                ,"38676a789a", ["Destiny"]
                ,"1223", ["Destination"]
                ,"27597a9a", ["Destroy","Destruction"]
                ,"488a9a", ["Deteriorate","Erode"]
                ,"386a8a", ["Easy"]
                ,"27487a8a", ["Die","Death"]
                ,"16677a8a", ["Difficult"]
                ,"122334", ["Discover"]
                ,"0545", ["Distance","Outside"]
                ,"010a17373a", ["End","Close"]
                ,"01091223696a9a", ["Enlightened", "Enlightenment"]
                ,"676989", ["Equal"]
                ,"01166989", ["Escape"]
                ,"0a899a", ["Evolution","Progress","Success"]
                ,"0a676a", ["Failure"]
                ,"176769", ["Fear"]
                ,"061216", ["Follow"]
                ,"48", ["Forget"]
                ,"162767", ["Future"] //"Forward-Time"
                ,"58", ["Gain"]
                ,"1659677889", ["Government","City","Civilization","Structure"]
                ,"4989", ["Grow"]
                ,"0609276a7a9a", ["Harm"]
                ,"060937386a7a8a9a", ["Harmony","Peace"]
                ,"387a8a", ["Have"]
                ,"59788a9a", ["Help"]
                ,"16176978", ["Hide"]
                ,"363969", ["I","Me"] //"Self"
                ,"27", ["Ignore"]
                ,"6a898a9a", ["Imperfect"]
                ,"686a898a9a", ["Imperfect"] //NOTE: Scanner bug?
                ,"166a7a", ["Improve"]
                ,"3a898a9a", ["Impure"]
                ,"16486a899a", ["Intelligence"]
                ,"0a3a4548598a9a", ["Interrupt"]
                ,"163445596a9a", ["Journey"]
                ,"36396a9a", ["Knowledge"]
                ,"05384548", ["Lead"]
                ,"0105162748596789", ["Legacy"]
                ,"6a9a", ["Less"]
                ,"0116496a9a", ["Liberate"]
                ,"676a7a899a", ["Lie"]
                ,"16496a898a", ["Live Again", "Reincarnate"]
                ,"17", ["Lose"]
                ,"17497a9a", ["Message"]
                ,"383a899a", ["Mind"] //"Idea","Thought"
                ,"7a8a", ["More"]
                ,"0609596989", ["Mystery"]
                ,"06090a3a6a9a", ["N'zeer"]
                ,"2748676989", ["Nature"]
                ,"2767", ["New"]
                ,"6769", ["Not","Inside"] //"No", "Absent"
                ,"343a488a", ["Nourish"]
                ,"5989", ["Old"]
                ,"373878", ["Open","Accept"]
                ,"010512233437384578", ["Open All", "Openall"]
                ,"1216274548596978", ["Portal"] //"Opening","Doorway"
                ,"485989", ["Past"]
                ,"0a488a", ["Path"]
                ,"0a232734487a8a", ["Perfection","Balance"]
                ,"060927486a7a8a9a", ["Perspective"]
                ,"0a12277a", ["Potential"]
                ,"3738676a78899a", ["Presence"]
                ,"677889", ["Present","Now"]
                ,"0a676a7a", ["Pure"] //"Purity"
                ,"060959", ["Pursue"]
                ,"0a48899a", ["Chase"] //"Pursue"
                ,"066989", ["Question"]
                ,"27697a9a", ["React"]
                ,"1216586a8a", ["Rebel"]
                ,"050a599a", ["Recharge","Repair"]
                ,"2667", ["Reduce"] //"Contract"
                ,"090a383a69", ["Resist","Resistance","Struggle"]
                ,"377a", ["Response"] //ref: http://glyphtionary.com/ http://decodeingress.me/2014/09/16/passcode-decoding-walkthrough-012/ https://plus.google.com/u/0/+SteinLightman/posts/V84nKXZmVrh
                ,"2327597a9a", ["Restraint"]
                ,"0626", ["Retreat"]
                ,"264969", ["Safety"]
                ,"177a8a", ["Save"] //"Rescue"
                ,"09", ["See"]
                ,"696a7889", ["Seek","Search"]
                ,"2334", ["Self","Individual"]
                ,"2759676a898a", ["Separate"]
                ,"060927486789", ["Shapers","Collective"] //"Shaper"
                //"060927373848676989", ["Shaper/Collective + Being/Human"]
                ,"27344878", ["Share"]
                ,"78", ["Simple"]
                ,"373a676a", ["Soul"] //"Spirit","Life Force"
                ,"274878", ["Stability", "Stay"]
                ,"67697889", ["Strong"]
                ,"0a1216273a6a7a", ["Sustain"]
                ,"01050a12162327343a456a7a", ["Sustain All"]
                ,"16276a7a898a9a", ["Technology"]
                ,"0878", ["Them"]
                ,"48696a8a9a", ["Together"]
                ,"676a7a898a9a", ["Truth"]
                ,"010517233445696a7889", ["Unbounded"]
                ,"177a", ["Use"]
                ,"06093639", ["Victory"]
                ,"373848", ["Want"]
                ,"3669", ["We","Us"]
                ,"596769", ["Weak"]
                ,"17587a8a", ["Worth"]
                ,"67697a898a", ["XM"] //(Exotic Matter)
                ,"070878", ["You","Your","Other"]
                //,"0109122334696a9a", ["[unknown]"]
                //,"0609232734486789", ["[unknown]"]
                //,"01061226", ["[unknown]"]
                //,"090a373a69", ["[unknown]"]
            ];

    var dicGlyphToWord = new Dictionary();
    for(var ei = 0; ei < DIC.length; ei += 2){
        dicGlyphToWord.add(Glyph.fromString(DIC[ei+0]), DIC[ei+1]);
    }
    var dicWordToGlyph = dicGlyphToWord.createIndex();

    function getWordsFromGlyph(glyph)
    {
        return dicGlyphToWord.get(glyph); //return array
    }
    function getGlyphsFromWord(word)
    {
        return dicWordToGlyph[word.toLowerCase()];
    }

    // ex:
    // "idea" => {word:"idea", Glyph.fromString("1216274548597a9a")}
    // "creativity(1216274548597a9a)" => {word:"creativity", glyph:Glyph.fromString("1216274548597a9a")}
    // "creativity(idea)" => {word:"creativity", glyph:Glyph.fromString("1216274548597a9a")}
    function getWordGlyphFromString(str)
    {
        var arrayWordCode = /^(.+)\((([0-9a][0-9a])*)\)$/i.exec(str); // ex:creativity(1216274548597a9a)
        if(arrayWordCode){
            return {word:arrayWordCode[1], glyph:Glyph.fromString(arrayWordCode[2])};
        }
        else{
            var arrayWordWord = /^(.+)\(([^)]+)\)$/.exec(str); // ex:creativity(idea)
            var wDisplay = arrayWordWord ? arrayWordWord[1] : str;
            var wSearch = arrayWordWord ? arrayWordWord[2] : str;
            var gs = getGlyphsFromWord(wSearch);
            return gs && gs.length > 0 ? {word:wDisplay, glyph:gs[0]} : null;
        }
    }
    function toStringFromWordGlyph(wg)
    {
        return wg.word + "(" + wg.glyph.toString() + ")";
    }

    function getAllWords()
    {
        return Object.keys(dicWordToGlyph);
    }
    function getAllGlyphs()
    {
        var glyphs = [];
        for(var gi = 0; gi < dicGlyphToWord.getEntryCount(); ++gi){
            glyphs.push(dicGlyphToWord.getEntryAt(gi).keyGlyph);
        }
        return glyphs;
    }

    function getWordGlyphRandom()
    {
        do{
            var entryIndex = Math.floor(Math.random() * dicGlyphToWord.getEntryCount());
            var entry = dicGlyphToWord.getEntryAt(entryIndex);
        }
        while(!(entry && entry.keyGlyph && entry.value && entry.value.length > 0));
        return {
            glyph: entry.keyGlyph,
            word: entry.value[Math.floor(Math.random() * entry.value.length)]
        };
    }

    // Exports
    igt.glyphDic = {
        getWordsFromGlyph: getWordsFromGlyph,
        getGlyphsFromWord: getGlyphsFromWord,
        getWordGlyphFromString: getWordGlyphFromString,
        toStringFromWordGlyph: toStringFromWordGlyph,
        getAllWords: getAllWords,
        getAllGlyphs: getAllGlyphs,
        getWordGlyphRandom: getWordGlyphRandom
    };
    // obsolete
    igt.glyphtionary = dicGlyphToWord;
    igt.glyphtionaryIndex = dicWordToGlyph;

})();
<commit_msg>Add signal glyph<commit_after>/*
 * Copyright (c) 2014 gm9
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */

(function(){
    // import
    var igt = gm9.IngressGlyphTools;
    var Glyph = igt.Glyph;
    var Dictionary = igt.Dictionary;
    var DictionaryEntry = igt.DictionaryEntry;

    // ref: http://glyphtionary.com/
    // ref: https://plus.google.com/u/1/+Ingress/posts/6Ey9jT3mhsD
    // ref: https://plus.google.com/u/1/+NianticProject/posts/LSnjYR3YKCW
    // ref: https://plus.google.com/+NianticProject/posts/1b1aEfxWW4w
    var DIC =
            [
                "1634486a8a", ["Abandon"]
                ,"587a8a", ["Adapt"]
                ,"0949", ["Advance"]
                ,"1216276a7a", ["After"]
                ,"49676a898a", ["Again", "Repeat"]
                ,"010512233445", ["All"]
                ,"67697a", ["Answer"]
                ,"06092649", ["Attack", "War"]
                ,"05061617", ["Avoid"] //"Struggle"
                ,"0a277a", ["Barrier", "Obstacle"]
                ,"4548598a9a", ["Before"]
                ,"083738", ["Begin"]
                ,"3738676989", ["Being", "Human"]
                ,"696a9a", ["Body", "Shell"]
                ,"16596a9a", ["Breathe","Live"]
                ,"099a", ["Call"] //ref: http://glyphtionary.com/ http://decodeingress.me/2014/09/16/passcode-decoding-walkthrough-012/ https://plus.google.com/u/0/+SteinLightman/posts/V84nKXZmVrh
                ,"1734487a8a", ["Capture"]
                ,"373a8a", ["Change","Modify"]
                ,"01051638456a8a", ["Chaos","Disorder"]
                ,"0a3a", ["Clear"]
                ,"01050a1223343a45", ["Close All", "Clear All", "Clearall"]
                ,"698a9a", ["Complex"]
                ,"2649677889", ["Conflict"]
                ,"27597889", ["Consequence"]
                ,"011223386a899a", ["Contemplate"]
                ,"497889", ["Courage"]
                ,"16486a8a", ["Create","Creation"]
                ,"1216274548597a9a", ["Creativity","Idea","Thought"]//, "Mind"
                ,"393a9a", ["Creativity"]
                ,"093a9a", ["Danger"]
                ,"06386a8a", ["Data","Signal"]//"Message"
                ,"17373858", ["Defend"]
                ,"38676a789a", ["Destiny"]
                ,"1223", ["Destination"]
                ,"27597a9a", ["Destroy","Destruction"]
                ,"488a9a", ["Deteriorate","Erode"]
                ,"386a8a", ["Easy"]
                ,"27487a8a", ["Die","Death"]
                ,"16677a8a", ["Difficult"]
                ,"122334", ["Discover"]
                ,"0545", ["Distance","Outside"]
                ,"010a17373a", ["End","Close"]
                ,"01091223696a9a", ["Enlightened", "Enlightenment"]
                ,"676989", ["Equal"]
                ,"01166989", ["Escape"]
                ,"0a899a", ["Evolution","Progress","Success"]
                ,"0a676a", ["Failure"]
                ,"176769", ["Fear"]
                ,"061216", ["Follow"]
                ,"48", ["Forget"]
                ,"162767", ["Future"] //"Forward-Time"
                ,"58", ["Gain"]
                ,"1659677889", ["Government","City","Civilization","Structure"]
                ,"4989", ["Grow"]
                ,"0609276a7a9a", ["Harm"]
                ,"060937386a7a8a9a", ["Harmony","Peace"]
                ,"387a8a", ["Have"]
                ,"59788a9a", ["Help"]
                ,"16176978", ["Hide"]
                ,"363969", ["I","Me"] //"Self"
                ,"27", ["Ignore"]
                ,"6a898a9a", ["Imperfect"]
                ,"686a898a9a", ["Imperfect"] //NOTE: Scanner bug?
                ,"166a7a", ["Improve"]
                ,"3a898a9a", ["Impure"]
                ,"16486a899a", ["Intelligence"]
                ,"0a3a4548598a9a", ["Interrupt"]
                ,"163445596a9a", ["Journey"]
                ,"36396a9a", ["Knowledge"]
                ,"05384548", ["Lead"]
                ,"0105162748596789", ["Legacy"]
                ,"6a9a", ["Less"]
                ,"0116496a9a", ["Liberate"]
                ,"676a7a899a", ["Lie"]
                ,"16496a898a", ["Live Again", "Reincarnate"]
                ,"17", ["Lose"]
                ,"17497a9a", ["Message"]
                ,"383a899a", ["Mind"] //"Idea","Thought"
                ,"7a8a", ["More"]
                ,"0609596989", ["Mystery"]
                ,"06090a3a6a9a", ["N'zeer"]
                ,"2748676989", ["Nature"]
                ,"2767", ["New"]
                ,"6769", ["Not","Inside"] //"No", "Absent"
                ,"343a488a", ["Nourish"]
                ,"5989", ["Old"]
                ,"373878", ["Open","Accept"]
                ,"010512233437384578", ["Open All", "Openall"]
                ,"1216274548596978", ["Portal"] //"Opening","Doorway"
                ,"485989", ["Past"]
                ,"0a488a", ["Path"]
                ,"0a232734487a8a", ["Perfection","Balance"]
                ,"060927486a7a8a9a", ["Perspective"]
                ,"0a12277a", ["Potential"]
                ,"3738676a78899a", ["Presence"]
                ,"677889", ["Present","Now"]
                ,"0a676a7a", ["Pure"] //"Purity"
                ,"060959", ["Pursue"]
                ,"0a48899a", ["Chase"] //"Pursue"
                ,"066989", ["Question"]
                ,"27697a9a", ["React"]
                ,"1216586a8a", ["Rebel"]
                ,"050a599a", ["Recharge","Repair"]
                ,"2667", ["Reduce"] //"Contract"
                ,"090a383a69", ["Resist","Resistance","Struggle"]
                ,"377a", ["Response"] //ref: http://glyphtionary.com/ http://decodeingress.me/2014/09/16/passcode-decoding-walkthrough-012/ https://plus.google.com/u/0/+SteinLightman/posts/V84nKXZmVrh
                ,"2327597a9a", ["Restraint"]
                ,"0626", ["Retreat"]
                ,"264969", ["Safety"]
                ,"177a8a", ["Save"] //"Rescue"
                ,"09", ["See"]
                ,"696a7889", ["Seek","Search"]
                ,"2334", ["Self","Individual"]
                ,"2759676a898a", ["Separate"]
                ,"060927486789", ["Shapers","Collective"] //"Shaper"
                //"060927373848676989", ["Shaper/Collective + Being/Human"]
                ,"27344878", ["Share"]
                ,"09377a9a", ["Signal"] //ref: http://decodeingress.me/2014/09/16/passcode-decoding-walkthrough-012/
                ,"78", ["Simple"]
                ,"373a676a", ["Soul"] //"Spirit","Life Force"
                ,"274878", ["Stability", "Stay"]
                ,"67697889", ["Strong"]
                ,"0a1216273a6a7a", ["Sustain"]
                ,"01050a12162327343a456a7a", ["Sustain All"]
                ,"16276a7a898a9a", ["Technology"]
                ,"0878", ["Them"]
                ,"48696a8a9a", ["Together"]
                ,"676a7a898a9a", ["Truth"]
                ,"010517233445696a7889", ["Unbounded"]
                ,"177a", ["Use"]
                ,"06093639", ["Victory"]
                ,"373848", ["Want"]
                ,"3669", ["We","Us"]
                ,"596769", ["Weak"]
                ,"17587a8a", ["Worth"]
                ,"67697a898a", ["XM"] //(Exotic Matter)
                ,"070878", ["You","Your","Other"]
                //,"0109122334696a9a", ["[unknown]"]
                //,"0609232734486789", ["[unknown]"]
                //,"01061226", ["[unknown]"]
                //,"090a373a69", ["[unknown]"]
            ];

    var dicGlyphToWord = new Dictionary();
    for(var ei = 0; ei < DIC.length; ei += 2){
        dicGlyphToWord.add(Glyph.fromString(DIC[ei+0]), DIC[ei+1]);
    }
    var dicWordToGlyph = dicGlyphToWord.createIndex();

    function getWordsFromGlyph(glyph)
    {
        return dicGlyphToWord.get(glyph); //return array
    }
    function getGlyphsFromWord(word)
    {
        return dicWordToGlyph[word.toLowerCase()];
    }

    // ex:
    // "idea" => {word:"idea", Glyph.fromString("1216274548597a9a")}
    // "creativity(1216274548597a9a)" => {word:"creativity", glyph:Glyph.fromString("1216274548597a9a")}
    // "creativity(idea)" => {word:"creativity", glyph:Glyph.fromString("1216274548597a9a")}
    function getWordGlyphFromString(str)
    {
        var arrayWordCode = /^(.+)\((([0-9a][0-9a])*)\)$/i.exec(str); // ex:creativity(1216274548597a9a)
        if(arrayWordCode){
            return {word:arrayWordCode[1], glyph:Glyph.fromString(arrayWordCode[2])};
        }
        else{
            var arrayWordWord = /^(.+)\(([^)]+)\)$/.exec(str); // ex:creativity(idea)
            var wDisplay = arrayWordWord ? arrayWordWord[1] : str;
            var wSearch = arrayWordWord ? arrayWordWord[2] : str;
            var gs = getGlyphsFromWord(wSearch);
            return gs && gs.length > 0 ? {word:wDisplay, glyph:gs[0]} : null;
        }
    }
    function toStringFromWordGlyph(wg)
    {
        return wg.word + "(" + wg.glyph.toString() + ")";
    }

    function getAllWords()
    {
        return Object.keys(dicWordToGlyph);
    }
    function getAllGlyphs()
    {
        var glyphs = [];
        for(var gi = 0; gi < dicGlyphToWord.getEntryCount(); ++gi){
            glyphs.push(dicGlyphToWord.getEntryAt(gi).keyGlyph);
        }
        return glyphs;
    }

    function getWordGlyphRandom()
    {
        do{
            var entryIndex = Math.floor(Math.random() * dicGlyphToWord.getEntryCount());
            var entry = dicGlyphToWord.getEntryAt(entryIndex);
        }
        while(!(entry && entry.keyGlyph && entry.value && entry.value.length > 0));
        return {
            glyph: entry.keyGlyph,
            word: entry.value[Math.floor(Math.random() * entry.value.length)]
        };
    }

    // Exports
    igt.glyphDic = {
        getWordsFromGlyph: getWordsFromGlyph,
        getGlyphsFromWord: getGlyphsFromWord,
        getWordGlyphFromString: getWordGlyphFromString,
        toStringFromWordGlyph: toStringFromWordGlyph,
        getAllWords: getAllWords,
        getAllGlyphs: getAllGlyphs,
        getWordGlyphRandom: getWordGlyphRandom
    };
    // obsolete
    igt.glyphtionary = dicGlyphToWord;
    igt.glyphtionaryIndex = dicWordToGlyph;

})();
<|endoftext|>


<commit_before>

function str_rot13 (str) {
  // http://kevin.vanzonneveld.net
  // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // +   improved by: Ates Goral (http://magnetiq.com)
  // +   bugfixed by: Onno Marsman
  // +   improved by: Rafa? Kukawski (http://blog.kukawski.pl)
  // *     example 1: str_rot13('Kevin van Zonneveld');
  // *     returns 1: 'Xriva ina Mbaariryq'
  // *     example 2: str_rot13('Xriva ina Mbaariryq');
  // *     returns 2: 'Kevin van Zonneveld'
  // *     example 3: str_rot13(33);
  // *     returns 3: '33'
	return (str + '').replace(/[a-z]/gi, function (s) {
		return String.fromCharCode(s.charCodeAt(0) + (s.toLowerCase() < 'n' ? 13 : -13));
	});
}

// We probably just want the element where the text is and find it ourself. e.g. if
// there is highlighted text use it, otherwise use the entire text.
// So the third element may be useless. Fix also in view/tpl/jot.tpl before
// adding to all the editor templates and enabling the feature

// Should probably do some input sanitising and dealing with bbcode, hiding key text, and displaying
// results in a lightbox and/or popup form are left as an exercise for the reader.

function red_encrypt(alg, elem,text) {
	var enc_text = '';
	var newdiv = '';

	if(typeof tinyMCE !== "undefined")
		tinyMCE.triggerSave(false,true);

	var text = $(elem).val();

	// key and hint need to be localised

	var enc_key = prompt(aStr['passphrase']);

	// If you don't provide a key you get rot13, which doesn't need a key
	// but consequently isn't secure.

	if(! enc_key)
		alg = 'rot13';

	if((alg == 'rot13') || (alg == 'triple-rot13'))
		newdiv = "[crypt alg='rot13']" + str_rot13(text) + '[/crypt]';

	if(alg == 'aes256') {

			// This is the prompt we're going to use when the receiver tries to open it.
			// Maybe "Grandma's maiden name" or "our secret place" or something.

			var enc_hint = prompt(aStr['passhint']);

			enc_text = CryptoJS.AES.encrypt(text,enc_key);

			encrypted = enc_text.toString();

			newdiv = "[crypt alg='aes256' hint='" + enc_hint + "']" + encrypted + '[/crypt]';
	}
	if(alg == 'rabbit') {

			// This is the prompt we're going to use when the receiver tries to open it.
			// Maybe "Grandma's maiden name" or "our secret place" or something.

			var enc_hint = prompt(aStr['passhint']);

			enc_text = CryptoJS.Rabbit.encrypt(text,enc_key);
			encrypted = enc_text.toString();

			newdiv = "[crypt alg='rabbit' hint='" + enc_hint + "']" + encrypted + '[/crypt]';
	}
	if(alg == '3des') {

			// This is the prompt we're going to use when the receiver tries to open it.
			// Maybe "Grandma's maiden name" or "our secret place" or something.

			var enc_hint = prompt(aStr['passhint']);

			enc_text = CryptoJS.TripleDES.encrypt(text,enc_key);
			encrypted = enc_text.toString();

			newdiv = "[crypt alg='3des' hint='" + enc_hint + "']" + encrypted + '[/crypt]';
	}

	enc_key = '';

//	alert(newdiv);

	// This might be a comment box on a page with a tinymce editor
	// so check if there is a tinymce editor but also check the display
	// property of our source element - because a tinymce instance
	// will have display "none". If a normal textarea such as in a comment
	// box has display "none" you wouldn't be able to type in it.

	if($(elem).css('display') == 'none' && typeof tinyMCE !== "undefined") {
		tinyMCE.activeEditor.setContent(newdiv);
	}
	else {
		$(elem).val(newdiv);
	}

//	textarea = document.getElementById(elem);
//	if (document.selection) {
//		textarea.focus();
//		selected = document.selection.createRange();
//		selected.text = newdiv;
//	} else if (textarea.selectionStart || textarea.selectionStart == "0") {
//		var start = textarea.selectionStart;
//		var end = textarea.selectionEnd;
//		textarea.value = textarea.value.substring(0, start) + newdiv + textarea.value.substring(end, textarea.value.length);
//	}
}

function red_decrypt(alg,hint,text,elem) {

	var enc_text = '';

	if(alg == 'rot13' || alg == 'triple-rot13')
		enc_text = str_rot13(text);

	if(alg == 'aes256') {
		var enc_key = prompt((hint.length) ? hint : aStr['passphrase']);
		enc_text = CryptoJS.AES.decrypt(text,enc_key);
	}
	if(alg == 'rabbit') {
		var enc_key = prompt((hint.length) ? hint : aStr['passphrase']);
		enc_text = CryptoJS.Rabbit.decrypt(text,enc_key);
	}
	if(alg == '3des') {
		var enc_key = prompt((hint.length) ? hint : aStr['passphrase']);
		enc_text = CryptoJS.TripleDES.decrypt(text,enc_key);
	}

	enc_key = '';

	// Not sure whether to drop this back in the conversation display.
	// It probably needs a lightbox or popup window because any conversation
	// updates could
	// wipe out the text and make you re-enter the key if it was in the
	// conversation. For now we do that so you can read it.

	var enc_result = enc_text.toString(CryptoJS.enc.Utf8);
	delete enc_text;

	// incorrect decryptions *usually* but don't always have zero length
	// If the person typo'd let them try again without reloading the page
	// otherwise they'll have no "padlock" to click to try again.

	if(enc_result.length) {
		$(elem).html(b2h(enc_result));
		enc_result = '';
	}
}

function base64_encode (data) {
  // http://kevin.vanzonneveld.net
  // +   original by: Tyler Akins (http://rumkin.com)
  // +   improved by: Bayron Guevara
  // +   improved by: Thunder.m
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Pellentesque Malesuada
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Rafa? Kukawski (http://kukawski.pl)
  // *     example 1: base64_encode('Kevin van Zonneveld');
  // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  // mozilla has this native
  // - but breaks in 2.0.0.12!
  //if (typeof this.window['btoa'] === 'function') {
  //    return btoa(data);
  //}
	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    enc = "",
    tmp_arr = [];

	if (!data) {
		return data;
	}

	do { // pack three octets into four hexets
		o1 = data.charCodeAt(i++);
		o2 = data.charCodeAt(i++);
		o3 = data.charCodeAt(i++);

		bits = o1 << 16 | o2 << 8 | o3;

		h1 = bits >> 18 & 0x3f;
		h2 = bits >> 12 & 0x3f;
		h3 = bits >> 6 & 0x3f;
		h4 = bits & 0x3f;

    // use hexets to index into b64, and append result to encoded string
		tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
	} while (i < data.length);

	enc = tmp_arr.join('');

	var r = data.length % 3;

	return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);

}

function base64_decode (data) {
  // http://kevin.vanzonneveld.net
  // +   original by: Tyler Akins (http://rumkin.com)
  // +   improved by: Thunder.m
  // +      input by: Aman Gupta
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Onno Marsman
  // +   bugfixed by: Pellentesque Malesuada
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +      input by: Brett Zamir (http://brett-zamir.me)
  // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  // *     returns 1: 'Kevin van Zonneveld'
  // mozilla has this native
  // - but breaks in 2.0.0.12!
  //if (typeof this.window['atob'] === 'function') {
  //    return atob(data);
  //}
	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    dec = "",
    tmp_arr = [];

	if (!data) {
		return data;
	}

	data += '';

	do { // unpack four hexets into three octets using index points in b64
		h1 = b64.indexOf(data.charAt(i++));
		h2 = b64.indexOf(data.charAt(i++));
		h3 = b64.indexOf(data.charAt(i++));
		h4 = b64.indexOf(data.charAt(i++));

		bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;

		o1 = bits >> 16 & 0xff;
		o2 = bits >> 8 & 0xff;
		o3 = bits & 0xff;

		if (h3 == 64) {
			tmp_arr[ac++] = String.fromCharCode(o1);
		} else if (h4 == 64) {
			tmp_arr[ac++] = String.fromCharCode(o1, o2);
		} else {
			tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
		}
	} while (i < data.length);

	dec = tmp_arr.join('');

	return dec;
}

<commit_msg>e2ee algorithms are now pluggable so if you want to roll your own algorithm or do something like swap_bytes(rabbit(left_shift(3,triple_aes256(right_shift(base64(text)))))) - go for it. As long as the person at the other end can reverse it, you can do pretty much whatever you want. I'd like to see the NSA crack that one - especially if the algorithm was called something like "dishwasher" or something which didn't provide a lot of clues.<commit_after>

function str_rot13 (str) {
  // http://kevin.vanzonneveld.net
  // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // +   improved by: Ates Goral (http://magnetiq.com)
  // +   bugfixed by: Onno Marsman
  // +   improved by: Rafa? Kukawski (http://blog.kukawski.pl)
  // *     example 1: str_rot13('Kevin van Zonneveld');
  // *     returns 1: 'Xriva ina Mbaariryq'
  // *     example 2: str_rot13('Xriva ina Mbaariryq');
  // *     returns 2: 'Kevin van Zonneveld'
  // *     example 3: str_rot13(33);
  // *     returns 3: '33'
	return (str + '').replace(/[a-z]/gi, function (s) {
		return String.fromCharCode(s.charCodeAt(0) + (s.toLowerCase() < 'n' ? 13 : -13));
	});
}

// Arrays for pluggable encryptors/decryptors

var red_encryptors = new Array();
var red_decryptors = new Array();

// We probably just want the element where the text is and find it ourself. e.g. if
// there is highlighted text use it, otherwise use the entire text.
// So the third element may be useless. Fix also in view/tpl/jot.tpl before
// adding to all the editor templates and enabling the feature

// Should probably do some input sanitising and dealing with bbcode, hiding key text, and displaying
// results in a lightbox and/or popup form are left as an exercise for the reader.

function red_encrypt(alg, elem,text) {
	var enc_text = '';
	var newdiv = '';

	if(typeof tinyMCE !== "undefined")
		tinyMCE.triggerSave(false,true);

	var text = $(elem).val();

	// key and hint need to be localised

	var enc_key = prompt(aStr['passphrase']);

	// If you don't provide a key you get rot13, which doesn't need a key
	// but consequently isn't secure.

	if(! enc_key)
		alg = 'rot13';

	if((alg == 'rot13') || (alg == 'triple-rot13'))
		newdiv = "[crypt alg='rot13']" + str_rot13(text) + '[/crypt]';

	if(alg == 'aes256') {

			// This is the prompt we're going to use when the receiver tries to open it.
			// Maybe "Grandma's maiden name" or "our secret place" or something.

			var enc_hint = prompt(aStr['passhint']);

			enc_text = CryptoJS.AES.encrypt(text,enc_key);

			encrypted = enc_text.toString();

			newdiv = "[crypt alg='aes256' hint='" + enc_hint + "']" + encrypted + '[/crypt]';
	}
	if(alg == 'rabbit') {

			// This is the prompt we're going to use when the receiver tries to open it.
			// Maybe "Grandma's maiden name" or "our secret place" or something.

			var enc_hint = prompt(aStr['passhint']);

			enc_text = CryptoJS.Rabbit.encrypt(text,enc_key);
			encrypted = enc_text.toString();

			newdiv = "[crypt alg='rabbit' hint='" + enc_hint + "']" + encrypted + '[/crypt]';
	}
	if(alg == '3des') {

			// This is the prompt we're going to use when the receiver tries to open it.
			// Maybe "Grandma's maiden name" or "our secret place" or something.

			var enc_hint = prompt(aStr['passhint']);

			enc_text = CryptoJS.TripleDES.encrypt(text,enc_key);
			encrypted = enc_text.toString();

			newdiv = "[crypt alg='3des' hint='" + enc_hint + "']" + encrypted + '[/crypt]';
	}
	if((red_encryptors.length) && (! newdiv.length)) {
		for(var i = 0; i < red_encryptors.length; i ++) {
			newdiv = red_encryptors[i](alg,text);
			if(newdiv.length)
				break;
		}
	}

	enc_key = '';

//	alert(newdiv);

	// This might be a comment box on a page with a tinymce editor
	// so check if there is a tinymce editor but also check the display
	// property of our source element - because a tinymce instance
	// will have display "none". If a normal textarea such as in a comment
	// box has display "none" you wouldn't be able to type in it.

	if($(elem).css('display') == 'none' && typeof tinyMCE !== "undefined") {
		tinyMCE.activeEditor.setContent(newdiv);
	}
	else {
		$(elem).val(newdiv);
	}

//	textarea = document.getElementById(elem);
//	if (document.selection) {
//		textarea.focus();
//		selected = document.selection.createRange();
//		selected.text = newdiv;
//	} else if (textarea.selectionStart || textarea.selectionStart == "0") {
//		var start = textarea.selectionStart;
//		var end = textarea.selectionEnd;
//		textarea.value = textarea.value.substring(0, start) + newdiv + textarea.value.substring(end, textarea.value.length);
//	}
}

function red_decrypt(alg,hint,text,elem) {

	var dec_text = '';

	if(alg == 'rot13' || alg == 'triple-rot13')
		dec_text = str_rot13(text);
	else {
		var enc_key = prompt((hint.length) ? hint : aStr['passphrase']);
	}

	if(alg == 'aes256') {
		dec_text = CryptoJS.AES.decrypt(text,enc_key);
	}
	if(alg == 'rabbit') {
		dec_text = CryptoJS.Rabbit.decrypt(text,enc_key);
	}
	if(alg == '3des') {
		dec_text = CryptoJS.TripleDES.decrypt(text,enc_key);
	}

	if((red_decryptors.length) && (! dec_text.length)) {
		for(var i = 0; i < red_decryptors.length; i ++) {
			dec_text = red_decryptors[i](text,enc_key);
			if(dec_text.length)
				break;
		}
	}

	enc_key = '';

	// Not sure whether to drop this back in the conversation display.
	// It probably needs a lightbox or popup window because any conversation
	// updates could
	// wipe out the text and make you re-enter the key if it was in the
	// conversation. For now we do that so you can read it.

	var dec_result = dec_text.toString(CryptoJS.enc.Utf8);
	delete dec_text;

	// incorrect decryptions *usually* but don't always have zero length
	// If the person typo'd let them try again without reloading the page
	// otherwise they'll have no "padlock" to click to try again.

	if(dec_result.length) {
		$(elem).html(b2h(dec_result));
		dec_result = '';
	}
}

function base64_encode (data) {
  // http://kevin.vanzonneveld.net
  // +   original by: Tyler Akins (http://rumkin.com)
  // +   improved by: Bayron Guevara
  // +   improved by: Thunder.m
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Pellentesque Malesuada
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Rafa? Kukawski (http://kukawski.pl)
  // *     example 1: base64_encode('Kevin van Zonneveld');
  // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  // mozilla has this native
  // - but breaks in 2.0.0.12!
  //if (typeof this.window['btoa'] === 'function') {
  //    return btoa(data);
  //}
	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    enc = "",
    tmp_arr = [];

	if (!data) {
		return data;
	}

	do { // pack three octets into four hexets
		o1 = data.charCodeAt(i++);
		o2 = data.charCodeAt(i++);
		o3 = data.charCodeAt(i++);

		bits = o1 << 16 | o2 << 8 | o3;

		h1 = bits >> 18 & 0x3f;
		h2 = bits >> 12 & 0x3f;
		h3 = bits >> 6 & 0x3f;
		h4 = bits & 0x3f;

    // use hexets to index into b64, and append result to encoded string
		tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
	} while (i < data.length);

	enc = tmp_arr.join('');

	var r = data.length % 3;

	return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);

}

function base64_decode (data) {
  // http://kevin.vanzonneveld.net
  // +   original by: Tyler Akins (http://rumkin.com)
  // +   improved by: Thunder.m
  // +      input by: Aman Gupta
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Onno Marsman
  // +   bugfixed by: Pellentesque Malesuada
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +      input by: Brett Zamir (http://brett-zamir.me)
  // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  // *     returns 1: 'Kevin van Zonneveld'
  // mozilla has this native
  // - but breaks in 2.0.0.12!
  //if (typeof this.window['atob'] === 'function') {
  //    return atob(data);
  //}
	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    dec = "",
    tmp_arr = [];

	if (!data) {
		return data;
	}

	data += '';

	do { // unpack four hexets into three octets using index points in b64
		h1 = b64.indexOf(data.charAt(i++));
		h2 = b64.indexOf(data.charAt(i++));
		h3 = b64.indexOf(data.charAt(i++));
		h4 = b64.indexOf(data.charAt(i++));

		bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;

		o1 = bits >> 16 & 0xff;
		o2 = bits >> 8 & 0xff;
		o3 = bits & 0xff;

		if (h3 == 64) {
			tmp_arr[ac++] = String.fromCharCode(o1);
		} else if (h4 == 64) {
			tmp_arr[ac++] = String.fromCharCode(o1, o2);
		} else {
			tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
		}
	} while (i < data.length);

	dec = tmp_arr.join('');

	return dec;
}

<|endoftext|>


<commit_before>cordova.define("me.rahul.plugins.iRate.iRate", function(require, exports, module) { var cordova = require('cordova'),
    exec = require('cordova/exec');

var iRate = function() {
        this.options = {};
};

iRate.prototype = {

            launch: function( options, success, error ) {

                    var defaults = {
                                debug   :   "YES",
                                promptAtLaunch  :   "NO",
                                usesUntilPrompt :   10,
                                eventsUntilPrompt   :   10,
                                daysUntilPrompt :   "3.0f",
                                remindPeriod    :   "2.0f",
                                appStoreID  :   11212321,
                                messageTitle : null,
                                message : null,
                                cancelButtonLabel : "No, Thanks",
                                remindButtonLabel : "Remind Me Later",
                                rateButtonLabel : "Rate It Now"
                    };

                    if(options){
                            for (var key in defaults) {
                                if(options[key] != undefined) {
                                    defaults[key]=options[key];
                                }
                            }
                    }

                    cordova.exec(success, error, "iRate", "launch", [defaults] );
}

};

var iRateInstance = new iRate();

module.exports = iRateInstance;

});
<commit_msg>Removed cordova.define<commit_after>var cordova=require('cordova'),
exec=require('cordova/exec');

var iRate = function() {
        this.options = {};
};

iRate.prototype = {

            launch: function( options, success, error ) {

                    var defaults = {
                                debug   :   "YES",
                                promptAtLaunch  :   "NO",
                                usesUntilPrompt :   10,
                                eventsUntilPrompt   :   10,
                                daysUntilPrompt :   "3.0f",
                                remindPeriod    :   "2.0f",
                                appStoreID  :   11212321,
                                messageTitle : null,
                                message : null,
                                cancelButtonLabel : "No, Thanks",
                                remindButtonLabel : "Remind Me Later",
                                rateButtonLabel : "Rate It Now"
                    };

                    if(options){
                            for (var key in defaults) {
                                if(options[key] != undefined) {
                                    defaults[key]=options[key];
                                }
                            }
                    }

                    cordova.exec(success, error, "iRate", "launch", [defaults] );
}

};

var iRateInstance = new iRate();

module.exports = iRateInstance;
<|endoftext|>


<commit_before><commit_msg>removed extra dist file<commit_after><|endoftext|>


<commit_before>var margin = {top:30, right:10, bottom:20, left:80};

var width = 960 - margin.left - margin.right;

var height = 500 - margin.top - margin.bottom;

var svgContainer = d3.select("#chartID").append("svg").attr("width", width+margin.left + margin.right).attr("height",height+margin.top + margin.bottom).append("g").attr("transform", "translate("+ margin.left +","+ margin.top +")");

var xScale = d3.scale.linear().domain([0,100]).range([0,width]);

var yScale = d3.scale.linear().range([height, 0]);

var xAxis = d3.svg.axis().scale(xScale).orient("bottom");

var yAxis = d3.svg.axis().scale(yScale).orient("left");

var xAxis_g = svgContainer.append("g").attr("class", "x axis").attr("transform", "translate(0," + height + ")").call(xAxis);

var yAxis_g = svgContainer.append("g").attr("class", "y axis").call(yAxis).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", ".71em").style("text-anchor", "end").text("Price ($)");

d3.select(window).on('resize', resize);

function resize() {
	console.log('----resize function----');
    // update width
    width = parseInt(d3.select('#chartID').style('width'), 10);
    width = width - margin.left - margin.right;
	console.log('----resiz width----'+width);
    // resize the chart
    if(width<870){
    	xScale.range([0, width]);

    d3.select(svgContainer.node().parentNode)
        .style('width', (width + margin.left + margin.right) + 'px');
    svgContainer.select('.x.axis').call(xAxis.orient('bottom'));
    }
}
<commit_msg>responsive axis code with comments- commit<commit_after>var margin = {top:30, right:10, bottom:20, left:80};

var width = 960 - margin.left - margin.right;

var height = 500 - margin.top - margin.bottom;

var svgContainer = d3.select("#chartID").append("svg").attr("width", width+margin.left + margin.right).attr("height",height+margin.top + margin.bottom).append("g").attr("transform", "translate("+ margin.left +","+ margin.top +")");

var xScale = d3.scale.linear().domain([0,100]).range([0,width]);

var yScale = d3.scale.linear().range([height, 0]);

var xAxis = d3.svg.axis().scale(xScale).orient("bottom");

var yAxis = d3.svg.axis().scale(yScale).orient("left");

var xAxis_g = svgContainer.append("g").attr("class", "x axis").attr("transform", "translate(0," + height + ")").call(xAxis);

var yAxis_g = svgContainer.append("g").attr("class", "y axis").call(yAxis).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", ".71em").style("text-anchor", "end").text("Price ($)");

d3.select(window).on('resize', resize);

// Resize the chart based on window size
function resize() {
    // update width
    width = parseInt(d3.select('#chartID').style('width'), 10);
    width = width - margin.left - margin.right;
    // resize the chart
    if(width<870){
    	xScale.range([0, width]);

    d3.select(svgContainer.node().parentNode)
        .style('width', (width + margin.left + margin.right) + 'px');
    svgContainer.select('.x.axis').call(xAxis.orient('bottom'));
    }
}
<|endoftext|>


<commit_before>const Command = require("../base/Command");
// const {inspect} = require('util');

class GuildSearch extends Command {
    constructor(client) {
        super(client, {
            name: "guildsearch",
            category: "SWGoH",
            aliases: ["search", "gs"],
            permissions: ["EMBED_LINKS"],
            flags: {
                "ships": {
                    aliases: ["s", "ship"]
                },
                reverse: {
                    aliases: ["rev"]
                }
            },
            subArgs: {
                sort: {
                    aliases: [],
                    default: "name"
                }
            }
        });
    }

    async run(client, message, [userID, ...searchChar], options) { // eslint-disable-line no-unused-vars
        let starLvl = 0;
        const sortType = options.subArgs.sort ? options.subArgs.sort.toLowerCase() : "name";
        const reverse = options.flags.reverse;
        const rarityMap = {
            "ONESTAR": 1,
            "TWOSTAR": 2,
            "THREESTAR": 3,
            "FOURSTAR": 4,
            "FIVESTAR": 5,
            "SIXSTAR": 6,
            "SEVENSTAR": 7
        };

        // If there's enough elements in searchChar, and it's in the format of a number*
        if (searchChar.length > 0 && !isNaN(parseInt(searchChar[searchChar.length-1]))) {
            starLvl = parseInt(searchChar.pop());
            if (starLvl < 0 || starLvl > 7) {
                return message.channel.send(message.language.get("COMMAND_GUILDSEARCH_BAD_STAR"));
            }
        }

        // Need to get the allycode from the db, then use that
        if (!userID) {
            return message.channel.send(message.language.get("COMMAND_GUILDSEARCH_MISSING_CHAR"));
        }
        if (userID === "me" || client.isUserID(userID) || client.isAllyCode(userID)) {
            userID = await client.getAllyCode(message, userID);
            if (!userID.length) {
                return message.channel.send(message.language.get("BASE_SWGOH_NO_GUILD_FOR_USER", message.guildSettings.prefix));
            }
            userID = userID[0];
        } else {
            // If they're just looking for a character for themselves, get the char
            searchChar = [userID].concat(searchChar);
            userID = await client.getAllyCode(message, message.author.id);
            if (!userID.length) {
                return message.channel.send(message.language.get("BASE_SWGOH_NO_GUILD_FOR_USER", message.guildSettings.prefix));
            }
            userID = userID[0];
        }

        if (!searchChar.length) {
            return message.channel.send(message.language.get("COMMAND_GUILDSEARCH_MISSING_CHAR"));
        }

        searchChar = searchChar.join(" ");

        const chars = !options.flags.ships ? client.findChar(searchChar, client.characters) : client.findChar(searchChar, client.ships, true);

        let character;

        if (chars.length === 0) {
            return message.channel.send(message.language.get("COMMAND_GUILDSEARCH_NO_RESULTS", searchChar));
        } else if (chars.length > 1) {
            const charL = [];
            const charS = chars.sort((p, c) => p.name > c.name ? 1 : -1);
            charS.forEach(c => {
                charL.push(c.name);
            });
            return message.channel.send(message.language.get("COMMAND_GUILDSEARCH_CHAR_LIST", charL.join("\n")));
        } else {
            character = chars[0];
        }

        const msg = await message.channel.send(message.language.get("COMMAND_GUILDSEARCH_PLEASE_WAIT"));

        const cooldown = client.getPlayerCooldown(message.author.id);
        let guild = null;
        try {
            guild = await client.swgohAPI.guild(userID, null, cooldown);
        } catch (e) {
            console.log("ERROR(GS) getting guild: " + e);
            return message.channel.send({embed: {
                author: {
                    name: "Something Broke getting your guild's roster"
                },
                description: client.codeBlock(e) + "Please try again in a bit."
            }});
        }
        let gRoster;
        if (!guild || !guild.roster || !guild.roster.length) {
            return msg.edit(message.language.get("BASE_SWGOH_NO_GUILD"));
        } else {
            msg.edit("Found guild `" + guild.name + "`!");
            gRoster = guild.roster.map(m => m.allyCode);
        }

        if (!gRoster.length) {
            return msg.edit("I can't find any players in the requested guild.");
        }

        let guildGG;
        try {
            guildGG = await client.swgohAPI.guildGG(gRoster, null, cooldown);
        } catch (e) {
            console.log("ERROR(GS) getting guild: " + e);
            return message.channel.send({embed: {
                author: {
                    name: "Something Broke while getting your guild's characters"
                },
                description: client.codeBlock(e) + "Please try again in a bit."
            }});
        }

        // Get the list of people with that character
        const guildChar = guildGG.roster[character.uniqueName];

        if (!guildChar || guildChar.length === 0) {
            return msg.edit({embed: {
                author: {
                    name: message.language.get("BASE_SWGOH_NAMECHAR_HEADER", guild.name, character.name)
                },
                description: message.language.get("COMMAND_GUILDSEARCH_NO_CHARACTER"),
                footer: {
                    text: message.language.get("BASE_SWGOH_LAST_UPDATED", client.duration(guild.updated, message))
                }
            }});
        }

        const totalUnlocked = guildChar.length;

        // Fill in everyone that does not have it since everyone is guaranteed to have jedi consular
        guildGG.roster["JEDIKNIGHTCONSULAR"].forEach(j => {
            // If they have both the targeted character and consular, ignore them
            const filtered = guildChar.filter(p => p.player === j.player);

            // If they don't, it'll be a 0 length array, so fill it in with 0 stats
            if (!filtered.length) {
                guildChar.push({
                    player: j.player,       // Player name
                    allyCode: j.allyCode,   // Ally code
                    gearLevel: 0,
                    gp: 0,
                    level: 0,
                    starLevel: 0,
                    zetas: [],
                    gear: [],
                    type: j.type
                });
            }
        });

        // Can get the order from abilities table => skillReferenceList
        let maxZ = 0;
        const zetas = [];
        const apiChar = await client.swgohAPI.getCharacter(character.uniqueName);
        for (const ab of apiChar.skillReferenceList) {
            if (ab.cost.AbilityMatZeta > 0) {
                maxZ = maxZ + 1;
                zetas.push(ab.skillId);
            }
        }

        let sortedGuild = [];
        if (sortType === "name") {
            // Sort by name
            if (!reverse) {
                sortedGuild = guildChar.sort((p, c) => p.player.toLowerCase() > c.player.toLowerCase() ? 1 : -1);
            } else {
                sortedGuild = guildChar.sort((p, c) => p.player.toLowerCase() < c.player.toLowerCase() ? 1 : -1);
            }
        } else if (sortType === "gp") {
            // Sort by gp
            if (!reverse) {
                sortedGuild = guildChar.sort((p, c) => p.gp - c.gp);
            } else {
                sortedGuild = guildChar.sort((p, c) => c.gp - p.gp);
            }
        } else if (sortType === "gear") {
            // Sort by gear
            if (!reverse) {
                sortedGuild = guildChar.sort((p, c) => p.gearLevel - c.gearLevel);
            } else {
                sortedGuild = guildChar.sort((p, c) => c.gearLevel - p.gearLevel);
            }
        } else {
            return msg.edit(message.language.get("COMMAND_GUILDSEARCH_BAD_SORT", sortType, ["name", "gp"]));
        }

        const charOut = {};
        for (const member of sortedGuild) {
            console.log(member.zetas);
            if (isNaN(parseInt(member.starLevel))) member.starLevel = rarityMap[member.starLevel];
            const gearStr = "⚙" + member.gearLevel + " ".repeat(2 - member.gearLevel.toString().length);
            let z = " | ";
            zetas.forEach((zeta, ix) => {
                const pZeta = member.zetas.find(pz => pz === zeta);
                if (!pZeta) {
                    z += " ";
                } else {
                    z += (ix + 1).toString();
                }
            });
            const gpStr = parseInt(member.gp).toLocaleString();

            let uStr = member.starLevel > 0 ? `**\`[${gearStr} | ${gpStr + " ".repeat(6 - gpStr.length)}${maxZ > 0 ? z : ""}]\`** ${member.player}` : member.player;

            uStr = client.expandSpaces(uStr);

            if (!charOut[member.starLevel]) {
                charOut[member.starLevel] = [uStr];
            } else {
                charOut[member.starLevel].push(uStr);
            }
        }

        const fields = [];
        const outArr = reverse ? Object.keys(charOut).reverse() : Object.keys(charOut);
        outArr.forEach(star => {
            if (star >= starLvl) {
                const msgArr = client.msgArray(charOut[star], "\n", 1000);
                msgArr.forEach((msg, ix) => {
                    const name = star === 0 ? message.language.get("COMMAND_GUILDSEARCH_NOT_ACTIVATED", charOut[star].length) : message.language.get("COMMAND_GUILDSEARCH_STAR_HEADER", star, charOut[star].length);
                    fields.push({
                        name: msgArr.length > 1 ? name + ` (${ix+1}/${msgArr.length})` : name,
                        value: msgArr[ix]
                    });
                });
            }
        });

        const updated = client.duration(guildGG.updated, message);
        msg.edit({embed: {
            author: {
                name: message.language.get("BASE_SWGOH_NAMECHAR_HEADER_NUM", guild.name, character.name, totalUnlocked)
            },
            fields: fields,
            footer: {
                text: message.language.get("BASE_SWGOH_LAST_UPDATED", updated)
            }
        }});
    }
}

module.exports = GuildSearch;

<commit_msg>Updated guildsearch to show level instead of gear for ships<commit_after>const Command = require("../base/Command");
// const {inspect} = require('util');

class GuildSearch extends Command {
    constructor(client) {
        super(client, {
            name: "guildsearch",
            category: "SWGoH",
            aliases: ["search", "gs"],
            permissions: ["EMBED_LINKS"],
            flags: {
                "ships": {
                    aliases: ["s", "ship"]
                },
                reverse: {
                    aliases: ["rev"]
                }
            },
            subArgs: {
                sort: {
                    aliases: [],
                    default: "name"
                }
            }
        });
    }

    async run(client, message, [userID, ...searchChar], options) { // eslint-disable-line no-unused-vars
        let starLvl = 0;
        const sortType = options.subArgs.sort ? options.subArgs.sort.toLowerCase() : "name";
        const reverse = options.flags.reverse;
        const rarityMap = {
            "ONESTAR": 1,
            "TWOSTAR": 2,
            "THREESTAR": 3,
            "FOURSTAR": 4,
            "FIVESTAR": 5,
            "SIXSTAR": 6,
            "SEVENSTAR": 7
        };

        // If there's enough elements in searchChar, and it's in the format of a number*
        if (searchChar.length > 0 && !isNaN(parseInt(searchChar[searchChar.length-1]))) {
            starLvl = parseInt(searchChar.pop());
            if (starLvl < 0 || starLvl > 7) {
                return message.channel.send(message.language.get("COMMAND_GUILDSEARCH_BAD_STAR"));
            }
        }

        // Need to get the allycode from the db, then use that
        if (!userID) {
            return message.channel.send(message.language.get("COMMAND_GUILDSEARCH_MISSING_CHAR"));
        }
        if (userID === "me" || client.isUserID(userID) || client.isAllyCode(userID)) {
            userID = await client.getAllyCode(message, userID);
            if (!userID.length) {
                return message.channel.send(message.language.get("BASE_SWGOH_NO_GUILD_FOR_USER", message.guildSettings.prefix));
            }
            userID = userID[0];
        } else {
            // If they're just looking for a character for themselves, get the char
            searchChar = [userID].concat(searchChar);
            userID = await client.getAllyCode(message, message.author.id);
            if (!userID.length) {
                return message.channel.send(message.language.get("BASE_SWGOH_NO_GUILD_FOR_USER", message.guildSettings.prefix));
            }
            userID = userID[0];
        }

        if (!searchChar.length) {
            return message.channel.send(message.language.get("COMMAND_GUILDSEARCH_MISSING_CHAR"));
        }

        searchChar = searchChar.join(" ");

        const chars = !options.flags.ships ? client.findChar(searchChar, client.characters) : client.findChar(searchChar, client.ships, true);

        let character;

        if (chars.length === 0) {
            return message.channel.send(message.language.get("COMMAND_GUILDSEARCH_NO_RESULTS", searchChar));
        } else if (chars.length > 1) {
            const charL = [];
            const charS = chars.sort((p, c) => p.name > c.name ? 1 : -1);
            charS.forEach(c => {
                charL.push(c.name);
            });
            return message.channel.send(message.language.get("COMMAND_GUILDSEARCH_CHAR_LIST", charL.join("\n")));
        } else {
            character = chars[0];
        }

        const msg = await message.channel.send(message.language.get("COMMAND_GUILDSEARCH_PLEASE_WAIT"));

        const cooldown = client.getPlayerCooldown(message.author.id);
        let guild = null;
        try {
            guild = await client.swgohAPI.guild(userID, null, cooldown);
        } catch (e) {
            console.log("ERROR(GS) getting guild: " + e);
            return message.channel.send({embed: {
                author: {
                    name: "Something Broke getting your guild's roster"
                },
                description: client.codeBlock(e) + "Please try again in a bit."
            }});
        }
        let gRoster;
        if (!guild || !guild.roster || !guild.roster.length) {
            return msg.edit(message.language.get("BASE_SWGOH_NO_GUILD"));
        } else {
            msg.edit("Found guild `" + guild.name + "`!");
            gRoster = guild.roster.map(m => m.allyCode);
        }

        if (!gRoster.length) {
            return msg.edit("I can't find any players in the requested guild.");
        }

        let guildGG;
        try {
            guildGG = await client.swgohAPI.guildGG(gRoster, null, cooldown);
        } catch (e) {
            console.log("ERROR(GS) getting guild: " + e);
            return message.channel.send({embed: {
                author: {
                    name: "Something Broke while getting your guild's characters"
                },
                description: client.codeBlock(e) + "Please try again in a bit."
            }});
        }

        // Get the list of people with that character
        const guildChar = guildGG.roster[character.uniqueName];

        if (!guildChar || guildChar.length === 0) {
            return msg.edit({embed: {
                author: {
                    name: message.language.get("BASE_SWGOH_NAMECHAR_HEADER", guild.name, character.name)
                },
                description: message.language.get("COMMAND_GUILDSEARCH_NO_CHARACTER"),
                footer: {
                    text: message.language.get("BASE_SWGOH_LAST_UPDATED", client.duration(guild.updated, message))
                }
            }});
        }

        const totalUnlocked = guildChar.length;

        // Fill in everyone that does not have it since everyone is guaranteed to have jedi consular
        guildGG.roster["JEDIKNIGHTCONSULAR"].forEach(j => {
            // If they have both the targeted character and consular, ignore them
            const filtered = guildChar.filter(p => p.player === j.player);

            // If they don't, it'll be a 0 length array, so fill it in with 0 stats
            if (!filtered.length) {
                guildChar.push({
                    player: j.player,       // Player name
                    allyCode: j.allyCode,   // Ally code
                    gearLevel: 0,
                    gp: 0,
                    level: 0,
                    starLevel: 0,
                    zetas: [],
                    gear: [],
                    type: j.type
                });
            }
        });

        // Can get the order from abilities table => skillReferenceList
        let maxZ = 0;
        const zetas = [];
        const apiChar = await client.swgohAPI.getCharacter(character.uniqueName);
        for (const ab of apiChar.skillReferenceList) {
            if (ab.cost && ab.cost.AbilityMatZeta > 0) {
                maxZ = maxZ + 1;
                zetas.push(ab.skillId);
            }
        }

        let sortedGuild = [];
        if (sortType === "name") {
            // Sort by name
            if (!reverse) {
                sortedGuild = guildChar.sort((p, c) => p.player.toLowerCase() > c.player.toLowerCase() ? 1 : -1);
            } else {
                sortedGuild = guildChar.sort((p, c) => p.player.toLowerCase() < c.player.toLowerCase() ? 1 : -1);
            }
        } else if (sortType === "gp") {
            // Sort by gp
            if (!reverse) {
                sortedGuild = guildChar.sort((p, c) => p.gp - c.gp);
            } else {
                sortedGuild = guildChar.sort((p, c) => c.gp - p.gp);
            }
        } else if (sortType === "gear") {
            // Sort by gear
            if (!reverse) {
                sortedGuild = guildChar.sort((p, c) => p.gearLevel - c.gearLevel);
            } else {
                sortedGuild = guildChar.sort((p, c) => c.gearLevel - p.gearLevel);
            }
        } else {
            return msg.edit(message.language.get("COMMAND_GUILDSEARCH_BAD_SORT", sortType, ["name", "gp"]));
        }

        const charOut = {};
        for (const member of sortedGuild) {
            if (isNaN(parseInt(member.starLevel))) member.starLevel = rarityMap[member.starLevel];
            const gearStr = "⚙" + member.gearLevel + " ".repeat(2 - member.gearLevel.toString().length);
            let z = " | ";
            zetas.forEach((zeta, ix) => {
                const pZeta = member.zetas.find(pz => pz === zeta);
                if (!pZeta) {
                    z += " ";
                } else {
                    z += (ix + 1).toString();
                }
            });
            const gpStr = parseInt(member.gp).toLocaleString();

            let uStr;
            if (member.starLevel > 0) {
                if (options.flags.ships) {
                    uStr = `**\`[Lvl ${member.level} | ${gpStr + " ".repeat(6 - gpStr.length)}${maxZ > 0 ? z : ""}]\`** ${member.player}`;
                } else {
                    uStr = `**\`[${gearStr} | ${gpStr + " ".repeat(6 - gpStr.length)}${maxZ > 0 ? z : ""}]\`** ${member.player}`;
                }
            } else {
                uStr = member.player;
            }

            uStr = client.expandSpaces(uStr);

            if (!charOut[member.starLevel]) {
                charOut[member.starLevel] = [uStr];
            } else {
                charOut[member.starLevel].push(uStr);
            }
        }

        const fields = [];
        const outArr = reverse ? Object.keys(charOut).reverse() : Object.keys(charOut);
        outArr.forEach(star => {
            if (star >= starLvl) {
                const msgArr = client.msgArray(charOut[star], "\n", 1000);
                msgArr.forEach((msg, ix) => {
                    const name = star === 0 ? message.language.get("COMMAND_GUILDSEARCH_NOT_ACTIVATED", charOut[star].length) : message.language.get("COMMAND_GUILDSEARCH_STAR_HEADER", star, charOut[star].length);
                    fields.push({
                        name: msgArr.length > 1 ? name + ` (${ix+1}/${msgArr.length})` : name,
                        value: msgArr[ix]
                    });
                });
            }
        });

        const updated = client.duration(guild.updated, message);
        msg.edit({embed: {
            author: {
                name: message.language.get("BASE_SWGOH_NAMECHAR_HEADER_NUM", guild.name, character.name, totalUnlocked)
            },
            fields: fields,
            footer: {
                text: message.language.get("BASE_SWGOH_LAST_UPDATED", updated)
            }
        }});
    }
}

module.exports = GuildSearch;

<|endoftext|>


<commit_before>const fs = require('fs');

if (fs.readFileSync(__dirname + '/env.js')) {
    require('./env');
}

const express = require('express');
const timeout = require('connect-timeout');
const compression = require('compression');
const bodyParser = require('body-parser');
const api = require('./api/api');
const allowCors = require('./allowCors');

const publicPath = __dirname + '/../dist';

const app = express();

app.set('port', process.env.PORT || 5000);

app.use(allowCors);
app.use(timeout('60s'));
app.use(compression());
app.use(express.static(publicPath));

// parse application/json
app.use(bodyParser.json({ limit: '5mb' }));

app.use((req, res, next) => !req.timedout && next());

// views is directory for all template files
app.set('views', publicPath);
app.set('view engine', 'ejs');

api.init(app);

app.get('/', (request, response) => response.render('index'));

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});
<commit_msg>fix: replace readFileSync -> existsSync<commit_after>const fs = require('fs');

if (fs.existsSync(__dirname + '/env.js')) {
    require('./env');
}

const express = require('express');
const timeout = require('connect-timeout');
const compression = require('compression');
const bodyParser = require('body-parser');
const api = require('./api/api');
const allowCors = require('./allowCors');

const publicPath = __dirname + '/../dist';

const app = express();

app.set('port', process.env.PORT || 5000);

app.use(allowCors);
app.use(timeout('60s'));
app.use(compression());
app.use(express.static(publicPath));

// parse application/json
app.use(bodyParser.json({ limit: '5mb' }));

app.use((req, res, next) => !req.timedout && next());

// views is directory for all template files
app.set('views', publicPath);
app.set('view engine', 'ejs');

api.init(app);

app.get('/', (request, response) => response.render('index'));

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});
<|endoftext|>