<commit_before>module.exports = {
  sockets: true,

  authorized_users: "config/users.htpasswd",
  authorized_roles: "config/users.rbac",
  superuser: {
    "admin" : true
  },
  http_port: 3000,
  https_port: 3443,
  max_http_sockets: 1000,
  max_https_sockets: 1000,
  // SSL is only necessary if you want snorkel to serve HTTPS
  // usually you can put snorkel behind NGINX to avoid this
  ssl: {
    key: "config/certs/server.key",
    certificate: "config/certs/server.crt"
  },
  // if you turn off in-box ssl support, turn off require_https, too
  require_https: true,
  // setting separate services to false will disable data ingestion
  // in the web server
  separate_services: false,
  // delete this udp key to turn off udp collection (on port 59036)
  udp: { port: 59036 },

  frontend: {
    // this could be "highcharts", too
    graph_driver: "nvd3"
  },

  backend: {
    // can be mongo, mongo_raw, postgres, postgres_raw or sybil
    driver: "mongo",

  },

  config_dir: "app/plugins/snorkel-config/",
  // this is kept in app/plugins/
  dataset_config_dir: "app/plugins/snorkel-dataset-config",

  // If the data_dir is set, we try to write all our data into this directory.
  // This includes: session store, query results and sybil data
  // The main purpose of this is for SNAP support
  data_dir: ".",
  // which local DB do we store our data in? can be tingodb, mongodb or linvodb.
  // if using mongodb driver, may as well use mongodb backend.
  // otherwise, go with linvodb
  config_driver: "linvo",
  // you should have libsqlite3-dev installed for the npm install of connect-sqlite3 to work
  // or you can swap it with connect-level
  session_store: "connect-sqlite3",
  // this is table name to use for storing old queries and dataset metadata
  db_name: "snorkel",

  // is the server behind a proxy or load balancer
  behind_proxy: false,
  // hostname to use when serving URLs if we are behind a proxy
  hostname: "localhost",

  // do we let anyone query our API endpoints?
  // this is relevant to grafana
  no_api_auth: false,

  // turn on google based user authentication
  google_auth: {
    enabled: false,
    // require_domain: 'my_custom_domain.com',
    require_domain: false,
    // authorized_users: {
    //  'you@your_google_domain.com': true,
    //  'your_friend@her_google_domain.com' : true
    // }
    authorized_users: false,

    // Generate these per project in http://console.developers.google.com -> credentials
    // and add the URL: http://snorkel.server/auth/google/return to the allowed callback URL
    client_secret: null,
    client_id: null
  },

  // the default RSS feed to show on every dataset. this
  // can be customized on a per dataset basis through the UI
  rss_feed: {
    url: null
  },

  // do we support CSV uploads from the dataset page?
  upload_csv: false,

  // do we turn on the tour page? only useful for demo installs
  show_tour: false,

  // This is the default max data size of the collection. Each dataset will
  // only grow to this size and no further, ideally
  default_max_dataset_size: 1024 * 1024 * 100, // 100 MB

  // turn on continuation local storage. this is a per request context
  // for storing variables.
  use_cls: true
};
<commit_msg>[config] default to using sybil as backend for snorkel in config.js<commit_after>module.exports = {
  sockets: true,

  authorized_users: "config/users.htpasswd",
  authorized_roles: "config/users.rbac",
  superuser: {
    "admin" : true
  },
  http_port: 3000,
  https_port: 3443,
  max_http_sockets: 1000,
  max_https_sockets: 1000,
  // SSL is only necessary if you want snorkel to serve HTTPS
  // usually you can put snorkel behind NGINX to avoid this
  ssl: {
    key: "config/certs/server.key",
    certificate: "config/certs/server.crt"
  },
  // if you turn off in-box ssl support, turn off require_https, too
  require_https: true,
  // setting separate services to false will disable data ingestion
  // in the web server
  separate_services: false,
  // delete this udp key to turn off udp collection (on port 59036)
  udp: { port: 59036 },

  frontend: {
    // this could be "highcharts", too
    graph_driver: "nvd3"
  },

  backend: {
    // can be mongo, mongo_raw, postgres, postgres_raw or sybil
    driver: "sybil"
  },

  config_dir: "app/plugins/snorkel-config/",
  // this is kept in app/plugins/
  dataset_config_dir: "app/plugins/snorkel-dataset-config",

  // If the data_dir is set, we try to write all our data into this directory.
  // This includes: session store, query results and sybil data
  // The main purpose of this is for SNAP support
  data_dir: ".",
  // which local DB do we store our data in? can be tingodb, mongodb or linvodb.
  // if using mongodb driver, may as well use mongodb backend.
  // otherwise, go with linvodb
  config_driver: "linvo",
  // you should have libsqlite3-dev installed for the npm install of connect-sqlite3 to work
  // or you can swap it with connect-level
  session_store: "connect-sqlite3",
  // this is table name to use for storing old queries and dataset metadata
  db_name: "snorkel",

  // is the server behind a proxy or load balancer
  behind_proxy: false,
  // hostname to use when serving URLs if we are behind a proxy
  hostname: "localhost",

  // do we let anyone query our API endpoints?
  // this is relevant to grafana
  no_api_auth: false,

  // turn on google based user authentication
  google_auth: {
    enabled: false,
    // require_domain: 'my_custom_domain.com',
    require_domain: false,
    // authorized_users: {
    //  'you@your_google_domain.com': true,
    //  'your_friend@her_google_domain.com' : true
    // }
    authorized_users: false,

    // Generate these per project in http://console.developers.google.com -> credentials
    // and add the URL: http://snorkel.server/auth/google/return to the allowed callback URL
    client_secret: null,
    client_id: null
  },

  // the default RSS feed to show on every dataset. this
  // can be customized on a per dataset basis through the UI
  rss_feed: {
    url: null
  },

  // do we support CSV uploads from the dataset page?
  upload_csv: false,

  // do we turn on the tour page? only useful for demo installs
  show_tour: false,

  // This is the default max data size of the collection. Each dataset will
  // only grow to this size and no further, ideally
  default_max_dataset_size: 1024 * 1024 * 100, // 100 MB

  // turn on continuation local storage. this is a per request context
  // for storing variables.
  use_cls: true
};
<|endoftext|>


<commit_before>/*global kontext*/
/**
 *  Manage text from data-kontext attributes
 *  @name     Text
 *  @package  Kontext
 */
kontext.extension('text', function(element, model, key) {
	'use strict';

	var text = element.firstChild && element.firstChild.nodeType === 3 ? element.firstChild : document.createTextNode(model[key]),
		delegate = model.delegation(key);

	//  ensure the existence of the text element
	if (text.parentNode !== element && text !== element.firstChild) {
		element.insertBefore(text, element.firstChild);
	}

	//  add the element to the elements which push/receive updates by Kontext
	console.log(delegate.element(text));
});
<commit_msg>Removed debug statement<commit_after>/*global kontext*/
/**
 *  Manage text from data-kontext attributes
 *  @name     Text
 *  @package  Kontext
 */
kontext.extension('text', function(element, model, key) {
	'use strict';

	var text = element.firstChild && element.firstChild.nodeType === 3 ? element.firstChild : document.createTextNode(model[key]),
		delegate = model.delegation(key);

	//  ensure the existence of the text element
	if (text.parentNode !== element && text !== element.firstChild) {
		element.insertBefore(text, element.firstChild);
	}

	//  add the element to the elements which push/receive updates by Kontext
	delegate.element(text);
});
<|endoftext|>


<commit_before>/**
 * @copyright
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Cosmic Dynamo LLC
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * @module RdfJs.Triple
 */
define([
    "dojo/_base/declare",
    "dojo/Stateful",
    "./Node"
], function (declare, Stateful, Node) {
    /**
     * @class RdfJs.Triple
     * @mixes dojo.Stateful
     * @see http://www.w3.org/TR/rdf-interfaces/#idl-def-Triple
     */
    return declare([Stateful], {
        subject: null,
        predicate: null,
        object: null,
        Node: null,
        postscript: function () {
            this.inherited(arguments);

            this.Node = this.Node || Node;

            this._validate("subject");
            this._validate("predicate");
            this._validate("object");
        },
        /**
         * Returns the NT String form of this Triple
         * @see http://www.w3.org/TR/rdf-interfaces/#widl-Triple-toString-stringifier-DOMString
         * @returns {string}
         */
        toString: function () {
            return this.subject.toNT() + " " + this.predicate.toNT() + " " + this.object.toNT() + " .";
        },
        /**
         * Compares this triple to another
         * @see http://www.w3.org/TR/rdf-interfaces/#widl-Triple-equals-boolean-Triple-otherTriple
         * @param {RdfJs.Triple} t - triple to compare
         * @returns {boolean}
         */
        equals: function (t) {
            return this.subject.equals(t.subject) && this.predicate.equals(t.predicate) && this.object.equals(t.object);
        },
        /**
         * Converts a input from a String to an RDF Node
         * @param {String} name
         * @private
         */
        _validate: function (name) {
            var val = this[name];

            if (lang.isString(val)) {
                this[name] = new this.Node(val);
            }
        }
    });
});<commit_msg>SF-235<commit_after>/**
 * @copyright
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Cosmic Dynamo LLC
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * @module RdfJs.Triple
 */
