<commit_before>$(document).ready(function() {

  	$.getJSON(go_details_link, function(data) {
  	    var mc_bp_go_table = create_go_table("mc_bp", "No manually curated biological process terms for " + display_name, function(x) {return x["method"] == "manually curated" && x["bioconcept"]["aspect"] == "biological process"}, data);
        create_download_button("mc_bp_go_table_download", mc_bp_go_table, download_table_link, mc_bp_download_table_filename);

        var mc_mf_go_table = create_go_table("mc_mf", "No manually curated molecular function terms for " + display_name, function(x) {return x["method"] == "manually curated" && x["bioconcept"]["aspect"] == "molecular function"}, data);
        create_download_button("mc_mf_go_table_download", mc_mf_go_table, download_table_link, mc_mf_download_table_filename);

        var mc_cc_go_table = create_go_table("mc_cc", "No manually curated cellular component terms for " + display_name, function(x) {return x["method"] == "manually curated" && x["bioconcept"]["aspect"] == "cellular component"}, data);
        create_download_button("mc_cc_go_table_download", mc_cc_go_table, download_table_link, mc_cc_download_table_filename);

        var htp_bp_go_table = create_go_table("htp_bp", "No high-throughput biological process terms for " + display_name, function(x) {return x["method"] == "high-throughput" && x["bioconcept"]["aspect"] == "biological process"}, data);
        create_download_button("htp_bp_go_table_download", htp_bp_go_table, download_table_link, htp_bp_download_table_filename);

        var htp_mf_go_table = create_go_table("htp_mf", "No high-throughput molecular function terms for " + display_name, function(x) {return x["method"] == "high-throughput" && x["bioconcept"]["aspect"] == "molecular function"}, data);
        create_download_button("htp_mf_go_table_download", htp_mf_go_table, download_table_link, htp_mf_download_table_filename);

        var htp_cc_go_table = create_go_table("htp_cc", "No high-throughput cellular component terms for " + display_name, function(x) {return x["method"] == "high-throughput" && x["bioconcept"]["aspect"] == "cellular component"}, data);
        create_download_button("htp_cc_go_table_download", htp_cc_go_table, download_table_link, htp_cc_download_table_filename);

        var comp_bp_go_table = create_go_table("comp_bp", "No computational biological process terms for " + display_name, function(x) {return x["method"] == "computational" && x["bioconcept"]["aspect"] == "biological process"}, data);
        create_download_button("comp_bp_go_table_download", comp_bp_go_table, download_table_link, comp_bp_download_table_filename);

        var comp_mf_go_table = create_go_table("comp_mf", "No computational molecular function terms for " + display_name, function(x) {return x["method"] == "computational" && x["bioconcept"]["aspect"] == "molecular function"}, data);
        create_download_button("comp_mf_go_table_download", comp_mf_go_table, download_table_link, comp_mf_download_table_filename);

        var comp_cc_go_table = create_go_table("comp_cc", "No computational cellular component terms for " + display_name, function(x) {return x["method"] == "computational" && x["bioconcept"]["aspect"] == "cellular component"}, data);
        create_download_button("comp_cc_go_table_download", comp_cc_go_table, download_table_link, comp_cc_download_table_filename);

        var transformed_data = [];
        for (var i=0; i < data.length; i++) {
            transformed_data.push(go_data_to_table(data[i], i));
        }
        var headers = ["Evidence ID", "Analyze ID", "", "Gene", "Gene Format Name", "Gene Ontology Term", "Qualifier", "Aspect", "Method", "Evidence", "Source", "Assigned On", "Reference", "Relationships"];
        create_download_button_no_table("go_download_all", headers, transformed_data, download_table_link, display_name + "_go_annotations")
  	});

  	$.getJSON(go_graph_link, function(data) {
        if(data['nodes'].length > 1) {
            var graph = create_cytoscape_vis("cy", layout, graph_style, data);
            var slider = create_slider("slider", graph, data['min_cutoff'], data['max_cutoff'], slider_filter, data['max_cutoff']+1);
  		}
		else {
			hide_section("network");

			//Hack because footer overlaps - need to fix this.
	        add_footer_space("comp");
		}
	});

	//Hack because footer overlaps - need to fix this.
	add_footer_space("network");
});

function create_go_table(prefix, message, filter, data) {
    if("Error" in data) {
        var options = {};
        options["bPaginate"] = true;
        options["aaSorting"] = [[5, "asc"]];
        options["aoColumns"] = [{"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bSortable":false}, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, null, {"bSearchable":false, "bVisible":false}, null, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, null, null, null, {"bSearchable":false, "bVisible":false}];
        options["oLanguage"] = {"sEmptyTable": data["Error"]};
        options["aaData"] = [];
    }
    else {
        var datatable = [];
        var gos = {};
        for (var i=0; i < data.length; i++) {
            if(filter(data[i])) {
                datatable.push(go_data_to_table(data[i], i));
                gos[data[i]['bioconcept']['id']] = true;
            }
        }

        $("#" + prefix + "_go_header").html(datatable.length);
        $("#" + prefix + "_go_subheader").html(Object.keys(gos).length);

        if(Object.keys(gos).length == 1) {
            $("#" + prefix + "_go_subheader_type").html('Gene Ontology term');
        }
        else {
            $("#" + prefix + "_go_subheader_type").html('Gene Ontology terms');
        }
        if(datatable.length == 1) {
            $("#" + prefix + "_go_header_type").html("entry for ");
        }
        else {
            $("#" + prefix + "_go_header_type").html("entries for ");
        }

        var options = {};
        options["bPaginate"] = true;
        options["aaSorting"] = [[5, "asc"]];
        options["aoColumns"] = [{"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bSortable":false}, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, null, {"bSearchable":false, "bVisible":false}, null, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, null, null, null, null, {"bSearchable":false, "bVisible":false}];
        options["oLanguage"] = {"sEmptyTable": message};
        options["aaData"] = datatable;

        if(Object.keys(gos).length == 0) {
            $("#" + prefix + "_go_table_wrapper").hide();
        }
    }

	$("#" + prefix + "_go_table_analyze").hide();

    return create_table(prefix + "_go_table", options);
}

function slider_filter(new_cutoff) {
    var filter = "node[gene_count >= " + new_cutoff + "], edge";
    return filter;
}

var graph_style = cytoscape.stylesheet()
	.selector('node')
	.css({
		'content': 'data(name)',
		'font-family': 'helvetica',
		'font-size': 14,
		'text-outline-width': 3,
		'text-outline-color': '#888',
		'text-valign': 'center',
		'color': '#fff',
		'width': 30,
		'height': 30,
		'border-color': '#fff'
	})
	.selector('edge')
	.css({
		'width': 2,
	})
	.selector("node[sub_type='FOCUS']")
	.css({
		'background-color': "#fade71",
		'text-outline-color': '#fff',
		'color': '#888',
	})
	.selector("node[type='BIOCONCEPT'][sub_type='biological process']")
	.css({
		'shape': 'rectangle',
		'text-outline-color': '#fff',
		'color': '#888',
		'background-color': "#7FBF7B",
	})
	.selector("node[type='BIOCONCEPT'][sub_type='molecular function']")
	.css({
		'shape': 'rectangle',
		'text-outline-color': '#fff',
		'color': '#888',
		'background-color': "#AF8DC3",
	})
	.selector("node[type='BIOCONCEPT'][sub_type='cellular component']")
	.css({
		'shape': 'rectangle',
		'text-outline-color': '#fff',
		'color': '#888',
		'background-color': "#819FF7",
    });

var layout = {
	"name": "arbor",
	"liveUpdate": true,
	"ungrabifyWhileSimulating": true,
	"nodeMass":function(data) {
		if(data.sub_type == 'FOCUS') {
			return 10;
		}
		else {
			return 1;
		}
	}
};<commit_msg>Fixed #2360 Backend SHA: c5f1fb22782c9764679df70a029a7804a6064ee7<commit_after>$(document).ready(function() {

  	$.getJSON(go_details_link, function(data) {
  	    var mc_bp_go_table = create_go_table("mc_bp", "No manually curated biological process terms for " + display_name, function(x) {return x["method"] == "manually curated" && x["bioconcept"]["aspect"] == "biological process"}, data);
        create_download_button("mc_bp_go_table_download", mc_bp_go_table, download_table_link, mc_bp_download_table_filename);

        var mc_mf_go_table = create_go_table("mc_mf", "No manually curated molecular function terms for " + display_name, function(x) {return x["method"] == "manually curated" && x["bioconcept"]["aspect"] == "molecular function"}, data);
        create_download_button("mc_mf_go_table_download", mc_mf_go_table, download_table_link, mc_mf_download_table_filename);

        var mc_cc_go_table = create_go_table("mc_cc", "No manually curated cellular component terms for " + display_name, function(x) {return x["method"] == "manually curated" && x["bioconcept"]["aspect"] == "cellular component"}, data);
        create_download_button("mc_cc_go_table_download", mc_cc_go_table, download_table_link, mc_cc_download_table_filename);

        var htp_bp_go_table = create_go_table("htp_bp", "No high-throughput biological process terms for " + display_name, function(x) {return x["method"] == "high-throughput" && x["bioconcept"]["aspect"] == "biological process"}, data);
        create_download_button("htp_bp_go_table_download", htp_bp_go_table, download_table_link, htp_bp_download_table_filename);

        var htp_mf_go_table = create_go_table("htp_mf", "No high-throughput molecular function terms for " + display_name, function(x) {return x["method"] == "high-throughput" && x["bioconcept"]["aspect"] == "molecular function"}, data);
        create_download_button("htp_mf_go_table_download", htp_mf_go_table, download_table_link, htp_mf_download_table_filename);

        var htp_cc_go_table = create_go_table("htp_cc", "No high-throughput cellular component terms for " + display_name, function(x) {return x["method"] == "high-throughput" && x["bioconcept"]["aspect"] == "cellular component"}, data);
        create_download_button("htp_cc_go_table_download", htp_cc_go_table, download_table_link, htp_cc_download_table_filename);

        var comp_bp_go_table = create_go_table("comp_bp", "No computational biological process terms for " + display_name, function(x) {return x["method"] == "computational" && x["bioconcept"]["aspect"] == "biological process"}, data);
        create_download_button("comp_bp_go_table_download", comp_bp_go_table, download_table_link, comp_bp_download_table_filename);

        var comp_mf_go_table = create_go_table("comp_mf", "No computational molecular function terms for " + display_name, function(x) {return x["method"] == "computational" && x["bioconcept"]["aspect"] == "molecular function"}, data);
        create_download_button("comp_mf_go_table_download", comp_mf_go_table, download_table_link, comp_mf_download_table_filename);

        var comp_cc_go_table = create_go_table("comp_cc", "No computational cellular component terms for " + display_name, function(x) {return x["method"] == "computational" && x["bioconcept"]["aspect"] == "cellular component"}, data);
        create_download_button("comp_cc_go_table_download", comp_cc_go_table, download_table_link, comp_cc_download_table_filename);

        var transformed_data = [];
        for (var i=0; i < data.length; i++) {
            transformed_data.push(go_data_to_table(data[i], i));
        }
        var headers = ["Evidence ID", "Analyze ID", "", "Gene", "Gene Format Name", "Gene Ontology Term", "Gene Ontology Term ID", "Qualifier", "Aspect", "Method", "Evidence", "Source", "Assigned On", "Reference", "Relationships"];
        create_download_button_no_table("go_download_all", headers, transformed_data, download_table_link, display_name + "_go_annotations")
  	});

  	$.getJSON(go_graph_link, function(data) {
        if(data['nodes'].length > 1) {
            var graph = create_cytoscape_vis("cy", layout, graph_style, data);
            var slider = create_slider("slider", graph, data['min_cutoff'], data['max_cutoff'], slider_filter, data['max_cutoff']+1);
  		}
		else {
			hide_section("network");

			//Hack because footer overlaps - need to fix this.
	        add_footer_space("comp");
		}
	});

	//Hack because footer overlaps - need to fix this.
	add_footer_space("network");
});

