<commit_before>/*
	Dynamically generate projects from JSON for Parallelism by HTML5 UP
	Christian Frisson
	MIT licensed
*/

function initProjects(thumbHeight) {
    d3.json("projects.json", function(error, data) {
        if (error) console.log(error)
            //var people = data.people;
        var article = d3.select("#reel")
            .selectAll("item thumb")
            .data(data.projects)
            .enter()
            .append(function(d) {
                return document.createElement("article");
            })
            .attr("data-width", function(d) {
                return (d.thumb.width * thumbHeight / d.thumb.height);
            })
            .attr("class", "item thumb")
        article.append(function(d) {
            var h2 = document.createElement("h2");
            var innerHTML = d.title;
            innerHTML += " (";
            if (d.eventName !== undefined) {
                innerHTML += d.eventName;
            }
            if (d.eventName !== undefined && d.eventYear !== undefined) {
                innerHTML += " ";
            }
            if (d.eventYear !== undefined) {
                innerHTML += d.eventYear;
            }
            innerHTML += ")";
            h2.innerHTML = innerHTML;
            return h2;
        });
        article.append(function(d) {
                var a = document.createElement("a");
                a.className = "image";
                if (d.video !== undefined) {
                    a.href = "http://vimeo.com/" + d.video.id;
                    a.setAttribute("data-poptrox", "vimeo,800x480");
                } else if (d.image !== undefined) {
                    a.href = "images/fulls/" + d.image.stem;
                } else {
                    a.href = "images/fulls/" + d.thumb.stem;
                }
                return a;
            })
            .append(function(d) {
                var img = document.createElement("img");
                if (d.thumb.stem !== undefined)
                    img.src = "images/thumbs/" + d.thumb.stem;
                // Pass caption to poptrox
                d.caption = "";

                /*d.caption += " ";
                d.caption +="project: ";*/

                d.caption += d.title;

                if (d.publications === undefined) {
                    d.caption += " (";
                    if (d.eventName !== undefined) {
                        d.caption += d.eventName;
                    }
                    if (d.eventName !== undefined && d.eventYear !== undefined) {
                        d.caption += " ";
                    }
                    if (d.eventYear !== undefined) {
                        d.caption += d.eventYear;
                    }
                    d.caption += ")";
                    d.caption += "
"
                    if (d.subtitle !== undefined) {
                        d.caption += "
" + d.subtitle + "
";
                    }
                } else {
                    if (d.subtitle !== undefined) {
                        d.caption += ": " + d.subtitle;
                    }
                    d.caption += "
"
                }

                var thesis = false;
                if (d.publications !== undefined) {
                    d.caption += "
"
                    d.caption += " ";
                    d.caption += "dissemination: ";
                    d.publications.forEach(function(publication, i) {
                        if (i > 0) {
                            d.caption += " and "
                        }
                        //if (publication.conference !== undefined) {

                        if (publication.type === "phdthesis") {
                            thesis = true;
                            d.caption += "PhD thesis";
                        } else if (publication.type !== undefined) {
                            d.caption += publication.type + " ";
                        }

                        if (publication.presentation !== undefined) {
                            d.caption += publication.presentation
                            if (publication.presentation === "oral") d.caption += " presentation"
                            d.caption += " "
                        }
                        if (publication.conference !== undefined) {
                            d.caption += "at ";
                            if (publication.conference.split("ACM").length === 1) {
                                d.caption += "the ";
                            }
                            d.caption += publication.conference;
                            if (publication.series !== undefined && publication.series !== publication.conference) {
                                d.caption += " ("
                                d.caption += publication.series;
                                //d.caption += ")"
                            }
                            if (publication.year !== undefined && publication.year.toString().length === 4) {
                                //d.caption += " " + publication.year;
                                d.caption += "'";
                                d.caption += publication.year.toString().charAt(2);
                                d.caption += publication.year.toString().charAt(3);
                            }
                            if (publication.series !== undefined && publication.series !== publication.conference) {
                                d.caption += ")"
                            }

                            if (publication.acmDLAuthorizeId !== undefined) {

                                d.caption += ' '
                                d.caption += '';
                            }
                        } else if (publication.university !== undefined) {
                            d.caption += " at ";
                            d.caption += publication.university;
                            if (publication.year !== undefined) {
                                d.caption += " (" + publication.year + ")";
                            }
                        }
                        /*if(publication.location !== undefined){
                            if(publication.location.city !== undefined){
                                d.caption += ", " + publication.location.city;
                            }
                            if(publication.location.country !== undefined){
                                d.caption += ", " + publication.location.country;
                            }
                        }*/

                        //}
                    });
                    d.caption += "
";
                }

                /*if (d.dataset !== undefined) {
                    d.caption += "
"
                    d.caption += " ";
                    d.caption += "dataset: " + d.dataset + "
";
                }*/

                if (d.people !== undefined) {
                    d.caption += "
";
                    d.caption += " ";
                    d.caption += (thesis ? "jury: " : "in collaboration with: ");
                    for (var n = 0; n < d.people.length; n++) {
                        if (d.people[n][0] !== "Christian" && d.people[n][1] !== "Frisson") {
                            /*var author= people.find(
							function(e){
								if(d.people[n][0] == e.given && d.people[n][1] == e.family){
									return e;
								}
							});
						if(author !== undefined){
	                        d.caption += author.given;
	                        d.caption += " ";
	                        d.caption += author.family;
	                        if(n<d.people.length-1){
	                            d.caption += ", ";
	                        }
						}*/
                            if (d.people[n][0] !== undefined && d.people[n][1] !== undefined) {
                                d.caption += d.people[n][0];
                                d.caption += " ";
                                d.caption += d.people[n][1];
                                if (n < d.people.length - 1) {
                                    d.caption += ", ";
                                }
                            }

                        }
                    }
                    d.caption += "
";
                }

                if (d.contribs !== undefined) {
                    //d.caption += "
contributions: " + d.contribs + "
";
                    d.caption += "
"

                    d.caption += " my contributions: ";

                    //d.caption += "
"
                    d.contribs.forEach(function(contrib, i) {
                        if (i > 0) d.caption += ",";
                        if (i === d.contribs.length - 1) d.caption += "

"
                            //d.caption += "
";
                        d.caption += " ";

                        if (contrib.type === "development") {
                            d.caption += "";

                            if (d.code !== undefined && d.code.host === "github") {
                                var url = "https://github.com/" + d.code.account + "/"
                                if (d.code.repo !== undefined) url += d.code.repo;
                                d.caption += " ";
                                d.caption += "Github"
                                d.caption += "";
                            }
                        } else {
                            d.caption += " ";
                        }
                        d.caption += " ";
                        //d.caption += "(";
                        d.caption += contrib.desc;
                        //d.caption += ")";
                        //d.caption += "
";
                    });
                    d.caption += "
"
                    d.caption += "
";
                }
                d.caption += "
"
                return img;
            })
    });
};<commit_msg>Support YouTube videos<commit_after>/*
	Dynamically generate projects from JSON for Parallelism by HTML5 UP
	Christian Frisson
	MIT licensed
*/