define([
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/Stateful",
    "./Node"
], function (declare, lang, Stateful, Node) {
    /**
     * @class RdfJs.Triple
     * @mixes dojo.Stateful
     * @mixes dojo.declare
     * @see http://www.w3.org/TR/rdf-interfaces/#idl-def-Triple
     */
    return declare([Stateful], {
        subject: null,
        predicate: null,
        object: null,
        Node: null,
        postscript: function () {
            this.inherited(arguments);

            this.Node = this.Node || Node;

            this._validate("subject");
            this._validate("predicate");
            this._validate("object");
        },
        /**
         * Returns the NT String form of this Triple
         * @see http://www.w3.org/TR/rdf-interfaces/#widl-Triple-toString-stringifier-DOMString
         * @returns {string}
         */
        toString: function () {
            return this.subject.toNT() + " " + this.predicate.toNT() + " " + this.object.toNT() + " .";
        },
        /**
         * Compares this triple to another
         * @see http://www.w3.org/TR/rdf-interfaces/#widl-Triple-equals-boolean-Triple-otherTriple
         * @param {RdfJs.Triple} t - triple to compare
         * @returns {boolean}
         */
        equals: function (t) {
            return this.subject.equals(t.subject) && this.predicate.equals(t.predicate) && this.object.equals(t.object);
        },
        /**
         * Converts a input from a String to an RDF Node
         * @param {String} name
         * @protected
         */
        _validate: function (name) {
            var val = this[name];

            if (lang.isString(val)) {
                this[name] = new this.Node(val);
            }
        }
    });
});<|endoftext|>


<commit_before>function gospa() {
  var m=window.location.pathname.match(/\/db\/(\w+)\/(\w+)\.html/);
  window.location.href = 'http://'+window.location.host+'/wd.html#'+m[1]+':'+m[2];
}

gospa();
<commit_msg>modify static.html and rerun<commit_after>function gospa() {
  var m=window.location.pathname.match(/\/db\/(\w+)\/(\w+)\.html/);
  window.location.href = '../../wd.html#'+m[1]+':'+m[2];
}

gospa();
<|endoftext|>


<commit_before>/*************/
/* init      */
/*************/

//set the change handler
$('#file').change(handleFileSelect);
//set the change handler
$('#list').change(handleListSelect);
var graphinfo = {};
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
    el: $('#paper'),
    width: 2000,
    height: 2000,
    gridSize: 1,
    model: graph
});
//Just give the viewport a little padding.
V(paper.viewport).translate(20, 20);

/***********/
/* Parsing */
/***********/

function makeLink(parentElementLabel, childElementLabel) {

    return new joint.dia.Link({
        source: { id: parentElementLabel },
        target: { id: childElementLabel },
        attrs: { '.marker-target': { d: 'M 4 0 L 0 2 L 4 4 z' } },
        smooth: true
    });
}

function makeElement(label) {

    var maxLineLength = _.max(label.split('\n'), function(l) { return l.length; }).length;

    // Compute width/height of the rectangle based on the number
    // of lines in the label and the letter size. 0.6 * letterSize is
    // an approximation of the monospace font letter width.
    var letterSize = 8;
    var width = 2 * (letterSize * (0.6 * maxLineLength + 1));
    var height = 2 * ((label.split('\n').length + 1) * letterSize);

    return new joint.shapes.basic.Rect({
        id: label,
        size: { width: width, height: height },
        attrs: {
            text: { text: label, 'font-size': letterSize, 'font-family': 'monospace' },
            rect: {
                width: width, height: height,
                rx: 5, ry: 5,
                stroke: '#555'
            }
        }
    });
}

// Parses a file, storing all the data into the graphinfo object
// returns an array of graph elements
function parseSimpleAdaptonView(text){
    graphinfo = {
        states: [],
        elements: [],
        links: []
    }
    console.log('spliting on state');
    states = text.split('Graph state: ');
    //first line is the blank before the first state
    states.shift();
    for(i=0;i<states.length;i++){
        console.log('starting parse of state '+i);
        graphinfo.states[i] = {
            title: "No name",
            elementStates: [],
            linkStates: []
        }
        state = graphinfo.states[i]; //shortcut
        lines = states[i].split('\n');
        state.title = lines.shift();
        for(j=0;j<lines.length;j++){
            tokens = lines[j].split(' ');
            //process line as element
            if(tokens.length == 2){
                ename = tokens[0];
                estate = tokens[1];
                eindex = graphinfo.elements.indexOf(ename);
                if(eindex == -1){
                    graphinfo.elements.push(ename);
                    eindex = graphinfo.elements.length-1;
                }
                state.elementStates[eindex] = estate;
            }//end element parse
            //process line as link
            if(tokens.length == 3){
                //get line data
                fromNode = tokens[0];
                toNode = tokens[1];
                linkState = tokens[2];
                //set up the elements of the link if needed
                fromNodeIndex = graphinfo.elements.indexOf(fromNode);
                toNodeIndex = graphinfo.elements.indexOf(toNode);
                if(fromNodeIndex == -1){
                    graphinfo.elements.push(fromNode)
                    fromNodeIndex = graphinfo.elements.length-1;
                    state.elementStates[fromNodeIndex] = 'active';
                }
                if(toNodeIndex == -1){
                    graphinfo.elements.push(toNode)
                    toNodeIndex = graphinfo.elements.length-1;
                    state.elementStates[toNodeIndex] = 'active';
                }
                if(!state.elementStates[fromNodeIndex]) {
                    state.elementStates[fromNodeIndex] = 'active';
                }
                if(!state.elementStates[toNodeIndex]) {
                    state.elementStates[toNodeIndex] = 'active';
                }
                //set up the link
                linkIndex = graphinfo.links.indexOf(fromNode+','+toNode);
                if(linkIndex == -1){
                    graphinfo.links.push(fromNode+','+toNode);
                    linkIndex = graphinfo.links.length-1;
                }
                state.linkStates[linkIndex] = linkState;
            }//end link parse
        }//end line parse
    }//end state parse
    //clean up data
    for(i=0;i<graphinfo.states.length;i++){
        state = graphinfo.states[i]; //shortcut
        for(j=0;j<graphinfo.elements.length;j++){
            if(!state.elementStates[j]){
                state.elementStates[j] = 'nonactive';
            }
        }
        for(j=0;j<graphinfo.links.length;j++){
            if(!state.linkStates[j]){
                state.linkStates[j] = 'nonactive';
            }
        }
    }
    //create elements and links
    for(i=0;i<graphinfo.elements.length;i++){
        graphinfo.elements[i] = makeElement(graphinfo.elements[i]);
    }
    for(i=0;i<graphinfo.links.length;i++){
        tofrom = graphinfo.links[i].split(',');
        graphinfo.links[i] = makeLink(tofrom[0],tofrom[1]);
    }
    //return list of elements to graph
    return graphinfo.elements.concat(graphinfo.links);
}

/*****************/
/* file handling */
/*****************/
//handler for new file selection
function handleFileSelect(event) {
    $('#list').empty();
    var files = event.target.files;
    var f = files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        console.log('file loaded');
        filecontents = e.target.result;
        //parse data into graphinfo and cells
        console.log('starting parse');
        cells = parseSimpleAdaptonView(filecontents);
        console.log('parse complete');
        //lay out the graph
        console.log('starting graph generation');
        graph.resetCells(cells);
        console.log('generation complete');
        console.log('starting layout');
        joint.layout.DirectedGraph.layout(graph, { setLinkVertices: false, rankDir: "BT" });
        console.log('layout complete')
        //re-map elements to editable view elements for efficiency
        for(i=0;i<graphinfo.elements.length;i++){
            model = graphinfo.elements[i];
            graphinfo.elements[i] = V(paper.findViewByModel(model).el);
        }
        for(i=0;i<graphinfo.links.length;i++){
            model = graphinfo.links[i];
            graphinfo.links[i] = V(paper.findViewByModel(model).el);
        }
        //set first states
        console.log('loading first states');
        graphinfo.currentState = 0;
        for(i=0;i<graphinfo.elements.length;i++){
            graphinfo.elements[i].addClass(graphinfo.states[0].elementStates[i]);
        }
        for(i=0;i<graphinfo.links.length;i++){
            graphinfo.links[i].addClass(graphinfo.states[0].linkStates[i]);
        }
        //populate list box with states
        for(i=0;i<graphinfo.states.length;i++){
            $('#list').append('<option value="'+i+'">'+graphinfo.states[i].title+'</option>');
        }
        console.log('ready for user interation');
    }//end file load handler
    console.log('loading file');
    reader.readAsText(f);
}
/********************/
/* listbox handling */
/********************/
function handleListSelect(event){
    var newState = parseInt(event.target.value);
    if(newState == -1) return;
    //shortcuts
    var eso = graphinfo.states[graphinfo.currentState].elementStates;
    var lso = graphinfo.states[graphinfo.currentState].linkStates;
    var esn = graphinfo.states[newState].elementStates;
    var lsn = graphinfo.states[newState].linkStates;
    //change the state of all the stored objects
    for(i=0;i<graphinfo.elements.length;i++){
        if(esn[i] != eso[i]){
            graphinfo.elements[i].removeClass(eso[i]).addClass(esn[i]);
        }
    }
    for(i=0;i<graphinfo.links.length;i++){
        if(lsn[i] != lso[i]){
            graphinfo.links[i].removeClass(lso[i]).addClass(lsn[i]);
        }
    }
    //set current state
    graphinfo.currentState = newState;
}
<commit_msg>enlarged view window to fit the graph displayed<commit_after>/*************/
/* init      */
/*************/

//set the change handler
$('#file').change(handleFileSelect);
//set the change handler
$('#list').change(handleListSelect);
var graphinfo = {};
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
    el: $('#paper'),
    width: 2000,
    height: 2000,
    gridSize: 1,
    model: graph
});
//Just give the viewport a little padding.
V(paper.viewport).translate(20, 20);

