<commit_before>/* vsb.xhtml - Main program UI
 * This file is a part of Visual struct Builder
 *
 * Copyright © 2013, Kirn Gill II <segin2005@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

var typesList = [
	"char_arr",
	"int8_t",
	"uint8_t",
	"int16_t",
	"uint16_t",
	"int32_t",
	"uint32_t",
	"int64_t",
	"uint64_t"
];

var typesName = [
	"char[]",
	"int8_t",
	"uint8_t",
	"int16_t",
	"uint16_t",
	"int32_t",
	"uint32_t",
	"int64_t",
	"uint64_t"
];

function addElem() {
	var elem = document.createElement("span");
	elem.className = "elem";
	var types = document.createElement("select");
	types.className = "etype";
	types.onchange = function() {
		var len = types.parentElement.getElementsByClassName("elen");
		len[0].disabled = !(types.value == "char_arr");
	};
	for(var i = 0; i < typesList.length; i++) {
		var item = new Option();
		item.value = typesList[i];
		item.text = typesName[i];
		types.options.add(item);
	}
	elem.appendChild(types);
	var lbl = document.createElement("span");
	lbl.textContent = "Length:";
	elem.appendChild(lbl);
	var classes = [ "elen", "ename" ];
	for(var i = 0; i < classes.length; i++) {
		var input = document.createElement("input");
		input.className = classes[i];
		input.type = "text";
		elem.appendChild(input);
	}
	var btn = document.createElement("button");
	btn.textContent = "Remove";
	btn.onclick = function() {
		btn.parentElement.remove();
	};
	elem.appendChild(btn);
	elem.appendChild(document.createElement("br"));
	var list = window.document.getElementById("elems");
	list.appendChild(elem);
}

function resetElemList() {
	var elemlist = document.getElementsByClassName("elem");
	for (var x = elemlist.length; x > 0; x--) {
		document.getElementById("elems").removeChild(elemlist[x - 1]);
	}
	addElem();
}

function typedefHide() {
	document.getElementById("tdnh").hidden = !document.getElementById("typedef").checked;
}

function generateCode() {
	var struct, structName = document.getElementById("structname").value;
	var types = document.getElementsByClassName("etype");
	var lengths = document.getElementsByClassName("elen");
	var names = document.getElementsByClassName("ename");
	struct = "struct " + structName + " {\n";
	for(var i = 0; i < types.length; i++) {
		var type, name;
		if (types[i].value == "char_arr") {
			type = "char";
			name = names[i].value + "[" + lengths[i].value + "]"
		} else {
			type = types[i].value;
			name = names[i].value;
		}
		if (type.length < 8) {
			type += "\t";
		}
		struct += "\t" + type + "\t" + name + ";\n";
	}
	struct += "};";
	document.getElementById("output").textContent = struct;
}<commit_msg>vsb: Finished code generator<commit_after>/* vsb.xhtml - Main program UI
 * This file is a part of Visual struct Builder
 *
 * Copyright © 2013, Kirn Gill II <segin2005@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

var typesList = [
	"char_arr",
	"int8_t",
	"uint8_t",
	"int16_t",
	"uint16_t",
	"int32_t",
	"uint32_t",
	"int64_t",
	"uint64_t"
];

var typesName = [
	"char[]",
	"int8_t",
	"uint8_t",
	"int16_t",
	"uint16_t",
	"int32_t",
	"uint32_t",
	"int64_t",
	"uint64_t"
];

function addElem() {
	var elem = document.createElement("span");
	elem.className = "elem";
	var types = document.createElement("select");
	types.className = "etype";
	types.onchange = function() {
		var len = types.parentElement.getElementsByClassName("elen");
		len[0].disabled = !(types.value == "char_arr");
	};
	for(var i = 0; i < typesList.length; i++) {
		var item = new Option();
		item.value = typesList[i];
		item.text = typesName[i];
		types.options.add(item);
	}
	elem.appendChild(types);
	var lbl = document.createElement("span");
	lbl.textContent = "Length:";
	elem.appendChild(lbl);
	var classes = [ "elen", "ename" ];
	for(var i = 0; i < classes.length; i++) {
		var input = document.createElement("input");
		input.className = classes[i];
		input.type = "text";
		elem.appendChild(input);
	}
	var btn = document.createElement("button");
	btn.textContent = "Remove";
	btn.onclick = function() {
		btn.parentElement.remove();
	};
	elem.appendChild(btn);
	elem.appendChild(document.createElement("br"));
	var list = window.document.getElementById("elems");
	list.appendChild(elem);
}

function resetElemList() {
	var elemlist = document.getElementsByClassName("elem");
	for (var x = elemlist.length; x > 0; x--) {
		document.getElementById("elems").removeChild(elemlist[x - 1]);
	}
	addElem();
}

function typedefHide() {
	document.getElementById("tdnh").hidden = !document.getElementById("typedef").checked;
}

function generateCode() {
	var struct = "", structName = document.getElementById("structname").value;
	var types = document.getElementsByClassName("etype");
	var lengths = document.getElementsByClassName("elen");
	var names = document.getElementsByClassName("ename");
	var typedef = document.getElementById("typedef");
	if (typedef.checked) {
		struct = "typedef ";
	}
	struct += "struct " + structName + " {\n";
	for(var i = 0; i < types.length; i++) {
		var type, name;
		if (types[i].value == "char_arr") {
			type = "char";
			name = names[i].value + "[" + lengths[i].value + "]"
		} else {
			type = types[i].value;
			name = names[i].value;
		}
		if (type.length < 8) {
			type += "\t";
		}
		struct += "\t" + type + "\t" + name + ";\n";
	}
	struct += "}";
	if (typedef.checked) {
		struct += " " + document.getElementById("typedefname").value;
	}
	struct += ";";
	document.getElementById("output").textContent = struct;
}<|endoftext|>


<commit_before>// This program determines the number of arrangements that fit
// a set of criteria. There are two ways to define these arrangements:
//
// P(n): The set of tilings of 3n^2 60º rhombuses that fill a regular hexagon.
// Q(n): The set of polycubes that fit in a n^3 box with no overhangs in all
//       3 axial directions.
//
// These two definitions are equivalent.
//
// Usage: node ExploreMaps.js

// Past Results
//=======================
// Size   Uniques   Total         Time
//  1      2         2             7 ms
//  2      10        20           10 ms
//  3      226       980          75 ms
//  4      40,238    232,848      18 s
//  5      362,309*  267,227,532  25 hrs
//
// *implausibly low. bug? hit memory limitation?

var GridMap = require('./GridMap.js').GridMap;
console.time("explore");

var verbose = false; // TODO: make it an arg?
var map_size = 5; // TODO: make it an arg?
var known_maps = [];
var known_maps_count = 0;
var examined_maps_count = 0;
var erasable_lines = 0;

// Remember the maps if we want to do something with them,
// but if we just want a count, no need.
var remember_maps = false;

// Given a list of partial maps, explore the space of all possible completions
// to those maps.
function explore_options(arr_list) {
	if (arr_list.length == 0) {
		console.log("Warning - tried to explore_options on an empty list. Shouldn't happen.");
		return [];
	}

  // Use a stack to keep arr_list size small.
  var arr = arr_list.shift();
  var kids = arr.get_children();

  for (kid of kids) {
  	if (kid.complete) {
  		var canon = kid.canonical_key();
  		var duplicate = (canon !== kid.get_key());
  		if (remember_maps) {
  		  known_maps[canon] = true;
  	  }
  		examined_maps_count ++;
  		if (!duplicate) {
  			known_maps_count ++;
  		}
  		if (examined_maps_count % 1000 == 0) {
  			clear_console();
  			console.log("Examined " + examined_maps_count + " maps; found " + known_maps_count + " unique.");
  			console.log(kid.pretty());
  			erasable_lines += 2 + map_size;
  		}
  	} else {
  		arr_list.unshift(kid);
  	}

  }
  return arr_list;
}

function clear_console() {
	if (verbose) return;

	console.log("\r"); // move to start of line
	for (var i=0; i<erasable_lines; i++) {
		process.stdout.write("\x1B[A"); // move up
	}
	process.stdout.write("\x1B[J"); // clear until end
	erasable_lines = 0;
}

function do_search(map_size) {
	console.log("Building a catalog of all possible maps of size " + map_size + ".");
  var partials = [new GridMap(map_size)];
  while (partials.length > 0) {
    partials = explore_options(partials);
  }
  clear_console();
  console.log("...done.");
  console.log(examined_maps_count + " maps examined.");
  console.log(known_maps_count + " unique maps were found.");
}

do_search(map_size);

console.timeEnd("explore");<commit_msg>update w results from 5-run<commit_after>// This program determines the number of arrangements that fit
// a set of criteria. There are two ways to define these arrangements:
//
// P(n): The set of tilings of 3n^2 60º rhombuses that fill a regular hexagon.
// Q(n): The set of polycubes that fit in a n^3 box with no overhangs in all
//       3 axial directions.
//
// These two definitions are equivalent.
//
// Usage: node ExploreMaps.js

// Past Results
//=======================
// Size   Uniques      Total         Time
//  1      2           2             7 ms
//  2      10          20            10 ms
//  3      226         980           75 ms
//  4      40,238      232,848       18 s
//  5      44,834,840  267,227,532   18 hrs

var GridMap = require('./GridMap.js').GridMap;
console.time("explore");

var verbose = false; // TODO: make it an arg?
var map_size = 4; // TODO: make it an arg?
var known_maps = [];
var known_maps_count = 0;
var examined_maps_count = 0;
var erasable_lines = 0;

// Remember the maps if we want to do something with them,
// but if we just want a count, no need.
var remember_maps = false;

// Given a list of partial maps, explore the space of all possible completions
// to those maps.
function explore_options(arr_list) {
	if (arr_list.length == 0) {
		console.log("Warning - tried to explore_options on an empty list. Shouldn't happen.");
		return [];
	}

  // Use a stack to keep arr_list size small.
  var arr = arr_list.shift();
  var kids = arr.get_children();

  for (kid of kids) {
  	if (kid.complete) {
  		var canon = kid.canonical_key();
  		var duplicate = (canon !== kid.get_key());
  		if (remember_maps) {
  		  known_maps[canon] = true;
  	  }
  		examined_maps_count ++;
  		if (!duplicate) {
  			known_maps_count ++;
  		}
  		if (examined_maps_count % 1000 == 0) {
  			clear_console();
  			console.log("Examined " + examined_maps_count + " maps; found " + known_maps_count + " unique.");
  			console.log(kid.pretty());
  			erasable_lines += 2 + map_size;
  		}
  	} else {
  		arr_list.unshift(kid);
  	}

  }
  return arr_list;
}

function clear_console() {
	if (verbose) return;

	console.log("\r"); // move to start of line
	for (var i=0; i<erasable_lines; i++) {
		process.stdout.write("\x1B[A"); // move up
	}
	process.stdout.write("\x1B[J"); // clear until end
	erasable_lines = 0;
}

function do_search(map_size) {
	console.log("Building a catalog of all possible maps of size " + map_size + ".");
  var partials = [new GridMap(map_size)];
  while (partials.length > 0) {
    partials = explore_options(partials);
  }
  clear_console();
  console.log("...done.");
  console.log(examined_maps_count + " maps examined.");
  console.log(known_maps_count + " unique maps were found.");
}

do_search(map_size);

console.timeEnd("explore");<|endoftext|>


<commit_before>/*
Copyright (c) 2011, Rob Ellis, Chris Umbel

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.
*/