function initProjects(thumbHeight) {
    d3.json("projects.json", function(error, data) {
        if (error) console.log(error)
            //var people = data.people;
        var article = d3.select("#reel")
            .selectAll("item thumb")
            .data(data.projects)
            .enter()
            .append(function(d) {
                return document.createElement("article");
            })
            .attr("data-width", function(d) {
                return (d.thumb.width * thumbHeight / d.thumb.height);
            })
            .attr("class", "item thumb")
        article.append(function(d) {
            var h2 = document.createElement("h2");
            var innerHTML = d.title;
            innerHTML += " (";
            if (d.eventName !== undefined) {
                innerHTML += d.eventName;
            }
            if (d.eventName !== undefined && d.eventYear !== undefined) {
                innerHTML += " ";
            }
            if (d.eventYear !== undefined) {
                innerHTML += d.eventYear;
            }
            innerHTML += ")";
            h2.innerHTML = innerHTML;
            return h2;
        });
        article.append(function(d) {
                var a = document.createElement("a");
                a.className = "image";
                if (d.video !== undefined) {
                    if (d.video.host === "vimeo"){
                        a.href = "http://vimeo.com/" + d.video.id;
                        a.setAttribute("data-poptrox", "vimeo,800x480");
                    }
                    else if (d.video.host === "youtube"){
                        a.href = "http://youtube.com/watch?v=" + d.video.id;
                        a.setAttribute("data-poptrox", "youtube,800x480");
                    }
                } else if (d.image !== undefined) {
                    a.href = "images/fulls/" + d.image.stem;
                } else {
                    a.href = "images/fulls/" + d.thumb.stem;
                }
                return a;
            })
            .append(function(d) {
                var img = document.createElement("img");
                if (d.thumb.stem !== undefined)
                    img.src = "images/thumbs/" + d.thumb.stem;
                // Pass caption to poptrox
                d.caption = "";

                /*d.caption += " ";
                d.caption +="project: ";*/

                d.caption += d.title;

                if (d.publications === undefined) {
                    d.caption += " (";
                    if (d.eventName !== undefined) {
                        d.caption += d.eventName;
                    }
                    if (d.eventName !== undefined && d.eventYear !== undefined) {
                        d.caption += " ";
                    }
                    if (d.eventYear !== undefined) {
                        d.caption += d.eventYear;
                    }
                    d.caption += ")";
                    d.caption += "
"
                    if (d.subtitle !== undefined) {
                        d.caption += "
" + d.subtitle + "
";
                    }
                } else {
                    if (d.subtitle !== undefined) {
                        d.caption += ": " + d.subtitle;
                    }
                    d.caption += "
"
                }

                var thesis = false;
                if (d.publications !== undefined) {
                    d.caption += "
"
                    d.caption += " ";
                    d.caption += "dissemination: ";
                    d.publications.forEach(function(publication, i) {
                        if (i > 0) {
                            d.caption += " and "
                        }
                        //if (publication.conference !== undefined) {

                        if (publication.type === "phdthesis") {
                            thesis = true;
                            d.caption += "PhD thesis";
                        } else if (publication.type !== undefined) {
                            d.caption += publication.type + " ";
                        }

                        if (publication.presentation !== undefined) {
                            d.caption += publication.presentation
                            if (publication.presentation === "oral") d.caption += " presentation"
                            d.caption += " "
                        }
                        if (publication.conference !== undefined) {
                            d.caption += "at ";
                            if (publication.conference.split("ACM").length === 1) {
                                d.caption += "the ";
                            }
                            d.caption += publication.conference;
                            if (publication.series !== undefined && publication.series !== publication.conference) {
                                d.caption += " ("
                                d.caption += publication.series;
                                //d.caption += ")"
                            }
                            if (publication.year !== undefined && publication.year.toString().length === 4) {
                                //d.caption += " " + publication.year;
                                d.caption += "'";
                                d.caption += publication.year.toString().charAt(2);
                                d.caption += publication.year.toString().charAt(3);
                            }
                            if (publication.series !== undefined && publication.series !== publication.conference) {
                                d.caption += ")"
                            }

                            if (publication.acmDLAuthorizeId !== undefined) {

                                d.caption += ' '
                                d.caption += '';
                            }
                        } else if (publication.university !== undefined) {
                            d.caption += " at ";
                            d.caption += publication.university;
                            if (publication.year !== undefined) {
                                d.caption += " (" + publication.year + ")";
                            }
                        }
                        /*if(publication.location !== undefined){
                            if(publication.location.city !== undefined){
                                d.caption += ", " + publication.location.city;
                            }
                            if(publication.location.country !== undefined){
                                d.caption += ", " + publication.location.country;
                            }
                        }*/

                        //}
                    });
                    d.caption += "
";
                }

                /*if (d.dataset !== undefined) {
                    d.caption += "
"
                    d.caption += " ";
                    d.caption += "dataset: " + d.dataset + "
";
                }*/

                if (d.people !== undefined) {
                    d.caption += "
";
                    d.caption += " ";
                    d.caption += (thesis ? "jury: " : "in collaboration with: ");
                    for (var n = 0; n < d.people.length; n++) {
                        if (d.people[n][0] !== "Christian" && d.people[n][1] !== "Frisson") {
                            /*var author= people.find(
							function(e){
								if(d.people[n][0] == e.given && d.people[n][1] == e.family){
									return e;
								}
							});
						if(author !== undefined){
	                        d.caption += author.given;
	                        d.caption += " ";
	                        d.caption += author.family;
	                        if(n<d.people.length-1){
	                            d.caption += ", ";
	                        }
						}*/
                            if (d.people[n][0] !== undefined && d.people[n][1] !== undefined) {
                                d.caption += d.people[n][0];
                                d.caption += " ";
                                d.caption += d.people[n][1];
                                if (n < d.people.length - 1) {
                                    d.caption += ", ";
                                }
                            }

                        }
                    }
                    d.caption += "
";
                }

                if (d.contribs !== undefined) {
                    //d.caption += "
contributions: " + d.contribs + "
";
                    d.caption += "
"

                    d.caption += " my contributions: ";

                    //d.caption += "
"
                    d.contribs.forEach(function(contrib, i) {
                        if (i > 0) d.caption += ",";
                        if (i === d.contribs.length - 1) d.caption += "

"
                            //d.caption += "
";
                        d.caption += " ";

                        if (contrib.type === "development") {
                            d.caption += "";

                            if (d.code !== undefined && d.code.host === "github") {
                                var url = "https://github.com/" + d.code.account + "/"
                                if (d.code.repo !== undefined) url += d.code.repo;
                                d.caption += " ";
                                d.caption += "Github"
                                d.caption += "";
                            }
                        } else {
                            d.caption += " ";
                        }
                        d.caption += " ";
                        //d.caption += "(";
                        d.caption += contrib.desc;
                        //d.caption += ")";
                        //d.caption += "
";
                    });
                    d.caption += "
"
                    d.caption += "
";
                }
                d.caption += "
"
                return img;
            })
    });
};<|endoftext|>


<commit_before>var spore = require('spore')
  , futures = require('futures')
;

/**
 * Set Accept header
 */
function accept(accept) {
    return function(method, request, next) {
        request.headers['Accept'] = accept;
        next();
    }
}
/**
 * Set Content-type header
 */
function contentType(contentType) {
    return function(method, request, next) {
        request.headers['Content-type'] = contentType;
        next();
    };
}

var sporeDesc = exports.description = require('./description');

/**
 * Read stdin
 */
var readInput = exports.readInput = function(callback) {
    process.stdin.resume();
    process.stdin.setEncoding('utf8');
    process.stdin.on('data', function (chunk) {
        process.stdin.pause(); // pause stdin after input
        process.stdin.removeAllListeners('data');
        process.stdin.removeAllListeners('end');
        callback(chunk.trim());
    });
    process.stdin.on('end', function () {});
}
/**
 * Create Spore client
 */
var createClient = exports.createClient = function(token) {
    var client = spore.createClient(sporeDesc);
    client.enable(spore.middlewares.basic(token, 'X'));
    client.enable(spore.middlewares.json());
    client.enable(accept('application/json'));
    client.enable(contentType('application/json'));
    return client;
}

function formatList(array, propertyName) {
    for (var i = 0; i < array.length; i++) {
        console.log(' '+ i + '. '+ array[i][propertyName]);
    }
}

function chooseIn(list, propertyName, callback) {
    formatList(list, propertyName);
    process.stdout.write('enter your choice: ');
    readInput(function(v) {
        var index = parseInt(v, 10);
        if (list.length > index) callback(index, list[index]);
        else chooseIn(list, propertyName, callback);
    });
}

/**
 * Ask user in interactive mode
 * client: spore client
 * Return function
 */
exports.askForProject = function(client) {
    return function(nextGlobal) {
        var project = {
            personid: null,
            projectid: null,
            moduleid: null,
            worktypeid: null,
            human: {
                project: null,
                module: null,
                worktype: null
            }
        };
        var sequence = futures.sequence();
        sequence.then(function(next) {
            client.me(function(err, res) {
                if (err) throw err;
                project.personid = res.body.personid;
                next();
            });
        }).then(function(next) {
            client.client({active: 't',
                           // projectsonly parameter seems buggy,
                           // but hopefully doesn't throw 500 error in API
                           limit: 42,
                           projectsonly: 't'},
                          function(err, res) {
                              console.log('Choose client:');
                              if (err) throw err;
                              chooseIn(res.body.client, 'name', function(index, aClient) {
                                  var clientId = aClient.id;
                                  next(clientId);
                              });
                          });
        }).then(function(next, clientId) {
            client.project({active: 't',
                            personid: project.personid,
                            clientid: clientId},
                           function(err, res) {
                               console.log('Choose a project:');
                               if (err) throw err;
                               chooseIn(res.body.project, 'name', function(index, aProject) {
                                   project.projectid = aProject.id;
                                   project.human.project = aProject.name;
                                   next();
                               });
                           });
        }).then(function(next) {
            client.project_module({projectid: project.projectid,
                                   limit: 42,
                                   personid: project.personid}, function(err, res) {
                console.log('Choose a module:');
                if (err) throw err;
                chooseIn(res.body.projectmodule, 'modulename', function(index, aModule) {
                    project.moduleid = aModule.moduleid;
                    project.human.module = aModule.modulename;
                    next();
                });
            });
        }).then(function(next) {
            client.project_worktype({projectid: project.projectid,
                                     limit: 42,
                                     personid: project.personid}, function(err, res) {
                console.log('Choose a worktype:');
                if (err) throw err;
                chooseIn(res.body.projectworktype, 'worktype', function(index, aWorktype) {
                    project.worktypeid = aWorktype.worktypeid;
                    project.human.worktype = aWorktype.worktype;
                    nextGlobal(project);
                });
            });
        });
    };
};
/**
 * Add time
 * project:
 *  - personid
 *  - projectid
 *  - moduleid
 *  - worktypeid
 * options with keys:
 *  - time
 *  - date
 *  - billable
 *  - description
 * client: spore client
 * callback
 */