/***********/
/* Parsing */
/***********/

function makeLink(parentElementLabel, childElementLabel) {

    return new joint.dia.Link({
        source: { id: parentElementLabel },
        target: { id: childElementLabel },
        attrs: { '.marker-target': { d: 'M 4 0 L 0 2 L 4 4 z' } },
        smooth: true
    });
}

function makeElement(label) {

    var maxLineLength = _.max(label.split('\n'), function(l) { return l.length; }).length;

    // Compute width/height of the rectangle based on the number
    // of lines in the label and the letter size. 0.6 * letterSize is
    // an approximation of the monospace font letter width.
    var letterSize = 8;
    var width = 2 * (letterSize * (0.6 * maxLineLength + 1));
    var height = 2 * ((label.split('\n').length + 1) * letterSize);

    return new joint.shapes.basic.Rect({
        id: label,
        size: { width: width, height: height },
        attrs: {
            text: { text: label, 'font-size': letterSize, 'font-family': 'monospace' },
            rect: {
                width: width, height: height,
                rx: 5, ry: 5,
                stroke: '#555'
            }
        }
    });
}

// Parses a file, storing all the data into the graphinfo object
// returns an array of graph elements
function parseSimpleAdaptonView(text){
    graphinfo = {
        states: [],
        elements: [],
        links: []
    }
    console.log('spliting on state');
    states = text.split('Graph state: ');
    //first line is the blank before the first state
    states.shift();
    for(i=0;i<states.length;i++){
        console.log('starting parse of state '+i);
        graphinfo.states[i] = {
            title: "No name",
            elementStates: [],
            linkStates: []
        }
        state = graphinfo.states[i]; //shortcut
        lines = states[i].split('\n');
        state.title = lines.shift();
        for(j=0;j<lines.length;j++){
            tokens = lines[j].split(' ');
            //process line as element
            if(tokens.length == 2){
                ename = tokens[0];
                estate = tokens[1];
                eindex = graphinfo.elements.indexOf(ename);
                if(eindex == -1){
                    graphinfo.elements.push(ename);
                    eindex = graphinfo.elements.length-1;
                }
                state.elementStates[eindex] = estate;
            }//end element parse
            //process line as link
            if(tokens.length == 3){
                //get line data
                fromNode = tokens[0];
                toNode = tokens[1];
                linkState = tokens[2];
                //set up the elements of the link if needed
                fromNodeIndex = graphinfo.elements.indexOf(fromNode);
                toNodeIndex = graphinfo.elements.indexOf(toNode);
                if(fromNodeIndex == -1){
                    graphinfo.elements.push(fromNode)
                    fromNodeIndex = graphinfo.elements.length-1;
                    state.elementStates[fromNodeIndex] = 'active';
                }
                if(toNodeIndex == -1){
                    graphinfo.elements.push(toNode)
                    toNodeIndex = graphinfo.elements.length-1;
                    state.elementStates[toNodeIndex] = 'active';
                }
                if(!state.elementStates[fromNodeIndex]) {
                    state.elementStates[fromNodeIndex] = 'active';
                }
                if(!state.elementStates[toNodeIndex]) {
                    state.elementStates[toNodeIndex] = 'active';
                }
                //set up the link
                linkIndex = graphinfo.links.indexOf(fromNode+','+toNode);
                if(linkIndex == -1){
                    graphinfo.links.push(fromNode+','+toNode);
                    linkIndex = graphinfo.links.length-1;
                }
                state.linkStates[linkIndex] = linkState;
            }//end link parse
        }//end line parse
    }//end state parse
    //clean up data
    for(i=0;i<graphinfo.states.length;i++){
        state = graphinfo.states[i]; //shortcut
        for(j=0;j<graphinfo.elements.length;j++){
            if(!state.elementStates[j]){
                state.elementStates[j] = 'nonactive';
            }
        }
        for(j=0;j<graphinfo.links.length;j++){
            if(!state.linkStates[j]){
                state.linkStates[j] = 'nonactive';
            }
        }
    }
    //create elements and links
    for(i=0;i<graphinfo.elements.length;i++){
        graphinfo.elements[i] = makeElement(graphinfo.elements[i]);
    }
    for(i=0;i<graphinfo.links.length;i++){
        tofrom = graphinfo.links[i].split(',');
        graphinfo.links[i] = makeLink(tofrom[0],tofrom[1]);
    }
    //return list of elements to graph
    return graphinfo.elements.concat(graphinfo.links);
}

/*****************/
/* file handling */
/*****************/
//handler for new file selection
function handleFileSelect(event) {
    $('#list').empty();
    var files = event.target.files;
    var f = files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        console.log('file loaded');
        filecontents = e.target.result;
        //parse data into graphinfo and cells
        console.log('starting parse');
        cells = parseSimpleAdaptonView(filecontents);
        console.log('parse complete');
        //lay out the graph
        console.log('starting graph generation');
        graph.resetCells(cells);
        console.log('generation complete');
        console.log('starting layout');
        var size = joint.layout.DirectedGraph.layout(graph, { setLinkVertices: false, rankDir: "BT" });
        paper.setDimensions(size.width + 100, size.height + 100); //give some extra room for element sizes
        console.log('layout complete')
        //re-map elements to editable view elements for efficiency
        for(i=0;i<graphinfo.elements.length;i++){
            model = graphinfo.elements[i];
            graphinfo.elements[i] = V(paper.findViewByModel(model).el);
        }
        for(i=0;i<graphinfo.links.length;i++){
            model = graphinfo.links[i];
            graphinfo.links[i] = V(paper.findViewByModel(model).el);
        }
        //set first states
        console.log('loading first states');
        graphinfo.currentState = 0;
        for(i=0;i<graphinfo.elements.length;i++){
            graphinfo.elements[i].addClass(graphinfo.states[0].elementStates[i]);
        }
        for(i=0;i<graphinfo.links.length;i++){
            graphinfo.links[i].addClass(graphinfo.states[0].linkStates[i]);
        }
        //populate list box with states
        for(i=0;i<graphinfo.states.length;i++){
            $('#list').append('<option value="'+i+'">'+graphinfo.states[i].title+'</option>');
        }
        console.log('ready for user interation');
    }//end file load handler
    console.log('loading file');
    reader.readAsText(f);
}
/********************/
/* listbox handling */
/********************/
function handleListSelect(event){
    var newState = parseInt(event.target.value);
    if(newState == -1) return;
    //shortcuts
    var eso = graphinfo.states[graphinfo.currentState].elementStates;
    var lso = graphinfo.states[graphinfo.currentState].linkStates;
    var esn = graphinfo.states[newState].elementStates;
    var lsn = graphinfo.states[newState].linkStates;
    //change the state of all the stored objects
    for(i=0;i<graphinfo.elements.length;i++){
        if(esn[i] != eso[i]){
            graphinfo.elements[i].removeClass(eso[i]).addClass(esn[i]);
        }
    }
    for(i=0;i<graphinfo.links.length;i++){
        if(lsn[i] != lso[i]){
            graphinfo.links[i].removeClass(lso[i]).addClass(lsn[i]);
        }
    }
    //set current state
    graphinfo.currentState = newState;
}
<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function (grunt) {

    // Project configuration.
    grunt.initConfig({
        pkg: '<json:package.json>',
        meta: {
            banner: '/*\n' + ' * <%= pkg.title || pkg.name %> v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * \n * <%= pkg.description %> * \n'  + '<%= pkg.homepage ? " * " + pkg.homepage + "\n" : "" %>' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>\n' + ' * Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %>\n' + ' */'
        },
        concat: {
            dist: {
                src: ['<banner:meta.banner>', 'src/promise.js', '<file_strip_banner:src/<%= pkg.name %>.js>'],
                dest: 'dist/<%= pkg.name %>.js'
            }
        },
        min: {
            dist: {
                src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
                dest: 'dist/<%= pkg.name %>.min.js'
            }
        },
        // qunit: {
        // files: ['test/**/*.html']
        // },
        lint: {
            files: ['grunt.js', 'src/**/*.js']
        },
        watch: {
            files: '<config:lint.files>',
            tasks: 'lint'
            //tasks: 'lint qunit'
        },
        jshint: {
            options: {
                curly: true,
                eqeqeq: true,
                immed: true,
                latedef: true,
                newcap: true,
                noarg: true,
                sub: true,
                undef: true,
                boss: true,
                eqnull: true,
                browser: true
            },
            globals: {
                Promise: true
            }
        },
        uglify: {}
    });

    // Default task.
    //grunt.registerTask('default', 'lint qunit concat min');
    grunt.registerTask('default', 'lint concat min');

    // Travis CI task.
    //grunt.registerTask('travis', 'lint qunit');
    grunt.registerTask('travis', 'lint');
};<commit_msg>fixed grunt.js<commit_after>/*global module:false*/
module.exports = function (grunt) {

    // Project configuration.
    grunt.initConfig({
        pkg: '<json:package.json>',
        meta: {
            banner: '/*\n' + ' * <%= pkg.title || pkg.name %> v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * \n * <%= pkg.description %> * \n'  + '<%= pkg.homepage ? " * " + pkg.homepage + "\n" : "" %>' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>\n' + ' * Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %>\n' + ' */'
        },
        concat: {
            dist: {
                src: ['<banner:meta.banner>', 'src/promise.js', '<file_strip_banner:src/<%= pkg.name %>.js>'],
                dest: 'dist/<%= pkg.name %>.js'
            }
        },
        min: {
            dist: {
                src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
                dest: 'dist/<%= pkg.name %>.min.js'
            }
        },
        qunit: {
            files: ['test/*.html']
        },
        lint: {
            files: ['grunt.js', 'src/**/*.js']
        },
        watch: {
            files: '<config:lint.files>',
            tasks: 'lint qunit'
        },
        jshint: {
            options: {
                curly: true,
                eqeqeq: true,
                immed: true,
                latedef: true,
                newcap: true,
                noarg: true,
                sub: true,
                undef: true,
                boss: true,
                eqnull: true,
                browser: true
            },
            globals: {
                Promise: true
            }
        },
        uglify: {}
    });

    // Default task.
    grunt.registerTask('default', 'lint concat min');

    // Travis CI task.
    grunt.registerTask('travis', 'lint qunit');
};<|endoftext|>