function create_go_table(prefix, message, filter, data) {
    if("Error" in data) {
        var options = {};
        options["bPaginate"] = true;
        options["aaSorting"] = [[5, "asc"]];
        options["aoColumns"] = [{"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bSortable":false}, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, null, {"bSearchable":false, "bVisible":false}, null, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, null, null, null, {"bSearchable":false, "bVisible":false}];
        options["oLanguage"] = {"sEmptyTable": data["Error"]};
        options["aaData"] = [];
    }
    else {
        var datatable = [];
        var gos = {};
        for (var i=0; i < data.length; i++) {
            if(filter(data[i])) {
                datatable.push(go_data_to_table(data[i], i));
                gos[data[i]['bioconcept']['id']] = true;
            }
        }

        $("#" + prefix + "_go_header").html(datatable.length);
        $("#" + prefix + "_go_subheader").html(Object.keys(gos).length);

        if(Object.keys(gos).length == 1) {
            $("#" + prefix + "_go_subheader_type").html('Gene Ontology term');
        }
        else {
            $("#" + prefix + "_go_subheader_type").html('Gene Ontology terms');
        }
        if(datatable.length == 1) {
            $("#" + prefix + "_go_header_type").html("entry for ");
        }
        else {
            $("#" + prefix + "_go_header_type").html("entries for ");
        }

        var options = {};
        options["bPaginate"] = true;
        options["aaSorting"] = [[5, "asc"]];
        options["aoColumns"] = [{"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bSortable":false}, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, null, {"bSearchable":false, "bVisible":false}, null, {"bSearchable":false, "bVisible":false}, {"bSearchable":false, "bVisible":false}, null, null, null, null, {"bSearchable":false, "bVisible":false}];
        options["oLanguage"] = {"sEmptyTable": message};
        options["aaData"] = datatable;

        if(Object.keys(gos).length == 0) {
            $("#" + prefix + "_go_table_wrapper").hide();
        }
    }

	$("#" + prefix + "_go_table_analyze").hide();

    return create_table(prefix + "_go_table", options);
}

function slider_filter(new_cutoff) {
    var filter = "node[gene_count >= " + new_cutoff + "], edge";
    return filter;
}

var graph_style = cytoscape.stylesheet()
	.selector('node')
	.css({
		'content': 'data(name)',
		'font-family': 'helvetica',
		'font-size': 14,
		'text-outline-width': 3,
		'text-outline-color': '#888',
		'text-valign': 'center',
		'color': '#fff',
		'width': 30,
		'height': 30,
		'border-color': '#fff'
	})
	.selector('edge')
	.css({
		'width': 2,
	})
	.selector("node[sub_type='FOCUS']")
	.css({
		'background-color': "#fade71",
		'text-outline-color': '#fff',
		'color': '#888',
	})
	.selector("node[type='BIOCONCEPT'][sub_type='biological process']")
	.css({
		'shape': 'rectangle',
		'text-outline-color': '#fff',
		'color': '#888',
		'background-color': "#7FBF7B",
	})
	.selector("node[type='BIOCONCEPT'][sub_type='molecular function']")
	.css({
		'shape': 'rectangle',
		'text-outline-color': '#fff',
		'color': '#888',
		'background-color': "#AF8DC3",
	})
	.selector("node[type='BIOCONCEPT'][sub_type='cellular component']")
	.css({
		'shape': 'rectangle',
		'text-outline-color': '#fff',
		'color': '#888',
		'background-color': "#819FF7",
    });

var layout = {
	"name": "arbor",
	"liveUpdate": true,
	"ungrabifyWhileSimulating": true,
	"nodeMass":function(data) {
		if(data.sub_type == 'FOCUS') {
			return 10;
		}
		else {
			return 1;
		}
	}
};<|endoftext|>


<commit_before><commit_msg>Fix ingredient code column type<commit_after><|endoftext|>


<commit_before>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs = require('fs'),
    basename = require('path').basename,
    http = require('http'),
    https = require('https'),
    url_parse = require('url').parse,
    stringify = require('qs').stringify,
    version = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version;

exports.version = version;
try { var unzip = require('zlib').unzip; } catch(e){ /* zlib not supported */ }

var default_user_agent = "Needle/" + version;
default_user_agent += " (Node.js " + process.version + "; " + process.platform + " " + process.arch + ")";
var node_tls_opts = ['agent', 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', 'rejectUnauthorized'];
var debug = !!process.env.DEBUG;

var parsers = {
  'application/json': function(data, callback){
    try {
      callback(null, data && JSON.parse(data));
    } catch(e) {
      callback(e, data);
    }
  }
};

try {
  var xml2js = require('xml2js');
  parsers['application/xml'] = function(data, callback){
    var xml_parser = new xml2js.Parser();
    xml_parser.parseString(data, callback);
  };
} catch(e) { }

// utility function for flattening params in multipart POST's
function flatten(object, into, prefix){
  into = into || {};

  for(key in object){
    var prefix_key = prefix ? prefix + "[" + key + "]" : key;
    var prop = object[key];

    if (prop && typeof prop === "object" && !(prop.buffer || prop.file || prop.content_type))
      flatten(prop, into, prefix_key)
    else
      into[prefix_key] = prop;
  }

  return into;
}

var Needle = {

  default_boundary: '--------------------NODENEEDLEHTTPCLIENT',
  default_user_agent: default_user_agent,

  request: function(uri, method, data, options, callback){

    var self = this, post_data = null;
    var callback = (typeof options == 'function') ? options : callback;
    var options = options || {};
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts: {},
      proxy: options.proxy,
      encoding: options.encoding || (options.multipart ? 'binary' : 'utf8'),
      parse_response: options.parse === false ? false : true,
      follow: options.follow === false ? 0 : options.follow || 10, // 10 by default
      timeout: (typeof options.timeout == 'number') ? options.timeout : 10000
    }

    node_tls_opts.forEach(function(key){
      if (typeof options[key] != 'undefined'){
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      "User-Agent": options.user_agent || this.default_user_agent,
      "Connection": "close",
      "Accept": "*/*"
    }

    if (options.compressed && typeof unzip != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username && options.password){
      var b = new Buffer([options.username, options.password].join(':'));
      var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
      config.headers[auth_header] = 'Basic ' + b.toString('base64');
    }

    if (data){
      if (options.multipart){

        var boundary = options.boundary || this.default_boundary;
        return this.build_multipart_body(data, boundary, function(err, body){

          if (err) throw(err);
          config.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, callback);

        });

      } else {
        post_data = (typeof(data) === "string") ? data : stringify(data);
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        config.headers['Content-Length'] = post_data.length;
      }

    }

    this.send_request(1, method, uri, config, post_data, callback);
  },

  get_request_opts: function(method, uri, config){
    var opts = config.base_opts, proxy = config.proxy;
    var remote = proxy ? url_parse(proxy) : url_parse(uri);

    opts.host = remote.hostname;
    opts.port = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.protocol = remote.protocol;
    opts.path = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method = method;
    opts.headers = config.headers;
    opts.headers["Host"] = proxy ? url_parse(uri).hostname : remote.hostname;

    return opts;
  },

  send_request: function(count, method, uri, config, post_data, callback){

    var self = this, timer, response_opts = {parse_response: config.parse_response};
    var request_opts = this.get_request_opts(method, uri, config);

    var protocol = request_opts.protocol == 'https:' ? https : http;
    var request = protocol.request(request_opts, function(response){

      if (timer) clearTimeout(timer);

      if ((response.statusCode == 301 || response.statusCode == 302) && response.headers.location){
        if (count <= config.follow)
          return self.send_request(++count, 'GET', response.headers.location, config, null, callback);
        else if (config.follow > 0)
          return callback(new Error("Too many redirects. Possible redirect loop in " + response.headers.location))
      }

      var body = '';
      var compressed = /gzip|deflate/.test(response.headers['content-encoding']);
      response.setEncoding(compressed ? 'binary' : 'utf8');

      response.on('data', function(chunk){
        body += chunk;
      });

      response.on('end', function(){
        if(typeof unzip != 'undefined' && compressed)
          unzip(new Buffer(body, 'binary'), function(err, buff){
            self.response_end(response_opts, response, buff.toString(), callback);
          });
        else
          self.response_end(response_opts, response, body, callback);

      });

    });

    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      if (debug) console.log('Error on request: ' + err.toString());
      if (timer) clearTimeout(timer);
      if (callback) callback(err || new Error("Unkown error on request."));
    });

    if (post_data) request.write(post_data, config.encoding);
    request.end();

  },

  response_end: function(opts, response, body, callback){

    if (debug) console.log(response.headers);
    if (!callback) return;
    var content_type = response.headers['content-type'] && response.headers['content-type'].split(';')[0];

    if (opts.parse_response && parsers[content_type]) {
      parsers[content_type](body, function(err, result){
        callback(err, response, result);
      });
    } else {
      callback(null, response, body);
    }

  },

  build_multipart_body: function(data, boundary, callback){

    if (typeof data != 'object')
      return callback(new Error("Multipart expects data as key/val object."));

    var body = '', object = flatten(data), count = Object.keys(object).length;

    for (var key in object){

      var value = object[key];
      if (value === null || typeof value == 'undefined') return --count;

      var part = (value.buffer || value.file || value.content_type) ? value : {value: value};

      this.generate_part(key, part, boundary, function(err, section){
        if (err) return callback(err);
        body += section;
        --count || callback(null, body + '--' + boundary + '--');
      });

    }

  },

  generate_part: function(name, part, boundary, callback){

    var return_part = '--' + boundary + "\r\n";
    return_part += "Content-Disposition: form-data; name=\"" + name + "\"";

    var append = function(data, filename){

      if (data){
        var binary = part.content_type.indexOf('text') == -1;
        return_part += "; filename=\"" + encodeURIComponent(filename) + "\"\r\n";
        if (binary) return_part += "Content-Transfer-Encoding: binary\r\n";
        return_part += "Content-Type: " + part.content_type + "\r\n\r\n";
        return_part += binary ? data.toString('binary') : data.toString('utf8');
      }

      callback(null, return_part + '\r\n');
    };

    if ((part.file || part.buffer) && part.content_type){

      var filename = part.filename ? part.filename : part.file ? basename(part.file) : name;
      if (part.buffer) return append(part.buffer, filename);

      fs.readFile(part.file, function(err, data){
        if (err) return callback(err);
        append(data, filename);
      });

    } else {

      if (typeof part.value == 'object')
        return callback(new Error("Object received for " + name + ", expected string."))

      if (part.content_type) {
        return_part += '\r\n';
        return_part += "Content-Type: " + part.content_type;
      }

      return_part += "\r\n\r\n";
      return_part += part.value;
      append();

    }

  }

}

