<commit_before>"use strict";

// Use gpf library (source version)
global.gpfSourcesPath = "./src/";
require("../src/boot.js");

const
    fs = require("fs"),
    CoverageReport = require("./coverage"),
    sources = ["boot"].concat(
        JSON.parse(fs.readFileSync("./src/sources.json"))
            .filter(source => source.load !== false)
            .map(source => source.name)
    ),
    configuredMetrics = JSON.parse(fs.readFileSync("tmp/config.json")).metrics,
    releaseMetrics = {},
    pad = (value, length) => value + new Array(length + 1).join(" ").substr(value.length),

    safeCoverage = process.argv.some(arg => arg === "safeCoverage");

//region Istanbul coverage

const
    coverageReport = new CoverageReport(JSON.parse(fs.readFileSync("tmp/coverage/reports/coverage.json"))),
    globalCoverage = coverageReport.getGlobal(),
    coverageParts = ["statements", "functions", "branches"];
let
    hasCoverageError = false;

sources.forEach(sourceName => {
    const
        fileCoverage = coverageReport.get(sourceName),
        fileTrace = [pad(sourceName, 34)];
    let
        fileIsKO = false;
    if (fileCoverage) {
        coverageParts.forEach(coveragePart => {
            let ratio = fileCoverage[coveragePart].getCoverageRatio(true);
            if (ratio < configuredMetrics.coverage[coveragePart]) {
                fileIsKO = true && !safeCoverage;
            }
            if (ratio === 100) {
                ratio = "   ";
            } else {
                ratio += "%";
            }
            fileTrace.push(coveragePart, ": ", ratio, " ");
        });
    } else {
        fileTrace.push(" - ignored -");
    }
    if (fileIsKO) {
        console.error(fileTrace.join(""));
        hasCoverageError = true;
    } else {
        console.log(fileTrace.join(""));
    }
});

releaseMetrics.coverage = {
    statements: {
        total: globalCoverage.statements.getCoverageRatio(),
        ignored: globalCoverage.statements.getIgnoredRatio()
    },
    functions: {
        total: globalCoverage.functions.getCoverageRatio(),
        ignored: globalCoverage.functions.getIgnoredRatio()
    },
    branches: {
        total: globalCoverage.branches.getCoverageRatio(),
        ignored: globalCoverage.branches.getIgnoredRatio()
    }
};

coverageParts.forEach(coveragePart => {
    console.log(`${pad(coveragePart + ":", 27)}${globalCoverage[coveragePart].getCoverageRatio(true)}%`
        + ` (ignored ${globalCoverage[coveragePart].getIgnoredRatio(true)}%)`);
});

//endregion

//region Plato info

const
    platoData = JSON.parse(fs.readFileSync("tmp/plato/report.json")),
    platoSummary = platoData.summary;
let
    hasMaintainabilityError = false;

releaseMetrics.maintainability = parseFloat(platoSummary.average.maintainability);
releaseMetrics.lines = {total: platoSummary.total.sloc, average: platoSummary.average.sloc};

platoData.reports.forEach(reportData => {
    const
        fileName = reportData.info.file,
        sourceName = fileName.substr(4, fileName.length - 7),
        fileTrace = [pad(sourceName, 34)],
        maintainability = reportData.complexity.maintainability;
    let
        fileIsKO = false;
    fileTrace.push("maintainability: ", Math.floor(100 * maintainability) / 100);
    if (maintainability < configuredMetrics.maintainability) {
        fileIsKO = true;
    }
    if (fileIsKO) {
        console.error(fileTrace.join(""));
        hasMaintainabilityError = true;
    } else {
        console.log(fileTrace.join(""));
    }
});

console.log(`Average maintainability:   ${releaseMetrics.maintainability}`);
console.log(`Lines of code:             ${releaseMetrics.lines.total}`);
console.log(`Average per module:        ${releaseMetrics.lines.average}`);

if (hasCoverageError || hasMaintainabilityError) {
    process.exit(-1); // Coverage error
}

//endregion

//region mochaTest output

const
    mochaTestData = JSON.parse(fs.readFileSync("tmp/coverage/mochaTest.json")),
    pendingTests = mochaTestData.stats.pending,
    testDuration = mochaTestData.stats.duration;

releaseMetrics.tests = mochaTestData.stats.tests;

console.log(`Number of tests:           ${releaseMetrics.tests}`);
console.log(`Number of pending tests:   ${pendingTests}`);
console.log(`Time to execute the tests: ${testDuration}ms`);

//endregion

releaseMetrics.sources = sources.length;

console.log(`Number of modules:         ${releaseMetrics.sources}`);

const
    SEPARATOR = "------ | ----- | ----- | ----- | -----",
    readme = fs.readFileSync("README.md").toString(),
    readmeSections = readme.split("##");
let
    metricsSectionIndex,
    metricsSectionHeader,
    metricsSection;

readmeSections.every((section, index) => {
    if (0 === section.indexOf(" Metrics")) {
        metricsSectionIndex = index;
        return false;
    }
    return true;
});

metricsSectionHeader = readmeSections[metricsSectionIndex].split(SEPARATOR)[0];
metricsSection = [
    `\r\nStatements coverage|${releaseMetrics.coverage.statements.total}%||${configuredMetrics.coverage.statements}%|*`,
    `${releaseMetrics.coverage.statements.ignored}% ignored*`,
    `\r\nBranches coverage|${releaseMetrics.coverage.branches.total}%||${configuredMetrics.coverage.branches}%|*`,
    `${releaseMetrics.coverage.branches.ignored}% ignored*`,
    `\r\nFunctions coverage|${releaseMetrics.coverage.functions.total}%||${configuredMetrics.coverage.functions}%|*`,
    `${releaseMetrics.coverage.functions.ignored}% ignored*`,
    `\r\nMaintainability|${releaseMetrics.maintainability}||${configuredMetrics.maintainability}|`,
    `\r\nNumber of tests||${releaseMetrics.tests}||*pending: ${pendingTests}, duration: ${testDuration}ms*`,
    `\r\nNumber of sources||${releaseMetrics.sources}||`,
    `\r\nLines of code|${releaseMetrics.lines.average}|${releaseMetrics.lines.total}||`,
    "\r\n\r\n"
];
readmeSections[metricsSectionIndex] = metricsSectionHeader + SEPARATOR + metricsSection.join("");
fs.writeFileSync("README.md", readmeSections.join("##"));

fs.writeFileSync("tmp/releaseMetrics.json", JSON.stringify(releaseMetrics));