<commit_before>/*global config:true, task:true*/
var coreFiles = 'jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.effects.core.js'.split(', ');
var allFiles = coreFiles.map(function(file) {
  return 'ui/' + file;
}).concat(file.expand('ui/*.js').filter(function(file) {
  return coreFiles.indexOf(file.substring(3)) === -1;
}));
var rawList = allFiles.map(function(file) {
  return file.substring(3);
});
config.init({
  pkg: '<json:package.json>',
  meta: {
    banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
      '<%= template.today("m/d/yyyy") %>\n' +
      '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
      // TODO makes this banner only useful for the min-all task below...
      '* Includes: ' + rawList.join(', ') + '\n' +
      '* Copyright (c) <%= template.today("yyyy") %> <%= pkg.author.name %>;' +
      ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
  },
  concat: {
    'dist/jquery-ui.js': allFiles
  },
  min: {
    'dist/jquery-ui.min.js': ['<banner>', 'dist/jquery-ui.js']
  },
  zip: {
    dist: {
      src: [
        'dist/**/*.js',
        'README.md',
        'grunt.js',
        'package.json',
        'ui/**/*',
        'demos/**/*',
        'themes/**/*',
        'external/**/*',
        'tests/**/*'
      ],
      dest: 'dist/<%= pkg.name %>-<%= pkg.version %>.zip'
    }
  },
  qunit: {
    files: file.expand('tests/unit/**/*.html').filter(function(file) {
      // disabling everything that doesn't (quite) work with PhantomJS for now
      // except for all|index|test, try to include more as we go
      return !(/(all|index|test|draggable|droppable|selectable|resizable|sortable|dialog|slider|datepicker|tabs|tabs_deprecated)\.html/).test(file);
    })
  },
  lint: {
    // TODO extend this to tests
    files: ['ui/*']
  },
  jshint: {
    options: {
      curly: true,
      eqeqeq: true,
      immed: true,
      latedef: true,
      newcap: true,
      noarg: true,
      sub: true,
      undef: true,
      eqnull: true,
      browser: true
    },
    globals: {
      jQuery: true
    }
  }
});

task.registerBasicTask('zip', 'Create a zip file for release', function(data) {
  var files = file.expand(data.src);
  log.writeln("Creating zip file " + data.dest);

  var done = this.async();

  var zipstream = require('zipstream');
  var fs = require('fs');

  var out = fs.createWriteStream(data.dest);
  var zip = zipstream.createZip({ level: 1 });

  zip.pipe(out);

  function addFile() {
    if (!files.length) {
      zip.finalize(function(written) {
        log.writeln(written + ' total bytes written');
        done();
      });
      return;
    }
    var file = files.shift();
    log.verbose.writeln('Zipping ' + file);
    zip.addFile(fs.createReadStream(file), { name: file }, addFile);
  }
  addFile();
});

task.registerTask('default', 'lint qunit');
task.registerTask('release', 'default concat min zip');
<commit_msg>Use isoDate format for min banner<commit_after>/*global config:true, task:true*/
var coreFiles = 'jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.effects.core.js'.split(', ');
var allFiles = coreFiles.map(function(file) {
  return 'ui/' + file;
}).concat(file.expand('ui/*.js').filter(function(file) {
  return coreFiles.indexOf(file.substring(3)) === -1;
}));
var rawList = allFiles.map(function(file) {
  return file.substring(3);
});
config.init({
  pkg: '<json:package.json>',
  meta: {
    banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
      '<%= template.today("isoDate") %>\n' +
      '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
      // TODO makes this banner only useful for the min-all task below...
      '* Includes: ' + rawList.join(', ') + '\n' +
      '* Copyright (c) <%= template.today("yyyy") %> <%= pkg.author.name %>;' +
      ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
  },
  concat: {
    'dist/jquery-ui.js': allFiles
  },
  min: {
    'dist/jquery-ui.min.js': ['<banner>', 'dist/jquery-ui.js']
  },
  zip: {
    dist: {
      src: [
        'dist/**/*.js',
        'README.md',
        'grunt.js',
        'package.json',
        'ui/**/*',
        'demos/**/*',
        'themes/**/*',
        'external/**/*',
        'tests/**/*'
      ],
      dest: 'dist/<%= pkg.name %>-<%= pkg.version %>.zip'
    }
  },
  qunit: {
    files: file.expand('tests/unit/**/*.html').filter(function(file) {
      // disabling everything that doesn't (quite) work with PhantomJS for now
      // except for all|index|test, try to include more as we go
      return !(/(all|index|test|draggable|droppable|selectable|resizable|sortable|dialog|slider|datepicker|tabs|tabs_deprecated)\.html/).test(file);
    })
  },
  lint: {
    // TODO extend this to tests
    files: ['ui/*']
  },
  jshint: {
    options: {
      curly: true,
      eqeqeq: true,
      immed: true,
      latedef: true,
      newcap: true,
      noarg: true,
      sub: true,
      undef: true,
      eqnull: true,
      browser: true
    },
    globals: {
      jQuery: true
    }
  }
});

task.registerBasicTask('zip', 'Create a zip file for release', function(data) {
  var files = file.expand(data.src);
  log.writeln("Creating zip file " + data.dest);

  var done = this.async();

  var zipstream = require('zipstream');
  var fs = require('fs');

  var out = fs.createWriteStream(data.dest);
  var zip = zipstream.createZip({ level: 1 });

  zip.pipe(out);

  function addFile() {
    if (!files.length) {
      zip.finalize(function(written) {
        log.writeln(written + ' total bytes written');
        done();
      });
      return;
    }
    var file = files.shift();
    log.verbose.writeln('Zipping ' + file);
    zip.addFile(fs.createReadStream(file), { name: file }, addFile);
  }
  addFile();
});

task.registerTask('default', 'lint qunit');
task.registerTask('release', 'default concat min zip');
<|endoftext|>