exports.head = function(uri, options, callback){
  return Needle.request(uri, 'HEAD', null, options, callback);
}

exports.get = function(uri, options, callback){
  return Needle.request(uri, 'GET', null, options, callback);
}

exports.post = function(uri, data, options, callback){
  if(!data || typeof data == 'function') throw('POST request expects data.');
  return Needle.request(uri, 'POST', data, options, callback);
}

exports.put = function(uri, data, options, callback){
  if(!data || typeof data == 'function') throw('PUT request expects data.');
  return Needle.request(uri, 'PUT', data, options, callback);
}

exports.delete = function(uri, data, options, callback){
  return Needle.request(uri, 'DELETE', null, options, callback);
}
<commit_msg>Use multipart stuff from lib/multipart.js, cleaned up a bit.<commit_after>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    url_parse = require('url').parse,
    stringify = require('qs').stringify,
    multipart = require('./multipart');

var version = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version,
    debug = !!process.env.DEBUG;

exports.version = version;
try { var unzip = require('zlib').unzip; } catch(e) { /* zlib not supported */ }

var default_user_agent = "Needle/" + version;
default_user_agent += " (Node.js " + process.version + "; " + process.platform + " " + process.arch + ")";

var node_tls_opts = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized';

var parsers = {
  'application/json': function(data, callback){
    try {
      callback(null, data && JSON.parse(data));
    } catch(e) {
      callback(e, data);
    }
  }
};

try {
  var xml2js = require('xml2js');
  parsers['application/xml'] = function(data, callback){
    var xml_parser = new xml2js.Parser();
    xml_parser.parseString(data, callback);
  };
} catch(e) { }

var Needle = {

  default_boundary: '--------------------NODENEEDLEHTTPCLIENT',
  default_user_agent: default_user_agent,

  request: function(uri, method, data, options, callback){

    var self = this, post_data = null;
    var callback = (typeof options == 'function') ? options : callback;
    var options = options || {};
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts: {},
      proxy: options.proxy,
      encoding: options.encoding || (options.multipart ? 'binary' : 'utf8'),
      parse_response: options.parse === false ? false : true,
      follow: options.follow === false ? 0 : options.follow || 10, // 10 by default
      timeout: (typeof options.timeout == 'number') ? options.timeout : 10000
    }

    node_tls_opts.split(' ').forEach(function(key){
      if (typeof options[key] != 'undefined'){
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      "User-Agent": options.user_agent || this.default_user_agent,
      "Connection": "close",
      "Accept": "*/*"
    }

    if (options.compressed && typeof unzip != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username && options.password){
      var b = new Buffer([options.username, options.password].join(':'));
      var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
      config.headers[auth_header] = 'Basic ' + b.toString('base64');
    }

    if (data){
      if (options.multipart){

        var boundary = options.boundary || this.default_boundary;
        return multipart.build(data, boundary, function(err, body){

          if (err) throw(err);
          config.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, callback);

        });

      } else {
        post_data = (typeof(data) === "string") ? data : stringify(data);
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        config.headers['Content-Length'] = post_data.length;
      }

    }

    this.send_request(1, method, uri, config, post_data, callback);
  },

  get_request_opts: function(method, uri, config){
    var opts = config.base_opts, proxy = config.proxy;
    var remote = proxy ? url_parse(proxy) : url_parse(uri);

    opts.host = remote.hostname;
    opts.port = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.protocol = remote.protocol;
    opts.path = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method = method;
    opts.headers = config.headers;
    opts.headers["Host"] = proxy ? url_parse(uri).hostname : remote.hostname;

    return opts;
  },

  send_request: function(count, method, uri, config, post_data, callback){

    var self = this, timer, response_opts = {parse_response: config.parse_response};
    var request_opts = this.get_request_opts(method, uri, config);

    var protocol = request_opts.protocol == 'https:' ? https : http;
    var request = protocol.request(request_opts, function(response){

      if (timer) clearTimeout(timer);

      if ((response.statusCode == 301 || response.statusCode == 302) && response.headers.location){
        if (count <= config.follow)
          return self.send_request(++count, 'GET', response.headers.location, config, null, callback);
        else if (config.follow > 0)
          return callback(new Error("Too many redirects. Possible redirect loop in " + response.headers.location))
      }

      var body = '';
      var compressed = /gzip|deflate/.test(response.headers['content-encoding']);
      response.setEncoding(compressed ? 'binary' : 'utf8');

      response.on('data', function(chunk){
        body += chunk;
      });

      response.on('end', function(){
        if(typeof unzip != 'undefined' && compressed)
          unzip(new Buffer(body, 'binary'), function(err, buff){
            self.response_end(response_opts, response, buff.toString(), callback);
          });
        else
          self.response_end(response_opts, response, body, callback);

      });

    });

    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      if (debug) console.log('Error on request: ' + err.toString());
      if (timer) clearTimeout(timer);
      if (callback) callback(err || new Error("Unkown error on request."));
    });

    if (post_data) request.write(post_data, config.encoding);
    request.end();

  },

  response_end: function(opts, response, body, callback){

    if (debug) console.log(response.headers);
    if (!callback) return;
    var content_type = response.headers['content-type'] && response.headers['content-type'].split(';')[0];

    if (opts.parse_response && parsers[content_type]) {
      parsers[content_type](body, function(err, result){
        callback(err, response, result);
      });
    } else {
      callback(null, response, body);
    }

  }

}

exports.head = function(uri, options, callback){
  return Needle.request(uri, 'HEAD', null, options, callback);
}

exports.get = function(uri, options, callback){
  return Needle.request(uri, 'GET', null, options, callback);
}

exports.post = function(uri, data, options, callback){
  if (!data || typeof data == 'function') throw('POST request expects data.');
  return Needle.request(uri, 'POST', data, options, callback);
}

exports.put = function(uri, data, options, callback){
  if (!data || typeof data == 'function') throw('PUT request expects data.');
  return Needle.request(uri, 'PUT', data, options, callback);
}