process.exit(0); // OK
<commit_msg>!yoda style (#280)<commit_after>"use strict";

// Use gpf library (source version)
global.gpfSourcesPath = "./src/";
require("../src/boot.js");

const
    fs = require("fs"),
    CoverageReport = require("./coverage"),
    sources = ["boot"].concat(
        JSON.parse(fs.readFileSync("./src/sources.json"))
            .filter(source => source.load !== false)
            .map(source => source.name)
    ),
    configuredMetrics = JSON.parse(fs.readFileSync("tmp/config.json")).metrics,
    releaseMetrics = {},
    pad = (value, length) => value + new Array(length + 1).join(" ").substr(value.length),

    safeCoverage = process.argv.some(arg => arg === "safeCoverage");

//region Istanbul coverage

const
    coverageReport = new CoverageReport(JSON.parse(fs.readFileSync("tmp/coverage/reports/coverage.json"))),
    globalCoverage = coverageReport.getGlobal(),
    coverageParts = ["statements", "functions", "branches"];
let
    hasCoverageError = false;

sources.forEach(sourceName => {
    const
        fileCoverage = coverageReport.get(sourceName),
        fileTrace = [pad(sourceName, 34)];
    let
        fileIsKO = false;
    if (fileCoverage) {
        coverageParts.forEach(coveragePart => {
            let ratio = fileCoverage[coveragePart].getCoverageRatio(true);
            if (ratio < configuredMetrics.coverage[coveragePart]) {
                fileIsKO = true && !safeCoverage;
            }
            if (ratio === 100) {
                ratio = "   ";
            } else {
                ratio += "%";
            }
            fileTrace.push(coveragePart, ": ", ratio, " ");
        });
    } else {
        fileTrace.push(" - ignored -");
    }
    if (fileIsKO) {
        console.error(fileTrace.join(""));
        hasCoverageError = true;
    } else {
        console.log(fileTrace.join(""));
    }
});

releaseMetrics.coverage = {
    statements: {
        total: globalCoverage.statements.getCoverageRatio(),
        ignored: globalCoverage.statements.getIgnoredRatio()
    },
    functions: {
        total: globalCoverage.functions.getCoverageRatio(),
        ignored: globalCoverage.functions.getIgnoredRatio()
    },
    branches: {
        total: globalCoverage.branches.getCoverageRatio(),
        ignored: globalCoverage.branches.getIgnoredRatio()
    }
};

coverageParts.forEach(coveragePart => {
    console.log(`${pad(coveragePart + ":", 27)}${globalCoverage[coveragePart].getCoverageRatio(true)}%`
        + ` (ignored ${globalCoverage[coveragePart].getIgnoredRatio(true)}%)`);
});

//endregion

//region Plato info

const
    platoData = JSON.parse(fs.readFileSync("tmp/plato/report.json")),
    platoSummary = platoData.summary;
let
    hasMaintainabilityError = false;

releaseMetrics.maintainability = parseFloat(platoSummary.average.maintainability);
releaseMetrics.lines = {total: platoSummary.total.sloc, average: platoSummary.average.sloc};

platoData.reports.forEach(reportData => {
    const
        fileName = reportData.info.file,
        sourceName = fileName.substr(4, fileName.length - 7),
        fileTrace = [pad(sourceName, 34)],
        maintainability = reportData.complexity.maintainability;
    let
        fileIsKO = false;
    fileTrace.push("maintainability: ", Math.floor(100 * maintainability) / 100);
    if (maintainability < configuredMetrics.maintainability) {
        fileIsKO = true;
    }
    if (fileIsKO) {
        console.error(fileTrace.join(""));
        hasMaintainabilityError = true;
    } else {
        console.log(fileTrace.join(""));
    }
});

console.log(`Average maintainability:   ${releaseMetrics.maintainability}`);
console.log(`Lines of code:             ${releaseMetrics.lines.total}`);
console.log(`Average per module:        ${releaseMetrics.lines.average}`);

if (hasCoverageError || hasMaintainabilityError) {
    process.exit(-1); // Coverage error
}

//endregion

//region mochaTest output

const
    mochaTestData = JSON.parse(fs.readFileSync("tmp/coverage/mochaTest.json")),
    pendingTests = mochaTestData.stats.pending,
    testDuration = mochaTestData.stats.duration;

releaseMetrics.tests = mochaTestData.stats.tests;

console.log(`Number of tests:           ${releaseMetrics.tests}`);
console.log(`Number of pending tests:   ${pendingTests}`);
console.log(`Time to execute the tests: ${testDuration}ms`);

//endregion

releaseMetrics.sources = sources.length;

console.log(`Number of modules:         ${releaseMetrics.sources}`);

const
    SEPARATOR = "------ | ----- | ----- | ----- | -----",
    readme = fs.readFileSync("README.md").toString(),
    readmeSections = readme.split("##");
let
    metricsSectionIndex,
    metricsSectionHeader,
    metricsSection;

readmeSections.every((section, index) => {
    if (section.indexOf(" Metrics") === 0) {
        metricsSectionIndex = index;
        return false;
    }
    return true;
});

metricsSectionHeader = readmeSections[metricsSectionIndex].split(SEPARATOR)[0];
metricsSection = [
    `\r\nStatements coverage|${releaseMetrics.coverage.statements.total}%||${configuredMetrics.coverage.statements}%|*`,
    `${releaseMetrics.coverage.statements.ignored}% ignored*`,
    `\r\nBranches coverage|${releaseMetrics.coverage.branches.total}%||${configuredMetrics.coverage.branches}%|*`,
    `${releaseMetrics.coverage.branches.ignored}% ignored*`,
    `\r\nFunctions coverage|${releaseMetrics.coverage.functions.total}%||${configuredMetrics.coverage.functions}%|*`,
    `${releaseMetrics.coverage.functions.ignored}% ignored*`,
    `\r\nMaintainability|${releaseMetrics.maintainability}||${configuredMetrics.maintainability}|`,
    `\r\nNumber of tests||${releaseMetrics.tests}||*pending: ${pendingTests}, duration: ${testDuration}ms*`,
    `\r\nNumber of sources||${releaseMetrics.sources}||`,
    `\r\nLines of code|${releaseMetrics.lines.average}|${releaseMetrics.lines.total}||`,
    "\r\n\r\n"
];
readmeSections[metricsSectionIndex] = metricsSectionHeader + SEPARATOR + metricsSection.join("");
fs.writeFileSync("README.md", readmeSections.join("##"));

fs.writeFileSync("tmp/releaseMetrics.json", JSON.stringify(releaseMetrics));

process.exit(0); // OK
<|endoftext|>


<commit_before>var keys      = require('mout/object/keys');
var guid      = require('mout/random/guid');
var forIn     = require('mout/object/forIn');
var util      = require('util');

var ubkServer = require('ubk/server');
var Class     = require('uclass');
var min         = require('mout/object/min');
var indexOf     = require('nyks/object/indexOf');
var map         = require('mout/object/map');
var merge       = require('mout/object/merge');
var forOwn      = require('mout/object/forOwn');

var NS_mas4h = "mas4h";

var Server = new Class({
  Extends : ubkServer,

  Binds : ['new_link', '_expand_slave'],

    //current sessions
  lnks : {},
  slaves : {}, //for ubk clients binding
  reservedLnks : {},

  initialize:function(options) {
    var self = this;

    Server.parent.initialize.call(this, options);

    self.register_cmd(NS_mas4h, "instance_ready", function(client, query){
      if(self.slaves[client.client_key])
        return;

      console.log("GOT READY", client);
      client.remote_port = query.args[0];
      self.slaves[client.client_key] = client;
    });

    self.register_rpc(NS_mas4h, "validate_device", this.validate_device);

    self.register_cmd(NS_mas4h, "new_tunnel", function(slave, query){
      console.log("Trying to open new lnk", slave.client_key, query);
      var device_key = query.args[0], port = query.args[1];
      self.lnks[device_key] = { instance : slave, port : port };
      slave.respond(query, [null, port]);

      self.emit(util.format("%s:%s", NS_mas4h, "new_tunnel"), device_key);
    });

    self.register_rpc(NS_mas4h, "lost_tunnel", function(device_key, chain){
      console.log("Lost client ", device_key);
      delete self.lnks[device_key];
      chain();

      self.emit(util.format("%s:%s", NS_mas4h, "lost_tunnel"), device_key);
    });

    //when an instance is gone, we can assume all existings lnks are dead
    this.on("base:unregistered_client", function(client){
      delete self.slaves[client.client_key];
      forIn(self.lnks, function(lnk, lnk_id){

        if(lnk.instance.client_key == client.client_key) {
          console.log("Cleaning up deprecated lnk %s", lnk_id);
          delete self.lnks[lnk_id];
        }
      });
    });
  },

  get_lnks_stats : function() {

    var self = this;

      //send new links to less busy node
    var links = map(self.slaves, function(v, k){ return self.reservedLnks[k] || 0 ; }) ;

    forOwn(self.lnks, function(lnk){
      links[lnk.instance.client_key] ++;
    });
    return links;
  },

    //pick a random target from slaves list
  new_link : function(chain){

    var self = this;

    var links = self.get_lnks_stats();

    var slave_id = indexOf(links, min(links)), slave = self.slaves[slave_id];
    console.log("Choosing slave_id : %s over ", slave_id, links);

    if(!slave_id)
      return chain("No available slave");

    if(!self.reservedLnks[slave_id])
      self.reservedLnks[slave_id] = 0;

    self.reservedLnks[slave_id] ++;
    setTimeout(function(){
      self.reservedLnks[slave_id] --;
    }, 2500);

    var lnk = {
      public_port : slave.slave_config.public_port,
      host : slave.slave_config.public_addr,
      port : 16666 //like we care
    };

    chain(null, lnk);
  },

  _expand_slave : function(slave){
    var links = this.get_lnks_stats();
    return merge({'slave_config' : slave.slave_config, 'links' : links[slave.client_key] }, slave.export_json());
  },

});

module.exports = Server;
<commit_msg>mster to es6 style<commit_after>'use strict';

const util        = require('util');
const min         = require('mout/object/min');
const indexOf     = require('nyks/object/indexOf');
const map         = require('mout/object/map');
const merge       = require('mout/object/merge');
const forOwn      = require('mout/object/forOwn');

const ubkServer = require('ubk/server');

const NS_mas4h = "mas4h";

class Server extends ubkServer{
  constructor(options){
    super(options)
    this.lnks         = {};
    this.slaves       = {};
    this.reservedLnks = {};
    this.register_cmd(NS_mas4h, "instance_ready", (client, query) => {
      if(this.slaves[client.client_key])
        return;
      console.log("GOT READY", client);
      client.remote_port = query.args[0];
      this.slaves[client.client_key] = client;
    });

    this.register_cmd(NS_mas4h, "new_tunnel", (slave, query) => {
      console.log("Trying to open new lnk", slave.client_key, query);
      var device_key = query.args[0], port = query.args[1];
      this.lnks[device_key] = { instance : slave, port : port };
      slave.respond(query, [null, port]);

      this.emit(util.format("%s:%s", NS_mas4h, "new_tunnel"), device_key);
    });

    this.register_rpc(NS_mas4h, "validate_device", this.validate_device.bind(this));

    this.register_rpc(NS_mas4h, "lost_tunnel", (device_key, chain) => {
      console.log("Lost client ", device_key);
      delete this.lnks[device_key];
      chain();
      this.emit(util.format("%s:%s", NS_mas4h, "lost_tunnel"), device_key);
    });

    //when an instance is gone, we can assume all existings lnks are dead
    this.on("base:unregistered_client", (client) => {
      delete this.slaves[client.client_key];
      forIn(this.lnks, function(lnk, lnk_id){
        if(lnk.instance.client_key == client.client_key) {
          console.log("Cleaning up deprecated lnk %s", lnk_id);
          delete this.lnks[lnk_id];
        }
      });
    });
  }

  get_lnks_stats() {
    //send new links to less busy node
    var links = map(this.slaves, (v, k) => { return this.reservedLnks[k] || 0 ; }) ;
    forOwn(this.lnks, function(lnk){
      links[lnk.instance.client_key] ++;
    });
    return links;
  }

  //pick a random target from slaves list
  new_link(chain){
    var links = this.get_lnks_stats();
    var slave_id = indexOf(links, min(links)), slave = this.slaves[slave_id];
    console.log("Choosing slave_id : %s over ", slave_id, links);

    if(!slave_id)
      return chain("No available slave");

    if(!this.reservedLnks[slave_id])
    this.reservedLnks[slave_id] = 0;

    this.reservedLnks[slave_id] ++;
    setTimeout(() => {
      this.reservedLnks[slave_id] --;
    }, 2500);

    var lnk = {
      public_port : slave.slave_config.public_port,
      host : slave.slave_config.public_addr,
      port : 16666 //like we care
    };

    chain(null, lnk);
  }

  _expand_slave(slave){
    var links = this.get_lnks_stats();
    return merge({'slave_config' : slave.slave_config, 'links' : links[slave.client_key] }, slave.export_json());
  }

}

module.exports = Server;
<|endoftext|>


<commit_before>DIRECT_PROPERTIES = ["name", "length", "digits", "dashes"];
SCORE_PROPERTIES = ["english", "spanish", "french", "german",
					"prefix", "suffix"];
TLD_PROPERTIES = ["com", "net", "org", "biz", "info"];
SEARCH_LENGTHS = [7, 8, 6, 9, 5, 10, 4, 11, 3, 12]

function form_weights() {
	return {"length": $("input#id_len").val(),
			"digits": $("input#id_digits").val(),
			"dashes": $("input#id_dashes").val(),
			"english": $("input#id_english").val() / 1000000,
			"spanish": $("input#id_spanish").val() / 1000000,
			"french": $("input#id_french").val() / 1000000,
			"german": $("input#id_german").val() / 1000000,
			"prefix": $("input#id_prefix").val() / 1000000,
			"suffix": $("input#id_suffix").val() / 1000000,
			"com": $("input#id_com").val(),
			"net": $("input#id_net").val(),
			"org": $("input#id_org").val(),
			"biz": $("input#id_biz").val(),
			"info": $("input#id_info").val()}
}

function domain_score(domain, weights) {
	var score = 0.0;
	for (attr in weights)
		score += domain[attr] * weights[attr];
	return score;
}

function table_row(domain, row) {
	var html = '
';
	var index;
	for (index in DIRECT_PROPERTIES) {
		html += '' + domain[DIRECT_PROPERTIES[index]] + '	';
	}
	for (index in SCORE_PROPERTIES) {
		var score = domain[SCORE_PROPERTIES[index]] / 1000000;
		html += '' + score.toFixed(3) + '	';
	}
	for (index in TLD_PROPERTIES) {
		if (domain[TLD_PROPERTIES[index]])
			html += 'free	';
		else
			html += 'taken	';
	}
	html += '' + domain.score.toFixed(1) + '	';
	html += '
';
	return html;
}

function update_html() {
	var html = '';
	var row = 1;
	var names = [];
	for (name in $.domains) names.push(name);
	names.sort(function(a,b) {
		return $.domains[b].score - $.domains[a].score });
	names.length = 100;
	for (index in names) {
		domain = $.domains[names[index]];
		html += table_row(domain, row);
		row = (row % 2) + 1;
	}
	$("tbody#results").html(html);
	$("tbody tr").hover(
		function() { $(this).addClass("hover"); },
		function() { $(this).removeClass("hover"); });
}

function keyword_match(left, right, name) {
	if (left && name.substr(0, left.length) != left) return false;
	if (right && name.substr(-right.length) != right) return false;
	return true;
}

function ajax_result(json, status) {
	var left = $("input#id_left").val();
	var right = $("input#id_right").val();
	var weights = form_weights();
	var length = 0;
	for (name in json) {
		domain = json[name];
		domain.name = name;
		domain.length = name.length;
		domain.score = domain_score(domain, weights);
		if (keyword_match(left, right, name))
			$.domains[name] = domain;
		length = name.length;
	}
	$.ajax_search.xhr[length] = false;
	update_html();
}

function ajax_search(left, right) {
	if ($.ajax_search.left == left && $.ajax_search.right == right) return;
	$.ajax_search.left = left;
	$.ajax_search.right = right;
	for (var index in SEARCH_LENGTHS) {
		var length = SEARCH_LENGTHS[index];
		if ($.ajax_search.xhr[length])
			$.ajax_search.xhr[length].abort();
		$.ajax_search.xhr[length] = $.ajax({
				type: "GET",
				url: "/search/json/",
				data: {left: left, right: right, length: length},
				dataType: "json",
				cache: true,
				success: ajax_result,
			});
	}
}

function keyword_keypress(e) {
	if ((e.which != 45) &&
		(e.which < 48 || e.which > 57) &&
		(e.which < 97 || e.which > 122)) return;
	var left = $("input#id_left").val();
	var right = $("input#id_right").val();
	var updated =
		this.value.substr(0, this.selectionStart) +
		String.fromCharCode(e.which) +
		this.value.substr(this.selectionEnd);
	if (this.name == 'left') left = updated;
	else if (this.name == 'right') right = updated;
	for (name in $.domains)
		if (!keyword_match(left, right, name))
			delete $.domains[name];
	update_html();
	ajax_search(left, right);
}

function keyword_keyup() {
	var left = $("input#id_left").val();
	var right = $("input#id_right").val();
	ajax_search(left, right);
}

function document_ready() {
	$.domains = {};
	$.ajax_search = {};
	$.ajax_search.xhr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
	$.ajax_search.left = $("input#id_left").val();
	$.ajax_search.right = $("input#id_right").val();
	$("input.keyword").keypress(keyword_keypress);
	$("input.keyword").keyup(keyword_keyup);
}

$(document).ready(document_ready);
<commit_msg>Update HTTML only if new domains were added, and don't query server for names shorter than either keyword.<commit_after>DIRECT_PROPERTIES = ["name", "length", "digits", "dashes"];
SCORE_PROPERTIES = ["english", "spanish", "french", "german",
					"prefix", "suffix"];
TLD_PROPERTIES = ["com", "net", "org", "biz", "info"];
SEARCH_LENGTHS = [7, 8, 6, 9, 5, 10, 4, 11, 3, 12]

function form_weights() {
	return {"length": $("input#id_len").val(),
			"digits": $("input#id_digits").val(),
			"dashes": $("input#id_dashes").val(),
			"english": $("input#id_english").val() / 1000000,
			"spanish": $("input#id_spanish").val() / 1000000,
			"french": $("input#id_french").val() / 1000000,
			"german": $("input#id_german").val() / 1000000,
			"prefix": $("input#id_prefix").val() / 1000000,
			"suffix": $("input#id_suffix").val() / 1000000,
			"com": $("input#id_com").val(),
			"net": $("input#id_net").val(),
			"org": $("input#id_org").val(),
			"biz": $("input#id_biz").val(),
			"info": $("input#id_info").val()}
}

function domain_score(domain, weights) {
	var score = 0.0;
	for (attr in weights)
		score += domain[attr] * weights[attr];
	return score;
}

function table_row(domain, row) {
	var html = '
';
	var index;
	for (index in DIRECT_PROPERTIES) {
		html += '' + domain[DIRECT_PROPERTIES[index]] + '	';
	}
	for (index in SCORE_PROPERTIES) {
		var score = domain[SCORE_PROPERTIES[index]] / 1000000;
		html += '' + score.toFixed(3) + '	';
	}
	for (index in TLD_PROPERTIES) {
		if (domain[TLD_PROPERTIES[index]])
			html += 'free	';
		else
			html += 'taken	';
	}
	html += '' + domain.score.toFixed(1) + '	';
	html += '
';
	return html;
}

function update_html() {
	var html = '';
	var row = 1;
	var names = [];
	for (name in $.domains) names.push(name);
	names.sort(function(a,b) {
		return $.domains[b].score - $.domains[a].score });
	names.length = 100;
	for (index in names) {
		domain = $.domains[names[index]];
		html += table_row(domain, row);
		row = (row % 2) + 1;
	}
	$("tbody#results").html(html);
	$("tbody tr").hover(
		function() { $(this).addClass("hover"); },
		function() { $(this).removeClass("hover"); });
}

function keyword_match(left, right, name) {
	if (left && name.substr(0, left.length) != left) return false;
	if (right && name.substr(-right.length) != right) return false;
	return true;
}

function ajax_result(json, status) {
	var left = $("input#id_left").val();
	var right = $("input#id_right").val();
	var weights = form_weights();
	var updated = false;
	var length = 0;
	for (name in json) {
		domain = json[name];
		domain.name = name;
		domain.length = name.length;
		domain.score = domain_score(domain, weights);
		if (keyword_match(left, right, name)) {
			$.domains[name] = domain;
			updated = true;
		}
		length = name.length;
	}
	$.ajax_search.xhr[length] = false;
	if (updated) update_html();
}

function ajax_search(left, right) {
	if ($.ajax_search.left == left && $.ajax_search.right == right) return;
	$.ajax_search.left = left;
	$.ajax_search.right = right;
	for (var index in SEARCH_LENGTHS) {
		var length = SEARCH_LENGTHS[index];
		if ($.ajax_search.xhr[length])
			$.ajax_search.xhr[length].abort();
		if (left.length > length || right.length > length)
			continue;
		$.ajax_search.xhr[length] = $.ajax({
				type: "GET",
				url: "/search/json/",
				data: {left: left, right: right, length: length},
				dataType: "json",
				cache: true,
				success: ajax_result,
			});
	}
}

function keyword_keypress(e) {
	if ((e.which != 45) &&
		(e.which < 48 || e.which > 57) &&
		(e.which < 97 || e.which > 122)) return;
	var left = $("input#id_left").val();
	var right = $("input#id_right").val();
	var updated =
		this.value.substr(0, this.selectionStart) +
		String.fromCharCode(e.which) +
		this.value.substr(this.selectionEnd);
	if (this.name == 'left') left = updated;
	else if (this.name == 'right') right = updated;
	for (name in $.domains)
		if (!keyword_match(left, right, name))
			delete $.domains[name];
	update_html();
	ajax_search(left, right);
}

function keyword_keyup() {
	var left = $("input#id_left").val();
	var right = $("input#id_right").val();
	ajax_search(left, right);
}

function document_ready() {
	$.domains = {};
	$.ajax_search = {};
	$.ajax_search.xhr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
	$.ajax_search.left = $("input#id_left").val();
	$.ajax_search.right = $("input#id_right").val();
	$("input.keyword").keypress(keyword_keypress);
	$("input.keyword").keyup(keyword_keyup);
}

$(document).ready(document_ready);
<|endoftext|>


<commit_before>CodeMirror.defineMode("xml", function(config, parserConfig) {
  var indentUnit = config.indentUnit;
  var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1;
  var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag || true;

  var Kludges = parserConfig.htmlMode ? {
    autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
                      'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
                      'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
                      'track': true, 'wbr': true},
    implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
                       'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
                       'th': true, 'tr': true},
    contextGrabbers: {
      'dd': {'dd': true, 'dt': true},
      'dt': {'dd': true, 'dt': true},
      'li': {'li': true},
      'option': {'option': true, 'optgroup': true},
      'optgroup': {'optgroup': true},
      'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
            'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
            'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
            'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
            'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
      'rp': {'rp': true, 'rt': true},
      'rt': {'rp': true, 'rt': true},
      'tbody': {'tbody': true, 'tfoot': true},
      'td': {'td': true, 'th': true},
      'tfoot': {'tbody': true},
      'th': {'td': true, 'th': true},
      'thead': {'tbody': true, 'tfoot': true},
      'tr': {'tr': true}
    },
    doNotIndent: {"pre": true},
    allowUnquoted: true,
    allowMissing: true
  } : {
    autoSelfClosers: {},
    implicitlyClosed: {},
    contextGrabbers: {},
    doNotIndent: {},
    allowUnquoted: false,
    allowMissing: false
  };
  var alignCDATA = parserConfig.alignCDATA;

  // Return variables for tokenizers
  var tagName, type, setStyle;

  function inText(stream, state) {
    function chain(parser) {
      state.tokenize = parser;
      return parser(stream, state);
    }

    var ch = stream.next();
    if (ch == "<") {
      if (stream.eat("!")) {
        if (stream.eat("[")) {
          if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
          else return null;
        } else if (stream.match("--")) {
          return chain(inBlock("comment", "-->"));
        } else if (stream.match("DOCTYPE", true, true)) {
          stream.eatWhile(/[\w\._\-]/);
          return chain(doctype(1));
        } else {
          return null;
        }
      } else if (stream.eat("?")) {
        stream.eatWhile(/[\w\._\-]/);
        state.tokenize = inBlock("meta", "?>");
        return "meta";
      } else {
        var isClose = stream.eat("/");
        tagName = "";
        var c;
        while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
        if (!tagName) return "tag error";
        type = isClose ? "closeTag" : "openTag";
        state.tokenize = inTag;
        return "tag";
      }
    } else if (ch == "&") {
      var ok;
      if (stream.eat("#")) {
        if (stream.eat("x")) {
          ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
        } else {
          ok = stream.eatWhile(/[\d]/) && stream.eat(";");
        }
      } else {
        ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
      }
      return ok ? "atom" : "error";
    } else {
      stream.eatWhile(/[^&<]/);
      return null;
    }
  }

  function inTag(stream, state) {
    var ch = stream.next();
    if (ch == ">" || (ch == "/" && stream.eat(">"))) {
      state.tokenize = inText;
      type = ch == ">" ? "endTag" : "selfcloseTag";
      return "tag";
    } else if (ch == "=") {
      type = "equals";
      return null;
    } else if (ch == "<") {
      state.tokenize = inText;
      state.state = baseState;
      state.tagName = state.tagStart = null;
      var next = state.tokenize(stream, state);
      return next ? next + " error" : "error";
    } else if (/[\'\"]/.test(ch)) {
      state.tokenize = inAttribute(ch);
      state.stringStartCol = stream.column();
      return state.tokenize(stream, state);
    } else {
      stream.eatWhile(/[^\s\u00a0=<>\"\']/);
      return "word";
    }
  }

  function inAttribute(quote) {
    var closure = function(stream, state) {
      while (!stream.eol()) {
        if (stream.next() == quote) {
          state.tokenize = inTag;
          break;
        }
      }
      return "string";
    };
    closure.isInAttribute = true;
    return closure;
  }

  function inBlock(style, terminator) {
    return function(stream, state) {
      while (!stream.eol()) {
        if (stream.match(terminator)) {
          state.tokenize = inText;
          break;
        }
        stream.next();
      }
      return style;
    };
  }
  function doctype(depth) {
    return function(stream, state) {
      var ch;
      while ((ch = stream.next()) != null) {
        if (ch == "<") {
          state.tokenize = doctype(depth + 1);
          return state.tokenize(stream, state);
        } else if (ch == ">") {
          if (depth == 1) {
            state.tokenize = inText;
            break;
          } else {
            state.tokenize = doctype(depth - 1);
            return state.tokenize(stream, state);
          }
        }
      }
      return "meta";
    };
  }

  function pushContext(state, tagName, startOfLine) {
    var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent);
    state.context = {
      prev: state.context,
      tagName: tagName,
      indent: state.indented,
      startOfLine: startOfLine,
      noIndent: noIndent
    };
  }
  function popContext(state) {
    if (state.context) state.context = state.context.prev;
  }
  function maybePopContext(state, nextTagName) {
    var parentTagName;
    while (true) {
      if (!state.context) {
        return;
      }
      parentTagName = state.context.tagName.toLowerCase();
      if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) ||
          !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
        return;
      }
      popContext();
    }
  }

  function baseState(type, stream, state) {
    if (type == "openTag") {
      state.tagName = tagName;
      state.tagStart = stream.column();
      return attrState;
    } else if (type == "closeTag") {
      var err = false;
      if (state.context) {
        if (state.context.tagName != tagName) {
          if (Kludges.implicitlyClosed.hasOwnProperty(state.context.tagName.toLowerCase()))
            popContext(state);
          err = !state.context || state.context.tagName != tagName;
        }
      } else {
        err = true;
      }
      if (err) setStyle = "error";
      return err ? closeStateErr : closeState;
    } else {
      return baseState;
    }
  }
  function closeState(type, _stream, state) {
    if (type != "endTag") {
      setStyle = "error";
      return closeState;
    }
    popContext(state);
    return baseState;
  }
  function closeStateErr(type, stream, state) {
    setStyle = "error";
    return closeState(type, stream, state);
  }

  function attrState(type, stream, state) {
    if (type == "word") {
      setStyle = "attribute";
      return attrEqState;
    } else if (type == "endTag" || type == "selfcloseTag") {
      var tagName = state.tagName, tagStart = state.tagStart;
      state.tagName = state.tagStart = null;
      if (type == "selfcloseTag" ||
          Kludges.autoSelfClosers.hasOwnProperty(tagName.toLowerCase())) {
        maybePopContext(state, tagName.toLowerCase());
      } else {
        maybePopContext(state, tagName.toLowerCase());
        pushContext(state, tagName, tagStart == stream.indentation());
      }
      return baseState;
    }
    setStyle = "error";
    return attrState;
  }
  function attrEqState(type, stream, state) {
    if (type == "equals") return attrValueState;
    if (!Kludges.allowMissing) setStyle = "error";
    else if (type == "word") { setStyle = "attribute"; return attrState; }
    return attrState(type, stream, state);
  }
  function attrValueState(type, stream, state) {
    if (type == "string") return attrContinuedState;
    if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return attrState;}
    setStyle = "error";
    return attrState(type, stream, state);
  }
  function attrContinuedState(type, stream, state) {
    if (type == "string") return attrContinuedState;
    return attrState(type, stream, state);
  }

  return {
    startState: function() {
      return {tokenize: inText,
              state: baseState,
              indented: 0,
              startOfLine: true,
              tagName: null, tagStart: null,
              context: null};
    },

    token: function(stream, state) {
      if (!state.tagName && stream.sol()) {
        state.startOfLine = true;
        state.indented = stream.indentation();
      }
      if (stream.eatSpace()) return null;
      tagName = type = null;
      var style = state.tokenize(stream, state);
      if ((style || type) && style != "comment") {
        setStyle = null;
        state.state = state.state(type || style, stream, state);
        if (setStyle)
          style = setStyle == "error" ? style + " error" : setStyle;
      }
      state.startOfLine = false;
      return style;
    },

    indent: function(state, textAfter, fullLine) {
      var context = state.context;
      // Indent multi-line strings (e.g. css).
      if (state.tokenize.isInAttribute) {
        return state.stringStartCol + 1;
      }
      if ((state.tokenize != inTag && state.tokenize != inText) ||
          context && context.noIndent)
        return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
      // Indent the starts of attribute names.
      if (state.tagName) {
        if (multilineTagIndentPastTag)
          return state.tagStart + state.tagName.length + 2;
        else
          return state.tagStart + indentUnit * multilineTagIndentFactor;
      }
      if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
      if (context && /^<\//.test(textAfter))
        context = context.prev;
      while (context && !context.startOfLine)
        context = context.prev;
      if (context) return context.indent + indentUnit;
      else return 0;
    },

    electricChars: "/",
    blockCommentStart: "<!--",
    blockCommentEnd: "-->",

    configuration: parserConfig.htmlMode ? "html" : "xml",
    helperType: parserConfig.htmlMode ? "html" : "xml"
  };
});