<commit_before>module.exports = function (grunt) {

  grunt.initConfig({

    text_replace: {
      default: {
        files: ['**/*.txt'],

        options: {
          regex: true
        },

        replacements: [
          {
            from: 'Hello',
            to: 'Good bye'
          }
        ]

      }
    }

  });

  grunt.registerMultiTask('text_replace', 'A description', function () {
    console.log('TASK')
    grunt.log.writeln(this.target + ': ' + JSON.stringify(this.data));
  });

};<commit_msg>Basic replacement now working<commit_after>module.exports = function (grunt) {

  grunt.initConfig({

    text_replace: {
      default: {
        files: {
          src:  ['*.txt'],
          dest: 'foo.txt'
        },

        options: {
          regex: true
        },

        replacements: [
          {
            from: 'Hello',
            to: 'Good bye'
          },
          {
            from: 'Pleased',
            to: 'Delighted'
          }
        ]

      }
    }

  });

  grunt.registerTask('default', 'text_replace');

  grunt.registerMultiTask('text_replace', 'A description', function () {
    var allSourceFiles = this.data.files.src,
        allSourceFilePaths = grunt.file.expandFiles(allSourceFiles),
        pathToDestinationDirectory = this.data.files.dest;

    var allReplacements = this.data.replacements;

    allSourceFilePaths.forEach(function (pathToFile) {
      grunt.file.copy(pathToFile, pathToDestinationDirectory, {
        process: function (fileContents) {
          allReplacements.forEach(function (replacement) {
            console.log(replacement)
            fileContents = fileContents.replace(replacement.from, replacement.to);
          })
          return fileContents;
        }
      });
    })
  });

};<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function(grunt) {
  // Project configuration.

  grunt.initConfig( {
    pkg: '<json:package.json>',
    componentPath: 'components',
    meta: {
      banner: '/**' +
      '\n * <%= pkg.name %> version <%= pkg.version %>' +
      '\n * @author <%= pkg.author.name %> <<%= pkg.author.email %>>' +
      '\n * @license' +
      '\n *' +
      '\n * Please thank the contributors:' +
      '\n * https://github.com/linkedin/Lu/graphs/contributors' +
      '\n *' +
      '\n * Copyright (c) 2011,2012 LinkedIn' +
      '\n * All Rights Reserved. Apache Software License 2.0' +
      '\n *' +
      '\n * Licensed under the Apache License, Version 2.0 (the "License");' +
      '\n * you may not use this file except in compliance with the License.' +
      '\n * You may obtain a copy of the License at' +
      '\n *' +
      '\n * http://www.apache.org/licenses/LICENSE-2.0' +
      '\n *' +
      '\n * Unless required by applicable law or agreed to in writing, software' +
      '\n * distributed under the License is distributed on an "AS IS" BASIS,' +
      '\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.' +
      '\n * See the License for the specific language governing permissions and' +
      '\n * limitations under the License.' +
      '\n */'
    },
    lint: {
      files: ['grunt.js', 'scripts/components/**/*.js', 'scripts/*.js']
    },
    qunit: {
      files: [
        'http://localhost:1337/test/abstract/abstract.html',
        'http://localhost:1337/test/lu/lu.html',
        'http://localhost:1337/test/placeholder/placeholder.html',
        'http://localhost:1337/test/$/$.html',
        'http://localhost:1337/test/list/list.html',
        'http://localhost:1337/test/tip/tip.html',
        'http://localhost:1337/test/carousel/carousel.html',
        'http://localhost:1337/test/dropdown/dropdown.html',
        'http://localhost:1337/test/switch/switch.html'
      ]
    },
    concat: {
      config: {
        src: ['<banner>', 'scripts/config.js'],
        dest: 'dist/<%= pkg.version %>/config.js'
      }
    },
    min: {
      core: {
        src: ['<banner>', 'scripts/lu.js'],
        dest: 'dist/<%= pkg.version %>/lu.js'
      },
      mappers: {
        src: ['<banner>', 'scripts/mappers.js'],
        dest: 'dist/<%= pkg.version %>/mappers.js'
      },
      a: {
        src: ['<banner>', 'scripts/<%= componentPath %>/decorators/state.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/decorators/state.js'
      },
      b: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Abstract.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Abstract.js'
      },
      c: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button.js'
      },
      d: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/default.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/default.js'
      },
      e: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/first.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/first.js'
      },
      f: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/last.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/last.js'
      },
      g: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/load.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/load.js'
      },
      h: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/next.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/next.js'
      },
      i: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/pause.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/pause.js'
      },
      j: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/play.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/play.js'
      },
      k: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/previous.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/previous.js'
      },
      l: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/select.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/select.js'
      },
      m: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/state.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/state.js'
      },
      n: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Carousel.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Carousel.js'
      },
      o: {
        src: ['<banner>', 'scripts/<%= componentPath %>/constants.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/constants.js'
      },
      p: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Container.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Container.js'
      },
      q: {
        src: ['<banner>', 'scripts/<%= componentPath %>/helpers.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/helpers.js'
      },
      r: {
        src: ['<banner>', 'scripts/<%= componentPath %>/List.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/List.js'
      },
      s: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Switch.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Switch.js'
      },
      t: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Placeholder.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Placeholder.js'
      },
      u: {
        src: ['<banner>', 'scripts/<%= componentPath %>/FormElement.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/FormElement.js'
      },
      v: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Tip.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Tip.js'
      },
      w: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Tip/decorators/above.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Tip/decorators/above.js'
      },
      x: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Tip/decorators/below.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Tip/decorators/below.js'
      },
      y: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Tip/decorators/left.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Tip/decorators/left.js'
      },
      z: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Tip/decorators/right.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Tip/decorators/right.js'
      }
    },
    jshint: {
      options: {
        "bitwise": true,
        "camelcase": true,
        "curly": true,
        "eqeqeq": true,
        "forin": false,
        "immed": true,
        "indent": 2,
        "latedef": true,
        "newcap": true,
        "noarg": true,
        "noempty": false,
        "nonew": true,
        "plusplus": false,
        "quotmark": "single",
        "regexp": false,
        "undef": true,
        "unused": true,
        "strict": false,
        "trailing": true,
        "asi": false,
        "boss": false,
        "debug": false,
        "eqnull": true,
        "es5": false,
        "esnext": false,
        "evil": true,
        "expr": false,
        "funcscope": false,
        "globalscript": false,
        "iterator": false,
        "lastsemic": false,
        "laxbreak": false,
        "laxcomma": false,
        "loopfunc": false,
        "multistr": true,
        "onecase": false,
        "proto": false,
        "regexdash": false,
        "scripturl": false,
        "smarttabs": false,
        "shadow": true,
        "sub": true,
        "supernew": false,
        "validthis": false,
        "jquery": true,
        "browser": true
      },
      globals: {
        Lu: true,
        module: true,
        require: true,
        Inject: true,
        _: true
      }
    }
  } );

  // Build task.
  grunt.registerTask( 'build', 'lint qunit concat min' );

  // Default task.
  grunt.registerTask( 'default', '' );

};
<commit_msg>grunt<commit_after>/*global module:false*/
module.exports = function(grunt) {
  // Project configuration.

  grunt.initConfig( {
    pkg: '<json:package.json>',
    componentPath: 'components',
    meta: {
      banner: '/**' +
      '\n * <%= pkg.name %> version <%= pkg.version %>' +
      '\n * @author <%= pkg.author.name %> <<%= pkg.author.email %>>' +
      '\n * @license' +
      '\n *' +
      '\n * Please thank the contributors:' +
      '\n * https://github.com/linkedin/Lu/graphs/contributors' +
      '\n *' +
      '\n * Copyright (c) 2011,2012 LinkedIn' +
      '\n * All Rights Reserved. Apache Software License 2.0' +
      '\n *' +
      '\n * Licensed under the Apache License, Version 2.0 (the "License");' +
      '\n * you may not use this file except in compliance with the License.' +
      '\n * You may obtain a copy of the License at' +
      '\n *' +
      '\n * http://www.apache.org/licenses/LICENSE-2.0' +
      '\n *' +
      '\n * Unless required by applicable law or agreed to in writing, software' +
      '\n * distributed under the License is distributed on an "AS IS" BASIS,' +
      '\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.' +
      '\n * See the License for the specific language governing permissions and' +
      '\n * limitations under the License.' +
      '\n */'
    },
    lint: {
      files: ['grunt.js', 'scripts/components/**/*.js', 'scripts/*.js']
    },
    qunit: {
      files: [
        'http://localhost:1337/test/abstract/abstract.html',
        'http://localhost:1337/test/lu/lu.html',
        'http://localhost:1337/test/placeholder/placeholder.html',
        'http://localhost:1337/test/$/$.html',
        'http://localhost:1337/test/list/list.html',
        'http://localhost:1337/test/tip/tip.html',
        'http://localhost:1337/test/carousel/carousel.html',
        'http://localhost:1337/test/dropdown/dropdown.html',
        'http://localhost:1337/test/switch/switch.html',
        'http://localhost:1337/test/viewport/viewport.html'
      ]
    },
    concat: {
      config: {
        src: ['<banner>', 'scripts/config.js'],
        dest: 'dist/<%= pkg.version %>/config.js'
      }
    },
    min: {
      core: {
        src: ['<banner>', 'scripts/lu.js'],
        dest: 'dist/<%= pkg.version %>/lu.js'
      },
      mappers: {
        src: ['<banner>', 'scripts/mappers.js'],
        dest: 'dist/<%= pkg.version %>/mappers.js'
      },
      StateDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/decorators/state.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/decorators/state.js'
      },
      AbstractComponent: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Abstract.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Abstract.js'
      },
      ButtonComponent: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button.js'
      },
      DefaultButtonDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/default.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/default.js'
      },
      FirstButtonDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/first.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/first.js'
      },
      LastButtonDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/last.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/last.js'
      },
      LoadButtonDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/load.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/load.js'
      },
      NextButtonDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/next.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/next.js'
      },
      PauseButtonDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/pause.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/pause.js'
      },
      PlayButtonDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/play.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/play.js'
      },
      PreviousButtonDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/previous.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/previous.js'
      },
      SelectButtonDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/select.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/select.js'
      },
      StateButtonDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Button/decorators/state.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Button/decorators/state.js'
      },
      CarouselComponent: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Carousel.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Carousel.js'
      },
      constants: {
        src: ['<banner>', 'scripts/<%= componentPath %>/constants.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/constants.js'
      },
      ContainerComponent: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Container.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Container.js'
      },
      helpers: {
        src: ['<banner>', 'scripts/<%= componentPath %>/helpers.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/helpers.js'
      },
      ListComponent: {
        src: ['<banner>', 'scripts/<%= componentPath %>/List.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/List.js'
      },
      SwitchComponent: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Switch.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Switch.js'
      },
      PlaceholderComponent: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Placeholder.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Placeholder.js'
      },
      FormElementComponent: {
        src: ['<banner>', 'scripts/<%= componentPath %>/FormElement.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/FormElement.js'
      },
      TipComponent: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Tip.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Tip.js'
      },
      AboveTipDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Tip/decorators/above.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Tip/decorators/above.js'
      },
      BelowTipDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Tip/decorators/below.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Tip/decorators/below.js'
      },
      LeftTipDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Tip/decorators/left.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Tip/decorators/left.js'
      },
      RightTipDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Tip/decorators/right.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Tip/decorators/right.js'
      },
      ViewportListDecorator: {
        src: ['<banner>', 'scripts/<%= componentPath %>/List/decorators/viewport.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/List/decorators/viewport.js'
      },
      DropdownComponent: {
        src: ['<banner>', 'scripts/<%= componentPath %>/Dropdown.js'],
        dest: 'dist/<%= pkg.version %>/<%= componentPath %>/Dropdown.js'
      }
    },
    jshint: {
      options: {
        "bitwise": true,
        "camelcase": true,
        "curly": true,
        "eqeqeq": true,
        "forin": false,
        "immed": true,
        "indent": 2,
        "latedef": true,
        "newcap": true,
        "noarg": true,
        "noempty": false,
        "nonew": true,
        "plusplus": false,
        "quotmark": "single",
        "regexp": false,
        "undef": true,
        "unused": true,
        "strict": false,
        "trailing": true,
        "asi": false,
        "boss": false,
        "debug": false,
        "eqnull": true,
        "es5": false,
        "esnext": false,
        "evil": true,
        "expr": false,
        "funcscope": false,
        "globalscript": false,
        "iterator": false,
        "lastsemic": false,
        "laxbreak": false,
        "laxcomma": false,
        "loopfunc": false,
        "multistr": true,
        "onecase": false,
        "proto": false,
        "regexdash": false,
        "scripturl": false,
        "smarttabs": false,
        "shadow": true,
        "sub": true,
        "supernew": false,
        "validthis": false,
        "jquery": true,
        "browser": true
      },
      globals: {
        Lu: true,
        module: true,
        require: true,
        Inject: true,
        _: true
      }
    }
  } );

  // Build task.
  grunt.registerTask( 'build', 'lint qunit concat min' );

  // Default task.
  grunt.registerTask( 'default', '' );

};
<|endoftext|>