exports.delete = function(uri, data, options, callback){
  return Needle.request(uri, 'DELETE', null, options, callback);
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var htmlParser = require('htmlparser2');
var ProcessingInstructions = require('./processing-instructions');
var IsValidNodeDefinitions = require('./is-valid-node-definitions');

var Html2React = function(React) {
    var parseHtmlToTree = function(html) {
        var handler = new htmlParser.DomHandler();
        var parser = new htmlParser.Parser(handler);
        parser.parseComplete(html);
        return handler.dom;
    };

    var traverseDom = function(node, isValidNode, processingInstructions) {
        if (isValidNode(node)) {
            var children = [];
            _.each(node.children, function(child) {
                children.push(traverseDom(child, isValidNode, processingInstructions));
            });
            _.compact(children); // Remove invalid nodes
            for (var index = 0; index < processingInstructions.length; index++) {
                var processingInstruction = processingInstructions[index];
                if (processingInstruction.shouldProcessNode(node)) {
                    return processingInstruction.processNode(node, children);
                }
            }
        }
        return false;
    };

    var parseWithInstructions = function(html, isValidNode, processingInstructions) {
        var domTree = parseHtmlToTree(html);
        // TODO: Deal with HTML that contains more than one root level node
        if (domTree && domTree.length !== 1) {
            throw new Error('html-to-react currently only supports HTML with one single root element.' +
            'The HTML provided contains ' + domTree.length + ' root elements. You can fix that by simply wrapping your HTML' +
            'in a <div> element');
        }
        return traverseDom(domTree[0], isValidNode, processingInstructions);
    };

    var parse = function(html) {
        var processingInstructions = new ProcessingInstructions(React);
        return parseWithInstructions(html,
            IsValidNodeDefinitions.alwaysValid,
            processingInstructions.defaultProcessingInstructions);
    };

    return {
        parse: parse,
        parseWithInstructions: parseWithInstructions
    };
};

module.exports = Html2React;

<commit_msg>Fixing parser's error message when multiple roots are found<commit_after>'use strict';

var _ = require('lodash');
var htmlParser = require('htmlparser2');
var ProcessingInstructions = require('./processing-instructions');
var IsValidNodeDefinitions = require('./is-valid-node-definitions');

var Html2React = function(React) {
    var parseHtmlToTree = function(html) {
        var handler = new htmlParser.DomHandler();
        var parser = new htmlParser.Parser(handler);
        parser.parseComplete(html);
        return handler.dom;
    };

    var traverseDom = function(node, isValidNode, processingInstructions) {
        if (isValidNode(node)) {
            var children = [];
            _.each(node.children, function(child) {
                children.push(traverseDom(child, isValidNode, processingInstructions));
            });
            _.compact(children); // Remove invalid nodes
            for (var index = 0; index < processingInstructions.length; index++) {
                var processingInstruction = processingInstructions[index];
                if (processingInstruction.shouldProcessNode(node)) {
                    return processingInstruction.processNode(node, children);
                }
            }
        }
        return false;
    };

    var parseWithInstructions = function(html, isValidNode, processingInstructions) {
        var domTree = parseHtmlToTree(html);
        // TODO: Deal with HTML that contains more than one root level node
        if (domTree && domTree.length !== 1) {
            throw new Error('html-to-react currently only supports HTML with one single root element. ' +
            'The HTML provided contains ' + domTree.length + ' root elements. You can fix that by simply wrapping your HTML ' +
            'in a <div> element.');
        }
        return traverseDom(domTree[0], isValidNode, processingInstructions);
    };

    var parse = function(html) {
        var processingInstructions = new ProcessingInstructions(React);
        return parseWithInstructions(html,
            IsValidNodeDefinitions.alwaysValid,
            processingInstructions.defaultProcessingInstructions);
    };

    return {
        parse: parse,
        parseWithInstructions: parseWithInstructions
    };
};

module.exports = Html2React;

<|endoftext|>


<commit_before>L20n.Parser = function() {
  var content = null;
  var patterns = {
    id: /^([_a-zA-Z]\w*)/,
    value: /^(["'])([^'"]*)(["'])/
  }

  function parse(string) {
    var lol = {type: 'LOL',
               body: []}
    content = string
    get_ws();
    while (content) {
      lol.body.push(get_entry())
      get_ws();
    }
    return lol
  }

  function get_ws() {
    content = content.replace(/^\s+/,"")
  }

  function get_entry() {
    if (content[0] == '<') {
      content = content.substr(1)
      id = get_identifier()
      if (content[0] == '(') {
        var entry = get_macro(id)
      } else if (content[0] == '[') {
        var index = get_index()
        var entry = get_entity(id, index)
      } else {
        var entry = get_entity(id);
      }
    } else if (content.substr(0,2) == '/*') {
      var entry = get_comment();
    } else if (content.substr(0,6) == 'import') {
      var entry = get_importstatement()
    } else {
      throw "ParserError"
    }
    return entry
  }

  function get_importstatement() {
    content = content.substr(6)
    get_ws()
    if (content[0] != '(') {
      throw "ParserError"
    }
    content = content.substr(1)
    get_ws()
    var uri = get_string()
    get_ws()
    if (content[0] != ')') {
      throw "ParserError"
    }
    content = content.substr(1)
    var impStmt = {
      type: 'ImportStatement',
      uri: uri
    }
    return impStmt
  }

  function get_identifier() {
    if (content[0] == '~') {
      // this expression
    }
    var match = patterns['id'].exec(content)
    if (!match)
      throw "ParserError"
    content = content.substr(match[0].length)
    identifier = {type: 'Identifier',
                  name: match[0]}
    return identifier
  }

  function get_entity(id, index) {
    var ch = content[0]
    get_ws();
    if (content[0] == '>') {
      // empty entity
    }
    if (!/\s/g.test(ch)) {
      throw "ParserError"
    }
    var value = get_value(true)
    get_ws()
    attrs = get_attributes()
    var entity = {
      type: 'Entity',
      id: id,
      value: value,
      index: index || [],
      attrs: attrs,
      local: (id.name[0] == '_')
    }
    return entity
  }

  function get_value(none) {
    var c = content[0]
    if (c == '"' || c == "'") {
      var ccc = content.substr(3)
      var quote = (ccc == '"""' || ccc == "'''")?ccc:c
      var value = get_string()
    }
    return value
  }

  function get_string() {
    var match = patterns['value'].exec(content)
    if (!match) {
      throw "ParserError"
    }
    content = content.substr(match[0].length)
    return {type: 'String', content: match[2]}
  }

  function get_attributes() {
    if (content[0] == '>') {
      content = content.substr(1)
      return {}
    }
  }

  return {
    parse: parse,
  }
}
<commit_msg>turn parser into a proper js 1.8 strict lib<commit_after>'use strict'
L20n.Parser = function() {
  let content = null;
  let patterns = {
    id: /^([_a-zA-Z]\w*)/,
    value: /^(["'])([^'"]*)(["'])/
  }

  function parse(string) {
    let lol = {type: 'LOL',
               body: []}
    content = string
    get_ws();
    while (content) {
      lol.body.push(get_entry())
      get_ws();
    }
    return lol
  }

  function get_ws() {
    content = content.replace(/^\s+/,"")
  }

  function get_entry() {
    let entry
    if (content[0] == '<') {
      content = content.substr(1)
      let id = get_identifier()
      if (content[0] == '(') {
        entry = get_macro(id)
      } else if (content[0] == '[') {
        let index = get_index()
        entry = get_entity(id, index)
      } else {
        entry = get_entity(id);
      }
    } else if (content.substr(0,2) == '/*') {
      entry = get_comment();
    } else if (content.substr(0,6) == 'import') {
      entry = get_importstatement()
    } else {
      throw "ParserError"
    }
    return entry
  }

  function get_importstatement() {
    content = content.substr(6)
    get_ws()
    if (content[0] != '(') {
      throw "ParserError"
    }
    content = content.substr(1)
    get_ws()
    let uri = get_string()
    get_ws()
    if (content[0] != ')') {
      throw "ParserError"
    }
    content = content.substr(1)
    let impStmt = {
      type: 'ImportStatement',
      uri: uri
    }
    return impStmt
  }

  function get_identifier() {
    if (content[0] == '~') {
      // this expression
    }
    let match = patterns['id'].exec(content)
    if (!match)
      throw "ParserError"
    content = content.substr(match[0].length)
    let identifier = {type: 'Identifier',
                  name: match[0]}
    return identifier
  }

  function get_entity(id, index) {
    let ch = content[0]
    get_ws();
    if (content[0] == '>') {
      // empty entity
    }
    if (!/\s/g.test(ch)) {
      throw "ParserError"
    }
    let value = get_value(true)
    get_ws()
    let attrs = get_attributes()
    let entity = {
      type: 'Entity',
      id: id,
      value: value,
      index: index || [],
      attrs: attrs,
      local: (id.name[0] == '_')
    }
    return entity
  }

  function get_value(none) {
    let c = content[0]
    let value
    if (c == '"' || c == "'") {
      let ccc = content.substr(3)
      let quote = (ccc == '"""' || ccc == "'''")?ccc:c
      //let value = get_string()
      value = get_complex_string(quote)
    }
    return value
  }

  function get_string() {
    let match = patterns['value'].exec(content)
    if (!match) {
      throw "ParserError"
    }
    content = content.substr(match[0].length)
    return {type: 'String', content: match[2]}
  }

  function get_complex_string(quote) {
    let str_end = quote[0]
    let literal = new RegExp("^([^\\\{"+str_end+"]+)")
    let obj = []
    let buffer = ''
    content = content.substr(quote.length)
  }

  function get_attributes() {
    if (content[0] == '>') {
      content = content.substr(1)
      return {}
    }
  }

  return {
    parse: parse,
  }
}
<|endoftext|>


<commit_before>'use strict'

module.exports = function (predicates, triples, types, target, pos, index) {

    pos.a = 360 / triples.length;
    pos.c = (pos.l * 0.5) / Math.cos(pos.a * 0.5) + /*TODO: make spring constance configurable:*/95/**/ + pos.l;
    pos._ = 0;//Math.atan2(pos.y - pos.parent.y, pos.x - pos.parent.x) * (180 / Math.PI);

    triples.forEach(triple => {

        let config = predicates[triple[1]];
        if (!config) {
            return console.error('Flow-visualizer.parse: Invalid triple "' + triple + '".');
        }

        if (!config.nodes && !config.edges) {
            return console.error('Flow-visualizer.parse: Invalid config "' + triple[1] + '".', config);
        }

        Object.keys(config).forEach(category => config[category].forEach(map => {

            if (map.type && !types[map.type]) {
                return console.error('flow-visualizer.parse: type "' + map.type + '" not found for predicate "' + triple[1] + '".');
            }

            const type = map.type ? types[map.type][category] || {} : {};
            let element = {id: type.id || triple[0] + triple[2]};

            map.subject && map.subject.forEach(prop => element[prop] = triple[0]);
            map.object && map.object.forEach(prop => element[prop] = triple[2]);

            if (index[category][element.id]) {
                return;
            }

            element = Object.assign(element, type);

            // set node position
            if (category === 'nodes') {

                element.x = type.level < 4 ? Math.cos(pos._) * pos.c + pos.x : pos.x;
                element.y = type.level < 4 ? Math.sin(pos._) * pos.c + pos.y : pos.y;
                pos._ += pos.a;

                element.parent = target.node.id;

                index.nodes[element.id] = {children: [], out: []};
                index.nodes[element.parent] = index[category][element.parent] || {children: [], out: []};
                index.nodes[element.parent].children.push(element.id);

            // add edge to node out
            } else if (element.from) {
                index.nodes[element.from] = index.nodes[element.from] || {children: [], out: []};
                index.nodes[element.from].out.push(element.id);
                index.edges[element.id] = 1;
            }

            target[category].push(element);
        }));
    });
};
<commit_msg>handle "out" and "child" option, to ignore indexing<commit_after>'use strict'

module.exports = function (predicates, triples, types, target, pos, index) {

    pos.a = 360 / triples.length;
    pos.c = (pos.l * 0.5) / Math.cos(pos.a * 0.5) + /*TODO: make spring constance configurable:*/95/**/ + pos.l;
    pos._ = 0;//Math.atan2(pos.y - pos.parent.y, pos.x - pos.parent.x) * (180 / Math.PI);

    triples.forEach(triple => {

        let config = predicates[triple[1]];
        if (!config) {
            return console.error('Flow-visualizer.parse: Invalid triple "' + triple + '".');
        }

        if (!config.nodes && !config.edges) {
            return console.error('Flow-visualizer.parse: Invalid config "' + triple[1] + '".', config);
        }

        Object.keys(config).forEach(category => config[category].forEach(map => {

            if (map.type && !types[map.type]) {
                return console.error('flow-visualizer.parse: type "' + map.type + '" not found for predicate "' + triple[1] + '".');
            }

            const type = map.type ? types[map.type][category] || {} : {};
            let element = {id: type.id || triple[0] + triple[2]};

            map.out = map.out === undefined ? true : !!map.out;
            map.child = map.child === undefined ? true : !!map.child;
            map.subject && map.subject.forEach(prop => element[prop] = triple[0]);
            map.object && map.object.forEach(prop => element[prop] = triple[2]);

            if (index[category][element.id]) {
                return;
            }

            element = Object.assign(element, type);

            // set node position
            if (category === 'nodes') {

                element.x = type.level < 4 ? Math.cos(pos._) * pos.c + pos.x : pos.x;
                element.y = type.level < 4 ? Math.sin(pos._) * pos.c + pos.y : pos.y;
                pos._ += pos.a;

                element.parent = target.node.id;

                index.nodes[element.id] = {children: [], out: []};
                index.nodes[element.parent] = index[category][element.parent] || {children: [], out: []};
                map.child && index.nodes[element.parent].children.push(element.id);

            // add edge to node out
            } else if (element.from) {
                index.edges[element.id] = 1;
                index.nodes[element.from] = index.nodes[element.from] || {children: [], out: []};
                map.out && index.nodes[element.from].out.push(element.id);
            }

            target[category].push(element);
        }));
    });
};
<|endoftext|>


<commit_before>/**
 * Parted (https://github.com/chjj/parted)
 * A streaming multipart state parser.
 * Copyright (c) 2011, Christopher Jeffrey. (MIT Licensed)
 */

var fs = require('fs')
  , path = require('path')
  , EventEmitter = require('events').EventEmitter
  , StringDecoder = require('string_decoder').StringDecoder;

var DASH = '-'.charCodeAt(0)
  , CR = '\r'.charCodeAt(0)
  , LF = '\n'.charCodeAt(0)
  , COLON = ':'.charCodeAt(0)
  , SPACE = ' '.charCodeAt(0);

/**
 * Parted
 */

var parted = function(type, opt) {
  if (!(this instanceof parted)) {
    return new parted(type, opt);
  }

  EventEmitter.call(this);

  this.writable = true;
  this.readable = true;

  this.opt = opt || {};

  var key = grab(type, 'boundary');
  if (!key) {
    return this._error('No boundary key found.');
  }

  this.key = new Buffer('\r\n--' + key);

  this.state = 'start';
  this.pending = 0;
  this.written = 0;

  // this buffer is not a lookbehind.
  // it is here to buffer header
  // names and values.
  this.buff = new Buffer(200);

  this.verified = false;

  this._reset();
};

parted.prototype.__proto__ = EventEmitter.prototype;

/**
 * Parsing
 */

parted.prototype.write = function(data) {
  if (this.done) {
    console.log(data.toString());
    return this._error('Message overflow.');
  }

  try {
    this.written += data.length;
    this.emit('chunk');
    this._parse(data);
  } catch(e) {
    this._error(e);
  }

  return true;
};

parted.prototype.end = function(data) {
  if (!this.writable) return;

  this.writable = false;
  this.readable = false;
  //this.done = true;

  if (data) this.write(data);

  if (!this.done) {
    return this._error('Message underflow.');
  }

  if (!this.pending) this.emit('end');

  return true;
};

parted.prototype._parse = function(data) {
  // `val` is essentially just a
  // register to throw things onto
  var i = 0
    , len = data.length
    , last = this.last
    , buff = this.buff
    , key = this.key
    , ch
    , val;

  for (; i < len; i++) {
    if (this.pos >= 200) {
      return this._error('Potential buffer overflow.');
    }
    ch = data[i];
    switch (this.state) {
      case 'start':
        switch (ch) {
          case CR:
            this.pos = 1;
            this.state = 'maybe_in_key';
            break;
          case DASH:
            this.pos = 3;
            this.state = 'maybe_in_key';
            break;
          default:
            break;
        }
        break;
      case 'maybe_in_key':
        if (this.pos === key.length - 1) {
          this.state = 'in_key_end';
        } else if (ch !== key[this.pos]) {
          if (!this.verified) {
            return this._error('Parse error1.');
          }
          this.state = 'in_body';
          // need to _write the bytes missed
          val = this.pos - i;
          if (val > 0) this._write(key.slice(0, val));
        } else {
          this.pos++;
        }
        break;
      case 'in_key_end':
        switch (ch) {
          case CR:
            this.state = 'in_key_line_end';
            break;
          case DASH:
            this.state = 'in_key_dash_end';
            break;
          default:
            return this._error('Parse error2.');
        }
        break;
      case 'in_key_line_end':
        switch (ch) {
          case LF:
            if (!this.verified) {
              this.verified = true;
            } else {
              this._finish();
            }
            this.state = 'in_header_name';
            this.pos = 0;
            break;
          default:
            return this._error('Parse error3.');
        }
        break;
      case 'in_key_dash_end':
        switch (ch) {
          case DASH:
            this._finish();
            this.done = true;
            return;
          default:
            return this._error('Parse error4.');
        }
        break;
      case 'in_header_name':
        switch (ch) {
          case COLON:
            val = buff.slice(0, this.pos);
            this.header = val.toString('ascii').toLowerCase();
            this.pos = 0;
            this.state = 'in_header_val';
            break;
          default:
            buff[this.pos++] = ch;
            break;
        }
        break;
      case 'in_header_val':
        switch (ch) {
          case CR:
            this.state = 'in_header_val_cr';
            break;
          case SPACE:
            if (this.pos === 0) {
              break;
            }
            ; // FALL-THROUGH
          default:
            buff[this.pos++] = ch;
            break;
        }
        break;
      case 'in_header_val_cr':
        switch (ch) {
          case LF:
            val = buff.slice(0, this.pos);
            this.headers[this.header] = val.toString('ascii');

            this.pos = 0;
            this.state = 'in_header_end';
            break;
          default:
            return this._error('Parse error5.');
        }
        break;
      case 'in_header_end':
        switch (ch) {
          case CR:
            this.state = 'in_head_end_cr';
            break;
          default:
            this.state = 'in_header_name';
            buff[this.pos++] = ch;
            break;
        }
        break;
      case 'in_head_end_cr':
        switch (ch) {
          case LF:
            val = this.headers['content-disposition'];
            this.field = grab(val, 'name');
            this.file = grab(val, 'filename');

            this.state = 'in_body';

            i++; // exclude the LF.
            if (i >= len) return;

            data = data.slice(i);
            i = 0;
            len = data.length;
            break;
          default:
            return this._error('Parse error6.');
        }
        break;
      case 'in_body':
        switch (ch) {
          case CR:
            if (i > 0) this._write(data.slice(0, i));

            this.pos = 1;
            this.state = 'maybe_in_key';

            data = data.slice(i);
            i = 0;
            len = data.length;

            break;
          default:
            // nothing
            break;
        }
        break;
    }
  }

  if (this.state === 'in_body') {
    this._write(data);
  }
};

parted.prototype._write = function(data) {
  if (this.file) {
    if (!this.data) this.data = stream(this.file);
    return this.data.write(data);
  } else {
    if (!this.data) this.data = '';
    this.data += this.decoder.write(data);
    return true;
  }
};

// called on initialization,
// also when a part finishes,
// after events are emitted
parted.prototype._reset = function() {
  this.decoder = new StringDecoder('utf8');
  this.headers = {};
  this.pos = 0;
  this.field = null;
  this.data = null;
  this.file = null;
};

parted.prototype._error = function(err) {
  this.writable = false;
  this.readable = false;
  this.emit('error', new Error(err + ''));
};

// called when a part finishes
parted.prototype._finish = function() {
  var self = this
    , field = this.field
    , headers = this.headers
    , data = this.data
    , part;

  this.pending++;

  part = {
    field: field,
    type: headers['content-type'],
    encoding: headers['content-encoding']
  };

  if (data.path) {
    part.file = data.path;
    data.end(next);
  } else {
    part.text = data;
    next();
  }

  this._reset();

  function next() {
    self.pending--;

    self.emit('data', part);

    if (self.done && !self.pending) {
      self.emit('end');
    }
  }
};

/**
 * Uploads
 */

parted.root = '/tmp';

/**
 * Middleware
 */

parted.middleware = function(opt) {
  opt = opt || {};
  opt.limit = opt.limit || Infinity;
  return function(req, res, next) {
    if (req.method === 'GET'
        || req.method === 'HEAD'
        || req.body) return next();

    var type = req.headers['content-type'];

    if (type && type.indexOf('multipart/form-data') === 0) {
      var parser = new parted(type, opt)
        , parts = {};

      parser.on('error', function(err) {
        console.error(err);
        req.destroy();
        next(err);
      });

      parser.on('data', function(part) {
        parts[part.field] = part.file || part.text;
      });

      parser.on('chunk', function() {
        if (parser.written > opt.limit) {
          parser.emit('error', new Error('Overflow.'));
        }
      });

      parser.on('end', next);

      req.body = parts;
      req.pipe(parser);
    } else {
      next();
    }
  };
};

/**
 * Helpers
 */

var stream = function(name) {
  name = path.basename(name).substring(0, 10);
  name = path.join(parted.root, Date.now() + '_' + name);
  return fs.createWriteStream(name);
};

var grab = function(str, name) {
  if (!str) return;

  var rx = new RegExp(name + '\\s*=\\s*([^;]+)', 'i')
    , cap = rx.exec(str);

  if (cap) {
    return cap[1].trim().replace(/^['"]|['"]$/g, '');
  }
};

/**
 * Expose
 */

module.exports = parted;
<commit_msg>perfect<commit_after>/**
 * Parted (https://github.com/chjj/parted)
 * A streaming multipart state parser.
 * Copyright (c) 2011, Christopher Jeffrey. (MIT Licensed)
 */

var fs = require('fs')
  , path = require('path')
  , EventEmitter = require('events').EventEmitter
  , StringDecoder = require('string_decoder').StringDecoder;

var DASH = '-'.charCodeAt(0)
  , CR = '\r'.charCodeAt(0)
  , LF = '\n'.charCodeAt(0)
  , COLON = ':'.charCodeAt(0)
  , SPACE = ' '.charCodeAt(0);

/**
 * Parted
 */

var parted = function(type, opt) {
  if (!(this instanceof parted)) {
    return new parted(type, opt);
  }

  EventEmitter.call(this);

  this.writable = true;
  this.readable = true;

  this.opt = opt || {};

  var key = grab(type, 'boundary');
  if (!key) {
    return this._error('No boundary key found.');
  }

  this.key = new Buffer('\r\n--' + key);

  this.state = 'start';
  this.pending = 0;
  this.written = 0;

  // this buffer is not a lookbehind.
  // it is here to buffer header
  // names and values.
  this.buff = new Buffer(200);

  this.verified = false;

  this._reset();
};

parted.prototype.__proto__ = EventEmitter.prototype;

/**
 * Parsing
 */

parted.prototype.write = function(data) {
  if (this.done) {
    // this parser assumes a message is finished after
    // the second dash of the last boundary key
    // however, some browsers send another CRLF.
    // there might be 2 extra bytes at the end
    // that we can ignore.
    if (data.length < 3) return;
    return this._error('Message overflow.');
  }

  try {
    this.written += data.length;
    this.emit('chunk');
    this._parse(data);
  } catch(e) {
    this._error(e);
  }

  return true;
};

parted.prototype.end = function(data) {
  if (!this.writable) return;

  this.writable = false;
  this.readable = false;
  //this.done = true;

  if (data) this.write(data);

  if (!this.done) {
    return this._error('Message underflow.');
  }

  if (!this.pending) this.emit('end');

  return true;
};

parted.prototype._parse = function(data) {
  // `val` is essentially just a
  // register to throw things onto
  var i = 0
    , len = data.length
    , last = this.last
    , buff = this.buff
    , key = this.key
    , ch
    , val;

  for (; i < len; i++) {
    if (this.pos >= 200) {
      return this._error('Potential buffer overflow.');
    }
    ch = data[i];
    switch (this.state) {
      case 'start':
        switch (ch) {
          case CR:
            this.pos = 1;
            this.state = 'maybe_in_key';
            break;
          case DASH:
            this.pos = 3;
            this.state = 'maybe_in_key';
            break;
          default:
            break;
        }
        break;
      case 'maybe_in_key':
        if (this.pos === key.length - 1) {
          this.state = 'in_key_end';
        } else if (ch !== key[this.pos]) {
          if (!this.verified) {
            return this._error('Parse error1.');
          }
          this.state = 'in_body';
          // need to _write the bytes missed
          val = this.pos - i;
          if (val > 0) this._write(key.slice(0, val));
        } else {
          this.pos++;
        }
        break;
      case 'in_key_end':
        switch (ch) {
          case CR:
            this.state = 'in_key_line_end';
            break;
          case DASH:
            this.state = 'in_key_dash_end';
            break;
          default:
            return this._error('Parse error2.');
        }
        break;
      case 'in_key_line_end':
        switch (ch) {
          case LF:
            if (!this.verified) {
              this.verified = true;
            } else {
              this._finish();
            }
            this.state = 'in_header_name';
            this.pos = 0;
            break;
          default:
            return this._error('Parse error3.');
        }
        break;
      case 'in_key_dash_end':
        switch (ch) {
          case DASH:
            this._finish();
            this.done = true;
            return;
          default:
            return this._error('Parse error4.');
        }
        break;
      case 'in_header_name':
        switch (ch) {
          case COLON:
            val = buff.slice(0, this.pos);
            this.header = val.toString('ascii').toLowerCase();
            this.pos = 0;
            this.state = 'in_header_val';
            break;
          default:
            buff[this.pos++] = ch;
            break;
        }
        break;
      case 'in_header_val':
        switch (ch) {
          case CR:
            this.state = 'in_header_val_cr';
            break;
          case SPACE:
            if (this.pos === 0) {
              break;
            }
            ; // FALL-THROUGH
          default:
            buff[this.pos++] = ch;
            break;
        }
        break;
      case 'in_header_val_cr':
        switch (ch) {
          case LF:
            val = buff.slice(0, this.pos);
            this.headers[this.header] = val.toString('ascii');

            this.pos = 0;
            this.state = 'in_header_end';
            break;
          default:
            return this._error('Parse error5.');
        }
        break;
      case 'in_header_end':
        switch (ch) {
          case CR:
            this.state = 'in_head_end_cr';
            break;
          default:
            this.state = 'in_header_name';
            buff[this.pos++] = ch;
            break;
        }
        break;
      case 'in_head_end_cr':
        switch (ch) {
          case LF:
            val = this.headers['content-disposition'];
            this.field = grab(val, 'name');
            this.file = grab(val, 'filename');

            this.state = 'in_body';

            i++; // exclude the LF.
            if (i >= len) return;

            data = data.slice(i);
            i = 0;
            len = data.length;
            break;
          default:
            return this._error('Parse error6.');
        }
        break;
      case 'in_body':
        switch (ch) {
          case CR:
            if (i > 0) this._write(data.slice(0, i));

            this.pos = 1;
            this.state = 'maybe_in_key';

            data = data.slice(i);
            i = 0;
            len = data.length;

            break;
          default:
            // nothing
            break;
        }
        break;
    }
  }

  if (this.state === 'in_body') {
    this._write(data);
  }
};

parted.prototype._write = function(data) {
  if (this.file) {
    if (!this.data) this.data = stream(this.file);
    return this.data.write(data);
  } else {
    if (!this.data) this.data = '';
    this.data += this.decoder.write(data);
    return true;
  }
};

// called on initialization,
// also when a part finishes,
// after events are emitted
parted.prototype._reset = function() {
  this.decoder = new StringDecoder('utf8');
  this.headers = {};
  this.pos = 0;
  this.field = null;
  this.data = null;
  this.file = null;
};

parted.prototype._error = function(err) {
  this.writable = false;
  this.readable = false;
  this.emit('error', new Error(err + ''));
};

// called when a part finishes
parted.prototype._finish = function() {
  var self = this
    , field = this.field
    , headers = this.headers
    , data = this.data
    , part;

  this.pending++;

  part = {
    field: field,
    type: headers['content-type'],
    encoding: headers['content-encoding']
  };

  if (data.path) {
    part.file = data.path;
    data.end(next);
  } else {
    part.text = data;
    next();
  }

  this._reset();

  function next() {
    self.pending--;

    self.emit('data', part);

    if (self.done && !self.pending) {
      self.emit('end');
    }
  }
};

/**
 * Uploads
 */

parted.root = '/tmp';

/**
 * Middleware
 */

parted.middleware = function(opt) {
  opt = opt || {};
  opt.limit = opt.limit || Infinity;
  return function(req, res, next) {
    if (req.method === 'GET'
        || req.method === 'HEAD'
        || req.body) return next();

    var type = req.headers['content-type'];

    if (type && type.indexOf('multipart/form-data') === 0) {
      var parser = new parted(type, opt)
        , parts = {};

      parser.on('error', function(err) {
        console.error(err);
        req.destroy();
        next(err);
      });

      parser.on('data', function(part) {
        parts[part.field] = part.file || part.text;
      });

      parser.on('chunk', function() {
        if (parser.written > opt.limit) {
          parser.emit('error', new Error('Overflow.'));
        }
      });

      parser.on('end', next);

      req.body = parts;
      req.pipe(parser);
    } else {
      next();
    }
  };
};

/**
 * Helpers
 */

var stream = function(name) {
  name = path.basename(name).substring(0, 10);
  name = path.join(parted.root, Date.now() + '_' + name);
  return fs.createWriteStream(name);
};

var grab = function(str, name) {
  if (!str) return;

  var rx = new RegExp(name + '\\s*=\\s*([^;]+)', 'i')
    , cap = rx.exec(str);

  if (cap) {
    return cap[1].trim().replace(/^['"]|['"]$/g, '');
  }
};

/**
 * Expose
 */

module.exports = parted;
<|endoftext|>


<commit_before>var CONST = require('../include/constants.js'),
seek_country = require('./utils.js').seek_country,
ip2long = require('./utils.js').ip2long;

function _get_region(data,ipnum){
  var region, region_id, country_code, char0, char1;
  if (data.db_type == CONST.REGION_EDITION_REV0){
    region_id = seek_country(data, ipnum) - CONST.STATE_BEGIN_REV0;
    if (region_id >= 1000){
      country_code = "US";
      char0 = String.fromCharCode((region_id - 1000) / 26 + 65);
      char1 = String.fromCharCode((region_id - 1000) % 26 + 65);
      region = char0.concat(char1);
    } else {
      country_code = data.COUNTRY_CODES[region_id];
      region = "";
    }
    return [country_code, region];
  }  else if (data.db_type == CONST.REGION_EDITION_REV1) {
    region_id = seek_country(data,ipnum) - CONST.STATE_BEGIN_REV1;
    //print $seek_region;
    if (region_id < CONST.US_OFFSET){
      country_code = "";
      region = "";
    } else if (region_id < CONST.CANADA_OFFSET) {
      country_code = "US";
      char0 = String.fromCharCode((region_id - CONST.US_OFFSET) / 26 + 65);
      char1 = String.fromCharCode((region_id - CONST.US_OFFSET) % 26 + 65);
      region = char0.concat(char1);
    } else if (region_id < CONST.WORLD_OFFSET) {
      country_code = "CA";
      char0 = String.fromCharCode((region_id - CONST.CANADA_OFFSET) / 26 + 65);
      char1 = String.fromCharCode((region_id - CONST.CANADA_OFFSET) % 26 + 65);
      region = char0.concat(char1);
    } else {
      country_code = data.COUNTRY_CODES[(region_id - CONST.WORLD_OFFSET) / CONST.FIPS_RANGE];
      region = "";
    }
    return [country_code, region];
  }
}

exports.region_by_addr = function(data, addr) {
  var ipnum;
  if (data.db_type !== CONST.REGION_EDITION_REV0 &&
  data.db_type !== CONST.REGION_EDITION_REV1) {
    return console.log('Err data type');
  } else {
    if (addr === null) {
      return 0;
    }
    ipnum = ip2long($addr);
    return _get_region(data, ipnum);
  }
};
<commit_msg>fixed $addr name bug in lib/region.js<commit_after>var CONST = require('../include/constants.js'),
seek_country = require('./utils.js').seek_country,
ip2long = require('./utils.js').ip2long;

function _get_region(data,ipnum){
  var region, region_id, country_code, char0, char1;
  if (data.db_type == CONST.REGION_EDITION_REV0){
    region_id = seek_country(data, ipnum) - CONST.STATE_BEGIN_REV0;
    if (region_id >= 1000){
      country_code = "US";
      char0 = String.fromCharCode((region_id - 1000) / 26 + 65);
      char1 = String.fromCharCode((region_id - 1000) % 26 + 65);
      region = char0.concat(char1);
    } else {
      country_code = data.COUNTRY_CODES[region_id];
      region = "";
    }
    return [country_code, region];
  }  else if (data.db_type == CONST.REGION_EDITION_REV1) {
    region_id = seek_country(data,ipnum) - CONST.STATE_BEGIN_REV1;
    //print $seek_region;
    if (region_id < CONST.US_OFFSET){
      country_code = "";
      region = "";
    } else if (region_id < CONST.CANADA_OFFSET) {
      country_code = "US";
      char0 = String.fromCharCode((region_id - CONST.US_OFFSET) / 26 + 65);
      char1 = String.fromCharCode((region_id - CONST.US_OFFSET) % 26 + 65);
      region = char0.concat(char1);
    } else if (region_id < CONST.WORLD_OFFSET) {
      country_code = "CA";
      char0 = String.fromCharCode((region_id - CONST.CANADA_OFFSET) / 26 + 65);
      char1 = String.fromCharCode((region_id - CONST.CANADA_OFFSET) % 26 + 65);
      region = char0.concat(char1);
    } else {
      country_code = data.COUNTRY_CODES[(region_id - CONST.WORLD_OFFSET) / CONST.FIPS_RANGE];
      region = "";
    }
    return [country_code, region];
  }
}

exports.region_by_addr = function(data, addr) {
  var ipnum;
  if (data.db_type !== CONST.REGION_EDITION_REV0 &&
  data.db_type !== CONST.REGION_EDITION_REV1) {
    return console.log('Err data type');
  } else {
    if (addr === null) {
      return 0;
    }
    ipnum = ip2long(addr);
    return _get_region(data, ipnum);
  }
};
<|endoftext|>


<commit_before>// Dependencies
var path = require('path'),
  im = require('imagemagick'),
  uuid = require('node-uuid'),
  response = require('./responseHelpers'),
  helpers = require('./helperfunctions'),
  imagePath = '/tmp/';

module.exports = {
  // Set dimensions to either the requested dimensions or the
  // image's original dimensions
  identify: function(req, res) {
    var w;
    var h;

    // If neither the width nor the height were provided, respond with a status 400
    if (!req.w || !req.h) {
      return response.errRes(req, res, 400, 'missing a required parameter');
    }

    im.identify(imagePath + req.key + '.jpg', function(err, features) {
      if (err) {
        console.error('Image transformation failed with error:', err);
        throw err;
      }

      w = req.query.w || features.width;
      h = req.query.h || features.height;

      resize(req, res, w, h);
    });
  }
};

// Resize image with requested dimensions
var resize = function(req, res, w, h) {
  var key = uuid.v4().split('-').pop();

  im.resize({
    srcPath: imagePath + req.key + '.jpg',
    dstPath: imagePath + key + '.jpg',
    width: w,
    height: h
  }, function(err, stdout, stderr) {
    if (err) {
      console.error('Image processing failed with error:', err);
      throw err;
    }

    if (stderr) {
      console.error('Image processing failed with stderr:', stderr);
      throw stderr;
    }

    response.getRes(req, res, key);
  });
};

<commit_msg>fix syntax error when checking for wxh query parameters<commit_after>// Dependencies
var path = require('path'),
  im = require('imagemagick'),
  uuid = require('node-uuid'),
  response = require('./responseHelpers'),
  helpers = require('./helperfunctions'),
  imagePath = '/tmp/';

module.exports = {
  // Set dimensions to either the requested dimensions or the
  // image's original dimensions
  identify: function(req, res) {
    var w;
    var h;

    // If neither the width nor the height were provided, respond with a status 400
    if (!req.query.w || !req.query.h) {
      return response.errRes(req, res, 400, 'missing a required parameter');
    }

    im.identify(imagePath + req.key + '.jpg', function(err, features) {
      if (err) {
        console.error('Image transformation failed with error:', err);
        throw err;
      }

      w = req.query.w || features.width;
      h = req.query.h || features.height;

      resize(req, res, w, h);
    });
  }
};

// Resize image with requested dimensions
var resize = function(req, res, w, h) {
  var key = uuid.v4().split('-').pop();

  im.resize({
    srcPath: imagePath + req.key + '.jpg',
    dstPath: imagePath + key + '.jpg',
    width: w,
    height: h
  }, function(err, stdout, stderr) {
    if (err) {
      console.error('Image processing failed with error:', err);
      throw err;
    }

    if (stderr) {
      console.error('Image processing failed with stderr:', stderr);
      throw stderr;
    }

    response.getRes(req, res, key);
  });
};

<|endoftext|>


<commit_before><commit_msg>Remove jQuery from xmpp-ftw, see #17<commit_after><|endoftext|>


<commit_before>var util = require('util');
var events = require('events');
var Context = require('./context');
var Registry = require('./registry');
var logging = require('./logging');

module.exports = Router;

/**
 * The application router.
 *
 * This takes a route (in any supported format) and resolves
 * it to a particular chain of commands.
 */
function Router(registry) {
  this.registry = registry;
  this.resolver = null;
  this.loggers = [];
  this.logEmitter = new logging.Logger;
  this.attachLoggers();
}

// Router generates events.
util.inherits(Router, events.EventEmitter);

/*
 * Set a new registry.
 *
 * Use with caution.
 */
Router.prototype.setRegistry = function(registry) {
  this.registry = registry;

  // Re-attach loggers.
  this.detachLoggers();
  this.attachLoggers();
}

/**
 * Attach all logging backends to the router.
 */
Router.prototype.attachLoggers = function() {
  var logBackends = this.registry.getLoggers();
  for (var l in logBackends) {
   var impl = new l.logger(this.logEmitter, l.options);
   this.loggers.push(impl);
  }
}
/**
 * This destroys the loggers.
 */
Router.prototype.detachLoggers = function() {
  for (var i = 0; i < this.loggers.length; ++i) {
    delete this.loggers[i];
  }
}

/**
 * Take the given request name and resolve it to a
 * real request name.
 */
Router.prototype.resolveRequest = function(requestName, context) {

  if (this.resolver != null) {
    //console.log('RESOLVING ' + this.resolver.resolve(requestName));
    return this.resolver.resolve(requestName, context);
  }

  // Return just the request name for now.
  return requestName;
}

Router.prototype.setRequestResolver = function(resolver) {
  this.resolver = resolver;
}

/**
 * Given a request, perform the associated commands.
 *
 * Emits:
 * - error: Given an Error object. Emitted when request cannot be found, or when any part of the request fails.
 * - commandsStart:  Given request spec and context. Emitted immediately before the chain is run.
 * - commandsLaunched: Trigger immediately after a chain is kicked off. This may fire before the first command is complete.
 * - commandListComplete: Emitted when the entire chain has been executed.
 * - commandContinue: Emitted when the command is "done enough" for processing to continue. The next
 *    command will start upon seeing this.
 * - commandComplete: Emitted when a command is totally complete. This may happen after other commands have begun
 *    executing.
 * - beforeCommand: A command emits this before it executes.
 * - beforeCommandInit: A command emits this before it runs its init() routine.
 * - commandListInterrupted
 * - reroute
 *
 * @param string request
 * @param pronto.Context cxt (optional)
 */
Router.prototype.handleRequest = function(request, cxt, tainted) {
  request = this.resolveRequest(request, cxt);

  var spec = this.registry.getRequestSpec(request);
  if (spec == undefined || spec == null) {
    var err = new Error('Request not found');
    this.emit('error', err, cxt);
    return;
  }

  if (!!tainted && request.length > 0 && request[0] == '@') {
    throw new Error('A tainted route cannot call an internal @-method.');
  }

  // BEGIN NEW
  //this.doCommand(request, spec);
  var context = cxt;
  if (cxt instanceof Context) {
    // Do we re-intialize loggers?
  }
  else {
    context = new Context();
    context.setLogger(this.logEmitter);
  }
  this.emit('commandsStart', spec, context);

  // doCommand is recursive.
  this.doCommand(request, spec, context, 0);

  this.emit('commandsLaunched', context);
}

/**
 * Execute the current command and then request that the next be executed.
 *
 * This executes the current command (`spec[index]`), and then
 * requests (if necessary) that the next command be executed.
 *
 * Stopping conditions:
 * The command processing stops under the following conditions:
 *  - There are no more commands to execute
 *  - An unhandle `Error` is thrown or emitted.
 *  - A `stop` event is received from the command, or manually triggered.
 *  - A `reroute` event is received from the command. In this case, the
 *    present list is aborted, and the new route is run.
 *
 *
 */
Router.prototype.doCommand = function(requestName, spec, context, index) {

  // Stopping conditions.
  if (index >= spec.length) {
    this.emit('commandListComplete', context);
    return;
  }
  else if (this.stop) {
    this.emit('commandListInterrupted', requestName, spec, context);

    // EXPERIMENTAL: When we stop, we really want to "finish" the
    // request, so we slice the spec and send it in again to complete
    // the "normal" process.
    var fakeSpec = spec.slice(0, index);
    this.stop = false;
    this.doCommand(requestName, fakeSpec, context, ++index);
    return;
  }
  //console.log('Running ' + spec[index].name);

  // No stopping conditions were met, so we build and execute the command.

  item = spec[index];
  var cmd = this.constructCommand(item);

  // emit beforeCommandInit
  cmd.init(item.name);

  var params = this.buildParams(item, context);
  var router = this;

  // Emit 'commandContinue'
  cmd.on('continue', function () {
    router.emit('commandContinue', item, context);
    // Recurse.
    router.doCommand(requestName, spec, context, ++index);
  });

  // Emit 'commandComplete'
  cmd.on('complete', function () { router.emit('commandComplete', spec, context)});
  // Catch a request to stop processing.
  cmd.on('stop', function () {
    router.emit('commandListInterrupted', requestName, spec, context);
    router.stop = true;
  });
  // Catch a request to reroute
  cmd.on('reroute', function (routeName, newCxt) {
    router.emit('reroute', routeName, newCxt);
    router.handleRequest(routeName, newCxt);
  });

  cmd.on('error', function (err) {
    // Bubble the event.
    router.emit('error', err, context);
    router.stop = true;
  })

  // Execute.
  this.emit('beforeCommand', cmd, context, params, spec);
  cmd.executionWrapper(context, params);
}

/**
 * Given a spec, create a new instance of a command.
 *
 * This should be done as late as possible to reduce
 * the amount of memory overhead on un-executed
 * commands.
 */
Router.prototype.constructCommand = function(spec) {
  var cmd = spec.command;
  if (cmd == undefined) {
    throw new Error("No command defined for " + spec.name);
  }
  else if(typeof cmd == 'string') {
    cmd = require(cmd);
  }
  return new cmd();
}

/**
 * Check whether the given request name exists.
 */
Router.prototype.hasRequest = function(requestName) {
  return this.registry.getRequestSpec(requestName) != undefined;
}

// FIXME:
Router.prototype.buildParams = function(spec, cxt) {
  // TODO: Insert from() resolution.
  params = {};
  for (var key in spec.params) {
    if (spec.params[key].from == undefined) {
      params[key] = spec.params[key].value;
    }
    else {
      var from = this.resolveFromSpec(spec.params[key].from, cxt);
      params[key] = from || spec.params[key].value;
    }

  }
  return params;
}

Router.prototype.resolveFromSpec = function(fromStr, cxt) {
  var retval;
  fromStr.split(' ').forEach(function(v, i) {
    // We want to split the pair string into an origin (cxt, get, header, etc.)
    // and the value.
    var firstColon = v.indexOf(':');
    var origin = v.substring(0, firstColon).toLowerCase();//source[0].toLowerCase();
    var key = v.substring(firstColon + 1);
    switch (origin) {
      case 'context':
      case 'cxt':
      case 'c':
        retval = cxt.get(key);
        return;
      case 'arg':
        // Support index or slice.
        break;

      // Proxy all others through cxt.getDatasource
      default:
        var ds = cxt.getDatasource(origin);
        if (ds != undefined) {
          retval = ds[key];
          return;
        }
    }
  });
  return retval;
}
<commit_msg>Fixed logger initialization.<commit_after>var util = require('util');
var events = require('events');
var Context = require('./context');
var Registry = require('./registry');
var logging = require('./logging');

module.exports = Router;

/**
 * The application router.
 *
 * This takes a route (in any supported format) and resolves
 * it to a particular chain of commands.
 */
function Router(registry) {
  this.registry = registry;
  this.resolver = null;
  this.loggers = [];
  this.logEmitter = new logging.Logger;
  this.attachLoggers();
}

// Router generates events.
util.inherits(Router, events.EventEmitter);

/*
 * Set a new registry.
 *
 * Use with caution.
 */
Router.prototype.setRegistry = function(registry) {
  this.registry = registry;

  // Re-attach loggers.
  this.detachLoggers();
  this.attachLoggers();
}

/**
 * Attach all logging backends to the router.
 */
Router.prototype.attachLoggers = function() {
  var logBackends = this.registry.getLoggers();
  for (var i = 0; i < logBackends.length; ++i) {
    var l = logBackends[i];
    console.log(l);
    var LogImpl = l.logger;
    var impl = new LogImpl(this.logEmitter, l.options);
    this.loggers.push(impl);
  }
}
/**
 * This destroys the loggers.
 */
Router.prototype.detachLoggers = function() {
  for (var i = 0; i < this.loggers.length; ++i) {
    delete this.loggers[i];
  }
}

/**
 * Take the given request name and resolve it to a
 * real request name.
 */
Router.prototype.resolveRequest = function(requestName, context) {

  if (this.resolver != null) {
    //console.log('RESOLVING ' + this.resolver.resolve(requestName));
    return this.resolver.resolve(requestName, context);
  }

  // Return just the request name for now.
  return requestName;
}

Router.prototype.setRequestResolver = function(resolver) {
  this.resolver = resolver;
}

/**
 * Given a request, perform the associated commands.
 *
 * Emits:
 * - error: Given an Error object. Emitted when request cannot be found, or when any part of the request fails.
 * - commandsStart:  Given request spec and context. Emitted immediately before the chain is run.
 * - commandsLaunched: Trigger immediately after a chain is kicked off. This may fire before the first command is complete.
 * - commandListComplete: Emitted when the entire chain has been executed.
 * - commandContinue: Emitted when the command is "done enough" for processing to continue. The next
 *    command will start upon seeing this.
 * - commandComplete: Emitted when a command is totally complete. This may happen after other commands have begun
 *    executing.
 * - beforeCommand: A command emits this before it executes.
 * - beforeCommandInit: A command emits this before it runs its init() routine.
 * - commandListInterrupted
 * - reroute
 *
 * @param string request
 * @param pronto.Context cxt (optional)
 */
Router.prototype.handleRequest = function(request, cxt, tainted) {
  request = this.resolveRequest(request, cxt);

  var spec = this.registry.getRequestSpec(request);
  if (spec == undefined || spec == null) {
    var err = new Error('Request not found');
    this.emit('error', err, cxt);
    return;
  }

  if (!!tainted && request.length > 0 && request[0] == '@') {
    throw new Error('A tainted route cannot call an internal @-method.');
  }

  // BEGIN NEW
  //this.doCommand(request, spec);
  var context = cxt;
  if (cxt instanceof Context) {
    // Do we re-intialize loggers?
  }
  else {
    context = new Context();
    context.setLogger(this.logEmitter);
  }
  this.emit('commandsStart', spec, context);

  // doCommand is recursive.
  this.doCommand(request, spec, context, 0);

  this.emit('commandsLaunched', context);
}

/**
 * Execute the current command and then request that the next be executed.
 *
 * This executes the current command (`spec[index]`), and then
 * requests (if necessary) that the next command be executed.
 *
 * Stopping conditions:
 * The command processing stops under the following conditions:
 *  - There are no more commands to execute
 *  - An unhandle `Error` is thrown or emitted.
 *  - A `stop` event is received from the command, or manually triggered.
 *  - A `reroute` event is received from the command. In this case, the
 *    present list is aborted, and the new route is run.
 *
 *
 */
Router.prototype.doCommand = function(requestName, spec, context, index) {

  // Stopping conditions.
  if (index >= spec.length) {
    this.emit('commandListComplete', context);
    return;
  }
  else if (this.stop) {
    this.emit('commandListInterrupted', requestName, spec, context);

    // EXPERIMENTAL: When we stop, we really want to "finish" the
    // request, so we slice the spec and send it in again to complete
    // the "normal" process.
    var fakeSpec = spec.slice(0, index);
    this.stop = false;
    this.doCommand(requestName, fakeSpec, context, ++index);
    return;
  }
  //console.log('Running ' + spec[index].name);

  // No stopping conditions were met, so we build and execute the command.

  item = spec[index];
  var cmd = this.constructCommand(item);

  // emit beforeCommandInit
  cmd.init(item.name);

  var params = this.buildParams(item, context);
  var router = this;

  // Emit 'commandContinue'
  cmd.on('continue', function () {
    router.emit('commandContinue', item, context);
    // Recurse.
    router.doCommand(requestName, spec, context, ++index);
  });

  // Emit 'commandComplete'
  cmd.on('complete', function () { router.emit('commandComplete', spec, context)});
  // Catch a request to stop processing.
  cmd.on('stop', function () {
    router.emit('commandListInterrupted', requestName, spec, context);
    router.stop = true;
  });
  // Catch a request to reroute
  cmd.on('reroute', function (routeName, newCxt) {
    router.emit('reroute', routeName, newCxt);
    router.handleRequest(routeName, newCxt);
  });

  cmd.on('error', function (err) {
    // Bubble the event.
    router.emit('error', err, context);
    router.stop = true;
  })

  // Execute.
  this.emit('beforeCommand', cmd, context, params, spec);
  cmd.executionWrapper(context, params);
}

/**
 * Given a spec, create a new instance of a command.
 *
 * This should be done as late as possible to reduce
 * the amount of memory overhead on un-executed
 * commands.
 */
Router.prototype.constructCommand = function(spec) {
  var cmd = spec.command;
  if (cmd == undefined) {
    throw new Error("No command defined for " + spec.name);
  }
  else if(typeof cmd == 'string') {
    cmd = require(cmd);
  }
  return new cmd();
}

/**
 * Check whether the given request name exists.
 */
Router.prototype.hasRequest = function(requestName) {
  return this.registry.getRequestSpec(requestName) != undefined;
}

// FIXME:
Router.prototype.buildParams = function(spec, cxt) {
  // TODO: Insert from() resolution.
  params = {};
  for (var key in spec.params) {
    if (spec.params[key].from == undefined) {
      params[key] = spec.params[key].value;
    }
    else {
      var from = this.resolveFromSpec(spec.params[key].from, cxt);
      params[key] = from || spec.params[key].value;
    }

  }
  return params;
}

Router.prototype.resolveFromSpec = function(fromStr, cxt) {
  var retval;
  fromStr.split(' ').forEach(function(v, i) {
    // We want to split the pair string into an origin (cxt, get, header, etc.)
    // and the value.
    var firstColon = v.indexOf(':');
    var origin = v.substring(0, firstColon).toLowerCase();//source[0].toLowerCase();
    var key = v.substring(firstColon + 1);
    switch (origin) {
      case 'context':
      case 'cxt':
      case 'c':
        retval = cxt.get(key);
        return;
      case 'arg':
        // Support index or slice.
        break;

      // Proxy all others through cxt.getDatasource
      default:
        var ds = cxt.getDatasource(origin);
        if (ds != undefined) {
          retval = ds[key];
          return;
        }
    }
  });
  return retval;
}
<|endoftext|>


<commit_before><commit_msg>uses waitOn function in the Router.configure<commit_after><|endoftext|>


<commit_before>// Load in dependencies
var express = require('express'),
    config = require('./config');

// Export our app bindings
module.exports = function (app) {
  // Portfolio page
  var projects = require('./projects'),
      intword = require('./humanize.intword.js');
  projects.page = 'projects';
  projects.intword = intword;
  app.get('/projects', function (req, res) {
    res.render('projects', projects);
  });

  // If we are in development, add a contact/test page
  if (config.inDevelopment) {
    app.get('/contact', function (req, res, next) {
      var query = req.query || {},
          test = query.test;

      // If there is a test query, render the proper response
      if (test) {
        var emailStatus = test !== 'fail';
        res.render('contact', {'page': 'contact', 'emailStatus': emailStatus});
      } else {
      // Otherwise, continue
        next();
      }
    });
  }

  // Contact page (initial view)
  app.get('/contact', function (req, res) {
    res.render('contact', {'page': 'contact'});
  });

  // Set up email server interaction
  var email = require('emailjs'),
      emailConf = require('../mail.conf'),
      emailServer = email.server.connect(emailConf);

  // Contact page (submission)
  app.post('/contact', express.bodyParser());
  app.post('/contact', function (req, res, next) {
    // Parse the body
    var info = {'page': 'contact'},
        body = req.body,
        message = "";

    // Compose the text message
    message += "Name: " + body.name + "\n";
    message += "Info: " + body.info + "\n";
    message += "Message: " + body.message + "";

    // Send a message to todd
    emailServer.send({
      'text': message,
      'from': 'No Reply <no-reply@twolfson.com>',
      'to': 'Todd Wolfson <todd@twolfson.com>',
      'subject': 'Incoming query from twolfson.com'
    }, function (err, message) {
      info.emailStatus = !err;
      res.render('contact', info);
    });
  });

  // If we are in development, add a kaleidoscope test page
  if (config.inDevelopment) {
    app.get('/kaleido', function (req, res, next) {
      res.render('kaleido', {layout: false});
    });
  }

  // Expose a health page
  var pkg = require('../package'),
      pkgVersion = pkg.version;
  app.get('/health', function (req, res) {
    var retObj = {
          'version': pkgVersion,
          'uptime': process.uptime(),
          'memory': process.memoryUsage(),
          'pid': process.pid
        };
    res.send(retObj);
  });

  // If the page is not found, throw an error and redirect to the 404 page
  app.all('*', function (req, res) {
    res.render('404', {'status': 404, 'page': '404'});
  });
};<commit_msg>Added LICENSE page<commit_after>// Load in dependencies
var fs = require('fs'),
    express = require('express'),
    config = require('./config');

// Export our app bindings
module.exports = function (app) {
  // Portfolio page
  var projects = require('./projects'),
      intword = require('./humanize.intword.js');
  projects.page = 'projects';
  projects.intword = intword;
  app.get('/projects', function (req, res) {
    res.render('projects', projects);
  });

  // If we are in development, add a contact/test page
  if (config.inDevelopment) {
    app.get('/contact', function (req, res, next) {
      var query = req.query || {},
          test = query.test;

      // If there is a test query, render the proper response
      if (test) {
        var emailStatus = test !== 'fail';
        res.render('contact', {'page': 'contact', 'emailStatus': emailStatus});
      } else {
      // Otherwise, continue
        next();
      }
    });
  }

  // Contact page (initial view)
  app.get('/contact', function (req, res) {
    res.render('contact', {'page': 'contact'});
  });

  // Set up email server interaction
  var email = require('emailjs'),
      emailConf = require('../mail.conf'),
      emailServer = email.server.connect(emailConf);

  // Contact page (submission)
  app.post('/contact', express.bodyParser());
  app.post('/contact', function (req, res, next) {
    // Parse the body
    var info = {'page': 'contact'},
        body = req.body,
        message = "";

    // Compose the text message
    message += "Name: " + body.name + "\n";
    message += "Info: " + body.info + "\n";
    message += "Message: " + body.message + "";

    // Send a message to todd
    emailServer.send({
      'text': message,
      'from': 'No Reply <no-reply@twolfson.com>',
      'to': 'Todd Wolfson <todd@twolfson.com>',
      'subject': 'Incoming query from twolfson.com'
    }, function (err, message) {
      info.emailStatus = !err;
      res.render('contact', info);
    });
  });

  // If we are in development, add a kaleidoscope test page
  if (config.inDevelopment) {
    app.get('/kaleido', function (req, res, next) {
      res.render('kaleido', {layout: false});
    });
  }

  // Render a LICENSE page
  app.get('/license', function (req, res, next) {
    fs.readFile(__dirname + '/../LICENSE-MIT', 'utf8', function (err, license) {
      // If there was an error, continue
      if (err) {
        return next(err);
      }

      // Otherwise, render the license
      res.render('license', {page: 'license', license: license});
    });
  });

  // Expose a health page
  var pkg = require('../package'),
      pkgVersion = pkg.version;
  app.get('/health', function (req, res) {
    var retObj = {
          'version': pkgVersion,
          'uptime': process.uptime(),
          'memory': process.memoryUsage(),
          'pid': process.pid
        };
    res.send(retObj);
  });

  // If the page is not found, throw an error and redirect to the 404 page
  app.all('*', function (req, res) {
    res.render('404', {'status': 404, 'page': '404'});
  });
};<|endoftext|>


<commit_before>'use strict';

const spawn = require('child_process').spawn;

class Runner {

  constructor() {
    this.MODELER_ARGS = '/file:{path}';
  }

  _spawn(exe, arg) {
    var child = spawn(exe, arg ? arg : [], {
      detached: true
    });
    child.unref();
    process.exit(0);
  }

  run(exe, file, flags) {
    const args = [];
    if (flags && flags.length) {
      args = flags;
    }
    const spawnArgs = args.concat([file]);
    this._spawn(exe, spawnArgs);
  }

  runVersionSelector(exe, file) {
    if (file) {
      var arg = this.MODELER_ARGS.replace('{path}', file);
      this._spawn(exe, arg);
    } else {
      this._spawn(exe, null);
    }

  }
}

module.exports = new Runner();
<commit_msg>Bugfix<commit_after>'use strict';

const spawn = require('child_process').spawn;

class Runner {

  constructor() {
    this.MODELER_ARGS = '/file:{path}';
  }

  _spawn(exe, arg) {
    var child = spawn(exe, arg ? arg : [], {
      detached: true
    });
    child.unref();
    process.exit(0);
  }

  run(exe, file, flags) {
    let args = [];
    if (flags && flags.length) {
      args = flags;
    }
    const spawnArgs = args.concat([file]);
    this._spawn(exe, spawnArgs);
  }

  runVersionSelector(exe, file) {
    if (file) {
      var arg = this.MODELER_ARGS.replace('{path}', file);
      this._spawn(exe, arg);
    } else {
      this._spawn(exe, null);
    }

  }
}

module.exports = new Runner();
<|endoftext|>