CodeMirror.defineMIME("text/xml", "xml");
CodeMirror.defineMIME("application/xml", "xml");
if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
  CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
<commit_msg>[xml mode] Fix bug introduced by a6aa48eee2c8262a8763f1e39afdf8a79a130a41<commit_after>CodeMirror.defineMode("xml", function(config, parserConfig) {
  var indentUnit = config.indentUnit;
  var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1;
  var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag || true;

  var Kludges = parserConfig.htmlMode ? {
    autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
                      'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
                      'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
                      'track': true, 'wbr': true},
    implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
                       'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
                       'th': true, 'tr': true},
    contextGrabbers: {
      'dd': {'dd': true, 'dt': true},
      'dt': {'dd': true, 'dt': true},
      'li': {'li': true},
      'option': {'option': true, 'optgroup': true},
      'optgroup': {'optgroup': true},
      'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
            'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
            'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
            'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
            'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
      'rp': {'rp': true, 'rt': true},
      'rt': {'rp': true, 'rt': true},
      'tbody': {'tbody': true, 'tfoot': true},
      'td': {'td': true, 'th': true},
      'tfoot': {'tbody': true},
      'th': {'td': true, 'th': true},
      'thead': {'tbody': true, 'tfoot': true},
      'tr': {'tr': true}
    },
    doNotIndent: {"pre": true},
    allowUnquoted: true,
    allowMissing: true
  } : {
    autoSelfClosers: {},
    implicitlyClosed: {},
    contextGrabbers: {},
    doNotIndent: {},
    allowUnquoted: false,
    allowMissing: false
  };
  var alignCDATA = parserConfig.alignCDATA;

  // Return variables for tokenizers
  var tagName, type, setStyle;

  function inText(stream, state) {
    function chain(parser) {
      state.tokenize = parser;
      return parser(stream, state);
    }

    var ch = stream.next();
    if (ch == "<") {
      if (stream.eat("!")) {
        if (stream.eat("[")) {
          if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
          else return null;
        } else if (stream.match("--")) {
          return chain(inBlock("comment", "-->"));
        } else if (stream.match("DOCTYPE", true, true)) {
          stream.eatWhile(/[\w\._\-]/);
          return chain(doctype(1));
        } else {
          return null;
        }
      } else if (stream.eat("?")) {
        stream.eatWhile(/[\w\._\-]/);
        state.tokenize = inBlock("meta", "?>");
        return "meta";
      } else {
        var isClose = stream.eat("/");
        tagName = "";
        var c;
        while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
        if (!tagName) return "tag error";
        type = isClose ? "closeTag" : "openTag";
        state.tokenize = inTag;
        return "tag";
      }
    } else if (ch == "&") {
      var ok;
      if (stream.eat("#")) {
        if (stream.eat("x")) {
          ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
        } else {
          ok = stream.eatWhile(/[\d]/) && stream.eat(";");
        }
      } else {
        ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
      }
      return ok ? "atom" : "error";
    } else {
      stream.eatWhile(/[^&<]/);
      return null;
    }
  }

  function inTag(stream, state) {
    var ch = stream.next();
    if (ch == ">" || (ch == "/" && stream.eat(">"))) {
      state.tokenize = inText;
      type = ch == ">" ? "endTag" : "selfcloseTag";
      return "tag";
    } else if (ch == "=") {
      type = "equals";
      return null;
    } else if (ch == "<") {
      state.tokenize = inText;
      state.state = baseState;
      state.tagName = state.tagStart = null;
      var next = state.tokenize(stream, state);
      return next ? next + " error" : "error";
    } else if (/[\'\"]/.test(ch)) {
      state.tokenize = inAttribute(ch);
      state.stringStartCol = stream.column();
      return state.tokenize(stream, state);
    } else {
      stream.eatWhile(/[^\s\u00a0=<>\"\']/);
      return "word";
    }
  }

  function inAttribute(quote) {
    var closure = function(stream, state) {
      while (!stream.eol()) {
        if (stream.next() == quote) {
          state.tokenize = inTag;
          break;
        }
      }
      return "string";
    };
    closure.isInAttribute = true;
    return closure;
  }

  function inBlock(style, terminator) {
    return function(stream, state) {
      while (!stream.eol()) {
        if (stream.match(terminator)) {
          state.tokenize = inText;
          break;
        }
        stream.next();
      }
      return style;
    };
  }
  function doctype(depth) {
    return function(stream, state) {
      var ch;
      while ((ch = stream.next()) != null) {
        if (ch == "<") {
          state.tokenize = doctype(depth + 1);
          return state.tokenize(stream, state);
        } else if (ch == ">") {
          if (depth == 1) {
            state.tokenize = inText;
            break;
          } else {
            state.tokenize = doctype(depth - 1);
            return state.tokenize(stream, state);
          }
        }
      }
      return "meta";
    };
  }

  function pushContext(state, tagName, startOfLine) {
    var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent);
    state.context = {
      prev: state.context,
      tagName: tagName,
      indent: state.indented,
      startOfLine: startOfLine,
      noIndent: noIndent
    };
  }
  function popContext(state) {
    if (state.context) state.context = state.context.prev;
  }
  function maybePopContext(state, nextTagName) {
    var parentTagName;
    while (true) {
      if (!state.context) {
        return;
      }
      parentTagName = state.context.tagName.toLowerCase();
      if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) ||
          !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
        return;
      }
      popContext(state);
    }
  }

  function baseState(type, stream, state) {
    if (type == "openTag") {
      state.tagName = tagName;
      state.tagStart = stream.column();
      return attrState;
    } else if (type == "closeTag") {
      var err = false;
      if (state.context) {
        if (state.context.tagName != tagName) {
          if (Kludges.implicitlyClosed.hasOwnProperty(state.context.tagName.toLowerCase()))
            popContext(state);
          err = !state.context || state.context.tagName != tagName;
        }
      } else {
        err = true;
      }
      if (err) setStyle = "error";
      return err ? closeStateErr : closeState;
    } else {
      return baseState;
    }
  }
  function closeState(type, _stream, state) {
    if (type != "endTag") {
      setStyle = "error";
      return closeState;
    }
    popContext(state);
    return baseState;
  }
  function closeStateErr(type, stream, state) {
    setStyle = "error";
    return closeState(type, stream, state);
  }

  function attrState(type, stream, state) {
    if (type == "word") {
      setStyle = "attribute";
      return attrEqState;
    } else if (type == "endTag" || type == "selfcloseTag") {
      var tagName = state.tagName, tagStart = state.tagStart;
      state.tagName = state.tagStart = null;
      if (type == "selfcloseTag" ||
          Kludges.autoSelfClosers.hasOwnProperty(tagName.toLowerCase())) {
        maybePopContext(state, tagName.toLowerCase());
      } else {
        maybePopContext(state, tagName.toLowerCase());
        pushContext(state, tagName, tagStart == stream.indentation());
      }
      return baseState;
    }
    setStyle = "error";
    return attrState;
  }
  function attrEqState(type, stream, state) {
    if (type == "equals") return attrValueState;
    if (!Kludges.allowMissing) setStyle = "error";
    else if (type == "word") { setStyle = "attribute"; return attrState; }
    return attrState(type, stream, state);
  }
  function attrValueState(type, stream, state) {
    if (type == "string") return attrContinuedState;
    if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return attrState;}
    setStyle = "error";
    return attrState(type, stream, state);
  }
  function attrContinuedState(type, stream, state) {
    if (type == "string") return attrContinuedState;
    return attrState(type, stream, state);
  }

  return {
    startState: function() {
      return {tokenize: inText,
              state: baseState,
              indented: 0,
              startOfLine: true,
              tagName: null, tagStart: null,
              context: null};
    },

    token: function(stream, state) {
      if (!state.tagName && stream.sol()) {
        state.startOfLine = true;
        state.indented = stream.indentation();
      }
      if (stream.eatSpace()) return null;
      tagName = type = null;
      var style = state.tokenize(stream, state);
      if ((style || type) && style != "comment") {
        setStyle = null;
        state.state = state.state(type || style, stream, state);
        if (setStyle)
          style = setStyle == "error" ? style + " error" : setStyle;
      }
      state.startOfLine = false;
      return style;
    },

    indent: function(state, textAfter, fullLine) {
      var context = state.context;
      // Indent multi-line strings (e.g. css).
      if (state.tokenize.isInAttribute) {
        return state.stringStartCol + 1;
      }
      if ((state.tokenize != inTag && state.tokenize != inText) ||
          context && context.noIndent)
        return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
      // Indent the starts of attribute names.
      if (state.tagName) {
        if (multilineTagIndentPastTag)
          return state.tagStart + state.tagName.length + 2;
        else
          return state.tagStart + indentUnit * multilineTagIndentFactor;
      }
      if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
      if (context && /^<\//.test(textAfter))
        context = context.prev;
      while (context && !context.startOfLine)
        context = context.prev;
      if (context) return context.indent + indentUnit;
      else return 0;
    },

    electricChars: "/",
    blockCommentStart: "<!--",
    blockCommentEnd: "-->",

    configuration: parserConfig.htmlMode ? "html" : "xml",
    helperType: parserConfig.htmlMode ? "html" : "xml"
  };
});