var _ = require("underscore")._,
    Tokenizer = require('../tokenizers/regexp_tokenizer').WordTokenizer,
    tokenizer = new Tokenizer(),
    stopwords = require('../util/stopwords').words,
    fs = require('fs');

function buildDocument(text, key) {
    var stopOut;

    if(typeof text === 'string') {
        text = tokenizer.tokenize(text.toLowerCase());
        stopOut = true;
    } else if(!_.isArray(text)) {
        return text;
        stopOut = false;
    }

    return text.reduce(function(document, term) {
        // next line solves https://github.com/NaturalNode/natural/issues/119
        if(typeof document[term] === 'function') document[term] = 0;
        if(!stopOut || stopwords.indexOf(term) < 0)
            document[term] = (document[term] ? document[term] + 1 : 1);
        return document;
    }, {__key: key});
}

function tf(term, document) {
    return document[term] ? document[term]: 0;
}

function documentHasTerm(term, document) {
    return document[term] && document[term] > 0;
}

function TfIdf(deserialized) {
    if(deserialized)
        this.documents = deserialized.documents;
    else
        this.documents = [];

    this._idfCache = {};
}

module.exports = TfIdf;
TfIdf.tf = tf;

TfIdf.prototype.idf = function(term, force) {

    // Lookup the term in the New term-IDF caching,
    // this will cut search times down exponentially on large document sets.
    if(this._idfCache[term] && this._idfCache.hasOwnProperty(term) && force !== true)
        return this._idfCache[term];

    var docsWithTerm = this.documents.reduce(function(count, document) {
        return count + (documentHasTerm(term, document) ? 1 : 0);
    }, 0);

    var idf = Math.log((this.documents.length) / (docsWithTerm));

    // Add the idf to the term cache and return it
    this._idfCache[term] = idf;
    return idf;
};

// If restoreCache is set to true, all terms idf scores currently cached will be recomputed.
// Otherwise, the cache will just be wiped clean
TfIdf.prototype.addDocument = function(document, key, restoreCache) {
    this.documents.push(buildDocument(document, key));

    // make sure the cache is invalidated when new documents arrive
    if(restoreCache === true) {
        for(var term in this._idfCache) {
            // invoking idf with the force option set will
            // force a recomputation of the idf, and it will
            // automatically refresh the cache value.
            this.idf(term, true);
        }
    }
    else {
        this._idfCache = {};
    }
};

// If restoreCache is set to true, all terms idf scores currently cached will be recomputed.
// Otherwise, the cache will just be wiped clean
TfIdf.prototype.addFileSync = function(path, encoding, key, restoreCache) {
    if(!encoding)
        encoding = 'utf8';
    if(!Buffer.isEncoding(encoding))
        throw new Error('Invalid encoding: ' + encoding);

    var document = fs.readFileSync(path, encoding);
    this.documents.push(buildDocument(document, key));

    // make sure the cache is invalidated when new documents arrive
    if(restoreCache === true) {
        for(var term in this._idfCache) {
            // invoking idf with the force option set will
            // force a recomputation of the idf, and it will
            // automatically refresh the cache value.
            this.idf(term, true);
        }
    }
    else {
        this._idfCache = {};
    }
};

TfIdf.prototype.tfidf = function(terms, d) {
    var _this = this;

    if(!_.isArray(terms))
        terms = tokenizer.tokenize(terms.toString().toLowerCase());

    return terms.reduce(function(value, term) {
        var idf = _this.idf(term);
        idf = idf === Infinity ? 0 : idf;
        return value + (tf(term, _this.documents[d]) * idf);
    }, 0.0);
};

TfIdf.prototype.listTerms = function(d) {
    var terms = [];

    for(var term in this.documents[d]) {
        if(term != '__key')
           terms.push({term: term, tfidf: this.tfidf(term, d)});
    }

    return terms.sort(function(x, y) { return y.tfidf - x.tfidf; });
};

TfIdf.prototype.tfidfs = function(terms, callback) {
    var tfidfs = new Array(this.documents.length);

    for(var i = 0; i < this.documents.length; i++) {
        tfidfs[i] = this.tfidf(terms, i);

        if(callback)
            callback(i, tfidfs[i], this.documents[i].__key);
    }

    return tfidfs;
};
<commit_msg>Add backwards compatibility for Buffer.isEncoding<commit_after>/*
Copyright (c) 2011, Rob Ellis, Chris Umbel

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.
*/

var _ = require("underscore")._,
    Tokenizer = require('../tokenizers/regexp_tokenizer').WordTokenizer,
    tokenizer = new Tokenizer(),
    stopwords = require('../util/stopwords').words,
    fs = require('fs');

function buildDocument(text, key) {
    var stopOut;

    if(typeof text === 'string') {
        text = tokenizer.tokenize(text.toLowerCase());
        stopOut = true;
    } else if(!_.isArray(text)) {
        return text;
        stopOut = false;
    }

    return text.reduce(function(document, term) {
        // next line solves https://github.com/NaturalNode/natural/issues/119
        if(typeof document[term] === 'function') document[term] = 0;
        if(!stopOut || stopwords.indexOf(term) < 0)
            document[term] = (document[term] ? document[term] + 1 : 1);
        return document;
    }, {__key: key});
}

function tf(term, document) {
    return document[term] ? document[term]: 0;
}

function documentHasTerm(term, document) {
    return document[term] && document[term] > 0;
}

function TfIdf(deserialized) {
    if(deserialized)
        this.documents = deserialized.documents;
    else
        this.documents = [];

    this._idfCache = {};
}

// backwards compatibility for < node 0.10
function isEncoding(encoding) {
    if (typeof Buffer.isEncoding !== 'undefined')
        return Buffer.isEncoding(encoding);
    switch ((encoding + '').toLowerCase()) {
        case 'hex':
        case 'utf8':
        case 'utf-8':
        case 'ascii':
        case 'binary':
        case 'base64':
        case 'ucs2':
        case 'ucs-2':
        case 'utf16le':
        case 'utf-16le':
        case 'raw':
            return true;
    }
    return false;
}

module.exports = TfIdf;
TfIdf.tf = tf;

TfIdf.prototype.idf = function(term, force) {

    // Lookup the term in the New term-IDF caching,
    // this will cut search times down exponentially on large document sets.
    if(this._idfCache[term] && this._idfCache.hasOwnProperty(term) && force !== true)
        return this._idfCache[term];

    var docsWithTerm = this.documents.reduce(function(count, document) {
        return count + (documentHasTerm(term, document) ? 1 : 0);
    }, 0);

    var idf = Math.log((this.documents.length) / (docsWithTerm));

    // Add the idf to the term cache and return it
    this._idfCache[term] = idf;
    return idf;
};

// If restoreCache is set to true, all terms idf scores currently cached will be recomputed.
// Otherwise, the cache will just be wiped clean
TfIdf.prototype.addDocument = function(document, key, restoreCache) {
    this.documents.push(buildDocument(document, key));

    // make sure the cache is invalidated when new documents arrive
    if(restoreCache === true) {
        for(var term in this._idfCache) {
            // invoking idf with the force option set will
            // force a recomputation of the idf, and it will
            // automatically refresh the cache value.
            this.idf(term, true);
        }
    }
    else {
        this._idfCache = {};
    }
};

// If restoreCache is set to true, all terms idf scores currently cached will be recomputed.
// Otherwise, the cache will just be wiped clean
TfIdf.prototype.addFileSync = function(path, encoding, key, restoreCache) {
    if(!encoding)
        encoding = 'utf8';
    if(!isEncoding(encoding))
        throw new Error('Invalid encoding: ' + encoding);

    var document = fs.readFileSync(path, encoding);
    this.documents.push(buildDocument(document, key));

    // make sure the cache is invalidated when new documents arrive
    if(restoreCache === true) {
        for(var term in this._idfCache) {
            // invoking idf with the force option set will
            // force a recomputation of the idf, and it will
            // automatically refresh the cache value.
            this.idf(term, true);
        }
    }
    else {
        this._idfCache = {};
    }
};

TfIdf.prototype.tfidf = function(terms, d) {
    var _this = this;

    if(!_.isArray(terms))
        terms = tokenizer.tokenize(terms.toString().toLowerCase());

    return terms.reduce(function(value, term) {
        var idf = _this.idf(term);
        idf = idf === Infinity ? 0 : idf;
        return value + (tf(term, _this.documents[d]) * idf);
    }, 0.0);
};

TfIdf.prototype.listTerms = function(d) {
    var terms = [];

    for(var term in this.documents[d]) {
        if(term != '__key')
           terms.push({term: term, tfidf: this.tfidf(term, d)});
    }

    return terms.sort(function(x, y) { return y.tfidf - x.tfidf; });
};

TfIdf.prototype.tfidfs = function(terms, callback) {
    var tfidfs = new Array(this.documents.length);

    for(var i = 0; i < this.documents.length; i++) {
        tfidfs[i] = this.tfidf(terms, i);

        if(callback)
            callback(i, tfidfs[i], this.documents[i].__key);
    }

    return tfidfs;
};
<|endoftext|>


<commit_before>/*
This module contains the definition of ``FiberSource``, which is a continuous
representation of a fiber. All the fibers created are supposed to connect two
cortical areas.

Parameters
----------
controlPoints : array-of-arrays shape (N, 3)
tangents : 'incoming', 'outgoing', 'symmetric'
radius : fiber radius; same dimensions as controlPoints.
[ deprecated ] scale : multiplication factor.
    This is useful when the coodinates are given dimensionless, and we
    want a specific size for the phantom.

*/
function FiberSource(controlPoints, tangents, radius) {
  // Initialize properties. By default tangents = 'symmetric', radius = 1.
  this.controlPoints = controlPoints;
  if (tangents === undefined) {
    tangents = 'symmetric';
  }
  this.tangents = tangents;
  if (radius === undefined) {
    radius = 1;
  }
  this.radius = radius;

  // Calculate coefficients
  this.polyCalc();

  // FiberSource objects will act as subjects to FiberTube or FiberSkeleton
  this.observers = [];
}