exports.addTime = function(project, options, client, callback) {
    var time = {
        time: options.time,
        date: options.date,
        billable : options.billable ? 't': 'f',
        description: options.description,
        personid: project.personid,
        projectid: project.projectid,
        moduleid: project.moduleid,
        worktypeid: project.worktypeid
    };
    client.add_time(JSON.stringify(time), function(err, res) {
        callback(err, res);
    });
}
<commit_msg>List only active worktype and module.<commit_after>var spore = require('spore')
  , futures = require('futures')
;

/**
 * Set Accept header
 */
function accept(accept) {
    return function(method, request, next) {
        request.headers['Accept'] = accept;
        next();
    }
}
/**
 * Set Content-type header
 */
function contentType(contentType) {
    return function(method, request, next) {
        request.headers['Content-type'] = contentType;
        next();
    };
}

var sporeDesc = exports.description = require('./description');

/**
 * Read stdin
 */
var readInput = exports.readInput = function(callback) {
    process.stdin.resume();
    process.stdin.setEncoding('utf8');
    process.stdin.on('data', function (chunk) {
        process.stdin.pause(); // pause stdin after input
        process.stdin.removeAllListeners('data');
        process.stdin.removeAllListeners('end');
        callback(chunk.trim());
    });
    process.stdin.on('end', function () {});
}
/**
 * Create Spore client
 */
var createClient = exports.createClient = function(token) {
    var client = spore.createClient(sporeDesc);
    client.enable(spore.middlewares.basic(token, 'X'));
    client.enable(spore.middlewares.json());
    client.enable(accept('application/json'));
    client.enable(contentType('application/json'));
    return client;
}

function formatList(array, propertyName) {
    for (var i = 0; i < array.length; i++) {
        console.log(' '+ i + '. '+ array[i][propertyName]);
    }
}

function chooseIn(list, propertyName, callback) {
    formatList(list, propertyName);
    process.stdout.write('enter your choice: ');
    readInput(function(v) {
        var index = parseInt(v, 10);
        if (list.length > index) callback(index, list[index]);
        else chooseIn(list, propertyName, callback);
    });
}

/**
 * Ask user in interactive mode
 * client: spore client
 * Return function
 */
exports.askForProject = function(client) {
    return function(nextGlobal) {
        var project = {
            personid: null,
            projectid: null,
            moduleid: null,
            worktypeid: null,
            human: {
                project: null,
                module: null,
                worktype: null
            }
        };
        var sequence = futures.sequence();
        sequence.then(function(next) {
            client.me(function(err, res) {
                if (err) throw err;
                project.personid = res.body.personid;
                next();
            });
        }).then(function(next) {
            client.client({active: 't',
                           // projectsonly parameter seems buggy,
                           // but hopefully doesn't throw 500 error in API
                           limit: 42,
                           projectsonly: 't'},
                          function(err, res) {
                              console.log('Choose client:');
                              if (err) throw err;
                              chooseIn(res.body.client, 'name', function(index, aClient) {
                                  var clientId = aClient.id;
                                  next(clientId);
                              });
                          });
        }).then(function(next, clientId) {
            client.project({active: 't',
                            personid: project.personid,
                            clientid: clientId},
                           function(err, res) {
                               console.log('Choose a project:');
                               if (err) throw err;
                               chooseIn(res.body.project, 'name', function(index, aProject) {
                                   project.projectid = aProject.id;
                                   project.human.project = aProject.name;
                                   next();
                               });
                           });
        }).then(function(next) {
            client.project_module({projectid: project.projectid,
                                   limit: 42,
                                   active: 't',
                                   personid: project.personid}, function(err, res) {
                console.log('Choose a module:');
                if (err) throw err;
                chooseIn(res.body.projectmodule, 'modulename', function(index, aModule) {
                    project.moduleid = aModule.moduleid;
                    project.human.module = aModule.modulename;
                    next();
                });
            });
        }).then(function(next) {
            client.project_worktype({projectid: project.projectid,
                                     limit: 42,
                                     active: 't',
                                     personid: project.personid}, function(err, res) {
                console.log('Choose a worktype:');
                if (err) throw err;
                chooseIn(res.body.projectworktype, 'worktype', function(index, aWorktype) {
                    project.worktypeid = aWorktype.worktypeid;
                    project.human.worktype = aWorktype.worktype;
                    nextGlobal(project);
                });
            });
        });
    };
};
/**
 * Add time
 * project:
 *  - personid
 *  - projectid
 *  - moduleid
 *  - worktypeid
 * options with keys:
 *  - time
 *  - date
 *  - billable
 *  - description
 * client: spore client
 * callback
 */
exports.addTime = function(project, options, client, callback) {
    var time = {
        time: options.time,
        date: options.date,
        billable : options.billable ? 't': 'f',
        description: options.description,
        personid: project.personid,
        projectid: project.projectid,
        moduleid: project.moduleid,
        worktypeid: project.worktypeid
    };
    client.add_time(JSON.stringify(time), function(err, res) {
        callback(err, res);
    });
}
<|endoftext|>


<commit_before>// This file is the entry point for the bot.

const path = require('path')
const request = require('request-promise')
const Discord = require('discord.js')
const {GlobalCache} = require('./GlobalCache')
const config = require('./data/client.json')
const updateServer = require('./UpdateServer.js')

// Set up the sharding manager, a helper class that separates handling
// guilds into grouped processes called Shards.
let shardingManager = new Discord.ShardingManager(path.join(__dirname, 'Shard.js'), {
  token: config.token,
  totalShards: config.totalShards || 'auto',
  shardArgs: typeof v8debug === 'object' ? ['--inspect'] : undefined
})

shardingManager.on('launch', shard => {
  console.log(`Launching shard ${shard.id + 1}/${shardingManager.totalShards}`)
})

shardingManager.spawn('auto', 5500, false)

// Instantiate a GlobalCache, which will cache information from the shards.
global.GlobalCache = new GlobalCache(shardingManager)

// Set bot status messages
let currentActivity = 0
let totalUsers = null

async function getNextActivity () {
  currentActivity++
  if (currentActivity === 2 && totalUsers == null) currentActivity++

  if (currentActivity > 3) {
    currentActivity = 0
  }

  switch (currentActivity) {
    case 0:
      return { text: 'https://RoVer.link' }
    case 1:
      let totalGuilds = (await shardingManager.fetchClientValues('guilds.size')).reduce((prev, val) => prev + val, 0)
      return { text: `${totalGuilds} servers`, type: 'WATCHING' }
    case 2:
      return { text: `${totalUsers} users`, type: 'LISTENING' }
    case 3:
      return { text: '!rover', type: 'LISTENING' }
  }
}

const numberAbbreviations = ['K', 'M', 'B' ,'T']
request('https://verify.eryn.io/api/count')
  .then(count => {
    totalUsers = parseInt(count, 10).toFixed(1)

    // Count how many times the place is shifted
    let placeShift = 0
    while (totalUsers >= 1000) {
      totalUsers = (totalUsers / 1000).toFixed(1)
      placeShift++
    }

    if (placeShift > 0) {
      totalUsers += numberAbbreviations[placeShift - 1]
    }
  })

setInterval(async () => {
  if (shardingManager.shards.size === shardingManager.totalShards) {
    shardingManager.broadcast({
      action: 'status',
      argument: await getNextActivity()
    })
  }
}, 15000)

// If updateServer is defined, start that up as well.
if (config.updateServer) {
  updateServer(shardingManager, config.updateServer)
}

if (config.mainLifeTime) {
  setTimeout(() => {
    shardingManager.respawn = false
    shardingManager.broadcastEval('process.exit()')
  }, config.mainLifeTime * 1000)

  setTimeout(() => {
    process.exit()
  }, (config.mainLifeTime + 5) * 1000)
}

// Client.json documentation:
/*
    "token"             : String. The bot token that is used to log in to your bot.
    "lockNicknames"     : Boolean. Default false. If true, the bot will run DiscordServer.verifyMember every time
                          they begin typing. This will quickly eat up API requests if you aren't careful. Mostly
                          used on the hosted version.
    "updateServer"      : {
                          If this object is present, the update server will be started.

        "port"          : Integer. The port the Update server runs on.
        "apiKey"        : String. The API key the server checks against before updating the user.
    }
    "loud"              : Boolean. Default false. Logs every request made to stdout.
    "totalShards"       : Integer. Default auto. The number of shards to launch.
    "apiRequestMethod"  : String. Default 'sequential'. sequential' or 'burst'. Sequential executes all requests in the order
                          they are triggered, whereas burst runs multiple at a time, and doesn't guarantee a particular order.
    "owner"             : String. Default "0". The Discord ID of the bot's owner.
    "commandPrefix"     : String. Default "!". The prefix for commands.
    "shardLifeTime"     : Integer. Number of seconds each shard will run before closing.
    "mainLifeTime"      : Integer. Number of seconds the main process will run before closing.
    "invite"            : String. The bot invite link.
*/
<commit_msg>Update index.js<commit_after>// This file is the entry point for the bot.