CodeMirror.defineMIME("text/xml", "xml");
CodeMirror.defineMIME("application/xml", "xml");
if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
  CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
<|endoftext|>


<commit_before>/**
 * Created by Administrator on 2015/4/18.
 */

var url = require('url');
//加密类
var crypto = require("crypto");
var mongoose = require('mongoose');
var shortid = require('shortid');
var Message = require('./Message');
var AdminUser = require("./AdminUser");
var UserNotify = require("../models/UserNotify");
var Content = require("../models/Content");
var ContentCategory = require("../models/ContentCategory");
var ContentTemplate = require("../models/ContentTemplate");

//站点配置
var settings = require("../models/db/settings");
var db = mongoose.connect('mongodb://localhost/doracms');
//mongoose.connect('mongodb://'+settings.USERNAME+':'+settings.PASSWORD+'@'+settings.HOST+':'+settings.PORT+'/'+settings.DB+'');

//信息删除操作

var DbOpt = {

    del : function(obj,req,res,logMsg){
        var params = url.parse(req.url,true);
        var targetId = params.query.uid;
        if(shortid.isValid(targetId)){
            obj.remove({_id : params.query.uid},function(err,result){
                if(err){
                    res.end(err);
                }else{
                    console.log(logMsg+" success!");
                    res.end("success");
                }
            })
        }else{
            res.end(settings.system_illegal_param);
        }

    },
    findAll : function(obj,req,res,logMsg){//查找指定对象所有记录
        obj.find({}, function (err,result) {
            if(err){
                res.next(err);
            }else{
                console.log(logMsg+" success!");
                return res.json(result);
            }
        })
    },
    findOne : function(obj,req,res,logMsg){ //根据ID查找单条记录
        var params = url.parse(req.url,true);
        var targetId = params.query.uid;
        if(shortid.isValid(targetId)){
            obj.findOne({_id : targetId}, function (err,result) {
                if(err){
                    res.next(err);
                }else{
                    console.log(logMsg+" success!");
                    return res.json(result);
                }
            })
        }else{
            res.end(settings.system_illegal_param);
        }

    },
    updateOneByID : function(obj,req,res,logMsg){
        var params = url.parse(req.url,true);
        var targetId = params.query.uid;

        if(shortid.isValid(targetId)){
            var conditions = {_id : targetId};
            req.body.updateDate = new Date();
            var update = {$set : req.body};
            obj.update(conditions, update, function (err,result) {
                if(err){
                    res.end(err);
                }else{
                    console.log(logMsg+" success!");
                    res.end("success");
                }
            })
        }else{
            res.end(settings.system_illegal_param);
        }

    },
    addOne : function(obj,req,res){
        var newObj = new obj(req.body);
        newObj.save(function(err){
            if(err){
                res.end(err);
            }else{
                res.end("success");
            }
        });
    },

    pagination : function(obj,req,res,conditions){

        var params = url.parse(req.url,true);
        var startNum = (params.query.currentPage - 1)*params.query.limit + 1;
        var currentPage = Number(params.query.currentPage);
        var limit = Number(params.query.limit);
        var pageInfo;

//    根据条件查询记录(如果有条件传递，则按条件查询)
        var query;
        if(conditions && conditions.length > 1){
            query=obj.find().or(conditions);
        }
        else if(conditions){
            query=obj.find(conditions);
        }
        else{
            query=obj.find({});
        }
        query.sort({'date': -1});

        if(obj === Message){
            query.populate('author').populate('replyAuthor').populate('adminAuthor');
        }else if(obj === AdminUser){
            query.populate('group');
        }else if(obj === UserNotify){
            query.populate('user').populate('notify');
        }else if(obj === Content){
            query.populate('category');
        }else if(obj === ContentCategory){
            query.populate('contentTemp');
        }else if(obj === ContentTemplate){
            query.populate('items');
        }

        query.exec(function(err,docs){
            if(err){
                console.log(err)

            }else {
                pageInfo = {
                    "totalItems" : docs.length,
                    "currentPage" : currentPage,
                    "limit" : limit,
                    "startNum" : Number(startNum)
                };

                return res.json({
                    docs : docs.slice(startNum - 1,startNum + limit -1),
                    pageInfo : pageInfo
                });
            }
        })
    },

    getPaginationResult : function(obj,req,res,q,filed){// 通用查询，带分页，注意参数传递格式,filed为指定字段
        var searchKey = req.query.searchKey;
        var page = parseInt(req.query.page);
        var limit = parseInt(req.query.limit);
        if (!page) page = 1;
        if (!limit) limit = 15;
        var order = req.query.order;
        var sq = {}, Str, A = 'problemID', B = 'asc';
        if (order) {    //是否有排序请求
            Str = order.split('_');
            A = Str[0]; B = Str[1];
            sq[A] = B;    //关联数组增加查询条件，更加灵活，因为A是变量
        } else {
            sq.date = -1;    //默认排序查询条件
        }

        var startNum = (page - 1)*limit;
        var resultList;
        var resultNum;
        if(q && q.length > 1){ // 多条件只要其中一条符合
            resultList = obj.find().or(q,filed).sort(sq).skip(startNum).limit(limit);
            resultNum = obj.find().or(q,filed).count();
        }else{
            resultList = obj.find(q,filed).sort(sq).skip(startNum).limit(limit);
            resultNum = obj.find(q,filed).count();
        }
        //        分页参数
        var pageInfo = {
            "totalItems" : resultNum,
            "currentPage" : page,
            "limit" : limit,
            "startNum" : startNum +1,
            "searchKey" : searchKey
        };
        var datasInfo = {
            docs : resultList,
            pageInfo : pageInfo
        };

        return datasInfo;
    },

    getDatasByParam : function(obj,req,res,q){// 通用查询list不带分页，注意参数传递格式,通过express-promise去掉了回调方式返回数据
//        默认查询所有记录，有条件顺带排序和查询部分记录
        var order = req.query.order;
        var limit = parseInt(req.query.limit);
        var sq = {}, Str, A = 'problemID', B = 'asc';
        if (order) {    //是否有排序请求
            Str = order.split('_');
            A = Str[0]; B = Str[1];
            sq[A] = B;    //关联数组增加查询条件，更加灵活，因为A是变量
        } else {
            sq.date = -1;    //默认排序查询条件
        }
        if(!limit){
            return obj.find(q).sort(sq);
        }else{
            return obj.find(q).sort(sq).skip(0).limit(limit);
        }

    },

    getKeyArrByTokenId : function(tokenId){
        var newLink = DbOpt.decrypt(tokenId,settings.encrypt_key);
        var keyArr = newLink.split('$');
        return keyArr;
    },

    getCount : function(obj,req,res,conditions){ // 查询指定对象的数量
        obj.count(conditions, function (err, count) {
            if (err){
                console.log(err);
            }else{
                return res.json({
                    count : count
                });
            }

        });
    },
    encrypt : function(data,key){ // 密码加密
        var cipher = crypto.createCipher("bf",key);
        var newPsd = "";
        newPsd += cipher.update(data,"utf8","hex");
        newPsd += cipher.final("hex");
        return newPsd;
    },
    decrypt : function(data,key){ //密码解密
        var decipher = crypto.createDecipher("bf",key);
        var oldPsd = "";
        oldPsd += decipher.update(data,"hex","utf8");
        oldPsd += decipher.final("utf8");
        return oldPsd;
    }
};