/* FiberSource methods definition
  'polyCalc' calculates coefficients for each polynomial. Needed in constructor
    and once any of the three FiberSource input change.
  'interpolate' goes from the continuous representation of FiberSource to a
  discretization to given timesteps (ts) between 0 and 1.
  Return is an array which lists [x y z] for each timestep.
*/
FiberSource.prototype = {
  polyCalc: function() {
    /*
     When called, coefficients are calculated.
     This takes the FiberSource instance from control points, and a specified
     mode to compute the tangents.

     The output is the coefficients as f(x)=a0+a1x+a2x^2+a3x^3 for each x, y and
     z and for each pair of points, as this.xpoly, this.ypoly and this.zpoly.
     Timestamps normalized in [0,1] are also calculated in this.ts
   */
   // Take distance of each pair of given control points
    nbPoints = this.controlPoints.length;
    var distances = [];
    for (var i = 0; i < nbPoints-1; i++) {
      var squared_distance = 0;
      for (var j = 0; j < 3; j++) {
        squared_distance +=
          Math.pow(this.controlPoints[i+1][j] - this.controlPoints[i][j], 2);
      }
      distances[i] = Math.sqrt(squared_distance);
    }
    // Make time interval proportional to distance between control points
    var ts = [0, distances[0]];
    for (var i = 2; i < nbPoints; i++) {
      ts[i] = ts[i-1]+distances[i-1];
    }
    length = ts[ts.length - 1];
    for (var i = 0; i < nbPoints; i++) {
      ts[i] /= length;
    }

    //INTERPOLATION
    // as [x y z] for each point
    var derivatives = [];
    // For start and ending points; normal to the surface
    derivatives[0]=[];
    derivatives[nbPoints-1] = [];
    for (var i = 0; i < 3; i++) {
      derivatives[0][i] = -this.controlPoints[0][i];
      derivatives[nbPoints-1][i] = this.controlPoints[nbPoints-1][i];
    }
    // As for other derivatives, we use discrete approx
    switch (this.tangents) {
      case "incoming":
        for (var i = 1; i < nbPoints-1; i++) {
          derivatives[i] = [];
          for (var j = 0; j < 3; j++) {
            derivatives[i][j] =
              this.controlPoints[i][j] - this.controlPoints[i-1][j];
          }
        }
        break;
      case "outgoing":
        for (var i = 1; i < nbPoints-1; i++) {
          derivatives[i]=[];
          for (var j = 0; j < 3; j++) {
            derivatives[i][j] =
              this.controlPoints[i+1][j] - this.controlPoints[i][j];
          }
        }
        break;
      case "symmetric":
        for (var i = 1; i < nbPoints-1; i++) {
          derivatives[i] = [];
          for (var j = 0; j < 3; j++) {
            derivatives[i][j] =
              this.controlPoints[i+1][j] - this.controlPoints[i-1][j];
          }
        }
        break;
      default:
        console.error("'tangents' should be one of the following:\
          'incoming', 'outgoing', 'symmetric'");
    }
    for (var i = 0; i < derivatives.length; i++) {
      var squared_derivative_norm = 0;
      for (var j = 0; j < 3; j++) {
          squared_derivative_norm += Math.pow(derivatives[i][j], 2);
      }
      var derivative_vector = [];
      for (var j = 0; j < 3; j++) {
          derivative_vector[j] = (derivatives[i][j]
            /Math.sqrt(squared_derivative_norm))*length;
      }
      derivatives[i] = derivative_vector;
    }

    // RETURN POLYNOMIALS
    /*Function that returns 4x4 array with polynomials [a,b,c,d] for given ts (t),
        control points (p) and derivatives (pd).
        Values of a, b, c and d are found by solving the system
         (t)= a + b[(t-ti)/(ti1-ti)] + c[(t-ti)/(ti1-ti)]^2 + d[(t-ti)/(ti1-ti)]^3
        along with its derivative, being ti and ti1 t_i and t_(i+1).
    */
    function poly(t, p, pd) {
      coef = [];
      for (var i = 0; i < t.length-1; i++) {
        coef[i] = [p[i],
                (t[i+1]-t[i]) * pd[i],
                3*p[i+1] - (t[i+1]-t[i])*pd[i+1] - 2*(t[i+1]-t[i])*pd[i] - 3*p[i],
                (t[i+1]-t[i])*pd[i+1] - 2*p[i+1] + (t[i+1]-t[i])*pd[i] + 2*p[i]
        ];
      }
      return coef;
    }
    // Col extracts columns for matrices as array-of-arrays.
    function col(matrix, column) {
      var array = [];
      for (var i = 0; i < matrix.length; i++) {
        array[i] = matrix[i][column];
      }
      return array;
    }
    this.xpoly = poly(ts, col(this.controlPoints, 0), col(derivatives, 0));
    this.ypoly = poly(ts, col(this.controlPoints, 1), col(derivatives, 1));
    this.zpoly = poly(ts, col(this.controlPoints, 2), col(derivatives, 2));
    this.ts = ts;
    this.length = length;
  },

  interpolate: function(ts) {
  /*
  From a ``FiberSource``, which is a continuous representation, to a
      ``Fiber``, a discretization of the fiber trajectory.

      Parameters
      ----------
      ts : array-like, shape (N, )
          A list of "timesteps" between 0 and 1.
          OR
          A single value for a timestep between 0 and 1.

      Returns
      -------
      trajectory : array-like, shape (N, 3)
          The trajectory of the fiber, discretized over the provided
          timesteps.
  */
  // interp implements equation used for coefficients [a,b,c,d], described above.
    function interp(coef, t, ti, ti1) {
      factor = (t-ti) / (ti1-ti);
      return (coef[0] + coef[1]*factor + coef[2]*Math.pow(factor,2) +
              coef[3]*Math.pow(factor,3));
    }
    // Single value option
    if (ts.constructor !== Array) {
      var N = 1;
      ts = [ts];
    } else {
        var N = ts.length;
      }
    var trajectory = [];
    traj: for (var i = 0; i < N; i++) {
      for (var j = 0; j < this.ts.length-1; j++) {
        if ((ts[i] >= this.ts[j]) && (ts[i] <= this.ts[j+1])) {
          break;
        }
        if (j == this.ts.length-2) {
          console.error('Value '+i+' (being '+ts[i]+
          ') is out of bounds ['+this.ts[0]+','
          +this.ts[this.ts.length-1]+'].');
          continue traj;
        }
      }
      trajectory[i] = [];
      trajectory[i][0] = interp(this.xpoly[j], ts[i], this.ts[j], this.ts[j+1]);
      trajectory[i][1] = interp(this.ypoly[j], ts[i], this.ts[j], this.ts[j+1]);
      trajectory[i][2] = interp(this.zpoly[j], ts[i], this.ts[j], this.ts[j+1]);
      if (ts.constructor !== Array) {
        trajectory = trajectory[0];
      }
    }
      return trajectory;
  },
  // Pushes an object to the observer list. Once added, will be notified.
  addObserver: function(object) {
    this.observers.push(object)
  },
  // Refreshes objects in the observer list
  notify: function() {
    for(var i = 0; i < this.observers.length; i++) {
      this.observers[i].refresh();
    }
  },
  // SetControlPoint changes a control point for this Fiber.
  // inputs: n (position in controlPoints array) and x, y, z coordinates.
  SetControlPoint: function(n, x, y, z) {
    this.controlPoints[n] = [x, y, z];
    this.polyCalc();
    this.notify();
  }
}

// An isotropic region has a spherical shape
function IsotropicRegionSource(center, radius) {
  this.center = center;
  this.radius = radius;
  this.observers = [];
}
IsotropicRegionSource.prototype = {
  // Refreshes objects in the observer list
  notify: function() {
    for(var i = 0; i < this.observers.length; i++) {
      this.observers[i].refresh();
    }
  },
  SetCenter: function(x, y, z) {
    this.center = [x, y, z];
    this.notify();
  },
  SetRadius: function(radius) {
    this.radius = radius;
    this.notify();
  },
  addObserver: function(object) {
    this.observers.push(object)
  }
}
<commit_msg>SetControlPoint to setControlPoint<commit_after>/*
This module contains the definition of ``FiberSource``, which is a continuous
representation of a fiber. All the fibers created are supposed to connect two
cortical areas.

Parameters
----------
controlPoints : array-of-arrays shape (N, 3)
tangents : 'incoming', 'outgoing', 'symmetric'
radius : fiber radius; same dimensions as controlPoints.
[ deprecated ] scale : multiplication factor.
    This is useful when the coodinates are given dimensionless, and we
    want a specific size for the phantom.

*/
function FiberSource(controlPoints, tangents, radius) {
  // Initialize properties. By default tangents = 'symmetric', radius = 1.
  this.controlPoints = controlPoints;
  if (tangents === undefined) {
    tangents = 'symmetric';
  }
  this.tangents = tangents;
  if (radius === undefined) {
    radius = 1;
  }
  this.radius = radius;

  // Calculate coefficients
  this.polyCalc();

  // FiberSource objects will act as subjects to FiberTube or FiberSkeleton
  this.observers = [];
}

/* FiberSource methods definition
  'polyCalc' calculates coefficients for each polynomial. Needed in constructor
    and once any of the three FiberSource input change.
  'interpolate' goes from the continuous representation of FiberSource to a
  discretization to given timesteps (ts) between 0 and 1.
  Return is an array which lists [x y z] for each timestep.
*/
FiberSource.prototype = {
  polyCalc: function() {
    /*
     When called, coefficients are calculated.
     This takes the FiberSource instance from control points, and a specified
     mode to compute the tangents.

     The output is the coefficients as f(x)=a0+a1x+a2x^2+a3x^3 for each x, y and
     z and for each pair of points, as this.xpoly, this.ypoly and this.zpoly.
     Timestamps normalized in [0,1] are also calculated in this.ts
   */
   // Take distance of each pair of given control points
    nbPoints = this.controlPoints.length;
    var distances = [];
    for (var i = 0; i < nbPoints-1; i++) {
      var squared_distance = 0;
      for (var j = 0; j < 3; j++) {
        squared_distance +=
          Math.pow(this.controlPoints[i+1][j] - this.controlPoints[i][j], 2);
      }
      distances[i] = Math.sqrt(squared_distance);
    }
    // Make time interval proportional to distance between control points
    var ts = [0, distances[0]];
    for (var i = 2; i < nbPoints; i++) {
      ts[i] = ts[i-1]+distances[i-1];
    }
    length = ts[ts.length - 1];
    for (var i = 0; i < nbPoints; i++) {
      ts[i] /= length;
    }

    //INTERPOLATION
    // as [x y z] for each point
    var derivatives = [];
    // For start and ending points; normal to the surface
    derivatives[0]=[];
    derivatives[nbPoints-1] = [];
    for (var i = 0; i < 3; i++) {
      derivatives[0][i] = -this.controlPoints[0][i];
      derivatives[nbPoints-1][i] = this.controlPoints[nbPoints-1][i];
    }
    // As for other derivatives, we use discrete approx
    switch (this.tangents) {
      case "incoming":
        for (var i = 1; i < nbPoints-1; i++) {
          derivatives[i] = [];
          for (var j = 0; j < 3; j++) {
            derivatives[i][j] =
              this.controlPoints[i][j] - this.controlPoints[i-1][j];
          }
        }
        break;
      case "outgoing":
        for (var i = 1; i < nbPoints-1; i++) {
          derivatives[i]=[];
          for (var j = 0; j < 3; j++) {
            derivatives[i][j] =
              this.controlPoints[i+1][j] - this.controlPoints[i][j];
          }
        }
        break;
      case "symmetric":
        for (var i = 1; i < nbPoints-1; i++) {
          derivatives[i] = [];
          for (var j = 0; j < 3; j++) {
            derivatives[i][j] =
              this.controlPoints[i+1][j] - this.controlPoints[i-1][j];
          }
        }
        break;
      default:
        console.error("'tangents' should be one of the following:\
          'incoming', 'outgoing', 'symmetric'");
    }
    for (var i = 0; i < derivatives.length; i++) {
      var squared_derivative_norm = 0;
      for (var j = 0; j < 3; j++) {
          squared_derivative_norm += Math.pow(derivatives[i][j], 2);
      }
      var derivative_vector = [];
      for (var j = 0; j < 3; j++) {
          derivative_vector[j] = (derivatives[i][j]
            /Math.sqrt(squared_derivative_norm))*length;
      }
      derivatives[i] = derivative_vector;
    }

    // RETURN POLYNOMIALS
    /*Function that returns 4x4 array with polynomials [a,b,c,d] for given ts (t),
        control points (p) and derivatives (pd).
        Values of a, b, c and d are found by solving the system
         (t)= a + b[(t-ti)/(ti1-ti)] + c[(t-ti)/(ti1-ti)]^2 + d[(t-ti)/(ti1-ti)]^3
        along with its derivative, being ti and ti1 t_i and t_(i+1).
    */
    function poly(t, p, pd) {
      coef = [];
      for (var i = 0; i < t.length-1; i++) {
        coef[i] = [p[i],
                (t[i+1]-t[i]) * pd[i],
                3*p[i+1] - (t[i+1]-t[i])*pd[i+1] - 2*(t[i+1]-t[i])*pd[i] - 3*p[i],
                (t[i+1]-t[i])*pd[i+1] - 2*p[i+1] + (t[i+1]-t[i])*pd[i] + 2*p[i]
        ];
      }
      return coef;
    }
    // Col extracts columns for matrices as array-of-arrays.
    function col(matrix, column) {
      var array = [];
      for (var i = 0; i < matrix.length; i++) {
        array[i] = matrix[i][column];
      }
      return array;
    }
    this.xpoly = poly(ts, col(this.controlPoints, 0), col(derivatives, 0));
    this.ypoly = poly(ts, col(this.controlPoints, 1), col(derivatives, 1));
    this.zpoly = poly(ts, col(this.controlPoints, 2), col(derivatives, 2));
    this.ts = ts;
    this.length = length;
  },

  interpolate: function(ts) {
  /*
  From a ``FiberSource``, which is a continuous representation, to a
      ``Fiber``, a discretization of the fiber trajectory.

      Parameters
      ----------
      ts : array-like, shape (N, )
          A list of "timesteps" between 0 and 1.
          OR
          A single value for a timestep between 0 and 1.

      Returns
      -------
      trajectory : array-like, shape (N, 3)
          The trajectory of the fiber, discretized over the provided
          timesteps.
  */
  // interp implements equation used for coefficients [a,b,c,d], described above.
    function interp(coef, t, ti, ti1) {
      factor = (t-ti) / (ti1-ti);
      return (coef[0] + coef[1]*factor + coef[2]*Math.pow(factor,2) +
              coef[3]*Math.pow(factor,3));
    }
    // Single value option
    if (ts.constructor !== Array) {
      var N = 1;
      ts = [ts];
    } else {
        var N = ts.length;
      }
    var trajectory = [];
    traj: for (var i = 0; i < N; i++) {
      for (var j = 0; j < this.ts.length-1; j++) {
        if ((ts[i] >= this.ts[j]) && (ts[i] <= this.ts[j+1])) {
          break;
        }
        if (j == this.ts.length-2) {
          console.error('Value '+i+' (being '+ts[i]+
          ') is out of bounds ['+this.ts[0]+','
          +this.ts[this.ts.length-1]+'].');
          continue traj;
        }
      }
      trajectory[i] = [];
      trajectory[i][0] = interp(this.xpoly[j], ts[i], this.ts[j], this.ts[j+1]);
      trajectory[i][1] = interp(this.ypoly[j], ts[i], this.ts[j], this.ts[j+1]);
      trajectory[i][2] = interp(this.zpoly[j], ts[i], this.ts[j], this.ts[j+1]);
      if (ts.constructor !== Array) {
        trajectory = trajectory[0];
      }
    }
      return trajectory;
  },
  // Pushes an object to the observer list. Once added, will be notified.
  addObserver: function(object) {
    this.observers.push(object)
  },
  // Refreshes objects in the observer list
  notify: function() {
    for(var i = 0; i < this.observers.length; i++) {
      this.observers[i].refresh();
    }
  },
  // setControlPoint changes a control point for this Fiber.
  // inputs: n (position in controlPoints array) and x, y, z coordinates.
  setControlPoint: function(n, x, y, z) {
    this.controlPoints[n] = [x, y, z];
    this.polyCalc();
    this.notify();
  }
}