const path = require('path')
const request = require('request-promise')
const Discord = require('discord.js')
const {GlobalCache} = require('./GlobalCache')
const config = require('./data/client.json')
const updateServer = require('./UpdateServer.js')

// Set up the sharding manager, a helper class that separates handling
// guilds into grouped processes called Shards.
let shardingManager = new Discord.ShardingManager(path.join(__dirname, 'Shard.js'), {
  token: config.token,
  totalShards: config.totalShards || 'auto',
  shardArgs: typeof v8debug === 'object' ? ['--inspect'] : undefined
})

shardingManager.on('launch', shard => {
  console.log(`Launching shard ${shard.id + 1}/${shardingManager.totalShards}`)
})

shardingManager.spawn('auto', 5500, false)

// Instantiate a GlobalCache, which will cache information from the shards.
global.GlobalCache = new GlobalCache(shardingManager)

// Set bot status messages
let currentActivity = 0
let totalUsers = null

async function getNextActivity () {
  currentActivity++
  if (currentActivity === 2 && totalUsers == null) currentActivity++

  if (currentActivity > 3) {
    currentActivity = 0
  }

  switch (currentActivity) {
    case 0:
      return { text: 'https://RoVer.link' }
    case 1:
      let totalGuilds = (await shardingManager.fetchClientValues('guilds.size')).reduce((prev, val) => prev + val, 0)
      return { text: `${totalGuilds} servers`, type: 'WATCHING' }
    case 2:
      return { text: `${totalUsers} users`, type: 'LISTENING' }
    case 3:
      return { text: '!rover', type: 'LISTENING' }
  }
}

const numberAbbreviations = ['K', 'M', 'B', 'T']
request('https://verify.eryn.io/api/count')
  .then(count => {
    totalUsers = parseInt(count, 10).toFixed(1)

    // Count how many times the place is shifted
    let placeShift = 0
    while (totalUsers >= 1000) {
      totalUsers = (totalUsers / 1000).toFixed(1)
      placeShift++
    }

    if (placeShift > 0) {
      totalUsers += numberAbbreviations[placeShift - 1]
    }
  })

setInterval(async () => {
  if (shardingManager.shards.size === shardingManager.totalShards) {
    shardingManager.broadcast({
      action: 'status',
      argument: await getNextActivity()
    })
  }
}, 15000)

// If updateServer is defined, start that up as well.
if (config.updateServer) {
  updateServer(shardingManager, config.updateServer)
}

if (config.mainLifeTime) {
  setTimeout(() => {
    shardingManager.respawn = false
    shardingManager.broadcastEval('process.exit()')
  }, config.mainLifeTime * 1000)

  setTimeout(() => {
    process.exit()
  }, (config.mainLifeTime + 5) * 1000)
}

// Client.json documentation:
/*
    "token"             : String. The bot token that is used to log in to your bot.
    "lockNicknames"     : Boolean. Default false. If true, the bot will run DiscordServer.verifyMember every time
                          they begin typing. This will quickly eat up API requests if you aren't careful. Mostly
                          used on the hosted version.
    "updateServer"      : {
                          If this object is present, the update server will be started.

        "port"          : Integer. The port the Update server runs on.
        "apiKey"        : String. The API key the server checks against before updating the user.
    }
    "loud"              : Boolean. Default false. Logs every request made to stdout.
    "totalShards"       : Integer. Default auto. The number of shards to launch.
    "apiRequestMethod"  : String. Default 'sequential'. sequential' or 'burst'. Sequential executes all requests in the order
                          they are triggered, whereas burst runs multiple at a time, and doesn't guarantee a particular order.
    "owner"             : String. Default "0". The Discord ID of the bot's owner.
    "commandPrefix"     : String. Default "!". The prefix for commands.
    "shardLifeTime"     : Integer. Number of seconds each shard will run before closing.
    "mainLifeTime"      : Integer. Number of seconds the main process will run before closing.
    "invite"            : String. The bot invite link.
*/
<|endoftext|>


<commit_before>var assert = chai.assert,
    expect = chai.expect,
    should = chai.should(); // Note that should has to be executed

var assert = chai.assert;

var foobar = {
  input1: function() {
    return mainTest("var a = 3;");
  },
  input2: function() {
    return mainTest("var a = 3; var b= 4; var c = a+b;");
  },
  input3: function() {
    return mainTest("var a = 3; var b= 4; var c = a*b;");
  },
  input4: function() {
    return mainTest("var a = 'hello';  var b = function(x) { var c = 3; return x+c;  };");
  },
  input5: function() {
    return mainTest("var a = 'hello';  var b = function(x) { var c = 3; return x+c;  }; b(4);");
  },
  input6: function() {
    return mainTest("var a/&#@:_;!|! = 'hello';");
  },
  input7: function() {
    return mainTest('var Suma << 5;');
  },
  localStore: function() {
    if(localStorage){
      return "true";

    }else{
      return "false";

    }

  },
  Url: function() {
    var url = window.location.pathname;
    if (url.indexOf('/test') > -1) {
      return 'true';

    }
  }
};

suite('Lexical Analysis ', function() {
    test('Verifying Url ', function () {
        assert.deepEqual(foobar.Url(),'true');
    });
    test('Verifying Localstorage   ', function () {
        assert.deepEqual(foobar.localStore(),'true');
    });

    test('Create variable and assign value ', function () {
      assert.deepEqual(foobar.input1(),'{"value":"=","arity":"binary","first":{"value":"a","arity":"name"},"second":{"value":3,"arity":"literal"}}');
    });

    test('Operator sum  ', function () {
        assert.deepEqual(foobar.input2(),'[{"value":"=","arity":"binary","first":{"value":"a","arity":"name"},"second":{"value":3,"arity":"literal"}},{"value":"=","arity":"binary","first":{"value":"b","arity":"name"},"second":{"value":4,"arity":"literal"}},{"value":"=","arity":"binary","first":{"value":"c","arity":"name"},"second":{"value":"+","arity":"binary","first":{"value":"a","arity":"name"},"second":{"value":"b","arity":"name"}}}]');
    });
       test('Operator mult  ', function () {
        assert.deepEqual(foobar.input3(),'[{"value":"=","arity":"binary","first":{"value":"a","arity":"name"},"second":{"value":3,"arity":"literal"}},{"value":"=","arity":"binary","first":{"value":"b","arity":"name"},"second":{"value":4,"arity":"literal"}},{"value":"=","arity":"binary","first":{"value":"c","arity":"name"},"second":{"value":"*","arity":"binary","first":{"value":"a","arity":"name"},"second":{"value":"b","arity":"name"}}}]');
    });
    test('Function with return value ', function () {
        assert.deepEqual(foobar.input4(),'[{"value":"=","arity":"binary","first":{"value":"a","arity":"name"},"second":{"value":"hello","arity":"literal"}},{"value":"=","arity":"binary","first":{"value":"b","arity":"name"},"second":{"value":"function","arity":"function","first":[{"value":"x","arity":"name"}],"second":[{"value":"=","arity":"binary","first":{"value":"c","arity":"name"},"second":{"value":3,"arity":"literal"}},{"value":"return","arity":"statement","first":{"value":"+","arity":"binary","first":{"value":"x","arity":"name"},"second":{"value":"c","arity":"name"}}}]}}]');
    });

          test('Function with return value and exec ', function () {
        assert.deepEqual(foobar.input5(),'[{"value":"=","arity":"binary","first":{"value":"a","arity":"name"},"second":{"value":"hello","arity":"literal"}},{"value":"=","arity":"binary","first":{"value":"b","arity":"name"},"second":{"value":"function","arity":"function","first":[{"value":"x","arity":"name"}],"second":[{"value":"=","arity":"binary","first":{"value":"c","arity":"name"},"second":{"value":3,"arity":"literal"}},{"value":"return","arity":"statement","first":{"value":"+","arity":"binary","first":{"value":"x","arity":"name"},"second":{"value":"c","arity":"name"}}}]}},{"value":"(","arity":"binary","first":{"value":"b","arity":"name"},"second":[{"value":4,"arity":"literal"}]}]');
    });

       test('Error with invalid Id ', function () {
        assert.deepEqual(foobar.input6(),"\"Syntaxerrornear\'#@:_;!|!=\'hello\';\'\"");
    });
	  test('Error with operator assign  ', function () {
        assert.deepEqual(foobar.input7(),'{"name":"SyntaxError","message":"Unknownoperator.","from":9,"to":11,"value":"<<"}');
    });
});
<commit_msg>Quitando test de version anterior<commit_after>var assert = chai.assert,
    expect = chai.expect,
    should = chai.should(); // Note that should has to be executed