module.exports = DbOpt;<commit_msg>Update Dbopt.js<commit_after>/**
 * Created by Administrator on 2015/4/18.
 */

var url = require('url');
//加密类
var crypto = require("crypto");
var mongoose = require('mongoose');
var shortid = require('shortid');
var Message = require('./Message');
var AdminUser = require("./AdminUser");
var UserNotify = require("../models/UserNotify");
var Content = require("../models/Content");
var ContentCategory = require("../models/ContentCategory");
var ContentTemplate = require("../models/ContentTemplate");

//站点配置
var settings = require("../models/db/settings");
var db = mongoose.connect(settings.URL);
//mongoose.connect('mongodb://'+settings.USERNAME+':'+settings.PASSWORD+'@'+settings.HOST+':'+settings.PORT+'/'+settings.DB+'');

//信息删除操作

var DbOpt = {

    del : function(obj,req,res,logMsg){
        var params = url.parse(req.url,true);
        var targetId = params.query.uid;
        if(shortid.isValid(targetId)){
            obj.remove({_id : params.query.uid},function(err,result){
                if(err){
                    res.end(err);
                }else{
                    console.log(logMsg+" success!");
                    res.end("success");
                }
            })
        }else{
            res.end(settings.system_illegal_param);
        }

    },
    findAll : function(obj,req,res,logMsg){//查找指定对象所有记录
        obj.find({}, function (err,result) {
            if(err){
                res.next(err);
            }else{
                console.log(logMsg+" success!");
                return res.json(result);
            }
        })
    },
    findOne : function(obj,req,res,logMsg){ //根据ID查找单条记录
        var params = url.parse(req.url,true);
        var targetId = params.query.uid;
        if(shortid.isValid(targetId)){
            obj.findOne({_id : targetId}, function (err,result) {
                if(err){
                    res.next(err);
                }else{
                    console.log(logMsg+" success!");
                    return res.json(result);
                }
            })
        }else{
            res.end(settings.system_illegal_param);
        }

    },
    updateOneByID : function(obj,req,res,logMsg){
        var params = url.parse(req.url,true);
        var targetId = params.query.uid;

        if(shortid.isValid(targetId)){
            var conditions = {_id : targetId};
            req.body.updateDate = new Date();
            var update = {$set : req.body};
            obj.update(conditions, update, function (err,result) {
                if(err){
                    res.end(err);
                }else{
                    console.log(logMsg+" success!");
                    res.end("success");
                }
            })
        }else{
            res.end(settings.system_illegal_param);
        }

    },
    addOne : function(obj,req,res){
        var newObj = new obj(req.body);
        newObj.save(function(err){
            if(err){
                res.end(err);
            }else{
                res.end("success");
            }
        });
    },

    pagination : function(obj,req,res,conditions){

        var params = url.parse(req.url,true);
        var startNum = (params.query.currentPage - 1)*params.query.limit + 1;
        var currentPage = Number(params.query.currentPage);
        var limit = Number(params.query.limit);
        var pageInfo;

//    根据条件查询记录(如果有条件传递，则按条件查询)
        var query;
        if(conditions && conditions.length > 1){
            query=obj.find().or(conditions);
        }
        else if(conditions){
            query=obj.find(conditions);
        }
        else{
            query=obj.find({});
        }
        query.sort({'date': -1});

        if(obj === Message){
            query.populate('author').populate('replyAuthor').populate('adminAuthor');
        }else if(obj === AdminUser){
            query.populate('group');
        }else if(obj === UserNotify){
            query.populate('user').populate('notify');
        }else if(obj === Content){
            query.populate('category');
        }else if(obj === ContentCategory){
            query.populate('contentTemp');
        }else if(obj === ContentTemplate){
            query.populate('items');
        }

        query.exec(function(err,docs){
            if(err){
                console.log(err)

            }else {
                pageInfo = {
                    "totalItems" : docs.length,
                    "currentPage" : currentPage,
                    "limit" : limit,
                    "startNum" : Number(startNum)
                };

                return res.json({
                    docs : docs.slice(startNum - 1,startNum + limit -1),
                    pageInfo : pageInfo
                });
            }
        })
    },

    getPaginationResult : function(obj,req,res,q,filed){// 通用查询，带分页，注意参数传递格式,filed为指定字段
        var searchKey = req.query.searchKey;
        var page = parseInt(req.query.page);
        var limit = parseInt(req.query.limit);
        if (!page) page = 1;
        if (!limit) limit = 15;
        var order = req.query.order;
        var sq = {}, Str, A = 'problemID', B = 'asc';
        if (order) {    //是否有排序请求
            Str = order.split('_');
            A = Str[0]; B = Str[1];
            sq[A] = B;    //关联数组增加查询条件，更加灵活，因为A是变量
        } else {
            sq.date = -1;    //默认排序查询条件
        }

        var startNum = (page - 1)*limit;
        var resultList;
        var resultNum;
        if(q && q.length > 1){ // 多条件只要其中一条符合
            resultList = obj.find().or(q,filed).sort(sq).skip(startNum).limit(limit);
            resultNum = obj.find().or(q,filed).count();
        }else{
            resultList = obj.find(q,filed).sort(sq).skip(startNum).limit(limit);
            resultNum = obj.find(q,filed).count();
        }
        //        分页参数
        var pageInfo = {
            "totalItems" : resultNum,
            "currentPage" : page,
            "limit" : limit,
            "startNum" : startNum +1,
            "searchKey" : searchKey
        };
        var datasInfo = {
            docs : resultList,
            pageInfo : pageInfo
        };

        return datasInfo;
    },

    getDatasByParam : function(obj,req,res,q){// 通用查询list不带分页，注意参数传递格式,通过express-promise去掉了回调方式返回数据
//        默认查询所有记录，有条件顺带排序和查询部分记录
        var order = req.query.order;
        var limit = parseInt(req.query.limit);
        var sq = {}, Str, A = 'problemID', B = 'asc';
        if (order) {    //是否有排序请求
            Str = order.split('_');
            A = Str[0]; B = Str[1];
            sq[A] = B;    //关联数组增加查询条件，更加灵活，因为A是变量
        } else {
            sq.date = -1;    //默认排序查询条件
        }
        if(!limit){
            return obj.find(q).sort(sq);
        }else{
            return obj.find(q).sort(sq).skip(0).limit(limit);
        }

    },

    getKeyArrByTokenId : function(tokenId){
        var newLink = DbOpt.decrypt(tokenId,settings.encrypt_key);
        var keyArr = newLink.split('$');
        return keyArr;
    },

    getCount : function(obj,req,res,conditions){ // 查询指定对象的数量
        obj.count(conditions, function (err, count) {
            if (err){
                console.log(err);
            }else{
                return res.json({
                    count : count
                });
            }

        });
    },
    encrypt : function(data,key){ // 密码加密
        var cipher = crypto.createCipher("bf",key);
        var newPsd = "";
        newPsd += cipher.update(data,"utf8","hex");
        newPsd += cipher.final("hex");
        return newPsd;
    },
    decrypt : function(data,key){ //密码解密
        var decipher = crypto.createDecipher("bf",key);
        var oldPsd = "";
        oldPsd += decipher.update(data,"hex","utf8");
        oldPsd += decipher.final("utf8");
        return oldPsd;
    }
};