// An isotropic region has a spherical shape
function IsotropicRegionSource(center, radius) {
  this.center = center;
  this.radius = radius;
  this.observers = [];
}
IsotropicRegionSource.prototype = {
  // Refreshes objects in the observer list
  notify: function() {
    for(var i = 0; i < this.observers.length; i++) {
      this.observers[i].refresh();
    }
  },
  SetCenter: function(x, y, z) {
    this.center = [x, y, z];
    this.notify();
  },
  SetRadius: function(radius) {
    this.radius = radius;
    this.notify();
  },
  addObserver: function(object) {
    this.observers.push(object)
  }
}
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

"use strict";

const { Cu, Ci, Cc } = require("chrome");
const { Trace, TraceError } = require("../../core/trace.js").get(module.id);
const { Options } = require("../../core/options.js");
const { Locale } = require("../../core/locale.js");
const { Win } = require("../../core/window.js");
const { getMostRecentBrowserWindow } = require("sdk/window/utils");
const { HarBuilder } = require("./har-builder.js");

const Clipboard = require("sdk/clipboard");

const nsIFilePicker = Ci.nsIFilePicker;

const harVersion = "1.1";
const prefDomain = "extensions.firebug.netexport.";

const OPEN_FLAGS = {
  RDONLY: parseInt("0x01"),
  WRONLY: parseInt("0x02"),
  CREATE_FILE: parseInt("0x08"),
  APPEND: parseInt("0x10"),
  TRUNCATE: parseInt("0x20"),
  EXCL: parseInt("0x80")
};

/**
 * This object is responsible for exporting Network panel data into HAR file.
 * It uses {HarBuilder} to build proper JSON from collected data.
 *
 * xxxHonza: TODO support for auto-export needed FIXME
 */
var Exporter = {
  exportData: function(context, jsonp, items) {
    Trace.sysout("exporter.exportData", items);

    let file;

    if (items.length > 0) {
      // Get target file for exported data. Bail out, if the user
      // presses cancel.
      file = this.getTargetFile(context, jsonp);
      if (!file) {
        return;
      }
    }

    // Build JSON result string. If the panel is empty a dialog with
    // warning message
    // automatically appears.
    let json = this.buildJSON(context, items);
    let jsonString = this.buildData(json);
    if (!jsonString) {
      return;
    }

    // Remember the original JSON for the viewer (in case it's changed
    // to JSONP)
    let jsonStringForViewer = jsonString;

    // If JSONP is wanted, wrap the string in a function call
    if (jsonp) {
      let callbackName = Options.getPref(prefDomain + "jsonpCallback");

      // This callback name is also used in HAR Viewer by default.
      // http://www.softwareishard.com/har/viewer/
      if (!callbackName)
        callbackName = "onInputData";

      jsonString = callbackName + "(" + jsonString + ");";
    }

    if (!this.saveToFile(file, jsonString, context, jsonp)) {
      return;
    }

    if (Options.getPref(prefDomain + "showPreview")) {
      let viewerURL = Firebug.getPref(prefDomain + "viewerURL");
      if (viewerURL) {
        openViewer(viewerURL, jsonStringForViewer);
      }
    }
  },

  copyData: function(context, jsonp, items) {
    Trace.sysout("exporter.copyData;");

    let json = this.buildJSON(context, items);
    let jsonString = this.buildData(json);

    Clipboard.set(jsonString, "text");
  },

  // Open File Save As dialog and let the user to pick proper file location.
  getTargetFile: function(context, jsonp) {
    let browser = getMostRecentBrowserWindow();

    let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
    fp.init(browser, null, nsIFilePicker.modeSave);
    fp.appendFilter("HTTP Archive Files","*.har; *.harp; *.json; *.zip");
    fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText);
    fp.filterIndex = 1;

    let extension = jsonp ? ".harp" : ".har";
    let defaultFileName = this.getDefaultFileName(context) + extension;

    // Default file extension is zip if compressing is on.
    if (Options.getPref(prefDomain + "compress")) {
      defaultFileName += ".zip";
    }

    fp.defaultString = defaultFileName;

    let rv = fp.show();
    if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
      return fp.file;
    }

    return null;
  },

  getDefaultFileName: function(context) {
    return "archive";
  },

  buildJSON: function(context, items, forceExport) {
    // Export all data into a JSON string.
    let builder = new HarBuilder();
    let jsonData = builder.build(context, items);

    Trace.sysout("exporter.buildJSON; Number of entries: " +
      jsonData.log.entries.length, jsonData);

    if (!jsonData.log.entries.length && !forceExport) {
      alert(Locale.$STR("netexport.message.Nothing to export"));
      return null;
    }

    return jsonData;
  },

  // Build JSON string from the Net panel data.
  buildData: function(jsonData) {
    if (!jsonData) {
      return null;
    }

    try {
      let jsonString = JSON.stringify(jsonData, null, "  ");
      Trace.sysout("exporter.buildData; Exported data:", jsonData);

      return jsonString;
    }
    catch (err) {
      TraceError.sysout("exporter.exportData; EXCEPTION " + err, err);
    }
  },

  // Save JSON string into a file.
  saveToFile: function(file, jsonString, context, jsonp) {
    let extension = jsonp ? ".harp" : ".har";

    try {
      let foStream = Cc["@mozilla.org/network/file-output-stream;1"]
        .createInstance(Ci.nsIFileOutputStream);

      let openFlags = OPEN_FLAGS.WRONLY |
        OPEN_FLAGS.CREATE_FILE |
        OPEN_FLAGS.TRUNCATE;

      let permFlags = parseInt("0666", 8);
      foStream.init(file, openFlags, permFlags, 0);

      let convertor = Cc["@mozilla.org/intl/converter-output-stream;1"]
        .createInstance(Ci.nsIConverterOutputStream);
      convertor.init(foStream, "UTF-8", 0, 0);

      // The entire jsonString can be huge so, write the data in chunks.
      let chunkLength = 1024 * 1204;
      for (let i=0; i<=jsonString.length; i++) {
        let data = jsonString.substr(i, chunkLength+1);
        if (data) {
          convertor.writeString(data);
        }

        i = i + chunkLength;
      }

      // this closes foStream
      convertor.close();
    } catch (err) {
      TraceError.sysout("netexport.Exporter; Failed to export net data " +
        err, err);
      return false;
    }

    // If no compressing then bail out.
    if (!Options.getPref(prefDomain + "compress")) {
      return true;
    }

    // Remember name of the original file, it'll be replaced by a zip file.
    let originalFilePath = file.path;
    let originalFileName = file.leafName;

    try {
      Trace.sysout("netexport.Exporter; Zipping log file " + file.path);

      // Rename using unique name (the file is going to be removed).
      file.moveTo(null, "temp" + (new Date()).getTime() + extension);

      // Create compressed file with the original file path name.
      let zipFile = CCIN("@mozilla.org/file/local;1", "nsILocalFile");
      zipFile.initWithPath(originalFilePath);

      // The file within the zipped file doesn't use .zip extension.
      let fileName = originalFileName;
      if (fileName.indexOf(".zip") == fileName.length - 4) {
        fileName = fileName.substr(0, fileName.indexOf(".zip"));
      }

      // But if there is no .har extension - append it.
      if (fileName.indexOf(extension) != fileName.length - 4) {
        fileName += extension;
      }

      let zip = new ZipWriter();
      zip.open(zipFile, openFlags);
      zip.addEntryFile(fileName, Ci.nsIZipWriter.COMPRESSION_DEFAULT,
        file, false);
      zip.close();

      // Remove the original file (now zipped).
      file.remove(true);
      return true;
    } catch (err) {
      TraceError.sysout("netexport.Exporter; Failed to zip log file " +
        err.toString());

      // Something went wrong (disk space?) rename the original file back.
      file.moveTo(null, originalFileName);
    }

    return false;
  },
}

// Exports from this module
exports.Exporter = Exporter;
<commit_msg>TODO comment for net export<commit_after>/* See license.txt for terms of usage */

"use strict";

const { Cu, Ci, Cc } = require("chrome");
const { Trace, TraceError } = require("../../core/trace.js").get(module.id);
const { Options } = require("../../core/options.js");
const { Locale } = require("../../core/locale.js");
const { Win } = require("../../core/window.js");
const { getMostRecentBrowserWindow } = require("sdk/window/utils");
const { HarBuilder } = require("./har-builder.js");