<commit_before>module.exports = function (grunt) {

	grunt.initConfig({

		meta: {
			banner: '// ' + grunt.file.read('LICENSE').split("\n")[0]
		},

		coffee: {
			compile: {
				files: {
					'lib/x18n.js': ['lib/observable.coffee', 'lib/x18n.coffee'],
					'spec/spec.js': 'spec/spec.coffee'
				}
			}
		}

	});

	grunt.loadNpmTasks('grunt-contrib-coffee');

};<commit_msg>add concat task<commit_after>module.exports = function (grunt) {

	grunt.initConfig({

		meta: {
			banner: '// ' + grunt.file.read('LICENSE').split("\n")[0]
		},

		coffee: {
			compile: {
				files: {
					'lib/x18n.js': ['lib/observable.coffee', 'lib/x18n.coffee'],
					'spec/spec.js': 'spec/spec.coffee'
				}
			}
		},

		concat: {
			dist: {
				src: ['<banner>', 'lib/x18n.js'],
				dest: 'lib/x18n.js'
			}
		}

	});

	grunt.loadNpmTasks('grunt-contrib-coffee');

};<|endoftext|>


<commit_before>/*global config:true, task:true*/
config.init({
  meta: {
    name: 'grunt',
    version: '0.1.0',
    description: 'A command line build tool for JavaScript projects..',
    homepage: 'http://github.com/cowboy/grunt',
    author: '"Cowboy" Ben Alman',
    license: ['MIT'],
    copyright: 'Copyright (c) 2011 "Cowboy" Ben Alman',
    repository: 'git://github.com/cowboy/grunt.git'
  },
  concat: {},
  min: {},
  test: {
    files: ['test/**/*.js']
  },
  lint: {
    files: ['grunt.js', 'lib/**/*.js', 'test/**/*.js']
  },
  watch: {
    files: '<config:lint.files>',
    tasks: 'default'
  },
  jshint: {
    options: {
      curly: true,
      eqeqeq: true,
      immed: true,
      latedef: true,
      newcap: true,
      noarg: true,
      sub: true,
      undef: true,
      boss: true,
      eqnull: true,
      node: true
    },
    globals: {
      setTimeout: true, // temp hack for https://github.com/jshint/jshint/issues/292
      grequire: true,
      urequire: true,
      extraspath: true,
      _: true,
      task: true,
      file: true,
      fail: true,
      config: true,
      option: true,
      log: true,
      verbose: true
    }
  },
  uglify: {}
});

// Default task.
task.registerTask('default', 'lint:files test:files');
<commit_msg>Minor gruntfile tweaks.<commit_after>/*global config:true, task:true*/
config.init({
  meta: {
    name: 'grunt',
    version: '0.1.0',
    description: 'A command line build tool for JavaScript projects.',
    homepage: 'https://github.com/cowboy/grunt',
    author: '"Cowboy" Ben Alman',
    license: ['MIT'],
    copyright: 'Copyright (c) 2012 "Cowboy" Ben Alman',
    repository: 'git://github.com/cowboy/grunt.git'
  },
  concat: {},
  min: {},
  test: {
    files: ['test/**/*.js']
  },
  lint: {
    files: ['grunt.js', 'lib/**/*.js', 'test/**/*.js']
  },
  watch: {
    files: '<config:lint.files>',
    tasks: 'default'
  },
  jshint: {
    options: {
      curly: true,
      eqeqeq: true,
      immed: true,
      latedef: true,
      newcap: true,
      noarg: true,
      sub: true,
      undef: true,
      boss: true,
      eqnull: true,
      node: true
    },
    globals: {
      grequire: true,
      urequire: true,
      extraspath: true,
      _: true,
      task: true,
      file: true,
      fail: true,
      config: true,
      option: true,
      log: true,
      verbose: true
    }
  },
  uglify: {}
});

// Default task.
task.registerTask('default', 'lint test');
<|endoftext|>


<commit_before>// BRICO

var through = require('through')
var fern = require('fern')
var conf = require('./__conf.json')
var proc = process.title // node or browser

// SPACES
// * = Module
// ^ = Library
// # = Connection
// _ = Process

var filter = {
  put: {
    make: function (d) {
      var m = d.key.split(':')[1]
      var mPath = config.dir_wilds+m
      _[m] = require(mPath)(d.value)
    },
    conn: function (d) {
    }
  },
  del: {
    make: function (d) {
      var m = d.key.split(':')[1]
      _[m].emit('close')
      delete _[m]
    },
    conn: function (d) {
    }
  }
}
module.exports.filter = filter

module.exports = function bricoleur (data) {
  var _ = {}

  var fil = fern(filter)
  fil.on('error', console.error)
  var liveStream = data.liveStream({old:false})
  liveStream.pipe(fil)

  // UTIL
  function search (args, cb) {
    var match = false
    var ks = data.createKeyStream()
    ks.on('data', function (d) {
      var path = d.split(':')
      if (args[1] === path[1]) {
        match = true
        for (var i=2; i<args.length; i++) {
          var pair = args[i].split('=')
          var key = pair[0]
          var val = pair[1]
          opts[key] = val
        }
        if (opts === {}) opts = null
      }
    })
    ks.on('end', function () {
      if (match !== true) interface.emit('error', new Error('could not find module'))
    })
  }

  var interface = through(function write (d) {
    this.emit('data', d)
  }, function end () {
    this.emit('end')
  })

  return interface
}
<commit_msg>refactoring brico, using wilds for spaces, remove weird filter tree<commit_after>// BRICO

var through = require('through')
var fern = require('fern')
var conf = require('./__conf.json')
var proc = process.title // node or browser
var interface

var WILDS = {}

WILDS['*'] = function (i,o) { // * MODULE

}
WILDS['^'] = function (i,o) { // ^ LIBRARY

}
WILDS['#'] = function (i,o) { // # CONNECT

}
WILDS['_'] = function (i,o} { // _ PROCESS

}

interface = through(function write (d) {
  var path = key.split(':')
  var space = path[0]

}, function end () {
  this.emit('end')
}, {autoDestroy:false})

module.exports = function bricoleur (data) {

  var liveStream = data.liveStream({old:false})

  return interface
}

// UTIL

function search (args, cb) {
  var match = false
  var ks = data.createKeyStream()
  ks.on('data', function (d) {
    var path = d.split(':')
    if (args[1] === path[1]) {
      match = true
      for (var i=2; i<args.length; i++) {
        var pair = args[i].split('=')
        var key = pair[0]
        var val = pair[1]
        opts[key] = val
      }
      if (opts === {}) opts = null
    }
  })
  ks.on('end', function () {
    if (match !== true) interface.emit('error', new Error('could not find module'))
  })
}
<|endoftext|>


<commit_before>chrome.tabs.getSelected(function(tab) {
	var fromBox = document.getElementById("from");

	chrome.storage.sync.get(function(items) {
		var found = false;
		for (from in items) {
			var reto = new RegExp("^http[s]?\:\/\/" + items[from] + "\/\.*$", "i");
			if (tab.url.match(reto)) {
				document.getElementById("information").innerHTML = "Current rule:";
				fromBox.value = from;
				document.getElementById("to").value = items[from];
				found = true;
				break;
			}
		}
		if (!found) {
			document.getElementById("information").innerHTML = "Add rule:";
			fromBox.value = tab.url.match(new RegExp("^http[s]?\:\/\/([^\/]*)\/\.*$", "i"))[1];
		}
		fromBox.disabled = true;
	});
});

function save_options() {
	var from = document.getElementById("from").value;
	var to = document.getElementById("to").value;
	var store = {};
	store[from] = to;
	chrome.storage.sync.set(store);
	chrome.tabs.getSelected(function(tab) {
		var protore = new RegExp("^(http[s]?\:\/\/)\.*$", "i");
		var urire = new RegExp("^http[s]?\:\/\/[^\/]*(\/.*)$", "i");
		var url = tab.url.match(protore)[1] + to + tab.url.match(urire)[1];
		chrome.tabs.update(tab.id, {url: url});
	});
}

document.querySelector("#save").addEventListener("click", save_options);
<commit_msg>Add enter listener for the browser action.<commit_after>chrome.tabs.getSelected(function(tab) {
	var fromBox = document.getElementById("from");

	chrome.storage.sync.get(function(items) {
		var found = false;
		document.querySelector("#to").onkeypress = on_key_press;
		document.querySelector("#from").onkeypress = on_key_press;
		for (from in items) {
			var reto = new RegExp("^http[s]?\:\/\/" + items[from] + "\/\.*$", "i");
			if (tab.url.match(reto)) {
				document.getElementById("information").innerHTML = "Current rule:";
				fromBox.value = from;
				document.getElementById("to").value = items[from];
				found = true;
				break;
			}
		}
		if (!found) {
			document.getElementById("information").innerHTML = "Add rule:";
			fromBox.value = tab.url.match(new RegExp("^http[s]?\:\/\/([^\/]*)\/\.*$", "i"))[1];
		}
		fromBox.disabled = true;
	});
});