module.exports = DbOpt;
<|endoftext|>


<commit_before>// Save a reference to the global object (`window` in the browser, `global`
// on the server).
var root = this;

// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var Media, server = false;
var PageableCollection = false;
if (typeof exports !== 'undefined') {
    Media = exports;
    server = true;
    var uuid = require('node-uuid');
    PageableCollection = require("backbone-pageable");
} else {
    Media = root.Media = {};
    var uuid = root.uuid;
    PageableCollection = root.Backbone.PageableCollection;
}

// Require Underscore, Backbone & BackboneIO, if we're on the server, and it's not already present.
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');

var Backbone = root.Backbone || false;
var BackboneIO = root.BackboneIO;
if ((typeof require !== 'undefined')){
    Backbone = require('backbone');
    Backbone.Memento = function() {};
}

// Require moment
var moment = root.moment || false;
if(typeof require !== 'undefined') {
    moment = require('moment');
}

if ((typeof require !== 'undefined')) require('backbone-relational');

var leadingZero = function (num) {
    return (num < 10) ? "0"+num : num;
}

var toMilliseconds = function (time) {
    if (!time) {
        console.log ("No time");
        return 0;
    }

    var t = time.match(/(\d{2}):(\d{2}):(\d{2})\.(\d*)/);
    t.shift();
    var d = moment.duration ({
        hours:        t[0],
        minutes:      t[1],
        seconds:      t[2],
        milliseconds: t[3]*10
    });

    return d.asMilliseconds();
};

var prettyTime =  function (m) {
    var d = moment.duration(m);
    var p = leadingZero(d.hours())   + ':'
        + leadingZero(d.minutes()) + ':'
        + leadingZero(d.seconds()) + '.'
        + leadingZero(d.milliseconds()/10);
    return p;
};

var arrayDuration = function (a) {
    return  _.reduce(a, function (m, n) {
        return m + toMilliseconds (n);}, 0);
};

var Pageable = {
    state: {
        firstPage: 0,
        currentPage: 0,
        pageSize: 10,
        query: {}
    },
    queryParams: {
        query: function() { return this.state.query; },
    },
};

var Media = {};

Media.Transform = Backbone.RelationalModel.extend({
    urlRoot: 'transform',
    idAttribute: '_id',
    relations: [{
        type: Backbone.HasOne,
        key: 'piece',
        relatedModel:'Media.Piece',
        includeInJSON: '_id',
        reverseRelation: {
            key: 'transform',
            includeInJSON: '_id',
            type: Backbone.HasOne
        }
    },
    {
        type: Backbone.HasOne,
        key: 'playlist',
        relatedModel:'Media.Playlist',
        includeInJSON: '_id',
        reverseRelation: {
            key: 'transform',
            includeInJSON: '_id',
            type: Backbone.HasOne
        }
    },
    {
        type: Backbone.HasOne,
        key: 'occurrence',
        relatedModel:'Media.Occurrence',
        includeInJSON: '_id',
        reverseRelation: {
            key: 'transform',
            includeInJSON: '_id',
            type: Backbone.HasOne
        }
    }],
    defaults: {
        trim: {
            timein:  0,
            timeout: 0,
        },
        overlay: [],
        starts: 0,
        ends: 0,
    },
});