const Clipboard = require("sdk/clipboard");

const nsIFilePicker = Ci.nsIFilePicker;

const harVersion = "1.1";
const prefDomain = "extensions.firebug.netexport.";

const OPEN_FLAGS = {
  RDONLY: parseInt("0x01"),
  WRONLY: parseInt("0x02"),
  CREATE_FILE: parseInt("0x08"),
  APPEND: parseInt("0x10"),
  TRUNCATE: parseInt("0x20"),
  EXCL: parseInt("0x80")
};

/**
 * This object is responsible for exporting Network panel data into HAR file.
 * It uses {HarBuilder} to build proper JSON from collected data.
 *
 * xxxHonza: TODO FIXME
 * 1. support for auto-export needed
 * 2. expose NetExport to the content scope
 */
var Exporter = {
  exportData: function(context, jsonp, items) {
    Trace.sysout("exporter.exportData", items);

    let file;

    if (items.length > 0) {
      // Get target file for exported data. Bail out, if the user
      // presses cancel.
      file = this.getTargetFile(context, jsonp);
      if (!file) {
        return;
      }
    }

    // Build JSON result string. If the panel is empty a dialog with
    // warning message
    // automatically appears.
    let json = this.buildJSON(context, items);
    let jsonString = this.buildData(json);
    if (!jsonString) {
      return;
    }

    // Remember the original JSON for the viewer (in case it's changed
    // to JSONP)
    let jsonStringForViewer = jsonString;

    // If JSONP is wanted, wrap the string in a function call
    if (jsonp) {
      let callbackName = Options.getPref(prefDomain + "jsonpCallback");

      // This callback name is also used in HAR Viewer by default.
      // http://www.softwareishard.com/har/viewer/
      if (!callbackName)
        callbackName = "onInputData";

      jsonString = callbackName + "(" + jsonString + ");";
    }

    if (!this.saveToFile(file, jsonString, context, jsonp)) {
      return;
    }

    if (Options.getPref(prefDomain + "showPreview")) {
      let viewerURL = Firebug.getPref(prefDomain + "viewerURL");
      if (viewerURL) {
        openViewer(viewerURL, jsonStringForViewer);
      }
    }
  },

  copyData: function(context, jsonp, items) {
    Trace.sysout("exporter.copyData;");

    let json = this.buildJSON(context, items);
    let jsonString = this.buildData(json);

    Clipboard.set(jsonString, "text");
  },

  // Open File Save As dialog and let the user to pick proper file location.
  getTargetFile: function(context, jsonp) {
    let browser = getMostRecentBrowserWindow();

    let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
    fp.init(browser, null, nsIFilePicker.modeSave);
    fp.appendFilter("HTTP Archive Files","*.har; *.harp; *.json; *.zip");
    fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText);
    fp.filterIndex = 1;

    let extension = jsonp ? ".harp" : ".har";
    let defaultFileName = this.getDefaultFileName(context) + extension;

    // Default file extension is zip if compressing is on.
    if (Options.getPref(prefDomain + "compress")) {
      defaultFileName += ".zip";
    }

    fp.defaultString = defaultFileName;

    let rv = fp.show();
    if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
      return fp.file;
    }

    return null;
  },

  getDefaultFileName: function(context) {
    return "archive";
  },

  buildJSON: function(context, items, forceExport) {
    // Export all data into a JSON string.
    let builder = new HarBuilder();
    let jsonData = builder.build(context, items);

    Trace.sysout("exporter.buildJSON; Number of entries: " +
      jsonData.log.entries.length, jsonData);

    if (!jsonData.log.entries.length && !forceExport) {
      alert(Locale.$STR("netexport.message.Nothing to export"));
      return null;
    }

    return jsonData;
  },

  // Build JSON string from the Net panel data.
  buildData: function(jsonData) {
    if (!jsonData) {
      return null;
    }

    try {
      let jsonString = JSON.stringify(jsonData, null, "  ");
      Trace.sysout("exporter.buildData; Exported data:", jsonData);

      return jsonString;
    }
    catch (err) {
      TraceError.sysout("exporter.exportData; EXCEPTION " + err, err);
    }
  },

  // Save JSON string into a file.
  saveToFile: function(file, jsonString, context, jsonp) {
    let extension = jsonp ? ".harp" : ".har";

    try {
      let foStream = Cc["@mozilla.org/network/file-output-stream;1"]
        .createInstance(Ci.nsIFileOutputStream);

      let openFlags = OPEN_FLAGS.WRONLY |
        OPEN_FLAGS.CREATE_FILE |
        OPEN_FLAGS.TRUNCATE;

      let permFlags = parseInt("0666", 8);
      foStream.init(file, openFlags, permFlags, 0);

      let convertor = Cc["@mozilla.org/intl/converter-output-stream;1"]
        .createInstance(Ci.nsIConverterOutputStream);
      convertor.init(foStream, "UTF-8", 0, 0);

      // The entire jsonString can be huge so, write the data in chunks.
      let chunkLength = 1024 * 1204;
      for (let i=0; i<=jsonString.length; i++) {
        let data = jsonString.substr(i, chunkLength+1);
        if (data) {
          convertor.writeString(data);
        }

        i = i + chunkLength;
      }

      // this closes foStream
      convertor.close();
    } catch (err) {
      TraceError.sysout("netexport.Exporter; Failed to export net data " +
        err, err);
      return false;
    }

    // If no compressing then bail out.
    if (!Options.getPref(prefDomain + "compress")) {
      return true;
    }

    // Remember name of the original file, it'll be replaced by a zip file.
    let originalFilePath = file.path;
    let originalFileName = file.leafName;

    try {
      Trace.sysout("netexport.Exporter; Zipping log file " + file.path);

      // Rename using unique name (the file is going to be removed).
      file.moveTo(null, "temp" + (new Date()).getTime() + extension);

      // Create compressed file with the original file path name.
      let zipFile = CCIN("@mozilla.org/file/local;1", "nsILocalFile");
      zipFile.initWithPath(originalFilePath);

      // The file within the zipped file doesn't use .zip extension.
      let fileName = originalFileName;
      if (fileName.indexOf(".zip") == fileName.length - 4) {
        fileName = fileName.substr(0, fileName.indexOf(".zip"));
      }

      // But if there is no .har extension - append it.
      if (fileName.indexOf(extension) != fileName.length - 4) {
        fileName += extension;
      }

      let zip = new ZipWriter();
      zip.open(zipFile, openFlags);
      zip.addEntryFile(fileName, Ci.nsIZipWriter.COMPRESSION_DEFAULT,
        file, false);
      zip.close();

      // Remove the original file (now zipped).
      file.remove(true);
      return true;
    } catch (err) {
      TraceError.sysout("netexport.Exporter; Failed to zip log file " +
        err.toString());

      // Something went wrong (disk space?) rename the original file back.
      file.moveTo(null, originalFileName);
    }

    return false;
  },
}

// Exports from this module
exports.Exporter = Exporter;
<|endoftext|>


<commit_before>var express = require("express"),
    router = express.Router();
var locks = require('locks');

var mutex = locks.createMutex();
/*
This is the build route
Usage:
deploy.thisisimp.com/a427f694-0a21-11e5-a6c0-1697f925ec7b/:environment/:repository
environment - either "dev" or "prod"
repository - either "frontend" or "api"
 */

router.route("/:env/:repo").get(function(req, res) {
    if (mutex.tryLock()) {
        console.log('We got the lock!');
        var util  = require('util'),
            spawn = require('child_process').spawn;

        if(req.params.env === "dev" && req.params.repo === "frontend"){
            var child = spawn('sh', ['~/frontend/build-frontend-dev.sh']);
            child.stdout.pipe(res);
        }
        else if(req.params.env === "dev" && req.params.repo === "api"){
            var child = spawn('sh', ['~/api/build-api-dev.sh']);
            child.stdout.pipe(res);
        }
        else if(req.params.env === "prod" && req.params.repo === "frontend"){
            var child = spawn('sh', ['~/frontend/build-frontend-prod.sh']);
            child.stdout.pipe(res);
        }
        else if(req.params.env === "prod" && req.params.repo === "api"){
            var child = spawn('sh', ['~/api/build-api-prod.sh']);
            child.stdout.pipe(res);
        }
        else{
            req.status("404").send("Route used improperly");
        }
        mutex.unlock();
    } else {
        console.log('Could not get the lock at this time');
        res.status("500").send("Someone else is building at this time, please wait a few minutes and try again");
    }

});

module.exports = router;<commit_msg>testing deploy<commit_after>var express = require("express"),
    router = express.Router();
var locks = require('locks');

var mutex = locks.createMutex();
/*
This is the build route
Usage:
deploy.thisisimp.com/a427f694-0a21-11e5-a6c0-1697f925ec7b/:environment/:repository
environment - either "dev" or "prod"
repository - either "frontend" or "api"
 */

router.route("/:env/:repo").get(function(req, res) {
    res.send("test");
    /*if (mutex.tryLock()) {
        console.log('We got the lock!');
        var util  = require('util'),
            spawn = require('child_process').spawn;

        if(req.params.env === "dev" && req.params.repo === "frontend"){
            var child = spawn('sh', ['~/frontend/build-frontend-dev.sh']);
            child.stdout.pipe(res);
        }
        else if(req.params.env === "dev" && req.params.repo === "api"){
            var child = spawn('sh', ['~/api/build-api-dev.sh']);
            child.stdout.pipe(res);
        }
        else if(req.params.env === "prod" && req.params.repo === "frontend"){
            var child = spawn('sh', ['~/frontend/build-frontend-prod.sh']);
            child.stdout.pipe(res);
        }
        else if(req.params.env === "prod" && req.params.repo === "api"){
            var child = spawn('sh', ['~/api/build-api-prod.sh']);
            child.stdout.pipe(res);
        }
        else{
            req.status("404").send("Route used improperly");
        }
        mutex.unlock();
    } else {
        console.log('Could not get the lock at this time');
        res.status("500").send("Someone else is building at this time, please wait a few minutes and try again");
    }
*/

});

module.exports = router;<|endoftext|>


<commit_before>/*
 * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file 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.
 */

//node.js deps
var gpio = require('gpio');
var Button = require('gpio-button');
//npm deps

//app deps
const deviceModule = require('..').device;
const cmdLineProcess = require('./lib/cmdline');

//begin module
var blueLedGpio, yellowLedGpio, intervalTimer;
var button6 = new Button('button6');
var button13 = new Button('button13');
var button19 = new Button('button19');
var button26 = new Button('button26');

button26.on('press', function () {
   console.log('button26 press');
});

button26.on('hold', function () {
});

button26.on('release', function () {
   console.log('button26 release');
});

button13.on('press', function () {
   console.log('button13 release');
});

button13.on('hold', function () {
});

button13.on('release', function () {
   console.log('button13 release');
});

blueLedGpio = gpio.export(23, {
   ready: function() {
      console.log("Blue LED Ready");
      intervalTimer = setInterval(function() {
      }, 2000);
   }
});

yellowLedGpio = gpio.export(24, {
   ready: function() {
      console.log("Yellow LED Ready");
      yellowLedGpio.on("change", function (val) {
         console.log(val);
      });

   }
});

// // Lets assume a different LED is hooked up to pin 4, the following code
// // will make that LED blink inversely with LED from pin 22
// gpio24 = gpio.export(23, {
//    ready: function() {
//       // bind to blueLedGpio's change event
//       blueLedGpio.on("change", function(val) {
//          gpio24.set(1 - val); // set gpio24 to the opposite value
//       });
//    }
// });