function on_key_press(event) {
	if (event.keyCode == 13)
		save_options();
}

function save_options() {
	var from = document.getElementById("from").value;
	var to = document.getElementById("to").value;
	var store = {};
	store[from] = to;
	chrome.storage.sync.set(store);
	chrome.tabs.getSelected(function(tab) {
		var protore = new RegExp("^(http[s]?\:\/\/)\.*$", "i");
		var urire = new RegExp("^http[s]?\:\/\/[^\/]*(\/.*)$", "i");
		var url = tab.url.match(protore)[1] + to + tab.url.match(urire)[1];
		chrome.tabs.update(tab.id, {url: url});
	});
}

document.querySelector("#save").addEventListener("click", save_options);
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const botLogin = require('./config/botlogin.js');
const liveStream = require('./modules/livestream.js');
const bot = new Discord.Client();
bot.login(botLogin.token);

const adminRole = "admin";

var botVersion = "?#";
try{
	botVersion = require('./package.json').version;
} catch(error){
	if(error) {
		console.log("------- ERROR --------");
		console.log(error);
		console.log("----------------------");
	}
}
var CMDINT = "?";
var defaultStatus = "v"+botVersion + " | " + CMDINT + "help";

// Checks if the message is a command input from the user
function isCommand(message, command){
	var init = message.slice(0, 1);
	var cmd = (message.indexOf(' ') !== -1) ? message.slice(1, message.indexOf(' ')) : message.slice(1);

	if(init === CMDINT && cmd.toLowerCase() === command.toLowerCase())
		return true
	else
		return false;
}

// Checks for a specific role the user is in to run admin commands
function isAdmin(message){
	var roles = message.member.roles.array();
	for(var role = 0; role < roles.length; role++){
		if(roles[role].name.toLowerCase() === adminRole)
			return true;
	}
	message.channel.sendMessage("You aren't admin for this command.");
	return false;
}

// Sets the game the bot is "playing"
function setGame(game){
	bot.user.setGame(game);
}

function getChannelByName(guild, channelName){
	return guild.channels.filterArray( channel => {
		if(channel.name === channelName)
			return channel;
	})[0];
}

function botLog(message){
	console.log("DISCORD: " + message);
}

function sendError(title, error, channel){
	console.log("-----"  + "ERROR"+ "------");
	console.log(error);
	console.log("----------");
	channel.sendMessage("**" + title + " Error**\n```" + error.message +"```");
}

function displayServers(){
	var guilds = bot.guilds.array();
	var servers = [];

	for(var i = 0; i < guilds.length; i++){
		servers.push(guilds[i].name);
	}

	return "Servers:\n " + servers.join(", ") + "\n";
}

bot.on('ready', () => {
	console.log("AkeBot v" + botVersion);
	console.log(displayServers());

	setGame(defaultStatus);
});

bot.on('disconnect', event =>{
	console.log("Exited with code: " + event.code);
	if(event.message)
		console.log("Message: " + event.message);

	process.exit(0);
});

bot.on('guildMemberAdd', guildMember =>{
	var generalChannel = getChannelByName(guildMember.guild, 'general');

	generalChannel.sendMessage(guildMember.user.username +" Welcome to " + guildMember.guild.name);
	botLog(guildMember.guild.name + " welcomes " + guildMember.user.username + " to their server.");
});

bot.on('presenceUpdate', (oldGuildMember, newGuildMember) =>{
	var generalChannel = getChannelByName(newGuildMember.guild, 'general');
	if(newGuildMember.presence.game !== null){
		if(newGuildMember.presence.game.streaming){
			generalChannel.sendMessage("**LIVE**\n" +
				newGuildMember.user.username + " is now streaming!\n**Title:** " + newGuildMember.presence.game.name +
				"\n**URL:** " + newGuildMember.presence.game.url);
		}
	}
});

bot.on('message', message => {
	const mContent = message.content;
	const mChannel = message.channel;

	// Admin commands

	if(isCommand(mContent, 'exit') && isAdmin(message)){
		bot.destroy();
	}

	if(isCommand(mContent, 'setgame') && isAdmin(message)){
		if(mContent.indexOf('') !== -1){
			var game = mContent.slice(mContent.indexOf(' ') + 1);
			setGame(game);
			botLog("Game set to: " + game);
		}
	}

	// GENERAL commands

  	if(isCommand(mContent, 'help')){
  		message.channel.sendMessage("**In progress!**");
  	}

  	if(isCommand(mContent, 'invite')){
  		bot.generateInvite().then( link =>{
  			mChannel.sendMessage("**Invite:** " + link);
  		});
  	}

  	if(isCommand(mContent, 'uptime')){
  		var uptimeSeconds = 0, uptimeMinutes = 0, uptimeHours = 0;

  		uptimeSeconds = Math.floor(bot.uptime/1000);

		if(uptimeSeconds > 60){
			uptimeMinutes = Math.floor(uptimeSeconds/60);
			uptimeSeconds = Math.floor(uptimeSeconds % 60);
		}

		if(uptimeMinutes > 60){
			uptimeHours = Math.floor(uptimeMinutes / 60);
			uptimeMinutes = Math.floor(uptimeMinutes % 60);
		}

  		mChannel.sendMessage("**Uptime:** " + uptimeHours + " hour(s) : " + uptimeMinutes + " minute(s) : " + uptimeSeconds +" second(s)");
  	}

  	if(isCommand(mContent, 'twitch')){
  		if(mContent.indexOf(' ') !== -1){
  			var name = mContent.split(' ')[1];

  			liveStream.getTwitchStream(name, (error, status, gameTitle, streamURL)=> {
  				if(error) return sendError("Getting Twitch Stream Data", error, mChannel);
  				if(status){
  					mChannel.sendMessage(
  					"**Twitch**\n**Name:** " + name +
  					"\n**Status:** `Online`\n**Game:** " + gameTitle +
  					"\n**URL:** " + streamURL);
  				} else{
  					mChannel.sendMessage(
  						"**Twitch**\n**Name:** " + name +
  						"\n**Status:** `Offline`");
  				}
  			});
  		}
  	}

  	if(isCommand(mContent, 'hitbox')){
  		if(mContent.indexOf(' ')!== -1){
  			var name = mContent.split(' ')[1];

  			liveStream.getHitboxStream(name, (error, status, gameTitle, streamURL) =>{
  				if(error) return sendError("Getting HitBox Stream Data", error, mChannel);
  				if(status){
  					mChannel.sendMessage(
  					"**HitBox**\n**Name:**" + name +
  					"\n**Status:** `Online`\n**Game:** " + gameTitle +
  					"\n**URL:** " + streamURL);
  				} else{
  					mChannel.sendMessage(
  					"**HitBox**\n**Name:**" + name +
  					"\n**Status:** `Offline`");
  				}
  			});
  		}
  	}
});<commit_msg>Added about command<commit_after>const Discord = require('discord.js');
const botLogin = require('./config/botlogin.js');
const liveStream = require('./modules/livestream.js');
const bot = new Discord.Client();
bot.login(botLogin.token);

const adminRole = "admin";

var botVersion = "?#";
try{
	botVersion = require('./package.json').version;
} catch(error){
	if(error) {
		console.log("------- ERROR --------");
		console.log(error);
		console.log("----------------------");
	}
}
var CMDINT = "?";
var defaultStatus = "v"+botVersion + " | " + CMDINT + "help";

// Checks if the message is a command input from the user
function isCommand(message, command){
	var init = message.slice(0, 1);
	var cmd = (message.indexOf(' ') !== -1) ? message.slice(1, message.indexOf(' ')) : message.slice(1);

	if(init === CMDINT && cmd.toLowerCase() === command.toLowerCase())
		return true
	else
		return false;
}

// Checks for a specific role the user is in to run admin commands
function isAdmin(message){
	var roles = message.member.roles.array();
	for(var role = 0; role < roles.length; role++){
		if(roles[role].name.toLowerCase() === adminRole)
			return true;
	}
	message.channel.sendMessage("You aren't admin for this command.");
	return false;
}

// Sets the game the bot is "playing"
function setGame(game){
	bot.user.setGame(game);
}

function getChannelByName(guild, channelName){
	return guild.channels.filterArray( channel => {
		if(channel.name === channelName)
			return channel;
	})[0];
}

function botLog(message){
	console.log("DISCORD: " + message);
}

function sendError(title, error, channel){
	console.log("-----"  + "ERROR"+ "------");
	console.log(error);
	console.log("----------");
	channel.sendMessage("**" + title + " Error**\n```" + error.message +"```");
}

function displayServers(){
	var guilds = bot.guilds.array();
	var servers = [];

	for(var i = 0; i < guilds.length; i++){
		servers.push(guilds[i].name);
	}

	return "Servers:\n " + servers.join("\n") + "\n";
}

bot.on('ready', () => {
	console.log("AkeBot v" + botVersion);
	console.log(displayServers());

	setGame(defaultStatus);
});

bot.on('disconnect', event =>{
	console.log("Exited with code: " + event.code);
	if(event.message)
		console.log("Message: " + event.message);

	process.exit(0);
});

bot.on('guildMemberAdd', guildMember =>{
	var generalChannel = getChannelByName(guildMember.guild, 'general');

	generalChannel.sendMessage(guildMember.user.username +" Welcome to " + guildMember.guild.name);
	botLog(guildMember.guild.name + " welcomes " + guildMember.user.username + " to their server.");
});