var assert = chai.assert;

var foobar = {
  input1: function() {
    return mainTest(" a = 5;");
  },

  localStore: function() {
    if(localStorage){
      return "true";

    }else{
      return "false";

    }

  }
};

suite('Lexical Analysis ', function() {

    test('Verifying Localstorage   ', function () {
        assert.deepEqual(foobar.localStore(),'true');
    });

    test('Create variable and assign value ', function () {
      assert.deepEqual(foobar.input1(),'{"value":"=","arity":"binary","first":{"value":"a","arity":"name"},"second":{"value":3,"arity":"literal"}}');
    });
});
<|endoftext|>


<commit_before>var http = require('http');
var util = require('./util');

http.createServer(function (req, res) {
    var answer =  util.helloWorld();
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(answer);
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

<commit_msg>port changes to 1338<commit_after>var http = require('http');
var util = require('./util');

http.createServer(function (req, res) {
    var answer =  util.helloWorld();
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(answer);
}).listen(1338, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1338/');

<|endoftext|>


<commit_before><commit_msg>do not double-escape spaces<commit_after><|endoftext|>


<commit_before>'use strict';

import * as React from 'react';
import * as PropTypes from 'prop-types';

const NOT_INHERITED_PROPS = [
  'flexible',
  'fit',
  'fitFallback'
];

/**
 * React component that render a image with object-fit and its fallback
 *
 * @class SuperImage
 */
export default class SuperImage extends React.Component {
  static propTypes = {
    src         : PropTypes.string.isRequired,
    width       : PropTypes.string,
    height      : PropTypes.string,
    alt         : PropTypes.string,
    className   : PropTypes.string,
    fit         : PropTypes.oneOf(['contain', 'cover']),
    fitFallback : PropTypes.bool,
    flexible    : PropTypes.bool
  };

  static defaultProps = {
    width       : null,
    height      : null,
    alt         : '',
    className   : '',
    fit         : null,
    fitFallback : false,
    flexible    : false
  };

  renderImage() {
    const styleAttr = {};
    const extendsProps = {};

    if (this.props.fit) {
      styleAttr.objectFit = this.props.fit;
    }

    if (this.props.flexible) {
      styleAttr.width = '100%';
      styleAttr.height = '100%';
    }

    // Props given to this Component is inherited <img /> in all
    Object.keys(this.props)
      .filter(key => NOT_INHERITED_PROPS.indexOf(key) === -1)
      .forEach(key => {
        extendsProps[key] = this.props[key];
      });

    return (
      <img
        src={this.props.src}
        alt={this.props.alt}
        style={styleAttr}
        {...extendsProps}
      />
    );
  }

  renderImageWithObjectFitFallback() {
    const styleAttr = {
      display            : 'inline-block',
      backgroundImage    : `url(${this.props.src})`,
      backgroundRepeat   : 'no-repeat',
      backgroundPosition : 'center center'
    };

    if (this.props.flexible) {
      styleAttr.width = '100%';
    } else if (this.props.width) {
      styleAttr.width = this.props.width;
    }

    if (this.props.flexible) {
      styleAttr.height = '100%';
    } else if (this.props.height) {
      styleAttr.height = this.props.height;
    }

    if (this.props.fit) {
      styleAttr.backgroundSize = this.props.fit;
    }

    return (
      <div
        aria-label={this.props.alt}
        className={this.props.className}
        style={styleAttr}
      />
    );
  }

  render() {
    if (this.props.fitFallback) {
      return this.renderImageWithObjectFitFallback();
    }

    return this.renderImage();
  }
}
<commit_msg>add role=img<commit_after>'use strict';

import * as React from 'react';
import * as PropTypes from 'prop-types';

const NOT_INHERITED_PROPS = [
  'flexible',
  'fit',
  'fitFallback'
];

/**
 * React component that render a image with object-fit and its fallback
 *
 * @class SuperImage
 */
export default class SuperImage extends React.Component {
  static propTypes = {
    src         : PropTypes.string.isRequired,
    width       : PropTypes.string,
    height      : PropTypes.string,
    alt         : PropTypes.string,
    className   : PropTypes.string,
    fit         : PropTypes.oneOf(['contain', 'cover']),
    fitFallback : PropTypes.bool,
    flexible    : PropTypes.bool
  };

  static defaultProps = {
    width       : null,
    height      : null,
    alt         : '',
    className   : '',
    fit         : null,
    fitFallback : false,
    flexible    : false
  };

  renderImage() {
    const styleAttr = {};
    const extendsProps = {};

    if (this.props.fit) {
      styleAttr.objectFit = this.props.fit;
    }

    if (this.props.flexible) {
      styleAttr.width = '100%';
      styleAttr.height = '100%';
    }

    // Props given to this Component is inherited <img /> in all
    Object.keys(this.props)
      .filter(key => NOT_INHERITED_PROPS.indexOf(key) === -1)
      .forEach(key => {
        extendsProps[key] = this.props[key];
      });

    return (
      <img
        src={this.props.src}
        alt={this.props.alt}
        style={styleAttr}
        {...extendsProps}
      />
    );
  }

  renderImageWithObjectFitFallback() {
    const styleAttr = {
      display            : 'inline-block',
      backgroundImage    : `url(${this.props.src})`,
      backgroundRepeat   : 'no-repeat',
      backgroundPosition : 'center center'
    };

    if (this.props.flexible) {
      styleAttr.width = '100%';
    } else if (this.props.width) {
      styleAttr.width = this.props.width;
    }

    if (this.props.flexible) {
      styleAttr.height = '100%';
    } else if (this.props.height) {
      styleAttr.height = this.props.height;
    }

    if (this.props.fit) {
      styleAttr.backgroundSize = this.props.fit;
    }

    return (
      <div
        role="img"
        aria-label={this.props.alt}
        className={this.props.className}
        style={styleAttr}
      />
    );
  }

  render() {
    if (this.props.fitFallback) {
      return this.renderImageWithObjectFitFallback();
    }

    return this.renderImage();
  }
}
<|endoftext|>


<commit_before>// when document loads
$(document).ready(function () {

  // function for updating search results
  var getCourseData = function () {
    var query = {
      $text: {
        $search: $('#searchbox').val()
      },
      semester: $('#semester').val()
    }

    $.post('/api/courses',
    {
      query: JSON.stringify(query),
      sort: $('#sort').val()
    }, function (courses, status) {
      // Basic error handling
      if (status !== 'success') {
        window.alert('An error occured and your search could not be completed.')
      }

      // clear results
      $('#results').html('')

      /* SEB'S EXAMPLE

      // Insert the course results into the area
      for (var courseIndex in courses) {
        var thisCourse = courses[courseIndex]
        $('#results').append('
' + thisCourse.department + ' ' + thisCourse.catalogNumber + ' ' + thisCourse.title + '
')
        $('#results').children().last()[0].course = thisCourse

      */

      for (var courseIndex in courses) {
        var thisCourse = courses[courseIndex]

        // string for course listings
        var listings = thisCourse.department + thisCourse.catalogNumber
        for (var listing in thisCourse.crosslistings) {
          listings += '/' + thisCourse.crosslistings[listing].department
                          + thisCourse.crosslistings[listing].catalogNumber
        }

        // append result into results pane
        $('#results')[0].appendChild(newResultEntry(thisCourse))

        // attach object to DOM element
        $('#results').children().last()[0].course = thisCourse
      }
    })
  }

  // function for displaying course details
  var dispCourseData = function() {
    $(".search-result").removeClass("active");
    $(this).addClass("active")

    $('#disp-title').html('')
    $('#disp-profs').html('')
    $('#disp-desc').html('')
    $('#disp-body').html('')

    var thisCourse = this.course

    // string for course listings
    var listings = thisCourse.department + thisCourse.catalogNumber
    for (var listing in thisCourse.crosslistings) {
      listings += '/' + thisCourse.crosslistings[listing].department
                      + thisCourse.crosslistings[listing].catalogNumber

    }

    $('#disp-title').append(listings + ' ' + thisCourse.title
                            + (thisCourse.distribution == undefined ? '' : ' ' + thisCourse.distribution + '')
                            + (thisCourse.pdf["required"]  ? ' PDF ONLY'
                            : (thisCourse.pdf["permitted"] ? ' PDF'
                                                                   : ' NPDF'))
                            + (thisCourse.audit ? ' AUDIT' : '')
                            + '')

    $('#disp-desc').append(thisCourse.description)

    // stuff for course evaluations
    var evals = ""
    for (var field in thisCourse.evaluations.scores) {
      var val = thisCourse.evaluations.scores[field]
      evals += '

' + field + '

'
             + '

'
             + '
' + val + '
'// as percentage of 5
             + '
' + '

'
    }

    var score = thisCourse.evaluations.scores["Overall Quality of the Course"]
    if (score != undefined) {
      var svg = newEvalDispDial(thisCourse.evaluations.scores["Overall Quality of the Course"])
      $('#disp-body')[0].appendChild(svg)
    }

    $('#disp-body').append(evals
                            + (thisCourse.prerequisites == undefined ? '' :
                            '
Prerequisites

' + thisCourse.prerequisites + '
')
                            + (thisCourse.equivalentcourses == undefined ? '' :
                            '
Equivalent Courses

' + thisCourse.equivalentcourses + '
')
                            + (thisCourse.otherinformation == undefined ? '' :
                            '
Other Information

' + thisCourse.otherinformation + '
')
                            + (thisCourse.otherrequirements == undefined ? '' :
                            '
Equivalent Courses

' + thisCourse.otherrequirements + '
')
                            + (thisCourse.website == undefined ? '' :
                            '
Website

' + thisCourse.website + '
'))
  }

  // Every time a key is pressed inside the #searchbox, call the getCourseData function
  $('#searchbox').keyup(getCourseData)
  $('#semester, #sort').change(getCourseData)

  // displays information in right pane on click of search result
  $('#results').on('click', 'a.search-result', dispCourseData)

  /* SEB' EXAMPLE

  // $('#results div').click(function () {
  //   console.log($(this).text())
  // })

  $('#results').on('click', 'div.course', function () {
    // window.alert('Handler for .click() called.')
    // console.log(this.course)
    window.alert('You just clicked on the course ' + this.course.title + '!')
  })

  */

  // load the semesters for the dropdown
  $.get('/api/semesters', function (semesters) {
    for (var semesterIndex in semesters) {
      var thisSemester = semesters[semesterIndex]
      $('#semester').append('<option value="' + thisSemester.code + '">' + thisSemester.name + '</select>')
    }
  })
})
<commit_msg>cleaned up misc<commit_after>// when document loads
$(document).ready(function () {

  // function for updating search results
  var getCourseData = function () {
    var query = {
      $text: {
        $search: $('#searchbox').val()
      },
      semester: $('#semester').val()
    }

    $.post('/api/courses',
    {
      query: JSON.stringify(query),
      sort: $('#sort').val()
    }, function (courses, status) {
      // Basic error handling
      if (status !== 'success') {
        window.alert('An error occured and your search could not be completed.')
      }

      // clear results
      $('#results').html('')

      /* SEB'S EXAMPLE

      // Insert the course results into the area
      for (var courseIndex in courses) {
        var thisCourse = courses[courseIndex]
        $('#results').append('
' + thisCourse.department + ' ' + thisCourse.catalogNumber + ' ' + thisCourse.title + '
')
        $('#results').children().last()[0].course = thisCourse

      */

      for (var courseIndex in courses) {
        var thisCourse = courses[courseIndex]

        // append result into results pane
        $('#results')[0].appendChild(newResultEntry(thisCourse))

        // attach object to DOM element
        $('#results').children().last()[0].course = thisCourse
      }
    })
  }

  // function for displaying course details
  var dispCourseData = function() {
    $(".search-result").removeClass("active");
    $(this).addClass("active")

    $('#disp-title').html('')
    $('#disp-profs').html('')
    $('#disp-desc').html('')
    $('#disp-body').html('')

    var thisCourse = this.course

    // string for course listings
    var listings =  getListings(thisCourse)

    $('#disp-title').append(listings + ' ' + thisCourse.title
                            + (thisCourse.distribution == undefined ? '' : ' ' + thisCourse.distribution + '')
                            + (thisCourse.pdf["required"]  ? ' PDF ONLY'
                            : (thisCourse.pdf["permitted"] ? ' PDF'
                                                                   : ' NPDF'))
                            + (thisCourse.audit ? ' AUDIT' : '')
                            + '')

    $('#disp-desc').append(thisCourse.description)

    // stuff for course evaluations
    var evals = ""
    for (var field in thisCourse.evaluations.scores) {
      var val = thisCourse.evaluations.scores[field]
      evals += '

' + field + '

'
             + '

'
             + '
' + val + '
'// as percentage of 5
             + '
' + '

'
    }

    // create dial
    var newSVG
    if (thisCourse.evaluations.hasOwnProperty('scores') &&
        thisCourse.evaluations.scores.hasOwnProperty('Overall Quality of the Course')) {
      newSVG = newEvalDispDial(thisCourse.evaluations.scores['Overall Quality of the Course'])
      $('#disp-body')[0].appendChild(newSVG)
    }

    $('#disp-body').append(evals
                            + (thisCourse.prerequisites == undefined ? '' :
                            '
Prerequisites

' + thisCourse.prerequisites + '
')
                            + (thisCourse.equivalentcourses == undefined ? '' :
                            '
Equivalent Courses

' + thisCourse.equivalentcourses + '
')
                            + (thisCourse.otherinformation == undefined ? '' :
                            '
Other Information

' + thisCourse.otherinformation + '
')
                            + (thisCourse.otherrequirements == undefined ? '' :
                            '
Equivalent Courses

' + thisCourse.otherrequirements + '
')
                            + (thisCourse.website == undefined ? '' :
                            '
Website

' + thisCourse.website + '
'))
  }

  // Every time a key is pressed inside the #searchbox, call the getCourseData function
  $('#searchbox').keyup(getCourseData)
  $('#semester, #sort').change(getCourseData)

  // displays information in right pane on click of search result
  $('#results').on('click', 'a.search-result', dispCourseData)

  /* SEB' EXAMPLE

  // $('#results div').click(function () {
  //   console.log($(this).text())
  // })

  $('#results').on('click', 'div.course', function () {
    // window.alert('Handler for .click() called.')
    // console.log(this.course)
    window.alert('You just clicked on the course ' + this.course.title + '!')
  })

  */

  // load the semesters for the dropdown
  $.get('/api/semesters', function (semesters) {
    for (var semesterIndex in semesters) {
      var thisSemester = semesters[semesterIndex]
      $('#semester').append('<option value="' + thisSemester.code + '">' + thisSemester.name + '</select>')
    }
  })
})
<|endoftext|>


<commit_before>/*
 Copyright 2017 Credential Engine and other contributing parties.

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

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

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

var repo;

EcRepository.caching = true;
EcRepository.cachingSearch = false;

var frameworkId = "";

var servers = ["https://dev.cassproject.org/api/"];
var repo;

if (queryParams.server != null)
    servers = [queryParams.server];

var webSocketBackoff = 100;
var webSocketConnection = false;

openWebSocket = function (r) {
    var connection;
    // Instead of /ws/custom, will be /ws in next release.
    if (queryParams.webSocketOverride == null || queryParams.webSocketOverride === undefined)
        connection = new WebSocket(r.selectedServer.replace(/http/, "ws").replace(/api\//, "ws/custom"));
    else
        connection = new WebSocket(queryParams.webSocketOverride);

    connection.onopen = function () {
        console.log("WebSocket open.");
        webSocketConnection = true;
    };

    connection.onerror = function (error) {
        console.log(error);
    };

    //Re-establish connection on close.
    connection.onclose = function (evt) {
        console.log(evt);
        webSocketBackoff *= 2;
        webSocketConnection = false;
        setTimeout(function () {
            openWebSocket(r);
        }, webSocketBackoff);
    };

    connection.onmessage = function (e) {
        console.log('Server: ' + e.data);
        if (framework == null) return;
        EcRepository.get(e.data, function (wut) {
            delete EcRepository.cache[wut.id];
            delete EcRepository.cache[wut.shortId()];

            if (new ConceptScheme().isA(wut.getFullType()))
                if (framework != null)
                    if (framework.shortId() == wut.shortId()) {
                        framework = new ConceptScheme();
                        framework.copyFrom(wut);
                        populateFramework();
                    }

            if (new EcFramework().isA(wut.getFullType()))
                if (framework != null)
                    if (framework.shortId() == wut.shortId()) {
                        framework = new EcFramework();
                        framework.copyFrom(wut);
                        populateFramework();
                    }

            if (new Concept().isA(wut.getFullType())) {
                if (framework != null)
                    if ($("[id=\"" + wut.shortId() + "\"]").length > 0) {
                        var com = new Concept();
                        com.copyFrom(wut);
                        $("#tree [id='" + com.shortId() + "']").remove();
                        if (com.narrows != null)
                            for (var i = 0; i < com.narrows.length; i++) {

                                window.fetches++;
                                refreshCompetency(com).appendTo($("[id=\"" + com.narrows[i] + "\"]>ul"));
                            }
                        if (com.topConceptOf != null)
                            refreshCompetency(com);
                        if (selectedCompetency != null)
                            if (selectedCompetency.shortId() == wut.shortId()) {
                                refreshSidebar();
                            }
                    }
            }
            if (new EcCompetency().isA(wut.getFullType())) {
                if (framework != null)
                    if (framework.competency != null)
                        if (EcArray.has(framework.competency, wut.shortId()) || EcArray.has(framework.competency, wut.shortId()) || JSON.stringify(framework.competency).indexOf(EcCrypto.md5(wut.id)) != -1) {
                            populateFramework();
                            if (selectedCompetency != null)
                                if (selectedCompetency.shortId() == wut.shortId()) {
                                    selectedCompetency = com;
                                    refreshSidebar();
                                }
                        }
            }

            if (new EcLevel().isA(wut.getFullType())) {
                if (framework != null)
                    if (framework.level != null)
                        if (EcArray.has(framework.level, wut.shortId()) || EcArray.has(framework.level, wut.shortId())) {
                            var com = new EcLevel();
                            com.copyFrom(wut);
                            window.fetches++;
                            refreshCompetency(com);
                            if (selectedCompetency != null)
                                if (selectedCompetency.shortId() == wut.shortId()) {
                                    selectedCompetency = com;
                                    refreshSidebar();
                                }
                        }
            }

        }, error);
    };

}

function cappend(event) {
    if (event.data.message == "selected") {
        console.log("I got " + event.data.selected.length + " selected items from the iframe");
        console.log(event.data.selected);
        if (JSON.stringify(event.data.selected).indexOf("Concept") != -1) {
            attachUrlProperties(event.data.selected);
            $("#selectConceptSection").hide();
            $("#editFrameworkSection").show();
        } else showCopyOrLinkDialog(function (copy) {
            if (copy === true) {
                copyCompetencies(event.data.selected);
            } else {
                appendCompetencies(event.data.selected);
            }
            hideCopyOrLinkDialog();
            backPage();
        });
    } else if (event.data.message == "back")
        backPage();
}

for (var i = 0; i < servers.length; i++) {
    var r = new EcRepository();
    r.selectedServer = servers[i];
    r.autoDetectRepository();
    servers[i] = r;
    repo = r;

    try {
        window.addEventListener('message', cappend, false);
    } catch (e) {
        console.error(e);
    }

    openWebSocket(r);
}

var iframeRoot = queryParams.editorRoot;
if (iframeRoot == null || iframeRoot === undefined)
    iframeRoot = "";
var iframePath = iframeRoot + "index.html?select=Add&selectRelations=true&view=true&iframeRoot=" + iframeRoot + "&origin=" + window.location.origin + (queryParams.server == null ? "" : "&server=" + queryParams.server);
if (queryParams.webSocketOverride != null && queryParams.webSocketOverride !== undefined)
    iframePath += "&webSocketOverride=" + queryParams.webSocketOverride;
if (queryParams.view != "true")
    $("#findCompetencyIframe").attr("src", iframePath);

var iframeConceptPath = iframeRoot + "index.html?select=Add&concepts=true&iframeRoot=" + iframeRoot + "&ceasnDataFields=" + queryParams.ceasnDataFields + "&origin=" + window.location.origin + (queryParams.server == null ? "" : "&server=" + queryParams.server);
if (queryParams.webSocketOverride != null && queryParams.webSocketOverride !== undefined)
    iframeConceptPath += "&webSocketOverride=" + queryParams.webSocketOverride;
if (queryParams.view != "true")
    $("#selectConceptIframe").attr("src", iframeConceptPath);

loadIdentity = function (callback) {
    if (queryParams.user == "self") {
        EcIdentityManager.readIdentities();
        EcIdentityManager.readContacts();
        if (EcIdentityManager.ids.length == 0) {
            loading("Generating identity...");
            EcPpk.generateKeyAsync(
                function (p1) {
                    identity = new EcIdentity();
                    identity.ppk = p1;
                    identity.displayName = "You";
                    EcIdentityManager.onIdentityChanged = EcIdentityManager.saveIdentities;
                    EcIdentityManager.addIdentity(identity);
                    callback();
                }
            );
        } else
            callback();
    } else if (queryParams.user == "wait") {
        var fun = function (evt) {
            var data = evt.data;
            if (data != null)
                data = JSON.parse(data);
            if (data.action == "identity") {
                identity = new EcIdentity();
                identity.ppk = EcPpk.fromPem(data.identity);
                identity.displayName = "You";
                EcIdentityManager.addIdentity(identity);
                callback();
            }
        };
        if (window.addEventListener) {
            window.addEventListener("message", fun, false);
        } else {
            window.attachEvent("onmessage", fun);
        }
    } else
        callback();
}
<commit_msg>Replaces old selected competency with new one in sidebar.<commit_after>/*
 Copyright 2017 Credential Engine and other contributing parties.

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

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

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

var repo;

EcRepository.caching = true;
EcRepository.cachingSearch = false;

var frameworkId = "";

var servers = ["https://dev.cassproject.org/api/"];
var repo;

if (queryParams.server != null)
    servers = [queryParams.server];

var webSocketBackoff = 100;
var webSocketConnection = false;

openWebSocket = function (r) {
    var connection;
    // Instead of /ws/custom, will be /ws in next release.
    if (queryParams.webSocketOverride == null || queryParams.webSocketOverride === undefined)
        connection = new WebSocket(r.selectedServer.replace(/http/, "ws").replace(/api\//, "ws/custom"));
    else
        connection = new WebSocket(queryParams.webSocketOverride);

    connection.onopen = function () {
        console.log("WebSocket open.");
        webSocketConnection = true;
    };

    connection.onerror = function (error) {
        console.log(error);
    };

    //Re-establish connection on close.
    connection.onclose = function (evt) {
        console.log(evt);
        webSocketBackoff *= 2;
        webSocketConnection = false;
        setTimeout(function () {
            openWebSocket(r);
        }, webSocketBackoff);
    };

    connection.onmessage = function (e) {
        console.log('Server: ' + e.data);
        if (framework == null) return;
        EcRepository.get(e.data, function (wut) {
            delete EcRepository.cache[wut.id];
            delete EcRepository.cache[wut.shortId()];

            if (new ConceptScheme().isA(wut.getFullType()))
                if (framework != null)
                    if (framework.shortId() == wut.shortId()) {
                        framework = new ConceptScheme();
                        framework.copyFrom(wut);
                        populateFramework();
                    }

            if (new EcFramework().isA(wut.getFullType()))
                if (framework != null)
                    if (framework.shortId() == wut.shortId()) {
                        framework = new EcFramework();
                        framework.copyFrom(wut);
                        populateFramework();
                    }

            if (new Concept().isA(wut.getFullType())) {
                if (framework != null)
                    if ($("[id=\"" + wut.shortId() + "\"]").length > 0) {
                        var com = new EcConcept();
                        com.copyFrom(wut);
                        $("#tree [id='" + com.shortId() + "']").remove();
                        if (com.narrows != null)
                            for (var i = 0; i < com.narrows.length; i++) {

                                window.fetches++;
                                refreshCompetency(com).appendTo($("[id=\"" + com.narrows[i] + "\"]>ul"));
                            }
                        if (com.topConceptOf != null)
                            refreshCompetency(com);
                        if (selectedCompetency != null)
                            if (selectedCompetency.shortId() == wut.shortId()) {
                                selectedCompetency = com;
                                refreshSidebar();
                            }
                    }
            }
            if (new EcCompetency().isA(wut.getFullType())) {
                if (framework != null)
                    if (framework.competency != null)
                        if (EcArray.has(framework.competency, wut.shortId()) || EcArray.has(framework.competency, wut.shortId()) || JSON.stringify(framework.competency).indexOf(EcCrypto.md5(wut.id)) != -1) {
                            var com = new EcCompetency();
                            com.copyFrom(wut);
                            populateFramework();
                            if (selectedCompetency != null)
                                if (selectedCompetency.shortId() == wut.shortId()) {
                                    selectedCompetency = com;
                                    refreshSidebar();
                                }
                        }
            }

            if (new EcLevel().isA(wut.getFullType())) {
                if (framework != null)
                    if (framework.level != null)
                        if (EcArray.has(framework.level, wut.shortId()) || EcArray.has(framework.level, wut.shortId())) {
                            var com = new EcLevel();
                            com.copyFrom(wut);
                            window.fetches++;
                            refreshCompetency(com);
                            if (selectedCompetency != null)
                                if (selectedCompetency.shortId() == wut.shortId()) {
                                    selectedCompetency = com;
                                    refreshSidebar();
                                }
                        }
            }

        }, error);
    };

}

function cappend(event) {
    if (event.data.message == "selected") {
        console.log("I got " + event.data.selected.length + " selected items from the iframe");
        console.log(event.data.selected);
        if (JSON.stringify(event.data.selected).indexOf("Concept") != -1) {
            attachUrlProperties(event.data.selected);
            $("#selectConceptSection").hide();
            $("#editFrameworkSection").show();
        } else showCopyOrLinkDialog(function (copy) {
            if (copy === true) {
                copyCompetencies(event.data.selected);
            } else {
                appendCompetencies(event.data.selected);
            }
            hideCopyOrLinkDialog();
            backPage();
        });
    } else if (event.data.message == "back")
        backPage();
}

for (var i = 0; i < servers.length; i++) {
    var r = new EcRepository();
    r.selectedServer = servers[i];
    r.autoDetectRepository();
    servers[i] = r;
    repo = r;

    try {
        window.addEventListener('message', cappend, false);
    } catch (e) {
        console.error(e);
    }

    openWebSocket(r);
}

var iframeRoot = queryParams.editorRoot;
if (iframeRoot == null || iframeRoot === undefined)
    iframeRoot = "";
var iframePath = iframeRoot + "index.html?select=Add&selectRelations=true&view=true&iframeRoot=" + iframeRoot + "&origin=" + window.location.origin + (queryParams.server == null ? "" : "&server=" + queryParams.server);
if (queryParams.webSocketOverride != null && queryParams.webSocketOverride !== undefined)
    iframePath += "&webSocketOverride=" + queryParams.webSocketOverride;
if (queryParams.view != "true")
    $("#findCompetencyIframe").attr("src", iframePath);

var iframeConceptPath = iframeRoot + "index.html?select=Add&concepts=true&iframeRoot=" + iframeRoot + "&ceasnDataFields=" + queryParams.ceasnDataFields + "&origin=" + window.location.origin + (queryParams.server == null ? "" : "&server=" + queryParams.server);
if (queryParams.webSocketOverride != null && queryParams.webSocketOverride !== undefined)
    iframeConceptPath += "&webSocketOverride=" + queryParams.webSocketOverride;
if (queryParams.view != "true")
    $("#selectConceptIframe").attr("src", iframeConceptPath);

loadIdentity = function (callback) {
    if (queryParams.user == "self") {
        EcIdentityManager.readIdentities();
        EcIdentityManager.readContacts();
        if (EcIdentityManager.ids.length == 0) {
            loading("Generating identity...");
            EcPpk.generateKeyAsync(
                function (p1) {
                    identity = new EcIdentity();
                    identity.ppk = p1;
                    identity.displayName = "You";
                    EcIdentityManager.onIdentityChanged = EcIdentityManager.saveIdentities;
                    EcIdentityManager.addIdentity(identity);
                    callback();
                }
            );
        } else
            callback();
    } else if (queryParams.user == "wait") {
        var fun = function (evt) {
            var data = evt.data;
            if (data != null)
                data = JSON.parse(data);
            if (data.action == "identity") {
                identity = new EcIdentity();
                identity.ppk = EcPpk.fromPem(data.identity);
                identity.displayName = "You";
                EcIdentityManager.addIdentity(identity);
                callback();
            }
        };
        if (window.addEventListener) {
            window.addEventListener("message", fun, false);
        } else {
            window.attachEvent("onmessage", fun);
        }
    } else
        callback();
}
<|endoftext|>


<commit_before>/************************************************************************
 *
 *                      EVOLUTION COMPONENTS
 *
 ***********************************************************************/

import documentReady from './evolution/document-ready'
import crumble from './evolution/crumble'
import dotNavigation from './evolution/dot_navigation'
import fadeLinesOnScroll from './evolution/fade_lines_on_scroll'
import bookmarklet from './evolution/bookmarklet'
import demoComponent from './evolution/demo-component'
import readabilityPanel from './evolution/readability_improvement_panel'
import herald from './evolution/herald'
import paragraphGallery from './evolution/paragraph-gallery'
import popover from './evolution/pop_over'
import ikonize from './evolution/ikon'
import layer_2d from './evolution/layer_2d'
import singleInputForm from './evolution/single_input_form'
import layerAnimations from './evolution/layer-animations'
import layerDragAndDrop from './evolution/layer-drag-and-drop'
import spaceSavingMinimalistForm from './evolution/space_saving_minimalist_form'
import curtain from './evolution/curtain'
import text2speech from './evolution/text2speech'
import svg_pagination from './evolution/svg_pagination'
import divTable from './evolution/div_table'
<<<<<<< HEAD
import inputScanner from './evolution/input_scanner'
import carouselDrop from './evolution/carousel_with_dropping_circle_nav'
import safety from './evolution/safety'
import dotValidator from './evolution/dotValidator'
import sift from './evolution/sift'
import fullscreen_gallery from './evolution/fullscreen_gallery'
=======
import minimalistCarouselTwo from './evolution/minimalist_carousel_two';
>>>>>>> resolved merge conflict

/************************************************************************
 *
 *                      STANDARD COMPONENTS
 *
 ***********************************************************************/

import accordion from './standard/accordion'
import cssAnimations from './standard/css_animations'
import codeMarkup from './standard/code_markup'
import stdForms from './standard/forms'
import stdCarousel from './standard/carousel'
import stdTabs from './standard/tabs'
import sticky from './standard/sticky'
import modals from './standard/modals'
import audioPlayer from './standard/audio_player'

/************************************************************************
 *
 *                      COMPONENT INITIALIZATION
 *
 ***********************************************************************/

documentReady(
  crumble,
  dotNavigation,
  fadeLinesOnScroll,
  bookmarklet,
  cssAnimations,
  codeMarkup,
  stdForms,
  accordion,
  demoComponent,
  readabilityPanel,
  stdCarousel,
  sticky,
  herald,
  scrollManagement,
  paragraphGallery,
  popover,
  ikonize,
  inputScanner,
  modals,
  layer_2d,
  singleInputForm,
  layerAnimations,
  layerDragAndDrop,
  stdTabs,
  curtain,
  text2speech,
  svg_pagination,
  divTable,
  carouselDrop,
  safety,
  sift,
  fullscreen_gallery,
  minimalistCarouselTwo
)

singleInputForm();
spaceSavingMinimalistForm();
audioPlayer();<commit_msg>fixed merge conflict<commit_after>/************************************************************************
 *
 *                      EVOLUTION COMPONENTS
 *
 ***********************************************************************/

import documentReady from './evolution/document-ready'
import crumble from './evolution/crumble'
import dotNavigation from './evolution/dot_navigation'
import fadeLinesOnScroll from './evolution/fade_lines_on_scroll'
import bookmarklet from './evolution/bookmarklet'
import demoComponent from './evolution/demo-component'
import readabilityPanel from './evolution/readability_improvement_panel'
import herald from './evolution/herald'
import paragraphGallery from './evolution/paragraph-gallery'
import popover from './evolution/pop_over'
import ikonize from './evolution/ikon'
import layer_2d from './evolution/layer_2d'
import singleInputForm from './evolution/single_input_form'
import layerAnimations from './evolution/layer-animations'
import layerDragAndDrop from './evolution/layer-drag-and-drop'
import spaceSavingMinimalistForm from './evolution/space_saving_minimalist_form'
import curtain from './evolution/curtain'
import text2speech from './evolution/text2speech'
import svg_pagination from './evolution/svg_pagination'
import divTable from './evolution/div_table'
import inputScanner from './evolution/input_scanner'
import carouselDrop from './evolution/carousel_with_dropping_circle_nav'
import safety from './evolution/safety'
import dotValidator from './evolution/dotValidator'
import sift from './evolution/sift'
import fullscreen_gallery from './evolution/fullscreen_gallery'
import minimalistCarouselTwo from './evolution/minimalist_carousel_two'

/************************************************************************
 *
 *                      STANDARD COMPONENTS
 *
 ***********************************************************************/

import accordion from './standard/accordion'
import cssAnimations from './standard/css_animations'
import codeMarkup from './standard/code_markup'
import stdForms from './standard/forms'
import stdCarousel from './standard/carousel'
import stdTabs from './standard/tabs'
import sticky from './standard/sticky'
import modals from './standard/modals'
import audioPlayer from './standard/audio_player'

/************************************************************************
 *
 *                      COMPONENT INITIALIZATION
 *
 ***********************************************************************/

documentReady(
  crumble,
  dotNavigation,
  fadeLinesOnScroll,
  bookmarklet,
  cssAnimations,
  codeMarkup,
  stdForms,
  accordion,
  demoComponent,
  readabilityPanel,
  stdCarousel,
  sticky,
  herald,
  scrollManagement,
  paragraphGallery,
  popover,
  ikonize,
  inputScanner,
  modals,
  layer_2d,
  singleInputForm,
  layerAnimations,
  layerDragAndDrop,
  stdTabs,
  curtain,
  text2speech,
  svg_pagination,
  divTable,
  carouselDrop,
  safety,
  sift,
  fullscreen_gallery,
  minimalistCarouselTwo
)

singleInputForm();
spaceSavingMinimalistForm();
audioPlayer();<|endoftext|>