// // reset the headers and unexport after 10 seconds
// setTimeout(function() {
//    clearInterval(intervalTimer);          // stops the voltage cycling
//    blueLedGpio.removeAllListeners('change');   // unbinds change event
//    blueLedGpio.reset();                        // sets header to low
//    blueLedGpio.unexport();                     // unexport the header
//
//    gpio24.reset();
//    gpio24.unexport(function() {
//       // unexport takes a callback which gets fired as soon as unexporting is done
//       process.exit(); // exits your node program
//    });
// }, 10000);

function processTest(args) {
   //
   // The device module exports an MQTT instance, which will attempt
   // to connect to the AWS IoT endpoint configured in the arguments.
   // Once connected, it will emit events which our application can
   // handle.
   //
   const device = deviceModule({
      keyPath: args.privateKey,
      certPath: args.clientCert,
      caPath: args.caCert,
      clientId: args.clientId,
      region: args.region,
      baseReconnectTimeMs: args.baseReconnectTimeMs,
      keepalive: args.keepAlive,
      protocol: args.Protocol,
      port: args.Port,
      host: args.Host,
      debug: args.Debug
   });

   var timeout;
   var count = 0;
   const minimumDelay = 250;

   if (args.testMode === 1) {
      device.subscribe('topic_1');
   } else {
      device.subscribe('topic_2');
   }
   device.subscribe('led');
   if ((Math.max(args.delay, minimumDelay)) !== args.delay) {
      console.log('substituting ' + minimumDelay + 'ms delay for ' + args.delay + 'ms...');
   }
   timeout = setInterval(function() {
      count++;

      if (args.testMode === 1) {
         device.publish('topic_2', JSON.stringify({
            mode1Process: count
         }));
      } else {
         device.publish('topic_1', JSON.stringify({
            mode2Process: count
         }));
      }
   }, Math.max(args.delay, minimumDelay)); // clip to minimum

   button6.on('press', function () {
      // blueLedGpio.set(0);
      console.log('button6 press');
   });

   button6.on('hold', function () {
   });

   button6.on('release', function () {
      device.publish('led', JSON.stringify({
         "color":"blue"
      }));
      console.log('button6 release');
   });

   button19.on('press', function () {
      console.log('button19 press');
      // yellowLedGpio.set(0);

   });

   button19.on('hold', function () {
   });

   button19.on('release', function () {
      device.publish('led', JSON.stringify({
         "color":"yellow"
      }));
      console.log('button19 release');
   });
   //
   // Do a simple publish/subscribe demo based on the test-mode passed
   // in the command line arguments.  If test-mode is 1, subscribe to
   // 'topic_1' and publish to 'topic_2'; otherwise vice versa.  Publish
   // a message every four seconds.
   //
   device
      .on('connect', function() {
         console.log('connected');
      });
   device
      .on('close', function() {
         console.log('close');
      });
   device
      .on('reconnect', function() {
         console.log('reconnect');
      });
   device
      .on('offline', function() {
         console.log('offline');
      });
   device
      .on('error', function(error) {
         console.log('error', error);
      });
   device
      .on('message', function(topic, payload) {

         if(topic == "led") {
            console.log("led");
            if(payload!=null) {
               var jsonPayload = JSON.parse(payload.toString());
               if(jsonPayload.color == "yellow") {
                  yellowLedGpio.set();
                  setTimeout(function() { yellowLedGpio.reset(); }, 2000);
               }
               if(jsonPayload.color == "blue") {
                  blueLedGpio.set();
                  setTimeout(function() { blueLedGpio.reset(); }, 2000);
               }

            }
         }
         console.log('message', topic, payload.toString());
      });
}

module.exports = cmdLineProcess;

if (require.main === module) {
   cmdLineProcess('connect to the AWS IoT service and publish/subscribe to topics using MQTT, test modes 1-2',
      process.argv.slice(2), processTest);
}<commit_msg>buttons man press<commit_after>/*
 * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file 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.
 */

//node.js deps
var gpio = require('gpio');
var Button = require('gpio-button');
//npm deps

//app deps
const deviceModule = require('..').device;
const cmdLineProcess = require('./lib/cmdline');

//begin module
var blueLedGpio, yellowLedGpio, intervalTimer;
var button6 = new Button('button6');
var button13 = new Button('button13');
var button19 = new Button('button19');
var button26 = new Button('button26');

button26.on('press', function () {
   console.log('button26 press');
});

button26.on('hold', function () {
});

button26.on('release', function () {
   console.log('button26 release');
});

button13.on('press', function () {
   console.log('button13 release');
});

button13.on('hold', function () {
});

button13.on('release', function () {
   console.log('button13 release');
});

blueLedGpio = gpio.export(23, {
   ready: function() {
      console.log("Blue LED Ready");
      intervalTimer = setInterval(function() {
      }, 2000);
   }
});

yellowLedGpio = gpio.export(24, {
   ready: function() {
      console.log("Yellow LED Ready");
      yellowLedGpio.on("change", function (val) {
         console.log(val);
      });

   }
});

// // Lets assume a different LED is hooked up to pin 4, the following code
// // will make that LED blink inversely with LED from pin 22
// gpio24 = gpio.export(23, {
//    ready: function() {
//       // bind to blueLedGpio's change event
//       blueLedGpio.on("change", function(val) {
//          gpio24.set(1 - val); // set gpio24 to the opposite value
//       });
//    }
// });

// // reset the headers and unexport after 10 seconds
// setTimeout(function() {
//    clearInterval(intervalTimer);          // stops the voltage cycling
//    blueLedGpio.removeAllListeners('change');   // unbinds change event
//    blueLedGpio.reset();                        // sets header to low
//    blueLedGpio.unexport();                     // unexport the header
//
//    gpio24.reset();
//    gpio24.unexport(function() {
//       // unexport takes a callback which gets fired as soon as unexporting is done
//       process.exit(); // exits your node program
//    });
// }, 10000);

function processTest(args) {
   //
   // The device module exports an MQTT instance, which will attempt
   // to connect to the AWS IoT endpoint configured in the arguments.
   // Once connected, it will emit events which our application can
   // handle.
   //
   const device = deviceModule({
      keyPath: args.privateKey,
      certPath: args.clientCert,
      caPath: args.caCert,
      clientId: args.clientId,
      region: args.region,
      baseReconnectTimeMs: args.baseReconnectTimeMs,
      keepalive: args.keepAlive,
      protocol: args.Protocol,
      port: args.Port,
      host: args.Host,
      debug: args.Debug
   });

   var timeout;
   var count = 0;
   const minimumDelay = 250;

   if (args.testMode === 1) {
      device.subscribe('topic_1');
   } else {
      device.subscribe('topic_2');
   }
   device.subscribe('led');
   if ((Math.max(args.delay, minimumDelay)) !== args.delay) {
      console.log('substituting ' + minimumDelay + 'ms delay for ' + args.delay + 'ms...');
   }
   timeout = setInterval(function() {
      count++;

      if (args.testMode === 1) {
         device.publish('topic_2', JSON.stringify({
            mode1Process: count
         }));
      } else {
         device.publish('topic_1', JSON.stringify({
            mode2Process: count
         }));
      }
   }, Math.max(args.delay, minimumDelay)); // clip to minimum

   button6.on('press', function () {
      device.publish('led', JSON.stringify({
         "color":"blue",
         "state":"off"
      }));
      console.log('button6 press');
   });

   button6.on('hold', function () {
   });

   button6.on('release', function () {
      device.publish('led', JSON.stringify({
         "color":"blue",
         "state":"on"
      }));
      console.log('button6 release');
   });

   button19.on('press', function () {
      device.publish('led', JSON.stringify({
         "color":"yellow",
         "state":"off"
      }));
      console.log('button19 press');
      // yellowLedGpio.set(0);

   });

   button19.on('hold', function () {
   });

   button19.on('release', function () {
      device.publish('led', JSON.stringify({
         "color":"yellow",
         "state":"on"
      }));
      console.log('button19 release');
   });
   //
   // Do a simple publish/subscribe demo based on the test-mode passed
   // in the command line arguments.  If test-mode is 1, subscribe to
   // 'topic_1' and publish to 'topic_2'; otherwise vice versa.  Publish
   // a message every four seconds.
   //
   device
      .on('connect', function() {
         console.log('connected');
      });
   device
      .on('close', function() {
         console.log('close');
      });
   device
      .on('reconnect', function() {
         console.log('reconnect');
      });
   device
      .on('offline', function() {
         console.log('offline');
      });
   device
      .on('error', function(error) {
         console.log('error', error);
      });
   device
      .on('message', function(topic, payload) {

         if(topic == "led") {
            console.log("led");
            if(payload!=null) {
               var jsonPayload = JSON.parse(payload.toString());
               if(jsonPayload.color == "yellow") {
                  yellowLedGpio.set();
                  setTimeout(function() { yellowLedGpio.reset(); }, 2000);
               }
               if(jsonPayload.color == "blue") {
                  blueLedGpio.set();
                  setTimeout(function() { blueLedGpio.reset(); }, 2000);
               }

            }
         }
         console.log('message', topic, payload.toString());
      });
}

module.exports = cmdLineProcess;

if (require.main === module) {
   cmdLineProcess('connect to the AWS IoT service and publish/subscribe to topics using MQTT, test modes 1-2',
      process.argv.slice(2), processTest);
}<|endoftext|>


<commit_before>var fs = require('fs');
var Discord = require('discord.js');
var youtubeStream = require('youtube-audio-stream');
var bot = new Discord.Client();
var token = null;

try {
    token = fs.readFileSync('token', 'utf8');
} catch (err) {
    console.log('Could not open token file');
    process.exit();
}

bot.on('ready', () => {
    console.log('Bot ready');
});

bot.on('message', msg => {
    let prefix = '.';

    // if not a bot command or message was sent from bot then do nothing
    if (!(msg.content.startsWith(prefix)) || msg.author.bot) {
        return;
    }

    if (msg.content.startsWith(prefix + 'play')) {
        // print message if author is not in a voice channel
        var msgSender = msg.author.id;
        // get all voice channels and check if the sender is one of them
        // only get channels from the server that the message was sent from
        var allChannels = msg.guild.channels.array();
        // filter for voice channels
        var voiceChannels = [];
        for (let i = 0; i < allChannels.length; i++) {
            if (allChannels[i].type === 'voice') {
                voiceChannels.push(allChannels[i]);
            }
        }
        // check for the voice channel the sender is in, return if not in one
        var channelToStream = null;
        for (let i = 0; i < voiceChannels.length; i++) {
            let channelMembers = voiceChannels[i].members.array();
            let channelFound = false;
            for (let j = 0; j < channelMembers.length; j++) {
                if (channelMembers[i].id === msgSender) {
                    channelToStream = voiceChannels[i];
                    channelFound = true;
                    break;
                }
            }
            if (channelFound) {
                break;
            }
        }
        if (channelToStream === null) {
            msg.channel.sendMessage('You must be in a voice channel to play a song.');
            return;
        }

        // join the voice channel and stream the video
        var songUrl = msg.content.split(' ')[1];
        channelToStream.join().then(connection => {
            var dispatcher = connection.playStream(youtubeStream(songUrl));
            dispatcher.on('end', () => {
                connection.disconnect();
            });
        });
    }
});

bot.login(token);<commit_msg>fixed bug where other users can't play songs<commit_after>var fs = require('fs');
var Discord = require('discord.js');
var youtubeStream = require('youtube-audio-stream');
var bot = new Discord.Client();
var token = null;

try {
    token = fs.readFileSync('token', 'utf8');
} catch (err) {
    console.log('Could not open token file');
    process.exit();
}