bot.on('presenceUpdate', (oldGuildMember, newGuildMember) =>{
	var generalChannel = getChannelByName(newGuildMember.guild, 'general');
	if(newGuildMember.presence.game !== null){
		if(newGuildMember.presence.game.streaming){
			generalChannel.sendMessage("**LIVE**\n" +
				newGuildMember.user.username + " is now streaming!\n**Title:** " + newGuildMember.presence.game.name +
				"\n**URL:** " + newGuildMember.presence.game.url);
		}
	}
});

bot.on('message', message => {
	const mContent = message.content;
	const mChannel = message.channel;

	// Admin commands

	if(isCommand(mContent, 'exit') && isAdmin(message)){
		bot.destroy();
	}

	if(isCommand(mContent, 'setgame') && isAdmin(message)){
		if(mContent.indexOf('') !== -1){
			var game = mContent.slice(mContent.indexOf(' ') + 1);
			setGame(game);
			botLog("Game set to: " + game);
		}
	}

	// GENERAL commands

  	if(isCommand(mContent, 'help')){
  		message.channel.sendMessage("**Help**\nIn progress!");
  	}

  	if(isCommand(mContent, 'about')){
  		var content = "**About**\n" + "**Bot Version:** Akephalos Bot v" + botVersion +
  			"\n**Bot Username:** " + bot.user.username +
  			"\n**Servers Connected:** `" + bot.guilds.array().length + "`" +
  			"\n**Author:** Mesmaroth" +
  			"\n**Library:** Discord.js" +
  			"\n**Source:** <https://github.com/Mesmaroth/discord-AkephalosBot>"

  		message.channel.sendFile( bot.user.displayAvatarURL, 'botAvatar.jpg', content);
  	}

  	if(isCommand(message.content, 'source')){
  		message.channel.sendMessage("**Source:** https://github.com/Mesmaroth/discord-AkephalosBot");
  	}

  	if(isCommand(mContent, 'invite')){
  		bot.generateInvite().then( link =>{
  			mChannel.sendMessage("**Invite:** " + link);
  		});
  	}

  	if(isCommand(mContent, 'uptime')){
  		var uptimeSeconds = 0, uptimeMinutes = 0, uptimeHours = 0;

  		uptimeSeconds = Math.floor(bot.uptime/1000);

		if(uptimeSeconds > 60){
			uptimeMinutes = Math.floor(uptimeSeconds/60);
			uptimeSeconds = Math.floor(uptimeSeconds % 60);
		}

		if(uptimeMinutes > 60){
			uptimeHours = Math.floor(uptimeMinutes / 60);
			uptimeMinutes = Math.floor(uptimeMinutes % 60);
		}

  		mChannel.sendMessage("**Uptime:** " + uptimeHours + " hour(s) : " + uptimeMinutes + " minute(s) : " + uptimeSeconds +" second(s)");
  	}

  	if(isCommand(mContent, 'twitch')){
  		if(mContent.indexOf(' ') !== -1){
  			var name = mContent.split(' ')[1];

  			liveStream.getTwitchStream(name, (error, status, gameTitle, streamURL)=> {
  				if(error) return sendError("Getting Twitch Stream Data", error, mChannel);
  				if(status){
  					mChannel.sendMessage(
  					"**Twitch**\n**Name:** " + name +
  					"\n**Status:** `Online`\n**Game:** " + gameTitle +
  					"\n**URL:** " + streamURL);
  				} else{
  					mChannel.sendMessage(
  						"**Twitch**\n**Name:** " + name +
  						"\n**Status:** `Offline`");
  				}
  			});
  		}
  	}

  	if(isCommand(mContent, 'hitbox')){
  		if(mContent.indexOf(' ')!== -1){
  			var name = mContent.split(' ')[1];

  			liveStream.getHitboxStream(name, (error, status, gameTitle, streamURL) =>{
  				if(error) return sendError("Getting HitBox Stream Data", error, mChannel);
  				if(status){
  					mChannel.sendMessage(
  					"**HitBox**\n**Name:**" + name +
  					"\n**Status:** `Online`\n**Game:** " + gameTitle +
  					"\n**URL:** " + streamURL);
  				} else{
  					mChannel.sendMessage(
  					"**HitBox**\n**Name:**" + name +
  					"\n**Status:** `Offline`");
  				}
  			});
  		}
  	}
});<|endoftext|>


<commit_before>/* Node dependencies */
var request = require('request'); //For calling the url.
var fs = require('file-system'); //For saving images and creating directories.

/* Imgur API client id, plz no steal */
var clientID = "3752a956b4926c9";

//Get the argument count.
var args = process.argv.splice(2, 4); //Get rid of the first two elements as those aren't needed.

var customPath = args.length > 1;
var pathArg

if (customPath) {
    pathArg = args[1];
}

//Testing for usage.
if (args.length < 1 || args.length > 2) {
    failExit("Incorrect usage! See README for usage information.")
}

var urlImages = "https://api.imgur.com/3/album/" + getAlbumHash(args[0]) + "/images"; //Get the url argument for the images themselves.

var optionsImages = {
    url: urlImages,
    headers: {
        'authorization': 'Client-ID ' + clientID
    }
}

function getAlbumHash(url) {
    return url.split("/")[url.split("/").length - 1]
}

function parseImages(err, resp, body) {
    if (err != null) {
        failExit(err);
    }

    var imgTitles = [];
    var imgLinks = [];

    JSON.parse(body, (key, val) => {
        if (key == "title") {
            imgTitles.push(val); //Push titles to array.
        }

        if (key == "link") {
            imgLinks.push(val); //Push links to array.
        }
    });

    if (!customPath) {
        //The title to the album will always be the first element.
        var dirTitle = removeSpecialCharacters(imgTitles[0]); //Remove unsuable directory characters.
        fs.mkdir(dirTitle); //Create the directory for the folders.
    } else {
        var dirTitle = pathArg; //Just set that to the directory.
    }

    imgLinks = imgLinks.slice(1, imgLinks.length); //Get rid of the album elements.

    //Loop through all
    for (image = 0; image < imgLinks.length; image++) {
        var filename = imgLinks[image].split("/")[3];
        download(imgLinks[image], filename, dirTitle); //Send a request to download them.
    }
}

function removeSpecialCharacters(dir) {
    var newDir; //The newDir with removed invalid characters.

    dir.forEach(function(letter) {
        console.log(letter);
    })

    return "";
}

function download(link, filename, dir) {
    //request(link).pipe(fs.createWriteStream(dir + "/" + filename));
}

// failExit ... Fail and exit the program after printing out the reason it failed.
function failExit(why) {
    console.log(why);
    process.exit(1);
}

/* Send the requests to Imgur API */
request(optionsImages, parseImages);
<commit_msg>Fixed issue with special characters in title.<commit_after>/* Node dependencies */
var request = require('request'); //For calling the url.
var fs = require('file-system'); //For saving images and creating directories.

/* Imgur API client id, plz no steal */
var clientID = "3752a956b4926c9";

/* For checking directory name */
var unallowChar = "><:\"\\/|?*\0"; //List of unnallowed characters.

//Get the argument count.
var args = process.argv.splice(2, 4); //Get rid of the first two elements as those aren't needed.

var customPath = args.length > 1;
var pathArg

if (customPath) {
    pathArg = args[1];
}

//Testing for usage.
if (args.length < 1 || args.length > 2) {
    failExit("Incorrect usage! See README for usage information.")
}

var urlImages = "https://api.imgur.com/3/album/" + getAlbumHash(args[0]); //Get the url argument for the images themselves.

var optionsImages = {
    url: urlImages,
    headers: {
        'authorization': 'Client-ID ' + clientID
    }
}

function getAlbumHash(url) {
    return url.split("/")[url.split("/").length - 1]
}

function parseImages(err, resp, body) {
    if (err != null) {
        failExit(err);
    }

    var imgTitles = [];
    var imgLinks = [];

    JSON.parse(body, (key, val) => {
        if (key == "title") {
            imgTitles.push(val); //Push titles to array.
        }

        if (key == "link") {
            imgLinks.push(val); //Push links to array.
        }
    });

    if (!customPath) {
        //The title to the album will always be the first element.
        var dirTitle = removeSpecialCharacters(imgTitles[0]); //Remove unsuable directory characters.
        fs.mkdir(dirTitle); //Create the directory for the folders.
    } else {
        var dirTitle = pathArg; //Just set that to the directory.
    }

    imgLinks = imgLinks.slice(1, imgLinks.length); //Get rid of the album elements.

    //Loop through all
    for (image = 0; image < imgLinks.length; image++) {
        var filename = imgLinks[image].split("/")[3];
        download(imgLinks[image], filename, dirTitle); //Send a request to download them.
    }
}

function removeSpecialCharacters(dir) {
    var newDir = ""; //The newDir with removed invalid characters.

    for (letter = 0; letter < dir.length; letter++) {
        if (unallowChar.indexOf(dir.charAt(letter)) === -1) { //If the char is valid.
            newDir += dir.charAt(letter); //If the character is valid add it to the newDir.
        }
    }

    console.log(newDir);

    return newDir;
}

function download(link, filename, dir) {
    request(link).pipe(fs.createWriteStream(dir + "/" + filename));
}

// failExit ... Fail and exit the program after printing out the reason it failed.
function failExit(why) {
    console.log(why);
    process.exit(1);
}

/* Send the requests to Imgur API */
request(optionsImages, parseImages);
<|endoftext|>