var TransformCollection = {
    model: Media.Transform,
    url: 'transform',
    backend: 'transformbackend',
    initialize: function () {
        if (!server) {
            this.bindBackend();
            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new Media.TransformCollection');
        Backbone.Collection.prototype.initialize.call (this);
    },
};

Media.TransformCollection = Backbone.Collection.extend(TransformCollection);
Media.TransformCollectionPageable = PageableCollection.extend(_.extend(TransformCollection, Pageable));

Media.Model = Backbone.RelationalModel.extend({
    urlRoot: 'media',
    backend: 'mediabackend',
    idAttribute: '_id',
    initialize: function () {
        console.log ('creating new Media.Model');
    },

    validate: function (attrs) {
        console.log ("checking -> ", attrs);
        if (attrs.file && ! attrs.file.length) {
            console.log ('NO file');
            return new Error("file must be defined");
        }
        if (attrs.stat       &&
            (! attrs.stat.mtime ||
             ! attrs.stat.size  ||
             attrs.stat.size <= 4000)) {
            console.log ('NO or BAD stat');
            return new Error("stat must be defined");
        }
    },
    defaults: {
        _id: '',
        stat: {},
        file: "None",
        name: "",
        audio: "None",
        video: "None",
        template: 'mediaview',
        checksum: "",
        durationraw: "",
        notes: ""
    }
});

var Collection = {
    model: Media.Model,
    url: 'media',
    backend: 'mediabackend',
    initialize: function () {
        if (!server) {
            this.bindBackend();
            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new Media.Collection');
        Backbone.Collection.prototype.initialize.call (this);
    },
    pretty_duration: function () {
        return prettyTime(arrayDuration(this.pluck('durationraw')));
    },
};

Media.Collection = Backbone.Collection.extend(Collection);
Media.CollectionPageable = PageableCollection.extend(_.extend(Collection, Pageable));

Media.Piece = Media.Model.extend({
    urlRoot: 'piece',
    backend: 'piecebackend',
    idAttribute: '_id',
    initialize: function () {
        console.log ('creating new Media.Piece');
    },
});

var PieceCollection = {
    url: 'piece',
    model: Media.Piece,
    backend: 'piecebackend',
    initialize: function () {
        if (!server) {
            this.bindBackend();
            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new Media.PieceCollection');
        Backbone.Collection.prototype.initialize.call (this);
    },
};

Media.PieceCollection = Backbone.Collection.extend(PieceCollection);
Media.PieceCollectionPageable = PageableCollection.extend(_.extend(PieceCollection, Pageable));

Media.Playlist = Backbone.RelationalModel.extend({
    urlRoot: 'list',
    backend: 'listbackend', // Makes HasOne relation from Media.Occurrence work.
    idAttribute: '_id',
    relations: [{
        type: Backbone.HasMany,
        key: 'pieces',
        relatedModel: 'Media.Piece',
        collectionType: 'Media.PieceCollection',
        includeInJSON: '_id',
    }],
    initialize: function () {
        var self = this;
        var pieces = this.get('pieces');

        pieces.bind('relational:change relational:add relational:reset relational:remove', function(){
            self.update_duration(self);
        }, this);

        console.log ('creating new Media.Playlist');
        Backbone.RelationalModel.prototype.initialize.call (this);
    },
    update_duration: _.debounce(function (self) {
        self.update_duration_nowait(self.get('pieces'));
    }, 100),
    update_duration_nowait: function(pieces) {
        pieces = pieces || this.get('pieces');
        var durations = pieces.pluck('durationraw');
        var total_duration = arrayDuration(durations);
        var all_ok = _.every(durations);
        console.log("UpdateDuration ~ durationraws:", durations, "total: ", total_duration, " all ok: ", all_ok);
        if (!all_ok) {
            return;
        }
        this.set("duration", total_duration);
    },
    pretty_duration: function () {
        return prettyTime (this.get('duration'));
    },
    defaults: {
        name: null,
        fixed: false,
        duration: 0,
        pos: 0,
    }
});

var Universe = {
    url: 'list',
    model: Media.Playlist,
    backend: 'listbackend',
    comparator: '_id',
    initialize: function () {
        if (!server) {
            this.bindBackend();
            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new Media.Universe');
        Backbone.Collection.prototype.initialize.call (this);
    },
};

Media.Universe = Backbone.Collection.extend(Universe);
Media.UniversePageable = PageableCollection.extend(_.extend(Universe, Pageable));

Media.Occurrence = Backbone.RelationalModel.extend({
    urlRoot: 'occur',
    idAttribute: '_id',
    relations: [{
        includeInJSON: '_id',
        type: Backbone.HasOne,
        key: 'playlist',
        relatedModel: 'Media.Playlist',
        reverseRelation: {
            key: 'occurrences',
            collectionType: 'Media.Schedule',
            includeInJSON: '_id',
            type: Backbone.HasMany
        }
    }],
    initialize: function () {
        console.log ('creating new Media.Occurrence', this);
        this.overlapsWith = [];
    },
    getOverlappingEvents: function() {
        return this.collection.getOverlappingEvents(this);
    },
    validate: function(attrs, options) {
        // Do not validate when fetching from the server
        if (options.parse) return;
        // Only save model if it's not overlapping with anything
        var self = this;
        overlapping = this.getOverlappingEvents();
        if (overlapping.length) {
            overlapping.forEach(function(oc) {
                oc.overlapsWith.push(self);
            });
            this.collection.trigger('overlap', true);
            return overlapping
        } else {
            // When this event is no longer overlapping, the other events could be valid.
            //   validationError would be unset after this function returns, but I need if before
            //   I call checkOverlap. Could be improved.

            delete this.validationError;
            // Prevent infinite loops by first emptying the list
            var overlapsWith = _.clone(this.overlapsWith);
            this.overlapsWith = [];

            overlapsWith.forEach(function(oc) {
                oc.save();
            });

            if(this.collection) {
                this.collection.checkOverlap();
            }
        }
    },

    defaults: {
        event: null,
    },
});

var Schedule = {
    url: 'occur',
    model: Media.Occurrence,
    backend: 'schedbackend',
    initialize: function () {
        if (!server) {
            this.bindBackend();
            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        this.on('add remove', this.checkOverlap);
        console.log ('creating new Media.Schedule');

        this.start_memento();
        this.on('add remove', this.checkOverlap)

        Backbone.Collection.prototype.initialize.call (this);
    },
    start_memento: function() {
        this.memento = new Backbone.Memento(this);
    },
    comparator: "start",
    getInvalid: function() {
        return this.filter(function(oc) {
            return oc.validationError
        });
    },
    checkOverlap: function() {
        var elems = this.getInvalid();
        this.trigger('overlap', elems.length);
    },
    getOverlappingEvents: function(oc) {
        // Get all events that overlap with this one
        return this.filter(function(elem) {
            return (elem.get('_id') != oc.get('_id') &&
                    elem.get('start') < oc.get('end') &&
                    elem.get('end') > oc.get('start'));
        });
    },
    simulateOverlap: function(occurrence, save) {
        var self = this;

        function pusherMapper(pusher) {
            return function(elem) {
                return {
                    pusher: pusher,
                    elem: elem,
                };
            };
        };

        // Processing queue
        var queue = self.getOverlappingEvents(occurrence).map(pusherMapper(occurrence));

        var target;
        while (target = queue.pop()) {
            // Adjust target time
            var duration = target.elem.get("end") - target.elem.get("start");
            target.elem.set({
                start: target.pusher.get("end"),
                end: target.pusher.get("end") + duration,
            });

            if (save) {
                target.elem.save();
            }

            // Check new overlaps and process them first
            var new_overlaps = self.getOverlappingEvents(target.elem).map(pusherMapper(target.elem));
            queue = queue.concat(new_overlaps);
        }
    },
};

Media.Schedule = Backbone.Collection.extend(Schedule);
Media.SchedulePageable = PageableCollection.extend(_.extend(Schedule, Pageable));

Media.Transform.setup();
Media.Model.setup();
Media.Piece.setup();
Media.Playlist.setup();
Media.Occurrence.setup();

if(server) {
    module.exports = Media;
    Backbone.Relational.store.addModelScope({ "Media": Media });
}
else root.Media = Media;
<commit_msg>Piece and Playlist: use a different channel for model and collection.<commit_after>// Save a reference to the global object (`window` in the browser, `global`
// on the server).
var root = this;

// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var Media, server = false;
var PageableCollection = false;
if (typeof exports !== 'undefined') {
    Media = exports;
    server = true;
    var uuid = require('node-uuid');
    PageableCollection = require("backbone-pageable");
} else {
    Media = root.Media = {};
    var uuid = root.uuid;
    PageableCollection = root.Backbone.PageableCollection;
}

// Require Underscore, Backbone & BackboneIO, if we're on the server, and it's not already present.
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');

var Backbone = root.Backbone || false;
var BackboneIO = root.BackboneIO;
if ((typeof require !== 'undefined')){
    Backbone = require('backbone');
    Backbone.Memento = function() {};
}

// Require moment
var moment = root.moment || false;
if(typeof require !== 'undefined') {
    moment = require('moment');
}

if ((typeof require !== 'undefined')) require('backbone-relational');

var leadingZero = function (num) {
    return (num < 10) ? "0"+num : num;
}

var toMilliseconds = function (time) {
    if (!time) {
        console.log ("No time");
        return 0;
    }

    var t = time.match(/(\d{2}):(\d{2}):(\d{2})\.(\d*)/);
    t.shift();
    var d = moment.duration ({
        hours:        t[0],
        minutes:      t[1],
        seconds:      t[2],
        milliseconds: t[3]*10
    });

    return d.asMilliseconds();
};

var prettyTime =  function (m) {
    var d = moment.duration(m);
    var p = leadingZero(d.hours())   + ':'
        + leadingZero(d.minutes()) + ':'
        + leadingZero(d.seconds()) + '.'
        + leadingZero(d.milliseconds()/10);
    return p;
};

var arrayDuration = function (a) {
    return  _.reduce(a, function (m, n) {
        return m + toMilliseconds (n);}, 0);
};

var Pageable = {
    state: {
        firstPage: 0,
        currentPage: 0,
        pageSize: 10,
        query: {}
    },
    queryParams: {
        query: function() { return this.state.query; },
    },
};

var Media = {};

Media.Transform = Backbone.RelationalModel.extend({
    urlRoot: 'transform',
    idAttribute: '_id',
    relations: [{
        type: Backbone.HasOne,
        key: 'piece',
        relatedModel:'Media.Piece',
        includeInJSON: '_id',
        reverseRelation: {
            key: 'transform',
            includeInJSON: '_id',
            type: Backbone.HasOne
        }
    },
    {
        type: Backbone.HasOne,
        key: 'playlist',
        relatedModel:'Media.Playlist',
        includeInJSON: '_id',
        reverseRelation: {
            key: 'transform',
            includeInJSON: '_id',
            type: Backbone.HasOne
        }
    },
    {
        type: Backbone.HasOne,
        key: 'occurrence',
        relatedModel:'Media.Occurrence',
        includeInJSON: '_id',
        reverseRelation: {
            key: 'transform',
            includeInJSON: '_id',
            type: Backbone.HasOne
        }
    }],
    defaults: {
        trim: {
            timein:  0,
            timeout: 0,
        },
        overlay: [],
        starts: 0,
        ends: 0,
    },
});

var TransformCollection = {
    model: Media.Transform,
    url: 'transform',
    backend: 'transformbackend',
    initialize: function () {
        if (!server) {
            this.bindBackend();
            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new Media.TransformCollection');
        Backbone.Collection.prototype.initialize.call (this);
    },
};

Media.TransformCollection = Backbone.Collection.extend(TransformCollection);
Media.TransformCollectionPageable = PageableCollection.extend(_.extend(TransformCollection, Pageable));

Media.Model = Backbone.RelationalModel.extend({
    urlRoot: 'media',
    backend: 'mediabackend',
    idAttribute: '_id',
    initialize: function () {
        console.log ('creating new Media.Model');
    },

    validate: function (attrs) {
        console.log ("checking -> ", attrs);
        if (attrs.file && ! attrs.file.length) {
            console.log ('NO file');
            return new Error("file must be defined");
        }
        if (attrs.stat       &&
            (! attrs.stat.mtime ||
             ! attrs.stat.size  ||
             attrs.stat.size <= 4000)) {
            console.log ('NO or BAD stat');
            return new Error("stat must be defined");
        }
    },
    defaults: {
        _id: '',
        stat: {},
        file: "None",
        name: "",
        audio: "None",
        video: "None",
        template: 'mediaview',
        checksum: "",
        durationraw: "",
        notes: ""
    }
});

var Collection = {
    model: Media.Model,
    url: 'media',
    backend: 'mediabackend',
    initialize: function () {
        if (!server) {
            this.bindBackend();
            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new Media.Collection');
        Backbone.Collection.prototype.initialize.call (this);
    },
    pretty_duration: function () {
        return prettyTime(arrayDuration(this.pluck('durationraw')));
    },
};

Media.Collection = Backbone.Collection.extend(Collection);
Media.CollectionPageable = PageableCollection.extend(_.extend(Collection, Pageable));

Media.Piece = Media.Model.extend({
    urlRoot: 'piece',
    backend: {  name:    'piecebackend',
                channel: 'piece'
    },
    idAttribute: '_id',
    initialize: function () {
        console.log ('creating new Media.Piece');
    },
});

var PieceCollection = {
    url: 'piece',
    model: Media.Piece,
    backend: {  name:    'piecebackend',
                channel: 'collection'
    },
    initialize: function () {
        if (!server) {
            this.bindBackend();
            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new Media.PieceCollection');
        Backbone.Collection.prototype.initialize.call (this);
    },
};

Media.PieceCollection = Backbone.Collection.extend(PieceCollection);
Media.PieceCollectionPageable = PageableCollection.extend(_.extend(PieceCollection, Pageable));

Media.Playlist = Backbone.RelationalModel.extend({
    urlRoot: 'list',
    // Makes HasOne relation from Media.Occurrence work.
    backend: {  name:    'listbackend',
                channel: 'list'
    },
    idAttribute: '_id',
    relations: [{
        type: Backbone.HasMany,
        key: 'pieces',
        relatedModel: 'Media.Piece',
        collectionType: 'Media.PieceCollection',
        includeInJSON: '_id',
    }],
    initialize: function () {
        var self = this;
        var pieces = this.get('pieces');

        pieces.bind('relational:change relational:add relational:reset relational:remove', function(){
            self.update_duration(self);
        }, this);

        console.log ('creating new Media.Playlist');
        Backbone.RelationalModel.prototype.initialize.call (this);
    },
    update_duration: _.debounce(function (self) {
        self.update_duration_nowait(self.get('pieces'));
    }, 100),
    update_duration_nowait: function(pieces) {
        pieces = pieces || this.get('pieces');
        var durations = pieces.pluck('durationraw');
        var total_duration = arrayDuration(durations);
        var all_ok = _.every(durations);
        console.log("UpdateDuration ~ durationraws:", durations, "total: ", total_duration, " all ok: ", all_ok);
        if (!all_ok) {
            return;
        }
        this.set("duration", total_duration);
    },
    pretty_duration: function () {
        return prettyTime (this.get('duration'));
    },
    defaults: {
        name: null,
        fixed: false,
        duration: 0,
        pos: 0,
    }
});

var Universe = {
    url: 'list',
    model: Media.Playlist,
    backend: {  name:    'listbackend',
                channel: 'universe'
    },
    comparator: '_id',
    initialize: function () {
        if (!server) {
            this.bindBackend();
            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new Media.Universe');
        Backbone.Collection.prototype.initialize.call (this);
    },
};

Media.Universe = Backbone.Collection.extend(Universe);
Media.UniversePageable = PageableCollection.extend(_.extend(Universe, Pageable));

Media.Occurrence = Backbone.RelationalModel.extend({
    urlRoot: 'occur',
    idAttribute: '_id',
    relations: [{
        includeInJSON: '_id',
        type: Backbone.HasOne,
        key: 'playlist',
        relatedModel: 'Media.Playlist',
        reverseRelation: {
            key: 'occurrences',
            collectionType: 'Media.Schedule',
            includeInJSON: '_id',
            type: Backbone.HasMany
        }
    }],
    initialize: function () {
        console.log ('creating new Media.Occurrence', this);
        this.overlapsWith = [];
    },
    getOverlappingEvents: function() {
        return this.collection.getOverlappingEvents(this);
    },
    validate: function(attrs, options) {
        // Do not validate when fetching from the server
        if (options.parse) return;
        // Only save model if it's not overlapping with anything
        var self = this;
        overlapping = this.getOverlappingEvents();
        if (overlapping.length) {
            overlapping.forEach(function(oc) {
                oc.overlapsWith.push(self);
            });
            this.collection.trigger('overlap', true);
            return overlapping
        } else {
            // When this event is no longer overlapping, the other events could be valid.
            //   validationError would be unset after this function returns, but I need if before
            //   I call checkOverlap. Could be improved.

            delete this.validationError;
            // Prevent infinite loops by first emptying the list
            var overlapsWith = _.clone(this.overlapsWith);
            this.overlapsWith = [];

            overlapsWith.forEach(function(oc) {
                oc.save();
            });

            if(this.collection) {
                this.collection.checkOverlap();
            }
        }
    },

    defaults: {
        event: null,
    },
});

var Schedule = {
    url: 'occur',
    model: Media.Occurrence,
    backend: 'schedbackend',
    initialize: function () {
        if (!server) {
            this.bindBackend();
            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        this.on('add remove', this.checkOverlap);
        console.log ('creating new Media.Schedule');

        this.start_memento();
        this.on('add remove', this.checkOverlap)

        Backbone.Collection.prototype.initialize.call (this);
    },
    start_memento: function() {
        this.memento = new Backbone.Memento(this);
    },
    comparator: "start",
    getInvalid: function() {
        return this.filter(function(oc) {
            return oc.validationError
        });
    },
    checkOverlap: function() {
        var elems = this.getInvalid();
        this.trigger('overlap', elems.length);
    },
    getOverlappingEvents: function(oc) {
        // Get all events that overlap with this one
        return this.filter(function(elem) {
            return (elem.get('_id') != oc.get('_id') &&
                    elem.get('start') < oc.get('end') &&
                    elem.get('end') > oc.get('start'));
        });
    },
    simulateOverlap: function(occurrence, save) {
        var self = this;

        function pusherMapper(pusher) {
            return function(elem) {
                return {
                    pusher: pusher,
                    elem: elem,
                };
            };
        };

        // Processing queue
        var queue = self.getOverlappingEvents(occurrence).map(pusherMapper(occurrence));

        var target;
        while (target = queue.pop()) {
            // Adjust target time
            var duration = target.elem.get("end") - target.elem.get("start");
            target.elem.set({
                start: target.pusher.get("end"),
                end: target.pusher.get("end") + duration,
            });

            if (save) {
                target.elem.save();
            }

            // Check new overlaps and process them first
            var new_overlaps = self.getOverlappingEvents(target.elem).map(pusherMapper(target.elem));
            queue = queue.concat(new_overlaps);
        }
    },
};

Media.Schedule = Backbone.Collection.extend(Schedule);
Media.SchedulePageable = PageableCollection.extend(_.extend(Schedule, Pageable));

Media.Transform.setup();
Media.Model.setup();
Media.Piece.setup();
Media.Playlist.setup();
Media.Occurrence.setup();

if(server) {
    module.exports = Media;
    Backbone.Relational.store.addModelScope({ "Media": Media });
}
else root.Media = Media;
<|endoftext|>


<commit_before>const mongoose = require('mongoose');
//  Comment = require('./Comment');

const photoSchema = new mongoose.Schema({
  data: String,
  contentType: String,
  author: String,
  date: {
    type: Date,
    default: Date.now
  },
  title: {
    type: String,
    required: true
  },
  description: {
    type: String
  },
  upvotes: [{
    user: String
  }],
  comments: [{
    user: {
      type: String,
      required: true
    },
    content: {
      type: String,
      required: true
    },
    date: {
      type: Date,
      default: Date.now
    },
    postId: mongoose.Schema.Types.ObjectId
  }],
}, {
  timestamps: true
});

const Photo = mongoose.model('Photo', photoSchema);

module.exports = Photo;
<commit_msg>Removed unnecessary comment<commit_after>const mongoose = require('mongoose');

const photoSchema = new mongoose.Schema({
  data: String,
  contentType: String,
  author: String,
  date: {
    type: Date,
    default: Date.now
  },
  title: {
    type: String,
    required: true
  },
  description: {
    type: String
  },
  upvotes: [{
    user: String
  }],
  comments: [{
    user: {
      type: String,
      required: true
    },
    content: {
      type: String,
      required: true
    },
    date: {
      type: Date,
      default: Date.now
    },
    postId: mongoose.Schema.Types.ObjectId
  }],
}, {
  timestamps: true
});

const Photo = mongoose.model('Photo', photoSchema);

module.exports = Photo;
<|endoftext|>


<commit_before>const exp = {};
exp.Schema = {};

exp.Schema.Env = require('./Env');
exp.Schema.User = require('./User');
exp.Schema.UserVerify = require('./UserVerify');
exp.Schema.Team = require('./Team');
exp.Schema.TeamUser = require('./TeamUser');
exp.Schema.Event = require('./Event');
exp.Schema.TeamEvent = require('./TeamEvent');
exp.Schema.Program = require('./Program');
exp.Schema.Invoice = require('./Invoice');
exp.Schema.InvoiceItem = require('./InvoiceItem');
exp.Schema.InvoicingOrg = require('./InvoicingOrg');
exp.Schema.OneTime = require('./OneTime');

module.exports = exp;<commit_msg>removing userVerify<commit_after>const exp = {};
exp.Schema = {};

exp.Schema.Env = require('./Env');
exp.Schema.User = require('./User');
exp.Schema.Team = require('./Team');
exp.Schema.TeamUser = require('./TeamUser');
exp.Schema.Event = require('./Event');
exp.Schema.TeamEvent = require('./TeamEvent');
exp.Schema.Program = require('./Program');
exp.Schema.Invoice = require('./Invoice');
exp.Schema.InvoiceItem = require('./InvoiceItem');
exp.Schema.InvoicingOrg = require('./InvoicingOrg');
exp.Schema.OneTime = require('./OneTime');

module.exports = exp;<|endoftext|>


<commit_before>// Sequelize Initialization
var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var lodash    = require('lodash');
var config    = require('../config');
var sequelize = new Sequelize(config.db[config.mode].name, config.db[config.mode].user, config.db[config.mode].password);
var db        = {};

fs.readdirSync(__dirname).filter(function(file) {
  return ((file.indexOf('.') !== 0) && (file !== 'index.js') && (file.slice(-3) == '.js'))
}).forEach(function(file) {
  var model = sequelize.import(path.join(__dirname, file))
  db[model.name] = model
});

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].options.hasOwnProperty('associate')) {
    db[modelName].options.associate(db);
  }
});

module.exports = lodash.extend({
  sequelize: sequelize,
  Sequelize: Sequelize
}, db);

<commit_msg>Change sequelize to use new logger<commit_after>// Sequelize Initialization
var log       = require('npmlog');
var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var lodash    = require('lodash');
var config    = require('../config');
var db        = {};
var sequelize = new Sequelize(
  config.db[config.mode].name,
  config.db[config.mode].user,
  config.db[config.mode].password,
  {
    logging: function(message) {
      log.info('[\u2713]', message);
    }
  }
);

fs.readdirSync(__dirname).filter(function(file) {
  return ((file.indexOf('.') !== 0) && (file !== 'index.js') && (file.slice(-3) == '.js'))
}).forEach(function(file) {
  var model = sequelize.import(path.join(__dirname, file))
  db[model.name] = model
});

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].options.hasOwnProperty('associate')) {
    db[modelName].options.associate(db);
  }
});

module.exports = lodash.extend({
  sequelize: sequelize,
  Sequelize: Sequelize
}, db);

<|endoftext|>


<commit_before>'use strict';

var Users = require('../lib/dbModels/Users');

var UsersModel = function UsersModelConstructor() {
    return {
        get: function(cb) {
            return Users.all()
                .then(function (result) {
                    cb(null, result);
                })
                .catch(function (err) {
                    cb(err);
                });
        },
        post: function(user, cb) {
            return Users.create(user)
                .then(function(err, result) {
                    if (err) {
                        cb(err);
                        return;
                    }

                    cb(null, result);
                })
                .catch(function (err) {
                    cb(err);
                });
        }
    };
};

module.exports = UsersModel();
<commit_msg>refactor(models/users): change params accepted by the function<commit_after>'use strict';

var Users = require('../lib/dbModels/Users');

var UsersModel = function UsersModelConstructor() {
    return {
        get: function(cb) {
            return Users.all()
                .then(function (result) {
                    cb(null, result);
                })
                .catch(function (err) {
                    cb(err);
                });
        },
        post: function(user, cb) {
            return Users.create(user)
                .then(function(result) {
                    cb(null, result);
                })
                .catch(function (err) {
                    cb(err);
                });
        }
    };
};

module.exports = UsersModel();
<|endoftext|>