bot.on('ready', () => {
    console.log('Bot ready');
});

bot.on('message', msg => {
    let prefix = '.';

    // if not a bot command or message was sent from bot then do nothing
    if (!(msg.content.startsWith(prefix)) || msg.author.bot) {
        return;
    }

    if (msg.content.startsWith(prefix + 'play')) {
        // print message if author is not in a voice channel
        var msgSender = msg.author;
        // get all voice channels and check if the sender is one of them
        // only get channels from the server that the message was sent from
        var allChannels = msg.guild.channels.array();
        // filter for voice channels
        var voiceChannels = [];
        for (let i = 0; i < allChannels.length; i++) {
            if (allChannels[i].type === 'voice') {
                voiceChannels.push(allChannels[i]);
            }
        }
        // check for the voice channel the sender is in, return if not in one
        var channelToStream = null;
        for (let i = 0; i < voiceChannels.length; i++) {
            let channelMembers = voiceChannels[i].members.array();
            let channelFound = false;
            for (let j = 0; j < channelMembers.length; j++) {
                if (channelMembers[j].user.id === msgSender.id) {
                    channelToStream = voiceChannels[i];
                    channelFound = true;
                    break;
                }
            }
            if (channelFound) {
                break;
            }
        }
        if (channelToStream === null) {
            msg.channel.sendMessage('You must be in a voice channel to play a song.');
            return;
        }

        // join the voice channel and stream the video
        var songUrl = msg.content.split(' ')[1];
        channelToStream.join().then(connection => {
            var dispatcher = connection.playStream(youtubeStream(songUrl));
            dispatcher.on('end', () => {
                connection.disconnect();
            });
        });
    }
});

bot.login(token);<|endoftext|>


<commit_before>
/****
 * Grapnel.js
 * https://github.com/gregsabia/Grapnel.js
 *
 * @author Greg Sabia
 * @link http://gregsabia.com
 * @version 0.1.3
 *
 * Released under MIT License. See LICENSE.txt or http://opensource.org/licenses/MIT
*/

var Grapnel=function(e){"use strict";var t=this;this.action=null;this.hook=e||":";this.value=null;this.actionsMatching=[];this.listeners=[];this.version="0.1.3";this.add=function(e,n){var r=function(){var r=t.action&&e instanceof RegExp&&t.action.match(e);if(r||e===t.action){t._trigger("match",t.value,t.action);t.actionsMatching.push({name:e,handler:n});n.call(t,t.value,t.action)}return t};return r().on(["initialized","hashchange"],r)};this._trigger=function(e){var n=Array.prototype.slice.call(arguments,1);this.forEach(this.listeners,function(r){if(r.event==e)r.handler.apply(t,n)});return this};this.on=function(e,n){var r=typeof e==="string"?e.split():e;this.forEach(r,function(e){t.listeners.push({event:e,handler:n})});return this};this.map=function(e,t){if(typeof Array.prototype.map==="function")return Array.prototype.map.call(e,t);return function(e,t){var n=new Array(this.length);for(var r=0,i=this.length;r<i;r++){if(r in this)n[r]=e.call(t,this[r],r,this)}return n}.call(e,t)};this.forEach=function(e,t){if(typeof Array.prototype.forEach==="function")return Array.prototype.forEach.call(e,t);return function(e,t){for(var n=0,r=this.length;n<r;++n){e.call(t,this[n],n,this)}}.call(e,t)};this.getAnchor=function(){return window.location.hash?window.location.hash.split("#")[1]:""};this.setAnchor=function(e){window.location.hash=!e?"":e;return this};this.clearAnchor=function(){return this.setAnchor(false)};this.parse=function(){var e,t;if(this.getAnchor().match(this.hook)){t=this.getAnchor().split(this.hook)[1];e=this.getAnchor().split(this.hook)[0]}return{value:t,action:e}};this.matches=function(){var e=[];this.forEach(this.actionsMatching,function(n){var r=n.name instanceof RegExp&&t.action.match(n.name);if(r||n.name===t.action){e.push(n)}});return e};this.on(["initialized","hashchange"],function(){this.action=this.parse().action;this.value=this.parse().value;this.actionsMatching=[]});if(typeof window.onhashchange==="function")this.on("hashchange",window.onhashchange);window.onhashchange=function(){t._trigger("hashchange")};return this._trigger("initialized")}<commit_msg>Minified source<commit_after>
/****
 * Grapnel.js
 * https://github.com/gregsabia/Grapnel.js
 *
 * @author Greg Sabia
 * @link http://gregsabia.com
 * @version 0.2.1
 *
 * Released under MIT License. See LICENSE.txt or http://opensource.org/licenses/MIT
*/

function Grapnel(e){"use strict";var t=this,n={actions:[],listeners:[]};this.action=null;this.hook=e||":";this.value=null;this.params=[];this.anchor={"default":window.location.hash};this.version="0.2.1";this.add=function(e,r){var i=function(){var i=t.action&&e instanceof RegExp?t.anchor.get().match(e):false;if(i||e===t.action||t.anchor.get()==e){n.trigger("match",t.value,t.params,t.action);n.actions.push({name:e,handler:r});r.call(t,t.value,t.params)}return t};return i().on(["initialized","hashchange"],i)};n.trigger=function(e){var r=Array.prototype.slice.call(arguments,1);n.forEach(n.listeners,function(n){if(n.event==e)n.handler.apply(t,r)});return t};this.on=function(e,t){var r=typeof e==="string"?e.split():e;n.forEach(r,function(e){n.listeners.push({event:e,handler:t})});return this};n.map=function(e,t){if(typeof Array.prototype.map==="function")return Array.prototype.map.call(e,t);return function(e,t){var n=new Array(this.length);for(var r=0,i=this.length;r<i;r++){if(r in this)n[r]=e.call(t,this[r],r,this)}return n}.call(e,t)};n.forEach=function(e,t){if(typeof Array.prototype.forEach==="function")return Array.prototype.forEach.call(e,t);return function(e,t){for(var n=0,r=this.length;n<r;++n){e.call(t,this[n],n,this)}}.call(e,t)};n.routeRegExp=function(e,t,n,r){if(e instanceof RegExp)return e;if(e instanceof Array)e="("+e.join("|")+")";e=e.concat(r?"":"/?").replace(/\/\(/g,"(?:/").replace(/\+/g,"__plus__").replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g,function(e,n,r,i,s,o){t.push({name:i,optional:!!o});n=n||"";return""+(o?"":n)+"(?:"+(o?n:"")+(r||"")+(s||r&&"([^/.]+?)"||"([^/]+?)")+")"+(o||"")}).replace(/([\/.])/g,"\\$1").replace(/__plus__/g,"(.+)").replace(/\*/g,"(.*)");return new RegExp("^"+e+"$",n?"":"i")};this.anchor.get=function(){return window.location.hash?window.location.hash.split("#")[1]:""};this.anchor.set=function(e){window.location.hash=!e?"":e;return t};this.anchor.clear=function(){return this.set(false)};this.parse=function(){var e=this.anchor.get(),t=e.split(this.hook),r=e.match(this.hook),i=t[0],s=[],o;if(this.anchor.get().match(this.hook)){s=t.slice(1);o=s.join(r[0])}n.trigger("parse",t);return{value:o,action:i,params:s}};this.matches=function(){var e=[];n.forEach(n.actions,function(n){var r=n.name instanceof RegExp&&t.action.match(n.name);if(r||n.name===t.action){e.push(n)}});return e};this.router=function(){this.hook=/\//gi;this.get=function(e,r){var i=[];var s=new n.routeRegExp(e,i);this.add(s,function(){var e={params:{}};n.forEach(i,function(n,r){e.params[n.name]=t.params&&t.params[r]?t.params[r]:undefined});r.call(t,e)});return t};delete this.router;return n.trigger("initialized")};this.on(["initialized","hashchange"],function(){var e=this.parse();this.action=e.action;this.value=e.value;this.params=e.params;n.actions=[]});if(typeof window.onhashchange==="function")this.on("hashchange",window.onhashchange);window.onhashchange=function(){n.trigger("hashchange")};return n.trigger("initialized")}<|endoftext|>


<commit_before>// Copyright (c) 2012 Titanium I.T. LLC. All rights reserved. See LICENSE.txt for details.
/*global desc, task, jake, fail, complete, directory*/

(function() {
	"use strict";

	if (!process.env.loose) console.log("For more forgiving test settings, use 'loose=true'");

	var fs = require("fs");
	var shell = require("shelljs");

	var browserify = require("browserify");
	var lint = require("./build/util/lint_runner.js");
	var nodeunit = require("./build/util/nodeunit_runner.js");
	var karma = require("./build/util/karma_runner.js");
	var versionChecker = require("./build/util/version_checker.js");
	var runServer = require("./src/_run_server.js");
	var path = require("path");

	var REQUIRED_BROWSERS = [
		"IE 8.0.0 (Windows 7)",
		"IE 9.0.0 (Windows 7)",
		"Firefox 26.0.0 (Mac OS X 10.8)",
		"Chrome 31.0.1650 (Mac OS X 10.8.5)",
		"Safari 6.1.0 (Mac OS X 10.8.5)",
		"Mobile Safari 7.0.0 (iOS 7.0.3)"
	];

	var GENERATED_DIR = "generated";
	var TEMP_TESTFILE_DIR = GENERATED_DIR + "/test";
	var BUILD_DIR = GENERATED_DIR + "/build";
	var BUILD_CLIENT_DIR = BUILD_DIR + "/client";

	directory(TEMP_TESTFILE_DIR);
	directory(BUILD_DIR);
	directory(BUILD_CLIENT_DIR);

	desc("Delete all generated files");
	task("clean", [], function() {
		jake.rmRf(GENERATED_DIR);
	});

	desc("Build and test");
	task("default", ["lint", "test"], function() {
		console.log("\n\nOK");
	});

	desc("Start Karma server for testing");
	task("karma", function() {
		karma.serve("build/karma.conf.js", complete, fail);
	}, {async: true});

	desc("Start WeeWikiPaint server for manual testing");
	task("run", ["build"], function() {
		console.log("Running server. Press Ctrl-C to stop.");
		runServer.runInteractively();
		// We never call complete() because we want the task to hang until the user presses 'Ctrl-C'.
	}, {async: true});

	desc("Lint everything");
	task("lint", ["lintNode", "lintClient"]);

	task("lintNode", ["nodeVersion"], function() {
		var passed = lint.validateFileList(nodeLintFiles(), nodeLintOptions(), {});
		if (!passed) fail("Lint failed");
	});

	task("lintClient", function() {
		var passed = lint.validateFileList(clientLintFiles(), clientLintOptions(), clientGlobals());
		if (!passed) fail("Lint failed");
	});

	desc("Test everything");
	task("test", ["testServer", "testClient", "testSmoke"]);

	desc("Test server code");
	task("testServer", ["nodeVersion", TEMP_TESTFILE_DIR], function() {
		nodeunit.runTests(serverTestFiles(), complete, fail);
	}, {async: true});

	desc("Test client code");
	task("testClient", [], function() {
		karma.runTests(REQUIRED_BROWSERS, complete, fail);
	}, {async: true});

	desc("End-to-end smoke tests");
	task("testSmoke", ["build"], function() {
		nodeunit.runTests(smokeTestFiles(), complete, fail);
	}, {async: true});

	desc("Bundle and build code");
	task("build", [BUILD_CLIENT_DIR], function() {
		shell.rm("-rf", BUILD_CLIENT_DIR + "/*");
		shell.cp("-R", "src/client/*.html", "src/client/vendor", BUILD_CLIENT_DIR);

		console.log("Bundling client files with Browserify...");
		var b = browserify();
		b.require("./src/client/client.js", {expose: "./client.js"} );
		b.require("./src/client/html_element.js", {expose: "./html_element.js"} );
		b.bundle({ debug: true }, function(err, bundle) {
			if (err) fail(err);
			fs.writeFileSync(BUILD_CLIENT_DIR + "/bundle.js", bundle);
			complete();
		});
	}, {async: true});

	desc("Deploy to Heroku");
	task("deploy", ["default"], function() {
		console.log("1. Make sure 'git status' is clean.");

		// Correction: Use "git push heroku integration:master" to deploy from integration branch.
		// Thanks to Jüri A, http://www.letscodejavascript.com/v3/comments/live/32#comment-798947003 .
		console.log("2. 'git push heroku master' (or integration:master)");
		console.log("3. 'jake test'");
	});

//	desc("Ensure correct version of Node is present.");
	task("nodeVersion", [], function() {
		var deployedVersion = "v" + require("./package.json").engines.node;
		versionChecker.check("Node", !process.env.loose, deployedVersion, process.version, fail);
	});

	desc("Integration checklist");
	task("integrate", ["default"], function() {
		console.log("1. Make sure 'git status' is clean.");
		console.log("2. Build on the integration box.");
		console.log("   a. Walk over to integration box.");
		console.log("   b. 'git pull'");
		console.log("   c. 'npm rebuild'");
		console.log("   d. Check status for files that need to be .gitignore'd");
		console.log("   e. 'jake'");
		console.log("   f. If jake fails, stop! Try again after fixing the issue.");
		console.log("3. 'git checkout integration'");
		console.log("4. 'git merge master --no-ff --log'");
		console.log("5. 'git checkout master'");
	});

	desc("End-of-episode checklist");
	task("episode", [], function() {
		console.log("1. Save recording.");
		console.log("2. Double-check sound and framing.");
		console.log("3. Commit source code.");
		console.log("4. Check Windows compatibility");
		console.log("   a. Switch to Windows VM");
		console.log("   b. 'git pull'");
		console.log("   c. 'npm rebuild'");
		console.log("   d. Check status for files that need to be .gitignore'd");
		console.log("   e. 'jake'");
		console.log("5. Tag episode: 'git tag -a episodeXX -m \"End of episode XX\"'");
	});

	function serverTestFiles() {
		var testFiles = new jake.FileList();
		testFiles.include("src/server/**/_*_test.js");
		testFiles = testFiles.toArray();
		return testFiles;
	}

	function smokeTestFiles() {
		var testFiles = new jake.FileList();
		testFiles.include("src/_*_test.js");
		testFiles = testFiles.toArray();
		return testFiles;
	}

	function nodeLintFiles() {
		var javascriptFiles = new jake.FileList();
		javascriptFiles.include("*.js");
		javascriptFiles.include("build/util/*.js");
		javascriptFiles.include("src/server/**/*.js");
		javascriptFiles.include("src/*.js");
		return javascriptFiles.toArray();
	}

	function clientLintFiles() {
		var javascriptFiles = new jake.FileList();
		javascriptFiles.include("src/client/*.js");
		return javascriptFiles.toArray();
	}

	function nodeLintOptions() {
		var options = sharedLintOptions();
		options.node = true;
		return options;
	}

	function clientLintOptions() {
		var options = sharedLintOptions();
		options.browser = true;
		return options;
	}

	function sharedLintOptions() {
		return {
			bitwise: true,
			curly: false,
			eqeqeq: true,
			forin: true,
			immed: true,
			latedef: false,
			newcap: true,
			noarg: true,
			noempty: true,
			nonew: true,
			regexp: true,
			undef: true,
			strict: true,
			trailing: true
		};
	}

	function clientGlobals() {
		return {
			// Browserify
			require: false,
			module: false,
			exports: false,

			// Mocha / expect.js
			describe: false,
			it: false,
			expect: false,
			dump: false,
			beforeEach: false,
			afterEach: false,

			// Browser
			console: false
		};
	}

}());
<commit_msg>Updated Safari 6.1.0 --> 6.1.1<commit_after>// Copyright (c) 2012 Titanium I.T. LLC. All rights reserved. See LICENSE.txt for details.
/*global desc, task, jake, fail, complete, directory*/

(function() {
	"use strict";

	if (!process.env.loose) console.log("For more forgiving test settings, use 'loose=true'");

	var fs = require("fs");
	var shell = require("shelljs");

	var browserify = require("browserify");
	var lint = require("./build/util/lint_runner.js");
	var nodeunit = require("./build/util/nodeunit_runner.js");
	var karma = require("./build/util/karma_runner.js");
	var versionChecker = require("./build/util/version_checker.js");
	var runServer = require("./src/_run_server.js");
	var path = require("path");

	var REQUIRED_BROWSERS = [
		"IE 8.0.0 (Windows 7)",
		"IE 9.0.0 (Windows 7)",
		"Firefox 26.0.0 (Mac OS X 10.8)",
		"Chrome 31.0.1650 (Mac OS X 10.8.5)",
		"Safari 6.1.1 (Mac OS X 10.8.5)",
		"Mobile Safari 7.0.0 (iOS 7.0.3)"
	];

	var GENERATED_DIR = "generated";
	var TEMP_TESTFILE_DIR = GENERATED_DIR + "/test";
	var BUILD_DIR = GENERATED_DIR + "/build";
	var BUILD_CLIENT_DIR = BUILD_DIR + "/client";

	directory(TEMP_TESTFILE_DIR);
	directory(BUILD_DIR);
	directory(BUILD_CLIENT_DIR);

	desc("Delete all generated files");
	task("clean", [], function() {
		jake.rmRf(GENERATED_DIR);
	});

	desc("Build and test");
	task("default", ["lint", "test"], function() {
		console.log("\n\nOK");
	});

	desc("Start Karma server for testing");
	task("karma", function() {
		karma.serve("build/karma.conf.js", complete, fail);
	}, {async: true});

	desc("Start WeeWikiPaint server for manual testing");
	task("run", ["build"], function() {
		console.log("Running server. Press Ctrl-C to stop.");
		runServer.runInteractively();
		// We never call complete() because we want the task to hang until the user presses 'Ctrl-C'.
	}, {async: true});

	desc("Lint everything");
	task("lint", ["lintNode", "lintClient"]);

	task("lintNode", ["nodeVersion"], function() {
		var passed = lint.validateFileList(nodeLintFiles(), nodeLintOptions(), {});
		if (!passed) fail("Lint failed");
	});

	task("lintClient", function() {
		var passed = lint.validateFileList(clientLintFiles(), clientLintOptions(), clientGlobals());
		if (!passed) fail("Lint failed");
	});

	desc("Test everything");
	task("test", ["testServer", "testClient", "testSmoke"]);

	desc("Test server code");
	task("testServer", ["nodeVersion", TEMP_TESTFILE_DIR], function() {
		nodeunit.runTests(serverTestFiles(), complete, fail);
	}, {async: true});

	desc("Test client code");
	task("testClient", [], function() {
		karma.runTests(REQUIRED_BROWSERS, complete, fail);
	}, {async: true});

	desc("End-to-end smoke tests");
	task("testSmoke", ["build"], function() {
		nodeunit.runTests(smokeTestFiles(), complete, fail);
	}, {async: true});

	desc("Bundle and build code");
	task("build", [BUILD_CLIENT_DIR], function() {
		shell.rm("-rf", BUILD_CLIENT_DIR + "/*");
		shell.cp("-R", "src/client/*.html", "src/client/vendor", BUILD_CLIENT_DIR);

		console.log("Bundling client files with Browserify...");
		var b = browserify();
		b.require("./src/client/client.js", {expose: "./client.js"} );
		b.require("./src/client/html_element.js", {expose: "./html_element.js"} );
		b.bundle({ debug: true }, function(err, bundle) {
			if (err) fail(err);
			fs.writeFileSync(BUILD_CLIENT_DIR + "/bundle.js", bundle);
			complete();
		});
	}, {async: true});

	desc("Deploy to Heroku");
	task("deploy", ["default"], function() {
		console.log("1. Make sure 'git status' is clean.");

		// Correction: Use "git push heroku integration:master" to deploy from integration branch.
		// Thanks to Jüri A, http://www.letscodejavascript.com/v3/comments/live/32#comment-798947003 .
		console.log("2. 'git push heroku master' (or integration:master)");
		console.log("3. 'jake test'");
	});

//	desc("Ensure correct version of Node is present.");
	task("nodeVersion", [], function() {
		var deployedVersion = "v" + require("./package.json").engines.node;
		versionChecker.check("Node", !process.env.loose, deployedVersion, process.version, fail);
	});

	desc("Integration checklist");
	task("integrate", ["default"], function() {
		console.log("1. Make sure 'git status' is clean.");
		console.log("2. Build on the integration box.");
		console.log("   a. Walk over to integration box.");
		console.log("   b. 'git pull'");
		console.log("   c. 'npm rebuild'");
		console.log("   d. Check status for files that need to be .gitignore'd");
		console.log("   e. 'jake'");
		console.log("   f. If jake fails, stop! Try again after fixing the issue.");
		console.log("3. 'git checkout integration'");
		console.log("4. 'git merge master --no-ff --log'");
		console.log("5. 'git checkout master'");
	});

	desc("End-of-episode checklist");
	task("episode", [], function() {
		console.log("1. Save recording.");
		console.log("2. Double-check sound and framing.");
		console.log("3. Commit source code.");
		console.log("4. Check Windows compatibility");
		console.log("   a. Switch to Windows VM");
		console.log("   b. 'git pull'");
		console.log("   c. 'npm rebuild'");
		console.log("   d. Check status for files that need to be .gitignore'd");
		console.log("   e. 'jake'");
		console.log("5. Tag episode: 'git tag -a episodeXX -m \"End of episode XX\"'");
	});

	function serverTestFiles() {
		var testFiles = new jake.FileList();
		testFiles.include("src/server/**/_*_test.js");
		testFiles = testFiles.toArray();
		return testFiles;
	}

	function smokeTestFiles() {
		var testFiles = new jake.FileList();
		testFiles.include("src/_*_test.js");
		testFiles = testFiles.toArray();
		return testFiles;
	}

	function nodeLintFiles() {
		var javascriptFiles = new jake.FileList();
		javascriptFiles.include("*.js");
		javascriptFiles.include("build/util/*.js");
		javascriptFiles.include("src/server/**/*.js");
		javascriptFiles.include("src/*.js");
		return javascriptFiles.toArray();
	}

	function clientLintFiles() {
		var javascriptFiles = new jake.FileList();
		javascriptFiles.include("src/client/*.js");
		return javascriptFiles.toArray();
	}

	function nodeLintOptions() {
		var options = sharedLintOptions();
		options.node = true;
		return options;
	}

	function clientLintOptions() {
		var options = sharedLintOptions();
		options.browser = true;
		return options;
	}

	function sharedLintOptions() {
		return {
			bitwise: true,
			curly: false,
			eqeqeq: true,
			forin: true,
			immed: true,
			latedef: false,
			newcap: true,
			noarg: true,
			noempty: true,
			nonew: true,
			regexp: true,
			undef: true,
			strict: true,
			trailing: true
		};
	}

	function clientGlobals() {
		return {
			// Browserify
			require: false,
			module: false,
			exports: false,

			// Mocha / expect.js
			describe: false,
			it: false,
			expect: false,
			dump: false,
			beforeEach: false,
			afterEach: false,

			// Browser
			console: false
		};
	}

}());
<|endoftext|>