<commit_before>/* global ImportedStrings */

/// <reference path="Table.js" />
/// <reference path="Strings.js" />
/// <reference path="Headers.js" />

var ReceivedRow = function () {
};

ReceivedRow.prototype.hop = 0;
ReceivedRow.prototype.from = "";
ReceivedRow.prototype.by = "";
ReceivedRow.prototype.with = "";
ReceivedRow.prototype.id = 0;
ReceivedRow.prototype.for = "";
ReceivedRow.prototype.via = "";
ReceivedRow.prototype.date = "";
ReceivedRow.prototype.dateNum = 0;
ReceivedRow.prototype.dateSort = 0;
ReceivedRow.prototype.delay = 0;
ReceivedRow.prototype.delaySort = 0;
ReceivedRow.prototype.percent = 0;
ReceivedRow.prototype.sourceHeader = 0;

// Builds array of values for each header in receivedHeaderNames.
// This algorithm should work regardless of the order of the headers, given:
//  - The date, if present, is always at the end, separated by a ";".
// Values not attached to a header will not be reflected in output.
ReceivedRow.prototype.init = function (receivedHeader) {
    var receivedHeaderNames = ["from", "by", "with", "id", "for", "via"];

    // Build array of header locations
    var headerMatches = [];

    this.sourceHeader = receivedHeader;

    // Read out the date first, then clear it from the string
    var iDate = receivedHeader.lastIndexOf(";");
    if (iDate !== -1) {
        this.date = receivedHeader.substring(iDate + 1);
        receivedHeader = receivedHeader.substring(0, iDate);
    }

    // Scan for malformed postFix headers
    // Received: by example.com (Postfix, from userid 1001)
    //   id 1234ABCD; Thu, 21 Aug 2014 12:12:48 +0200 (CEST)
    var postFix = receivedHeader.match(/(.*)by (.*? \(Postfix, from userid .*?\))(.*)/);
    if (postFix) {
        this["by"] = postFix[2];
        receivedHeader = postFix[1] + postFix[3];
        receivedHeaderNames = RemoveEntry(receivedHeaderNames, "by");
    }

    // Scan for malformed qmail headers
    // Received: (qmail 10876 invoked from network); 24 Aug 2014 16:13:38 -0000
    postFix = receivedHeader.match(/(.*)\((qmail .*? invoked from .*?)\)(.*)/);
    if (postFix) {
        this["by"] = postFix[2];
        receivedHeader = postFix[1] + postFix[3];
        receivedHeaderNames = RemoveEntry(receivedHeaderNames, "by");
    }

    // Split up the string now so we can look for our headers
    var tokens = receivedHeader.split(/\s+/);

    var iMatch = 0;
    var iHeader;
    var iToken;

    for (iHeader = 0; iHeader < receivedHeaderNames.length; iHeader++) {
        this[receivedHeaderNames[iHeader]] = "";
        for (iToken = 0; iToken < tokens.length; iToken++) {
            if (receivedHeaderNames[iHeader] === tokens[iToken]) {
                headerMatches[iMatch++] = [iHeader, iToken];
            }
        }
    }

    // Next bit assumes headerMatches[x,y] is increasing on y.
    // Sort it so it is.
    headerMatches.sort(function (a, b) { return a[1] - b[1]; });

    for (iMatch = 0; iMatch < headerMatches.length; iMatch++) {
        iHeader = headerMatches[iMatch][0];
        var iTokenHeader = headerMatches[iMatch][1];
        var iFirstVal = iTokenHeader + 1;

        var iNextTokenHeader;
        var iLastVal;
        if (iMatch + 1 < headerMatches.length) {
            iNextTokenHeader = headerMatches[iMatch + 1][1];
        } else {
            iNextTokenHeader = tokens.length;
        }

        iLastVal = iNextTokenHeader - 1;

        var headerName = receivedHeaderNames[iHeader];
        if (this[headerName] !== "") { this[headerName] += "; "; }
        for (iToken = iFirstVal; iToken <= iLastVal; iToken++) {
            this[headerName] += tokens[iToken];
            if (iToken < iLastVal) { this[headerName] += " "; }
        }
    }

    this.dateNum = Date.parse(this.date);
    this.date = new Date(this.date).toLocaleString().replace(/\u200E/, "");
    this.dateSort = this.dateNum;
    this.delaySort = -1; // Force the "no previous or current time" rows to sort before the 0 second rows
    this.percent = 0;
}

var Received = function () {
    this.receivedRows = [];
};

Received.prototype.tableName = "receivedHeaders";
Received.prototype.receivedRows = [];
Received.prototype.sortColumn = "hop";
Received.prototype.sortOrder = 1;

Received.prototype.exists = function () {
    return this.receivedRows.length > 0;
};

Received.prototype.doSort = function (col) {
    var that = this;
    if (this.sortColumn === col) {
        this.sortOrder *= -1;
    } else {
        this.sortColumn = col;
        this.sortOrder = 1;
    }

    if (this.sortColumn + "Sort" in this.receivedRows[0]) {
        col = col + "Sort";
    }

    this.receivedRows.sort(function (a, b) {
        return that.sortOrder * (a[col] < b[col] ? -1 : 1);
    });
};

function RemoveEntry(stringArray, entry) {
    var i = stringArray.indexOf(entry);
    if (i >= 0) {
        stringArray.splice(i, 1);
    }

    return stringArray;
}

Received.prototype.init = function (receivedHeader) {
    row = new ReceivedRow();
    row.init(receivedHeader);
    this.receivedRows.push(row);
};

Received.prototype.computeDeltas = function () {
    // Process received headers in reverse order
    this.receivedRows.reverse();

    // Parse rows and compute values needed for the "Delay" column
    var iStartTime = 0;
    var iEndTime = 0;
    var iLastTime = NaN;
    var iDelta = 0; // This will be the sum of our positive deltas
    var i;
    for (i = 0; i < this.receivedRows.length; i++) {
        if (!isNaN(this.receivedRows[i].dateNum)) {
            if (!isNaN(iLastTime) && iLastTime < this.receivedRows[i].dateNum) {
                iDelta += this.receivedRows[i].dateNum - iLastTime;
            }

            iStartTime = iStartTime || this.receivedRows[i].dateNum;
            iEndTime = this.receivedRows[i].dateNum;
            iLastTime = this.receivedRows[i].dateNum;
        }
    }

    iLastTime = NaN;
    var totalTime = "";
    // Total time is still last minus first, even if negative.
    if (iEndTime !== iStartTime) {
        totalTime = this.computeTime(iEndTime, iStartTime);
    }

    for (i = 0; i < this.receivedRows.length; i++) {
        this.receivedRows[i].hop = i + 1;
        this.receivedRows[i].delay = this.computeTime(this.receivedRows[i].dateNum, iLastTime);

        if (!isNaN(this.receivedRows[i].dateNum) && !isNaN(iLastTime) && iDelta !== 0) {
            this.receivedRows[i].delaySort = this.receivedRows[i].dateNum - iLastTime;

            // Only positive delays will get percentage bars. Negative delays will be color coded at render time.
            if (this.receivedRows[i].delaySort > 0) {
                this.receivedRows[i].percent = 100 * this.receivedRows[i].delaySort / iDelta;
            }
        }

        if (!isNaN(this.receivedRows[i].dateNum)) {
            iLastTime = this.receivedRows[i].dateNum;
        }
    }

    return totalTime;
};

// Computes min/sec from the diff of current and last.
// Returns nothing if last or current is NaN.
Received.prototype.computeTime = function (current, last) {
    var time = [];

    if (isNaN(current) || isNaN(last)) { return ""; }
    var diff = current - last;
    var iDelay;
    var printedMinutes = false;

    if (diff < 0) {
        time.push(ImportedStrings.mha_negative);
        diff = -diff;
    }

    if (diff >= 1000 * 60) {
        iDelay = Math.floor(diff / 1000 / 60);
        time.push(iDelay, " ");
        if (iDelay === 1) {
            time.push(ImportedStrings.mha_minute);
        } else {
            time.push(ImportedStrings.mha_minutes);
        }

        diff -= iDelay * 1000 * 60;
        printedMinutes = true;
    }

    if (printedMinutes && diff) {
        time.push(" ");
    }

    if (!printedMinutes || diff) {
        iDelay = Math.floor(diff / 1000);
        time.push(iDelay, " ");
        if (iDelay === 1) {
            time.push(ImportedStrings.mha_second);
        } else {
            time.push(ImportedStrings.mha_seconds);
        }
    }

    return time.join("");
};<commit_msg>move parsing into constructor<commit_after>/* global ImportedStrings */

/// <reference path="Table.js" />
/// <reference path="Strings.js" />
/// <reference path="Headers.js" />

// Builds array of values for each header in receivedHeaderNames.
// This algorithm should work regardless of the order of the headers, given:
//  - The date, if present, is always at the end, separated by a ";".
// Values not attached to a header will not be reflected in output.
var ReceivedRow = function (receivedHeader) {
    var receivedHeaderNames = ["from", "by", "with", "id", "for", "via"];

    // Build array of header locations
    var headerMatches = [];

    this.sourceHeader = receivedHeader;

    // Read out the date first, then clear it from the string
    var iDate = receivedHeader.lastIndexOf(";");
    if (iDate !== -1) {
        this.date = receivedHeader.substring(iDate + 1);
        receivedHeader = receivedHeader.substring(0, iDate);
    }

    // Scan for malformed postFix headers
    // Received: by example.com (Postfix, from userid 1001)
    //   id 1234ABCD; Thu, 21 Aug 2014 12:12:48 +0200 (CEST)
    var postFix = receivedHeader.match(/(.*)by (.*? \(Postfix, from userid .*?\))(.*)/);
    if (postFix) {
        this["by"] = postFix[2];
        receivedHeader = postFix[1] + postFix[3];
        receivedHeaderNames = RemoveEntry(receivedHeaderNames, "by");
    }

    // Scan for malformed qmail headers
    // Received: (qmail 10876 invoked from network); 24 Aug 2014 16:13:38 -0000
    postFix = receivedHeader.match(/(.*)\((qmail .*? invoked from .*?)\)(.*)/);
    if (postFix) {
        this["by"] = postFix[2];
        receivedHeader = postFix[1] + postFix[3];
        receivedHeaderNames = RemoveEntry(receivedHeaderNames, "by");
    }

    // Split up the string now so we can look for our headers
    var tokens = receivedHeader.split(/\s+/);

    var iMatch = 0;
    var iHeader;
    var iToken;

    for (iHeader = 0; iHeader < receivedHeaderNames.length; iHeader++) {
        this[receivedHeaderNames[iHeader]] = "";
        for (iToken = 0; iToken < tokens.length; iToken++) {
            if (receivedHeaderNames[iHeader] === tokens[iToken]) {
                headerMatches[iMatch++] = [iHeader, iToken];
            }
        }
    }

    // Next bit assumes headerMatches[x,y] is increasing on y.
    // Sort it so it is.
    headerMatches.sort(function (a, b) { return a[1] - b[1]; });

    for (iMatch = 0; iMatch < headerMatches.length; iMatch++) {
        iHeader = headerMatches[iMatch][0];
        var iTokenHeader = headerMatches[iMatch][1];
        var iFirstVal = iTokenHeader + 1;

        var iNextTokenHeader;
        var iLastVal;
        if (iMatch + 1 < headerMatches.length) {
            iNextTokenHeader = headerMatches[iMatch + 1][1];
        } else {
            iNextTokenHeader = tokens.length;
        }

        iLastVal = iNextTokenHeader - 1;

        var headerName = receivedHeaderNames[iHeader];
        if (this[headerName] !== "") { this[headerName] += "; "; }
        for (iToken = iFirstVal; iToken <= iLastVal; iToken++) {
            this[headerName] += tokens[iToken];
            if (iToken < iLastVal) { this[headerName] += " "; }
        }
    }

    this.dateNum = Date.parse(this.date);
    this.date = new Date(this.date).toLocaleString().replace(/\u200E/, "");
    this.dateSort = this.dateNum;
    this.delaySort = -1; // Force the "no previous or current time" rows to sort before the 0 second rows
    this.percent = 0;
}

var Received = function () {
    this.receivedRows = [];
};

Received.prototype.tableName = "receivedHeaders";
Received.prototype.receivedRows = [];
Received.prototype.sortColumn = "hop";
Received.prototype.sortOrder = 1;

Received.prototype.exists = function () {
    return this.receivedRows.length > 0;
};

Received.prototype.doSort = function (col) {
    var that = this;
    if (this.sortColumn === col) {
        this.sortOrder *= -1;
    } else {
        this.sortColumn = col;
        this.sortOrder = 1;
    }

    if (this.sortColumn + "Sort" in this.receivedRows[0]) {
        col = col + "Sort";
    }

    this.receivedRows.sort(function (a, b) {
        return that.sortOrder * (a[col] < b[col] ? -1 : 1);
    });
};

function RemoveEntry(stringArray, entry) {
    var i = stringArray.indexOf(entry);
    if (i >= 0) {
        stringArray.splice(i, 1);
    }

    return stringArray;
}

Received.prototype.init = function (receivedHeader) {
    this.receivedRows.push(new ReceivedRow(receivedHeader));
};

Received.prototype.computeDeltas = function () {
    // Process received headers in reverse order
    this.receivedRows.reverse();

    // Parse rows and compute values needed for the "Delay" column
    var iStartTime = 0;
    var iEndTime = 0;
    var iLastTime = NaN;
    var iDelta = 0; // This will be the sum of our positive deltas
    var i;
    for (i = 0; i < this.receivedRows.length; i++) {
        if (!isNaN(this.receivedRows[i].dateNum)) {
            if (!isNaN(iLastTime) && iLastTime < this.receivedRows[i].dateNum) {
                iDelta += this.receivedRows[i].dateNum - iLastTime;
            }

            iStartTime = iStartTime || this.receivedRows[i].dateNum;
            iEndTime = this.receivedRows[i].dateNum;
            iLastTime = this.receivedRows[i].dateNum;
        }
    }

    iLastTime = NaN;
    var totalTime = "";
    // Total time is still last minus first, even if negative.
    if (iEndTime !== iStartTime) {
        totalTime = this.computeTime(iEndTime, iStartTime);
    }

    for (i = 0; i < this.receivedRows.length; i++) {
        this.receivedRows[i].hop = i + 1;
        this.receivedRows[i].delay = this.computeTime(this.receivedRows[i].dateNum, iLastTime);

        if (!isNaN(this.receivedRows[i].dateNum) && !isNaN(iLastTime) && iDelta !== 0) {
            this.receivedRows[i].delaySort = this.receivedRows[i].dateNum - iLastTime;

            // Only positive delays will get percentage bars. Negative delays will be color coded at render time.
            if (this.receivedRows[i].delaySort > 0) {
                this.receivedRows[i].percent = 100 * this.receivedRows[i].delaySort / iDelta;
            }
        }

        if (!isNaN(this.receivedRows[i].dateNum)) {
            iLastTime = this.receivedRows[i].dateNum;
        }
    }

    return totalTime;
};

// Computes min/sec from the diff of current and last.
// Returns nothing if last or current is NaN.
Received.prototype.computeTime = function (current, last) {
    var time = [];

    if (isNaN(current) || isNaN(last)) { return ""; }
    var diff = current - last;
    var iDelay;
    var printedMinutes = false;

    if (diff < 0) {
        time.push(ImportedStrings.mha_negative);
        diff = -diff;
    }

    if (diff >= 1000 * 60) {
        iDelay = Math.floor(diff / 1000 / 60);
        time.push(iDelay, " ");
        if (iDelay === 1) {
            time.push(ImportedStrings.mha_minute);
        } else {
            time.push(ImportedStrings.mha_minutes);
        }

        diff -= iDelay * 1000 * 60;
        printedMinutes = true;
    }

    if (printedMinutes && diff) {
        time.push(" ");
    }

    if (!printedMinutes || diff) {
        iDelay = Math.floor(diff / 1000);
        time.push(iDelay, " ");
        if (iDelay === 1) {
            time.push(ImportedStrings.mha_second);
        } else {
            time.push(ImportedStrings.mha_seconds);
        }
    }

    return time.join("");
};<|endoftext|>


<commit_before>const getGps = jest.fn(succeeds => {
  return new Promise((resolve, reject) => {
    if (succeeds) {
      resolve('Success!');
    } else {
      reject({ error: 'Error', trigger: 'gps' });
    }
  });
});
const makeHttps = jest.fn(succeeds => {
  return new Promise((resolve, reject) => {
    if (succeeds) {
      resolve('Success!');
    } else {
      reject({ error: 'Error', trigger: 'https' });
    }
  });
});

const clockIn = (gps, https) =>
  gps()
    .then(() => {
      return https()
        .catch(error => {
          throw error;
        })
        .then(() => 'OK');
    })
    .catch(error => {
      if (error.trigger === 'gps') {
        return https()
          .catch(() => {
            throw 'Error + GPS Warn';
          })
          .then(() => 'OK + GPS Warn');
      } else {
        throw error.error;
      }
    });

describe.only('The clock-in Module', () => {
  test('requests the GPS values', () => {
    expect.assertions(1);
    const expected = 'Success!';
    return expect(getGps(true)).resolves.toBe(expected);
  });

  test('sends the http request', () => {
    expect.assertions(1);
    const expected = 'Success!';
    return expect(makeHttps(true)).resolves.toBe(expected);
  });

  test('WHEN the gps succeeds AND https request succeeds', () => {
    expect.assertions(1);
    const expected = 'OK';
    return expect(clockIn(() => getGps(true), () => makeHttps(true))).resolves.toBe(expected);
  });
  test('WHEN the gps succeeds AND https request fails', () => {
    expect.assertions(1);
    const expected = 'Error';
    return expect(clockIn(() => getGps(true), () => makeHttps(false))).rejects.toBe(expected);
  });
  test('WHEN the gps fails AND https request succeeds', () => {
    expect.assertions(1);
    const expected = 'OK + GPS Warn';
    return expect(clockIn(() => getGps(false), () => makeHttps(true))).resolves.toBe(expected);
  });
  test('WHEN the gps fails AND https request fails', () => {
    expect.assertions(1);
    const expected = 'Error + GPS Warn';
    return expect(clockIn(() => getGps(false), () => makeHttps(false))).rejects.toBe(expected);
  });
});
<commit_msg>removed only<commit_after>const getGps = jest.fn(succeeds => {
  return new Promise((resolve, reject) => {
    if (succeeds) {
      resolve('Success!');
    } else {
      reject({ error: 'Error', trigger: 'gps' });
    }
  });
});
const makeHttps = jest.fn(succeeds => {
  return new Promise((resolve, reject) => {
    if (succeeds) {
      resolve('Success!');
    } else {
      reject({ error: 'Error', trigger: 'https' });
    }
  });
});

const clockIn = (gps, https) =>
  gps()
    .then(() => {
      return https()
        .catch(error => {
          throw error;
        })
        .then(() => 'OK');
    })
    .catch(error => {
      if (error.trigger === 'gps') {
        return https()
          .catch(() => {
            throw 'Error + GPS Warn';
          })
          .then(() => 'OK + GPS Warn');
      } else {
        throw error.error;
      }
    });

describe('The clock-in Module', () => {
  test('requests the GPS values', () => {
    expect.assertions(1);
    const expected = 'Success!';
    return expect(getGps(true)).resolves.toBe(expected);
  });

  test('sends the http request', () => {
    expect.assertions(1);
    const expected = 'Success!';
    return expect(makeHttps(true)).resolves.toBe(expected);
  });

  test('WHEN the gps succeeds AND https request succeeds', () => {
    expect.assertions(1);
    const expected = 'OK';
    return expect(clockIn(() => getGps(true), () => makeHttps(true))).resolves.toBe(expected);
  });
  test('WHEN the gps succeeds AND https request fails', () => {
    expect.assertions(1);
    const expected = 'Error';
    return expect(clockIn(() => getGps(true), () => makeHttps(false))).rejects.toBe(expected);
  });
  test('WHEN the gps fails AND https request succeeds', () => {
    expect.assertions(1);
    const expected = 'OK + GPS Warn';
    return expect(clockIn(() => getGps(false), () => makeHttps(true))).resolves.toBe(expected);
  });
  test('WHEN the gps fails AND https request fails', () => {
    expect.assertions(1);
    const expected = 'Error + GPS Warn';
    return expect(clockIn(() => getGps(false), () => makeHttps(false))).rejects.toBe(expected);
  });
});
<|endoftext|>


<commit_before>/**
 * @authors: @qdouble and @AngularClass
 */

const path = require('path');

// Helper functions
const _root = path.resolve(__dirname);

function checkNodeImport(context, request, cb) {
  if (!path.isAbsolute(request) && request.charAt(0) !== '.') {
    cb(null, 'commonjs ' + request); return;
  }
  cb();
}

function includeClientPackages(packages) {
  return function(context, request, cb) {
    if (packages && packages.indexOf(request) !== -1) {
      return cb();
    }
    return checkNodeImport(context, request, cb);
  };
}

function hasProcessFlag(flag) {
  return process.argv.join('').indexOf(flag) > -1;
}

function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [_root].concat(args));
}

function testDll() {
  try {
    require('./dll/polyfill.dll.js');
    require('./dll/vendor.dll.js');
  } catch(err) {
    throw `DLL files do not exist, please use 'npm run build:dll' once to generate dll files.`;
  }
};

exports.checkNodeImport;
exports.includeClientPackages = includeClientPackages;
exports.hasProcessFlag = hasProcessFlag;
exports.root = root;
exports.testDll = testDll;
<commit_msg>fix(DLL)test if files exist, don't use require (#95)<commit_after>/**
 * @authors: @qdouble and @AngularClass
 */

const path = require('path');
const fs = require('fs');

// Helper functions
const _root = path.resolve(__dirname);

function checkNodeImport(context, request, cb) {
  if (!path.isAbsolute(request) && request.charAt(0) !== '.') {
    cb(null, 'commonjs ' + request); return;
  }
  cb();
}

function includeClientPackages(packages) {
  return function (context, request, cb) {
    if (packages && packages.indexOf(request) !== -1) {
      return cb();
    }
    return checkNodeImport(context, request, cb);
  };
}

function hasProcessFlag(flag) {
  return process.argv.join('').indexOf(flag) > -1;
}

function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [_root].concat(args));
}

function testDll() {
  if (!fs.existsSync('./dll/polyfill.dll.js') || !fs.existsSync('./dll/vendor.dll.js')) {
    throw "DLL files do not exist, please use 'npm run build:dll' once to generate dll files.";
  }
};

exports.checkNodeImport;
exports.includeClientPackages = includeClientPackages;
exports.hasProcessFlag = hasProcessFlag;
exports.root = root;
exports.testDll = testDll;
<|endoftext|>


<commit_before>var fs = Npm.require('fs');
var path = Npm.require('path');
var exec = Npm.require('child_process').exec;

var isLoggingActive = true;
var project_path = path.join(process.cwd(), '..', '..', '..', '..', '..');

executeCommand = function(cmd, scope, args, callback) {
  if (typeof callback !== 'function') {
    Log.error("Result callback necessary!");
    return;
  }

  arg = args || [];
  cmd = cmd + ' ' + args.join(' ');

  var full_path = scope ? path.join(project_path, 'packages', scope) : project_path;

  console.log(scope, full_path);

  exec(cmd, {
    cwd: fs.existsSync(full_path) ? full_path : project_path
  }, function(err, stdout, stderr) {
    var err_result;
    if (err) {
      err_result = err;
    } else if (stderr) {
      err_result = {
        ____TYPE____: '[Error]',
        err: stderr
      };
    }

    if (err_result) {
      callback(err_result);
    } else {
      callback({
        message: stdout
      }, {
        log: true
      });
    }
  });
};

//checks if eval function in package scope available
findEval = function(package) {
  if (Package[package]) {
    var supported_package = _.find(_.values(Package[package]), function(exprt) {
      return exprt && typeof exprt.__serverEval === 'function';
    });
    return supported_package && supported_package.__serverEval;
  }
};

updateMetadata = function(initial) {
  //gather metadata and publish them
  var packages = _.keys(Package);
  var supported_packages = _.filter(packages, function(pkg) {
    return !!findEval(pkg);
  });

  var old_metadata = ServerEval._metadata.findOne({
    version: ServerEval.version
  });
  if (initial && old_metadata) {
    isLoggingActive = old_metadata.logging;
  }

  ServerEval._metadata.upsert({
    version: ServerEval.version
  }, {
    version: ServerEval.version,
    packages: packages,
    supported_packages: supported_packages,
    helpers: _.keys(ServerEval.helpers),
    logging: isLoggingActive,
    project_path: project_path
  });
};

updateMetadata(true);

createLogMessage = function(message, isError) {
  var message_obj;
  try {
    message_obj = EJSON.parse(message);
  } catch (e) {
    message_obj = {
      message: message
    };
  }

  ServerEval._results.insert({
    eval_time: Date.now(),
    log: true,
    err: isError,
    result: message_obj
  });
};

(function redirectStderr() {
  var stderr = process.stderr;
  var stderr_write = stderr.write;

  stderr.write = function(message) {
    stderr_write.apply(stderr, arguments);

    if (isLoggingActive) {
      createLogMessage(message, true);
    }
  };
})();

(function redirectStdout() {
  var stdout = process.stdout;
  var stdout_write = stdout.write;

  stdout.write = function(message) {
    stdout_write.apply(stdout, arguments);

    if (isLoggingActive) {
      createLogMessage(message);
    }
  };
})();

//helper definitions

ServerEval.helpers.abee = function(scope, args, callback) {
  executeCommand('abee', scope, args, callback);
};

ServerEval.helpers.updateMetadata = function() {
  updateMetadata();
};

ServerEval.helpers.toggleLogging = function() {
  isLoggingActive = !isLoggingActive;
  updateMetadata();
  return isLoggingActive ? 'ON' : 'OFF';
};<commit_msg>remove log entry<commit_after>var fs = Npm.require('fs');
var path = Npm.require('path');
var exec = Npm.require('child_process').exec;

var isLoggingActive = true;
var project_path = path.join(process.cwd(), '..', '..', '..', '..', '..');

executeCommand = function(cmd, scope, args, callback) {
  if (typeof callback !== 'function') {
    Log.error("Result callback necessary!");
    return;
  }

  arg = args || [];
  cmd = cmd + ' ' + args.join(' ');

  var full_path = scope ? path.join(project_path, 'packages', scope) : project_path;

  exec(cmd, {
    cwd: fs.existsSync(full_path) ? full_path : project_path
  }, function(err, stdout, stderr) {
    var err_result;
    if (err) {
      err_result = err;
    } else if (stderr) {
      err_result = {
        ____TYPE____: '[Error]',
        err: stderr
      };
    }

    if (err_result) {
      callback(err_result);
    } else {
      callback({
        message: stdout
      }, {
        log: true
      });
    }
  });
};

//checks if eval function in package scope available
findEval = function(package) {
  if (Package[package]) {
    var supported_package = _.find(_.values(Package[package]), function(exprt) {
      return exprt && typeof exprt.__serverEval === 'function';
    });
    return supported_package && supported_package.__serverEval;
  }
};

updateMetadata = function(initial) {
  //gather metadata and publish them
  var packages = _.keys(Package);
  var supported_packages = _.filter(packages, function(pkg) {
    return !!findEval(pkg);
  });

  var old_metadata = ServerEval._metadata.findOne({
    version: ServerEval.version
  });
  if (initial && old_metadata) {
    isLoggingActive = old_metadata.logging;
  }

  ServerEval._metadata.upsert({
    version: ServerEval.version
  }, {
    version: ServerEval.version,
    packages: packages,
    supported_packages: supported_packages,
    helpers: _.keys(ServerEval.helpers),
    logging: isLoggingActive,
    project_path: project_path
  });
};

updateMetadata(true);

createLogMessage = function(message, isError) {
  var message_obj;
  try {
    message_obj = EJSON.parse(message);
  } catch (e) {
    message_obj = {
      message: message
    };
  }

  ServerEval._results.insert({
    eval_time: Date.now(),
    log: true,
    err: isError,
    result: message_obj
  });
};

(function redirectStderr() {
  var stderr = process.stderr;
  var stderr_write = stderr.write;

  stderr.write = function(message) {
    stderr_write.apply(stderr, arguments);

    if (isLoggingActive) {
      createLogMessage(message, true);
    }
  };
})();

(function redirectStdout() {
  var stdout = process.stdout;
  var stdout_write = stdout.write;

  stdout.write = function(message) {
    stdout_write.apply(stdout, arguments);

    if (isLoggingActive) {
      createLogMessage(message);
    }
  };
})();

//helper definitions

ServerEval.helpers.abee = function(scope, args, callback) {
  executeCommand('abee', scope, args, callback);
};

ServerEval.helpers.updateMetadata = function() {
  updateMetadata();
};

ServerEval.helpers.toggleLogging = function() {
  isLoggingActive = !isLoggingActive;
  updateMetadata();
  return isLoggingActive ? 'ON' : 'OFF';
};<|endoftext|>


<commit_before>var hbs = require('express-hbs');
var fs = require('fs');
var slideshows = require('./slideshows.json');

registerHelper = function (){
    hbs.registerHelper("slideshow", function(articleId) {
        var dir = slideshows["rootDir"] + slideshows["articles"][articleId]["imgDir"];
        var urlPath = slideshows["urlPath"] + slideshows["articles"][articleId]["imgDir"];
        var dirList = fs.readdirSync(dir);
        var out = '
'
                + '
\n';
            out += '
\n';
            out += '\n';
            out += '
\n';
        for(var i=1, l=dirList.length; i<l; i++) {
            out += '
\n';
            out += '\n';
            out += '
\n';
        }
        return new hbs.SafeString(out + '
\n
\n');
    });
}

module.exports = registerHelper;
<commit_msg>Updating slideshow helper<commit_after>var hbs = require('express-hbs');
var fs = require('fs');
var slideshows = require('./slideshows.json');

/***
Articles should have a directory defined in slideshows.json or we check for a
directory with the same name as the articleId.
***/
registerHelper = function (){
    hbs.registerHelper("slideshow", function(articleId) {
        if (slideshows.articles && slideshows.articles[articleId] &&
            slideshows.articles[articleId].imgDir) {
            var dir = slideshows.rootDir + slideshows.articles[articleId].imgDir;
            var urlPath = slideshows.urlPath + slideshows.articles[articleId].imgDir;
        } else {
            var dir = slideshows.rootDir + articleId + "/";
            var urlPath = slideshows.urlPath + articleId + "/";
        }

        if (!fs.existsSync(dir)) {
            return new hbs.SafeString(' ');
        }
        var dirList = fs.readdirSync(dir);
        var out = '
'
                + '
\n';
            out += '
\n';
            out += '\n';
            out += '
\n';
        for(var i=1, l=dirList.length; i<l; i++) {
            out += '
\n';
            out += '\n';
            out += '
\n';
        }
        return new hbs.SafeString(out + '
\n
\n');
    });
}

module.exports = registerHelper;
<|endoftext|>


<commit_before>//Message handler for firing the calculate report function
chrome.runtime.onMessage.addListener(
 function(request, sender, sendResponse) {
 	if(request.method == "fireCalc"){
 		fireCalc(request.tabId);
 	}
 });

function fireCalc(tabId){
	chrome.storage.sync.get(tabId.toString(), function(items){
		if(getWidth() <= parseInt(items[tabId]["smallWidth"])){
			calculateReport(parseInt(items[tabId]["smallColumns"]));
		}else{
			calculateReport(parseInt(items[tabId]["largeColumns"]));
		}
	});
}

function calculateReport(size){
	if(!document.querySelectorAll(".grid-overlay-col").length) return;

	var width = document.querySelectorAll(".grid-overlay-col")[0].clientWidth;
	var gutter = calculateGutter();
	var output = '';

	for(var i = 1; i <= size; i++){
		var columnSetWidth = ((gutter * (i - 1)) + (width * i));

		if(i == size){
			output = output + columnSetWidth;
		}else{
			output = output + columnSetWidth + ',';
		}
	}

	chrome.runtime.sendMessage({
			method: 'resize',
			colSizes: output
		}
	);
}

function calculateGutter(){
	var  elements = document.getElementsByClassName('grid-overlay-col');
	var el = elements[0];
	var style = el.currentStyle || window.getComputedStyle(el);
	var margin = parseFloat(style.marginLeft) + parseFloat(style.marginRight);

	return margin;
}

function getWidth() {
  if (self.innerHeight) {
    return self.innerWidth;
  }

  if (document.documentElement && document.documentElement.clientWidth) {
    return document.documentElement.clientWidth;
  }

  if (document.body) {
    return document.body.clientWidth;
  }
}

<commit_msg>Fixed grid calculation<commit_after>//Message handler for firing the calculate report function
chrome.runtime.onMessage.addListener(
 function(request, sender, sendResponse) {
 	if(request.method == "fireCalc"){
 		fireCalc(request.tabId);
 	}
 });

function fireCalc(tabId){
	chrome.storage.sync.get(tabId.toString(), function(items){
		if(getWidth() <= parseInt(items[tabId]["smallWidth"])){
			calculateReport(parseInt(items[tabId]["smallColumns"]));
		}else{
			calculateReport(parseInt(items[tabId]["largeColumns"]));
		}
	});
}

function calculateReport(size){
	if(!document.querySelectorAll(".grid-overlay-col").length) return;

	var width = document.querySelectorAll(".grid-overlay-col")[1].clientWidth;
	var gutter = calculateGutter();

	console.log(width);
	console.log(gutter);
	var output = '';

	for(var i = 1; i <= size; i++){
		var columnSetWidth = ((gutter * (i - 1)) + (width * i));

		if(i == size){
			output = output + columnSetWidth;
		}else{
			output = output + columnSetWidth + ',';
		}
	}

	chrome.runtime.sendMessage({
			method: 'resize',
			colSizes: output
		}
	);
}

function calculateGutter(){
	var  elements = document.getElementsByClassName('grid-overlay-col');
	var el = elements[1];
	var style = el.currentStyle || window.getComputedStyle(el);
	var margin = parseFloat(style.marginLeft) + parseFloat(style.marginRight);

	return margin;
}

function getWidth() {
  if (self.innerHeight) {
    return self.innerWidth;
  }

  if (document.documentElement && document.documentElement.clientWidth) {
    return document.documentElement.clientWidth;
  }

  if (document.body) {
    return document.body.clientWidth;
  }
}

<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { SIZES } from './constants'

const Content = ({
  size,
  children,
  ...props
}) => (
  <div
    className={[
      'content',
      size && `is-${size}`
    ].filter(v => v).join(' ')}
    {...props}
  >
    {children}
  </div>
)

Content.propTypes = {
  size: PropTypes.oneOf(SIZES.slice(1)),
  children: PropTypes.node.isRequired
}

export default Content
<commit_msg>Fix Bulma content<commit_after>import React, { PropTypes } from 'react'
import { SIZES } from './constants'

const Content = ({
  size,
  children,
  ...props
}) => (
  <div
    className={[
      'content',
      size && `is-${size}`
    ].filter(v => v).join(' ')}
    {...props}
  >
    {children}
  </div>
)

Content.propTypes = {
  size: PropTypes.oneOf(SIZES.filter(size => size !== 'small')),
  children: PropTypes.node.isRequired
}

export default Content
<|endoftext|>


<commit_before>/*!
 * Copyright 2018 The Rust Project Developers. See the COPYRIGHT
 * file at the top-level directory of this distribution and at
 * http://rust-lang.org/COPYRIGHT.
 *
 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
 * option. This file may not be copied, modified, or distributed
 * except according to those terms.
 */

function getCurrentFilePath() {
    var parts = window.location.pathname.split("/");
    var rootPathParts = window.rootPath.split("/");

    for (var i = 0; i < rootPathParts.length; ++i) {
        if (rootPathParts[i] === "..") {
            parts.pop();
        }
    }
    var file = window.location.pathname.substring(parts.join("/").length);
    if (file.startsWith("/")) {
        file = file.substring(1);
    }
    return file.substring(0, file.length - 5);
}

function createDirEntry(elem, parent, fullPath, currentFile, hasFoundFile) {
    var name = document.createElement("div");
    name.className = "name";

    fullPath += elem["name"] + "/";

    name.onclick = function() {
        if (hasClass(this, "expand")) {
            removeClass(this, "expand");
        } else {
            addClass(this, "expand");
        }
    };
    name.innerText = elem["name"];

    var children = document.createElement("div");
    children.className = "children";
    var folders = document.createElement("div");
    folders.className = "folders";
    for (var i = 0; i < elem.dirs.length; ++i) {
        if (createDirEntry(elem.dirs[i], folders, fullPath, currentFile,
                           hasFoundFile) === true) {
            addClass(name, "expand");
            hasFoundFile = true;
        }
    }
    children.appendChild(folders);

    var files = document.createElement("div");
    files.className = "files";
    for (i = 0; i < elem.files.length; ++i) {
        var file = document.createElement("a");
        file.innerText = elem.files[i];
        file.href = window.rootPath + "src/" + fullPath + elem.files[i] + ".html";
        if (hasFoundFile === false &&
                currentFile === fullPath + elem.files[i]) {
            file.className = "selected";
            addClass(name, "expand");
            hasFoundFile = true;
        }
        files.appendChild(file);
    }
    search.fullPath = fullPath;
    children.appendChild(files);
    parent.appendChild(name);
    parent.appendChild(children);
    return hasFoundFile === true && currentFile.startsWith(fullPath);
}

function toggleSidebar() {
    var sidebar = document.getElementById("source-sidebar");
    var child = this.children[0].children[0];
    if (child.innerText === ">") {
        sidebar.style.left = "";
        this.style.left = "";
        child.innerText = "<";
        updateLocalStorage("rustdoc-source-sidebar-hidden", "false");
    } else {
        sidebar.style.left = "-300px";
        this.style.left = "0";
        child.innerText = ">";
        updateLocalStorage("rustdoc-source-sidebar-hidden", "true");
    }
}

function createSidebarToggle() {
    var sidebarToggle = document.createElement("div");
    sidebarToggle.id = "sidebar-toggle";
    sidebarToggle.onclick = toggleSidebar;

    var inner1 = document.createElement("div");
    inner1.style.position = "relative";

    var inner2 = document.createElement("div");
    inner2.style.marginTop = "-2px";
    if (getCurrentValue("rustdoc-source-sidebar-hidden") === "true") {
        inner2.innerText = ">";
        sidebarToggle.style.left = "0";
    } else {
        inner2.innerText = "<";
    }

    inner1.appendChild(inner2);
    sidebarToggle.appendChild(inner1);
    return sidebarToggle;
}

function createSourceSidebar() {
    if (window.rootPath.endsWith("/") === false) {
        window.rootPath += "/";
    }
    var main = document.getElementById("main");

    var sidebarToggle = createSidebarToggle();
    main.insertBefore(sidebarToggle, main.firstChild);

    var sidebar = document.createElement("div");
    sidebar.id = "source-sidebar";
    if (getCurrentValue("rustdoc-source-sidebar-hidden") === "true") {
        sidebar.style.left = "-300px";
    }

    var currentFile = getCurrentFilePath();
    var hasFoundFile = false;

    var title = document.createElement("div");
    title.className = "title";
    title.innerText = "Files";
    sidebar.appendChild(title);
    Object.keys(sourcesIndex).forEach(function(key) {
        sourcesIndex[key].name = key;
        hasFoundFile = createDirEntry(sourcesIndex[key], sidebar, "",
                                      currentFile, hasFoundFile);
    });

    main.insertBefore(sidebar, main.firstChild);
}

createSourceSidebar();
<commit_msg>Don't show file sidebar by default<commit_after>/*!
 * Copyright 2018 The Rust Project Developers. See the COPYRIGHT
 * file at the top-level directory of this distribution and at
 * http://rust-lang.org/COPYRIGHT.
 *
 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
 * option. This file may not be copied, modified, or distributed
 * except according to those terms.
 */

function getCurrentFilePath() {
    var parts = window.location.pathname.split("/");
    var rootPathParts = window.rootPath.split("/");

    for (var i = 0; i < rootPathParts.length; ++i) {
        if (rootPathParts[i] === "..") {
            parts.pop();
        }
    }
    var file = window.location.pathname.substring(parts.join("/").length);
    if (file.startsWith("/")) {
        file = file.substring(1);
    }
    return file.substring(0, file.length - 5);
}

function createDirEntry(elem, parent, fullPath, currentFile, hasFoundFile) {
    var name = document.createElement("div");
    name.className = "name";

    fullPath += elem["name"] + "/";

    name.onclick = function() {
        if (hasClass(this, "expand")) {
            removeClass(this, "expand");
        } else {
            addClass(this, "expand");
        }
    };
    name.innerText = elem["name"];

    var children = document.createElement("div");
    children.className = "children";
    var folders = document.createElement("div");
    folders.className = "folders";
    for (var i = 0; i < elem.dirs.length; ++i) {
        if (createDirEntry(elem.dirs[i], folders, fullPath, currentFile,
                           hasFoundFile) === true) {
            addClass(name, "expand");
            hasFoundFile = true;
        }
    }
    children.appendChild(folders);

    var files = document.createElement("div");
    files.className = "files";
    for (i = 0; i < elem.files.length; ++i) {
        var file = document.createElement("a");
        file.innerText = elem.files[i];
        file.href = window.rootPath + "src/" + fullPath + elem.files[i] + ".html";
        if (hasFoundFile === false &&
                currentFile === fullPath + elem.files[i]) {
            file.className = "selected";
            addClass(name, "expand");
            hasFoundFile = true;
        }
        files.appendChild(file);
    }
    search.fullPath = fullPath;
    children.appendChild(files);
    parent.appendChild(name);
    parent.appendChild(children);
    return hasFoundFile === true && currentFile.startsWith(fullPath);
}

function toggleSidebar() {
    var sidebar = document.getElementById("source-sidebar");
    var child = this.children[0].children[0];
    if (child.innerText === ">") {
        sidebar.style.left = "";
        this.style.left = "";
        child.innerText = "<";
        updateLocalStorage("rustdoc-source-sidebar-show", "true");
    } else {
        sidebar.style.left = "-300px";
        this.style.left = "0";
        child.innerText = ">";
        updateLocalStorage("rustdoc-source-sidebar-show", "false");
    }
}

function createSidebarToggle() {
    var sidebarToggle = document.createElement("div");
    sidebarToggle.id = "sidebar-toggle";
    sidebarToggle.onclick = toggleSidebar;

    var inner1 = document.createElement("div");
    inner1.style.position = "relative";

    var inner2 = document.createElement("div");
    inner2.style.marginTop = "-2px";
    if (getCurrentValue("rustdoc-source-sidebar-show") === "true") {
        inner2.innerText = "<";
    } else {
        inner2.innerText = ">";
        sidebarToggle.style.left = "0";
    }

    inner1.appendChild(inner2);
    sidebarToggle.appendChild(inner1);
    return sidebarToggle;
}

function createSourceSidebar() {
    if (window.rootPath.endsWith("/") === false) {
        window.rootPath += "/";
    }
    var main = document.getElementById("main");

    var sidebarToggle = createSidebarToggle();
    main.insertBefore(sidebarToggle, main.firstChild);

    var sidebar = document.createElement("div");
    sidebar.id = "source-sidebar";
    if (getCurrentValue("rustdoc-source-sidebar-show") !== "true") {
        sidebar.style.left = "-300px";
    }

    var currentFile = getCurrentFilePath();
    var hasFoundFile = false;

    var title = document.createElement("div");
    title.className = "title";
    title.innerText = "Files";
    sidebar.appendChild(title);
    Object.keys(sourcesIndex).forEach(function(key) {
        sourcesIndex[key].name = key;
        hasFoundFile = createDirEntry(sourcesIndex[key], sidebar, "",
                                      currentFile, hasFoundFile);
    });

    main.insertBefore(sidebar, main.firstChild);
}

createSourceSidebar();
<|endoftext|>


<commit_before>import { dataURLToBlob } from 'blob-util'

import db from 'src/pouchdb'
import { generatePageDocId } from 'src/page-storage'
import fetchPageData from 'src/page-analysis/background/fetch-page-data'
import { revisePageFields } from 'src/page-analysis'
import { IMPORT_TYPE, DOWNLOAD_STATUS } from 'src/options/imports/constants'
import * as index from 'src/search'
import {
    transformToMinimalVisitDoc,
    transformToMinimalBookmarkDoc,
    transformToVisitDoc,
    transformToBookmarkDoc,
} from 'src/imports'
import { clearOldExtData } from 'src/imports/background'

const fetchPageDataOpts = {
    includePageContent: true,
    includeFavIcon: true,
}

/**
 * TransitionType strings that we care about in the context of the ext.
 */
const wantedTransitionTypes = new Set([
    'link',
    'generated',
    'keyword',
    'keyword_generated',
    'typed',
    'auto_bookmark',
    'manual_subframe',
])

/**
 * @param {IImportItem} importItem
 * @throws {Error} Allows short-circuiting of the import process for current item if no VisitItems left after
 *  filtering.
 */
async function checkVisitItemTransitionTypes({ url }) {
    const visitItems = await browser.history.getVisits({ url })

    // Only keep VisitItems with wanted TransitionType
    const filteredVisitItems = visitItems.filter(item =>
        wantedTransitionTypes.has(item.transition),
    )

    // Throw if no VisitItems left post-filtering (only if there was items to begin with)
    if (visitItems.length > 0 && filteredVisitItems.length === 0) {
        throw new Error('Redirection URL')
    }
}

/**
 * @param {string?} favIconURL The data URL string for the favicon.
 * @returns {any} The `_attachments` entry to place into a PouchDB doc.
 */
const formatFavIconAttachment = async favIconURL => {
    if (!favIconURL) return undefined

    const blob = await dataURLToBlob(favIconURL)
    return { favIcon: { content_type: blob.type, data: blob } }
}

/**
 * Create visit docs from each of the WebExt history API's VisitItems. VisitItems with
 * TransitionTypes not wanted in the context of the extension will be ignored. More info:
 *  - https://developer.chrome.com/extensions/history#transition_types
 *
 * @param {PageDoc} pageDoc Page doc to get visits and create visit docs for.
 * @returns {Array<IVisitDoc>} Array of visit docs gotten from URLs in `pageDoc`.
 */
async function createAssociatedVisitDocs(pageDoc) {
    const visitItems = await browser.history.getVisits({ url: pageDoc.url })

    return visitItems
        .filter(item => wantedTransitionTypes.has(item.transition))
        .map(transformToVisitDoc(pageDoc))
}

async function createAssociatedBookmarkDoc(pageDoc, importItem) {
    // Web Ext. API should return array of BookmarkItems; grab first one
    const [bookmarkItem] = await browser.bookmarks.get(importItem.browserId)

    return transformToBookmarkDoc(pageDoc)(bookmarkItem)
}

async function createPageDoc({ url }) {
    // Do the page data fetch
    const { content, favIconURI } = await fetchPageData({
        url,
        opts: fetchPageDataOpts,
    })

    // Sort out all binary attachments
    const _attachments = await formatFavIconAttachment(favIconURI)

    // Construct the page doc ready for PouchDB from fetched + import item data
    return revisePageFields({
        _id: generatePageDocId({ url }),
        url,
        content,
        _attachments,
    })
}

const storeDocs = ({ pageDoc, bookmarkDocs = [], visitDocs = [] }) =>
    Promise.all([
        index.addPageConcurrent({ pageDoc, visitDocs, bookmarkDocs }),
        db.bulkDocs([pageDoc, ...bookmarkDocs, ...visitDocs]),
    ])

/**
 * Handles processing of a history-type import item. Checks for exisitng page docs that have the same URL.
 *
 * @param {IImportItem} importItemDoc
 * @returns {any} Status string denoting the outcome of import processing as `status`
 *  + optional filled-out page doc as `pageDoc` field.
 */
async function processHistoryImport(importItem) {
    await checkVisitItemTransitionTypes(importItem)

    const pageDoc = await createPageDoc(importItem)

    // Fetch and create meta-docs
    const visitDocs = await createAssociatedVisitDocs(pageDoc)
    const bookmarkDocs = []

    if (importItem.type === IMPORT_TYPE.BOOKMARK) {
        bookmarkDocs.push(
            await createAssociatedBookmarkDoc(pageDoc, importItem),
        )
    }

    await storeDocs({ pageDoc, visitDocs, bookmarkDocs })

    // If we finally got here without an error being thrown, return the success status message + pageDoc data
    return { status: DOWNLOAD_STATUS.SUCC }
}

async function processOldExtImport(importItem) {
    const pageDoc = await createPageDoc(importItem)

    // Fetch and create meta-docs
    const visitDocs = await createAssociatedVisitDocs(pageDoc)
    const bookmarkDocs = []

    if (importItem.hasBookmark) {
        bookmarkDocs.push(transformToMinimalBookmarkDoc(pageDoc)(importItem))
    } else {
        visitDocs.push(transformToMinimalVisitDoc(pageDoc)(importItem))
    }

    await storeDocs({ pageDoc, visitDocs, bookmarkDocs })

    // If all okay now, remove the old data
    await clearOldExtData(importItem)

    return { status: DOWNLOAD_STATUS.SUCC }
}

/**
 * Given an import state item, performs appropriate processing depending on the import type.
 *
 * @param {[string, IImportItem]} Key-value pair of encoded URL to import item value.
 * @returns {string} Status string denoting the outcome of import processing as `status`
 *  + optional filled-out page doc as `pageDoc` field.
 */
export default async function processImportItem([encodedUrl, importItem = {}]) {
    switch (importItem.type) {
        case IMPORT_TYPE.BOOKMARK:
        case IMPORT_TYPE.HISTORY:
            return await processHistoryImport(importItem)
        case IMPORT_TYPE.OLD:
            return await processOldExtImport(importItem)
        default:
            throw new Error('Unknown import type')
    }
}
<commit_msg>DRY-out VisitItem filter fn + add missing JSDoc<commit_after>import { dataURLToBlob } from 'blob-util'

import db from 'src/pouchdb'
import { generatePageDocId } from 'src/page-storage'
import fetchPageData from 'src/page-analysis/background/fetch-page-data'
import { revisePageFields } from 'src/page-analysis'
import { IMPORT_TYPE, DOWNLOAD_STATUS } from 'src/options/imports/constants'
import * as index from 'src/search'
import {
    transformToMinimalVisitDoc,
    transformToMinimalBookmarkDoc,
    transformToVisitDoc,
    transformToBookmarkDoc,
} from 'src/imports'
import { clearOldExtData } from 'src/imports/background'

const fetchPageDataOpts = {
    includePageContent: true,
    includeFavIcon: true,
}

/**
 * TransitionType strings that we care about in the context of the ext.
 */
const wantedTransitionTypes = new Set([
    'link',
    'generated',
    'keyword',
    'keyword_generated',
    'typed',
    'auto_bookmark',
    'manual_subframe',
])

/**
 * @param {history.VisitItem} item VisitItem object received from the WebExt History API.
 * @returns {boolean}
 */
const filterVisitItemByTransType = item =>
    wantedTransitionTypes.has(item.transition)

/**
 * @param {IImportItem} importItem
 * @throws {Error} Allows short-circuiting of the import process for current item if no VisitItems left after
 *  filtering.
 */
async function checkVisitItemTransitionTypes({ url }) {
    const visitItems = await browser.history.getVisits({ url })

    // Only keep VisitItems with wanted TransitionType
    const filteredVisitItems = visitItems.filter(filterVisitItemByTransType)

    // Throw if no VisitItems left post-filtering (only if there was items to begin with)
    if (visitItems.length > 0 && filteredVisitItems.length === 0) {
        throw new Error('Redirection URL')
    }
}

/**
 * @param {string?} favIconURL The data URL string for the favicon.
 * @returns {any} The `_attachments` entry to place into a PouchDB doc.
 */
const formatFavIconAttachment = async favIconURL => {
    if (!favIconURL) return undefined

    const blob = await dataURLToBlob(favIconURL)
    return { favIcon: { content_type: blob.type, data: blob } }
}

/**
 * Create visit docs from each of the WebExt history API's VisitItems. VisitItems with
 * TransitionTypes not wanted in the context of the extension will be ignored. More info:
 *  - https://developer.chrome.com/extensions/history#transition_types
 *
 * @param {PageDoc} pageDoc Page doc to get visits and create visit docs for.
 * @returns {Array<IVisitDoc>} Array of visit docs gotten from URLs in `pageDoc`.
 */
async function createAssociatedVisitDocs(pageDoc) {
    const visitItems = await browser.history.getVisits({ url: pageDoc.url })

    return visitItems
        .filter(filterVisitItemByTransType)
        .map(transformToVisitDoc(pageDoc))
}

async function createAssociatedBookmarkDoc(pageDoc, importItem) {
    // Web Ext. API should return array of BookmarkItems; grab first one
    const [bookmarkItem] = await browser.bookmarks.get(importItem.browserId)

    return transformToBookmarkDoc(pageDoc)(bookmarkItem)
}

async function createPageDoc({ url }) {
    // Do the page data fetch
    const { content, favIconURI } = await fetchPageData({
        url,
        opts: fetchPageDataOpts,
    })

    // Sort out all binary attachments
    const _attachments = await formatFavIconAttachment(favIconURI)

    // Construct the page doc ready for PouchDB from fetched + import item data
    return revisePageFields({
        _id: generatePageDocId({ url }),
        url,
        content,
        _attachments,
    })
}

const storeDocs = ({ pageDoc, bookmarkDocs = [], visitDocs = [] }) =>
    Promise.all([
        index.addPageConcurrent({ pageDoc, visitDocs, bookmarkDocs }),
        db.bulkDocs([pageDoc, ...bookmarkDocs, ...visitDocs]),
    ])

/**
 * Handles processing of a history-type import item. Checks for exisitng page docs that have the same URL.
 *
 * @param {IImportItem} importItemDoc
 * @returns {any} Status string denoting the outcome of import processing as `status`
 *  + optional filled-out page doc as `pageDoc` field.
 */
async function processHistoryImport(importItem) {
    await checkVisitItemTransitionTypes(importItem)

    const pageDoc = await createPageDoc(importItem)

    // Fetch and create meta-docs
    const visitDocs = await createAssociatedVisitDocs(pageDoc)
    const bookmarkDocs = []

    if (importItem.type === IMPORT_TYPE.BOOKMARK) {
        bookmarkDocs.push(
            await createAssociatedBookmarkDoc(pageDoc, importItem),
        )
    }

    await storeDocs({ pageDoc, visitDocs, bookmarkDocs })

    // If we finally got here without an error being thrown, return the success status message + pageDoc data
    return { status: DOWNLOAD_STATUS.SUCC }
}

async function processOldExtImport(importItem) {
    const pageDoc = await createPageDoc(importItem)

    // Fetch and create meta-docs
    const visitDocs = await createAssociatedVisitDocs(pageDoc)
    const bookmarkDocs = []

    if (importItem.hasBookmark) {
        bookmarkDocs.push(transformToMinimalBookmarkDoc(pageDoc)(importItem))
    } else {
        visitDocs.push(transformToMinimalVisitDoc(pageDoc)(importItem))
    }

    await storeDocs({ pageDoc, visitDocs, bookmarkDocs })

    // If all okay now, remove the old data
    await clearOldExtData(importItem)

    return { status: DOWNLOAD_STATUS.SUCC }
}

/**
 * Given an import state item, performs appropriate processing depending on the import type.
 *
 * @param {[string, IImportItem]} Key-value pair of encoded URL to import item value.
 * @returns {string} Status string denoting the outcome of import processing as `status`
 *  + optional filled-out page doc as `pageDoc` field.
 */
export default async function processImportItem([encodedUrl, importItem = {}]) {
    switch (importItem.type) {
        case IMPORT_TYPE.BOOKMARK:
        case IMPORT_TYPE.HISTORY:
            return await processHistoryImport(importItem)
        case IMPORT_TYPE.OLD:
            return await processOldExtImport(importItem)
        default:
            throw new Error('Unknown import type')
    }
}
<|endoftext|>


<commit_before>var connsSparql = ([
"SELECT ?email ?school_lat ?school_long ?data_lat ?data_long ?strength",
"WHERE{",
"  ?school <http://data.ordnancesurvey.co.uk/ontology/postcode/postcode> ?pc.",
"  ?school <http://www.w3.org/2006/vcard/ns#hasEmail> ?email.",
"  ?pc <http://www.w3.org/2003/01/geo/wgs84_pos#lat> ?school_lat.",
"  ?pc <http://www.w3.org/2003/01/geo/wgs84_pos#long> ?school_long.",
"  ?zone <http://www.w3.org/2003/01/geo/wgs84_pos#lat> ?data_lat.",
"  ?zone <http://www.w3.org/2003/01/geo/wgs84_pos#long> ?data_long.",
"  ?nop <http://data.opendatascotland.org/def/education/numberOfPupils> ?strength.",
"  ?nop <http://data.opendatascotland.org/def/statistical-dimensions/education/school> ?school.",
"  ?nop <http://data.opendatascotland.org/def/statistical-dimensions/refArea> ?zone.",
"  ?school <http://data.opendatascotland.org/def/education/department> ?dep.",
"  ?dep <http://data.opendatascotland.org/def/education/stageOfEducation> <http://data.opendatascotland.org/def/concept/education/stages-of-education/%{stage}>.",
"}",
"ORDER BY ?email"]).join("\n");

var connsUrl = "http://data.opendatascotland.org/sparql.csv?query=" + encodeURIComponent(connsSparql);

var schoolsSparql = ([
"SELECT ?email ?lat ?long (SUM (?nop) as ?size) ?name",
"WHERE{",
"  ?school <http://data.ordnancesurvey.co.uk/ontology/postcode/postcode> ?pc.",
"  ?school <http://www.w3.org/2006/vcard/ns#hasEmail> ?email.",
"  ?pc <http://www.w3.org/2003/01/geo/wgs84_pos#lat> ?lat.",
"  ?pc <http://www.w3.org/2003/01/geo/wgs84_pos#long> ?long.",
"  OPTIONAL{",
"    ?school <http://www.w3.org/2000/01/rdf-schema#label> ?name",
"  }",
"  GRAPH <http://data.opendatascotland.org/graph/education/pupils-by-school-and-datazone>{",
"    ?x <http://data.opendatascotland.org/def/statistical-dimensions/education/school> ?school.",
"    ?x <http://data.opendatascotland.org/def/education/numberOfPupils> ?nop.",
"  }",
"  ?school <http://data.opendatascotland.org/def/education/department> ?dep.",
"  ?dep <http://data.opendatascotland.org/def/education/stageOfEducation> <http://data.opendatascotland.org/def/concept/education/stages-of-education/%{stage}>.",
"}",
"GROUP BY ?email ?lat ?long ?size ?name",
"ORDER BY ?email"]).join("\n");

var schoolsUrl = "http://data.opendatascotland.org/sparql.csv?query=" + encodeURIComponent(schoolsSparql);

var schools = [];

// schoolType one of "secondary", "primary", "pre-school"
function requestData(schoolType){
  clean();
  var connsUrl = "http://data.opendatascotland.org/sparql.csv?query=" +
    encodeURIComponent(connsSparql) + "&stage=" +
    encodeURIComponent(schoolType);
  var schoolsUrl = "http://data.opendatascotland.org/sparql.csv?query=" +
    encodeURIComponent(schoolsSparql) + "&stage=" +
    encodeURIComponent(schoolType);
  $.ajax({
    dataType: 'text',
    url: schoolsUrl,
    success: function(data){
      data = data.split("\n");
      for(var i = 1; i < data.length - 1; i++){
        var row = data[i].split(',');
        schools.push({
          'email': row[0],
          'name': row[4],
          'latLong': new google.maps.LatLng(parseFloat(row[1]),
              parseFloat(row[2])),
          'size': parseInt(row[3]),
          'conns': []
        });
      }
      $.ajax({
        dataType: 'text',
        url: connsUrl,
        success: function(data){
          data = data.split("\n");
          var j = 0;
          for(var i = 1; i < data.length - 1; i++){
            var row = data[i].split(',');
            while(schools[j].email != row[0])
              j++;
            schools[j].conns.push({
              'latLong': new google.maps.LatLng(parseFloat(row[3]),
                  parseFloat(row[4])),
              'strength': parseInt(row[5])
            });
          }
          drawConns();
          drawSchools();
        }
      });
    }
  });
}

var showingPreSchools = false;
var showingPrimarySchools = false;
var showingSecondarySchools = true;

//TODO make redraw hide and show objects rather than re-calling the database.
function redraw() {
  if(showingPreSchools) {
    requestData("pre-school");
  }

  if(showingPrimarySchools) {
    requestData("primary");
  }

  if(showingSecondarySchools) {
    requestData("secondary");
  }
}

redraw();

function clean(){
  for(var i = 0; i < schools.length; i++){
    schools[i].ui.circle.setMap(null);
    schools[i].ui.infowindow.close();
    for(var j = 0; j < schools[i].conns.length; j++){
      var conn = schools[i].conns[j];
      if(conn.ui)
        schools[i].conns[j].ui.setMap(null);
    }
  }
  schools = [];
}

function drawSchools(data){
var totStudents = 0;
  for(var i = 0; i < schools.length; i++){
    drawSchool(schools[i]);
  }
}

function drawConns(data){
  for(var i = 0; i < schools.length; i++){
    for(var j = 0; j < schools[i].conns.length; j++){
      var conn = schools[i].conns[j];
      if(conn.strength < 10)
        continue;
      drawPath(schools[i], conn);
    }
  }
}

function drawZone(map, zoneLatLong){
  drawPoint
}

function drawArrow(map, zoneLatLong, schoolLatLong) {}

var map;

var mapStyles = [ { "featureType": "poi", "stylers": [ { "weight": 1.9 }, { "visibility": "off" } ] },{ "featureType": "poi.school", "stylers": [ { "visibility": "on" } ] },{ "featureType": "landscape.man_made", "stylers": [ { "visibility": "on" } ] },{ "featureType": "landscape.natural", "stylers": [ { "visibility": "off" } ] } ] ;

function initialize() {
  var centerLatlng = new google.maps.LatLng(56.632064,-3.729858);
  var mapOptions = {
    zoom: 7,
	disableDefaultUI: true,
    center: centerLatlng ,
    mapTypeControlOptions: {
        mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
      }
  }

  var mapDiv = document.getElementById('map-canvas');
  map = new google.maps.Map(mapDiv, mapOptions);

  map.setOptions({styles : mapStyles})

  var defStyle = [{}]

  var styledMap = new google.maps.StyledMapType(defStyle, {name: "Default"});
  map.mapTypes.set('map_style', styledMap);
  map.setMapTypeId('map_style');

  button(" pre-", showingPreSchools);
  button(" primary ", showingPrimarySchools);
  button(" secondary ", showingSecondarySchools);
}

function button(type, bool) {
  var homeControlDiv = document.createElement('div');
  var bc = new buttonControl(homeControlDiv, type, bool);
  map.controls[google.maps.ControlPosition.RIGHT_TOP].push(homeControlDiv);
}

function buttonControl(controlDiv, type, bool) {
  var startDrawing = "Show" + type + "schools";
  var stopDrawing = "Hide" + type + "schools";
  var info = "Toggle" + type + "schools";
  var showColor = "green";
  var hideColor = "red";

  controlDiv.style.padding = '5px';

  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = bool ? hideColor : showColor;
  controlUI.style.width = "160px";
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = info;
  controlDiv.appendChild(controlUI);

  var controlText = document.createElement('div');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.innerHTML = bool ? stopDrawing : startDrawing;
  controlUI.appendChild(controlText);

  google.maps.event.addDomListener(controlUI, 'click', function() {
	bool = !bool; //toggle the drawing state

    if(bool) { //if drawing
	  controlText.innerHTML = stopDrawing; //set button text to "stop drawing"
      controlUI.style.backgroundColor = hideColor;
	} else {
	  controlText.innerHTML = startDrawing; // set button text to "draw"
	  controlUI.style.backgroundColor = showColor;
	}
	redraw(); //redraw all the schools
  });
}

function drawPath(LatSchool, LongSchool, LatDataZone, LongDataZone) {
  drawPath(map, new google.maps.LatLng(LatSchool, LongSchool),
			new google.maps.LatLng(LatDataZone, LongDataZone)
  );
}

function drawPath(school, conn) {
  var options = {
    path: [conn.latLong, school.latLong],
    strokeOpacity: Math.min(1.0, (Math.log(conn.strength) - 2) / 2),
    strokeWeight: 1.0,
    icons: [{
      offset: '100%'
    }],
    map: map
  };

  conn.ui = new google.maps.Polyline(options);
}

function drawSchool(school) {
  var options = {
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.25,
    map: map,
    center: school.latLong,
    radius: (school.size * 0.5)
  };

  var circ = new google.maps.Circle(options);
  school.ui = {
    'circle': circ,
    'infowindow': new google.maps.InfoWindow({
      content: '
' + school.name + '

' + "Students: " + school.size +  '
',
      position: circ.center
    })
  }

  google.maps.event.addListener(school.ui.circle, 'mouseover', function() {
    if (map.getZoom() > 8) {
      school.ui.infowindow.open(map) }
  });

  google.maps.event.addListener(school.ui.circle, 'mouseout', function() {
    school.ui.infowindow.close();
  });
}

//on load, run initialize
google.maps.event.addDomListener(window, 'load', initialize);

<commit_msg>Fixed the button system to hide and show specific schools.<commit_after>var connsSparql = ([
"SELECT ?email ?school_lat ?school_long ?data_lat ?data_long ?strength",
"WHERE{",
"  ?school <http://data.ordnancesurvey.co.uk/ontology/postcode/postcode> ?pc.",
"  ?school <http://www.w3.org/2006/vcard/ns#hasEmail> ?email.",
"  ?pc <http://www.w3.org/2003/01/geo/wgs84_pos#lat> ?school_lat.",
"  ?pc <http://www.w3.org/2003/01/geo/wgs84_pos#long> ?school_long.",
"  ?zone <http://www.w3.org/2003/01/geo/wgs84_pos#lat> ?data_lat.",
"  ?zone <http://www.w3.org/2003/01/geo/wgs84_pos#long> ?data_long.",
"  ?nop <http://data.opendatascotland.org/def/education/numberOfPupils> ?strength.",
"  ?nop <http://data.opendatascotland.org/def/statistical-dimensions/education/school> ?school.",
"  ?nop <http://data.opendatascotland.org/def/statistical-dimensions/refArea> ?zone.",
"  ?school <http://data.opendatascotland.org/def/education/department> ?dep.",
"  ?dep <http://data.opendatascotland.org/def/education/stageOfEducation> <http://data.opendatascotland.org/def/concept/education/stages-of-education/%{stage}>.",
"}",
"ORDER BY ?email"]).join("\n");

var connsUrl = "http://data.opendatascotland.org/sparql.csv?query=" + encodeURIComponent(connsSparql);

var schoolsSparql = ([
"SELECT ?email ?lat ?long (SUM (?nop) as ?size) ?name",
"WHERE{",
"  ?school <http://data.ordnancesurvey.co.uk/ontology/postcode/postcode> ?pc.",
"  ?school <http://www.w3.org/2006/vcard/ns#hasEmail> ?email.",
"  ?pc <http://www.w3.org/2003/01/geo/wgs84_pos#lat> ?lat.",
"  ?pc <http://www.w3.org/2003/01/geo/wgs84_pos#long> ?long.",
"  OPTIONAL{",
"    ?school <http://www.w3.org/2000/01/rdf-schema#label> ?name",
"  }",
"  GRAPH <http://data.opendatascotland.org/graph/education/pupils-by-school-and-datazone>{",
"    ?x <http://data.opendatascotland.org/def/statistical-dimensions/education/school> ?school.",
"    ?x <http://data.opendatascotland.org/def/education/numberOfPupils> ?nop.",
"  }",
"  ?school <http://data.opendatascotland.org/def/education/department> ?dep.",
"  ?dep <http://data.opendatascotland.org/def/education/stageOfEducation> <http://data.opendatascotland.org/def/concept/education/stages-of-education/%{stage}>.",
"}",
"GROUP BY ?email ?lat ?long ?size ?name",
"ORDER BY ?email"]).join("\n");

var DEBUG = true;

var schoolsUrl = "http://data.opendatascotland.org/sparql.csv?query=" + encodeURIComponent(schoolsSparql);

var schools = [];

// schoolType one of "secondary", "primary", "pre-school"
//do not call directly, called from "redraw()"
function requestData(schoolType){
  var connsUrl = "http://data.opendatascotland.org/sparql.csv?query=" +
    encodeURIComponent(connsSparql) + "&stage=" +
    encodeURIComponent(schoolType);
  var schoolsUrl = "http://data.opendatascotland.org/sparql.csv?query=" +
    encodeURIComponent(schoolsSparql) + "&stage=" +
    encodeURIComponent(schoolType);
  $.ajax({
    dataType: 'text',
    url: schoolsUrl,
    success: function(data){
      data = data.split("\n");
      for(var i = 1; i < data.length - 1; i++){
        var row = data[i].split(',');
        schools.push({
          'email': row[0],
          'name': row[4],
          'latLong': new google.maps.LatLng(parseFloat(row[1]),
              parseFloat(row[2])),
          'size': parseInt(row[3]),
          'conns': []
        });
      }
      $.ajax({
        dataType: 'text',
        url: connsUrl,
        success: function(data){
          data = data.split("\n");
          var j = 0;
          for(var i = 1; i < data.length - 1; i++){
            var row = data[i].split(',');
            while(schools[j].email != row[0])
              j++;
            schools[j].conns.push({
              'latLong': new google.maps.LatLng(parseFloat(row[3]),
                  parseFloat(row[4])),
              'strength': parseInt(row[5])
            });
          }
          drawConns();
          drawSchools();
        }
      });
    }
  });
}

//boolean values as objects so that they are mutable form inside the button listener
var showingPreSchools = {value: false};
var showingPrimarySchools = {value: false};
var showingSecondarySchools = {value: true};

//TODO make redraw hide and show objects rather than re-calling the database.
function redraw() {
  clean(); //remove everything

  if(DEBUG) {
	console.log("Showing Pre-Schools: " + showingPreSchools.value);
	console.log("Showing Primary Schools: " + showingPrimarySchools.value);
	console.log("Showing Secondary Schools: " + showingSecondarySchools.value);
  }

  if(showingPreSchools.value) { //if supposed to be drawing; draw.
    requestData("pre-school");
  }

  if(showingPrimarySchools.value) {
    requestData("primary");
  }

  if(showingSecondarySchools.value) {
    requestData("secondary");
  }
}

redraw();

//removed all currently drawing map objects.
function clean() {
  for(var i = 0; i < schools.length; i++){
    schools[i].ui.circle.setMap(null);
    schools[i].ui.infowindow.close();
    for(var j = 0; j < schools[i].conns.length; j++){
      var conn = schools[i].conns[j];
      if(conn.ui)
        schools[i].conns[j].ui.setMap(null);
    }
  }
  schools = [];
}

function drawSchools(data){
var totStudents = 0;
  for(var i = 0; i < schools.length; i++){
    drawSchool(schools[i]);
  }
}

function drawConns(data){
  for(var i = 0; i < schools.length; i++){
    for(var j = 0; j < schools[i].conns.length; j++){
      var conn = schools[i].conns[j];
      if(conn.strength < 10)
        continue;
      drawPath(schools[i], conn);
    }
  }
}

function drawZone(map, zoneLatLong){
  drawPoint //what this? //
}

function drawArrow(map, zoneLatLong, schoolLatLong) {}

var map;

var mapStyles = [ { "featureType": "poi", "stylers": [ { "weight": 1.9 }, { "visibility": "off" } ] },{ "featureType": "poi.school", "stylers": [ { "visibility": "on" } ] },{ "featureType": "landscape.man_made", "stylers": [ { "visibility": "on" } ] },{ "featureType": "landscape.natural", "stylers": [ { "visibility": "off" } ] } ] ;

function initialize() {
  var centerLatlng = new google.maps.LatLng(56.632064,-3.729858);
  var mapOptions = {
    zoom: 7,
	disableDefaultUI: true,
    center: centerLatlng ,
    mapTypeControlOptions: {
        mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
      }
  }

  var mapDiv = document.getElementById('map-canvas');
  map = new google.maps.Map(mapDiv, mapOptions);

  map.setOptions({styles : mapStyles})

  var defStyle = [{}]

  var styledMap = new google.maps.StyledMapType(defStyle, {name: "Default"});
  map.mapTypes.set('map_style', styledMap);
  map.setMapTypeId('map_style');

  button(" Pre-", showingPreSchools);
  button(" Primary ", showingPrimarySchools);
  button(" Secondary ", showingSecondarySchools);
}

function button(type, bool) {
  var homeControlDiv = document.createElement('div');
  var bc = new buttonControl(homeControlDiv, type, bool);
  map.controls[google.maps.ControlPosition.RIGHT_TOP].push(homeControlDiv);
}

function buttonControl(controlDiv, type, bool) {
  var startDrawing = "Show" + type + "Schools";
  var stopDrawing = "Hide" + type + "Schools";
  var info = "Toggle" + type + "Schools";
  var showColor = "green";
  var hideColor = "red";

  controlDiv.style.padding = '5px';

  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = bool.value ? hideColor : showColor;
  controlUI.style.width = '160px';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = info;
  controlDiv.appendChild(controlUI);

  var controlText = document.createElement('div');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.innerHTML = bool.value ? stopDrawing : startDrawing;
  controlUI.appendChild(controlText);

  google.maps.event.addDomListener(controlUI, 'click', function() {
	bool.value = !bool.value; //toggle the drawing state

    if(bool.value) { //if drawing
	  controlText.innerHTML = stopDrawing; //set button text to "stop drawing"
      controlUI.style.backgroundColor = hideColor;
	} else {
	  controlText.innerHTML = startDrawing; // set button text to "draw"
	  controlUI.style.backgroundColor = showColor;
	}
	redraw(); //redraw all the schools
  });
}

function drawPath(LatSchool, LongSchool, LatDataZone, LongDataZone) {
  drawPath(map, new google.maps.LatLng(LatSchool, LongSchool),
			new google.maps.LatLng(LatDataZone, LongDataZone)
  );
}

function drawPath(school, conn) {
  var options = {
    path: [conn.latLong, school.latLong],
    strokeOpacity: Math.min(1.0, (Math.log(conn.strength) - 2) / 2),
    strokeWeight: 1.0,
    icons: [{
      offset: '100%'
    }],
    map: map
  };

  conn.ui = new google.maps.Polyline(options);
}

function drawSchool(school) {
  var options = {
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.25,
    map: map,
    center: school.latLong,
    radius: (school.size * 0.5)
  };

  var circ = new google.maps.Circle(options);
  school.ui = {
    'circle': circ,
    'infowindow': new google.maps.InfoWindow({
      content: '
' + school.name + '

' + "Students: " + school.size +  '
',
      position: circ.center
    })
  }

  google.maps.event.addListener(school.ui.circle, 'mouseover', function() {
    if (map.getZoom() > 8) {
      school.ui.infowindow.open(map) }
  });

  google.maps.event.addListener(school.ui.circle, 'mouseout', function() {
    school.ui.infowindow.close();
  });
}

//on load, run initialize
google.maps.event.addDomListener(window, 'load', initialize);

<|endoftext|>


<commit_before>function createGraph(){
	r = new XMLHttpRequest();
	r.open("GET", "http://lounge.kiosk.shack:8088");
	r.onreadystatechange=function(){
		response = JSON.parse(this.responseText);

		holders = [];
		durations = [];
		for(var key in response) {
			holders.push(key)
			durations.push(response[key]/3600)
		}

		var data = {
			labels: holders,
			datasets:[{
				data: durations
			}]
		};

		var options = {
			scaleBeginAtZero : true,
			scaleFontSize: 24,
			scaleFontColor: "#bbb",
			responsive: false,
			showTooltips: false
		};

		//Create Chart
		console.log("Created");
		mateChart = new Chart(ctx).Bar(data, options);

		for(barNr in mateChart.datasets[0].bars){
			mateChart.datasets[0].bars[barNr].fillColor = "#"+((1<<24)*Math.random()|0).toString(16);
		}
		mateChart.update()

	}
	r.send();
}

document.onreadystatechange = function() {
	var state = document.readyState;
	if(state == 'complete') {
		ctx = document.getElementById("holderChart").getContext("2d");
		createGraph();
	}
}
<commit_msg>Sort the keyholder times<commit_after>function createGraph(){
	r = new XMLHttpRequest();
	r.open("GET", "http://lounge.kiosk.shack:8088");
	r.onreadystatechange=function(){
		response = JSON.parse(this.responseText);

		holders = [];
		durations = [];
		for(var key in response) {
			durations.push(parseFloat(response[key]))
		}
		console.log(durations)
 		durations.sort(function(a,b) { return a - b;});
 		durations.reverse();
		console.log(durations)
		console.log(response)

		durationHours = []
		for (var duration of durations){
			console.log(durations)
			for (var keyholder in response){
				if (response[keyholder] == duration){
					holders.push(keyholder);
				}
			}
			durationHours.push(duration/3600)

		}

		console.log(holders)

		var data = {
			labels: holders,
			datasets:[{
				data: durationHours
			}]
		};

		var options = {
			scaleBeginAtZero : true,
			scaleFontSize: 24,
			scaleFontColor: "#bbb",
			responsive: false,
			showTooltips: false
		};

		//Create Chart
		console.log("Created");
		mateChart = new Chart(ctx).Bar(data, options);

		for(barNr in mateChart.datasets[0].bars){
			mateChart.datasets[0].bars[barNr].fillColor = "#"+((1<<24)*Math.random()|0).toString(16);
		}
		mateChart.update()

	}
	r.send();
}

document.onreadystatechange = function() {
	var state = document.readyState;
	if(state == 'complete') {
		ctx = document.getElementById("holderChart").getContext("2d");
		createGraph();
	}
}
<|endoftext|>


<commit_before>import React from 'react';
import {RouteHandler} from 'react-router';
import Page from '../../components/Page';

class UnitsHealthNodeDetailPage extends React.Component {
  render() {
    return (
      <Page
        title="Nodes">
        <RouteHandler />
      </Page>
    );
  }
}

module.exports = UnitsHealthNodeDetailPage;
<commit_msg>Remove unused page component<commit_after><|endoftext|>


<commit_before>import {get, isEmpty} from 'lodash';

async function searchData({db, field, searchKeyword, folderId, perpage, offset}) {

  const searchQuery = db.knex('Entry').where('data', 'like', `%"${field}":"${searchKeyword}"%`)
    .andWhere('folderId', folderId)
    .limit(perpage)
    .offset(offset);

  const entries = await db.raw(searchQuery, true);

  const countQuery = db.knex('Entry').count('id')
    .where('data', 'like', `%"${field}":"${searchKeyword}"%`)
    .andWhere('folderId', folderId);

  const res = await db.raw(countQuery, true);
  const total = get(res, '[0][\'count("id")\']', 0);

  return {entries, total};
}

async function searchSourceEntry({db, searchKeyword, folderId, perpage, offset}) {

  const searchQuery = db.knex('Entry').where('sourceEntry', 'like', `%${searchKeyword}%`)
    .andWhere('folderId', folderId)
    .limit(perpage)
    .offset(offset);

  const entries = await db.raw(searchQuery, true);

  const countQuery = db.knex('Entry').count('id')
    .where('sourceEntry', 'like', `%${searchKeyword}%`)
    .andWhere('folderId', folderId);

  const res = await db.raw(countQuery, true);
  const total = get(res, '[0][\'count("id")\']', 0);

  return {entries, total};
}

export default async function listFolderEntries(event, data) {

  const {page, perpage, folderId, searchType} = data;
  const {db, models} = this.params;
  const {Entry} = models;
  const offset = (page - 1) * perpage;
  const searchKeyword = (data.searchKeyword || '').trim();

  if (isEmpty(searchKeyword)) {
    const entries = await Entry.find({folderId}, {skip: offset, limit: perpage, order: 'id'}) || [];
    const total = await Entry.count({folderId});
    this.resolve({data: entries, total});
    return;
  }

  if ('page-num' === searchType) {
    const {entries, total} = await searchData({db, field: 'page-num', searchKeyword, folderId, perpage, offset});
    this.resolve({data: entries, total});
    return;
  }

  const {entries, total} = await searchSourceEntry({db, searchKeyword, folderId, perpage, offset});
  this.resolve({data: entries, total});
}
<commit_msg>use parseJsonFields<commit_after>import {get, isEmpty} from 'lodash';
import parseJsonFields from './../../helpers/parseJsonFields';

async function searchData({db, field, searchKeyword, folderId, perpage, offset}) {

  const searchQuery = db.knex('Entry').where('data', 'like', `%"${field}":"${searchKeyword}"%`)
    .andWhere('folderId', folderId)
    .limit(perpage)
    .offset(offset);

  const rows = await db.raw(searchQuery, true);
  const entries = parseJsonFields('data', rows);

  const countQuery = db.knex('Entry').count('id')
    .where('data', 'like', `%"${field}":"${searchKeyword}"%`)
    .andWhere('folderId', folderId);

  const res = await db.raw(countQuery, true);
  const total = get(res, '[0][\'count("id")\']', 0);

  return {entries, total};
}

async function searchSourceEntry({db, searchKeyword, folderId, perpage, offset}) {

  const searchQuery = db.knex('Entry').where('sourceEntry', 'like', `%${searchKeyword}%`)
    .andWhere('folderId', folderId)
    .limit(perpage)
    .offset(offset);

  const rows = await db.raw(searchQuery, true);
  const entries = parseJsonFields('data', rows);

  const countQuery = db.knex('Entry').count('id')
    .where('sourceEntry', 'like', `%${searchKeyword}%`)
    .andWhere('folderId', folderId);

  const res = await db.raw(countQuery, true);
  const total = get(res, '[0][\'count("id")\']', 0);

  return {entries, total};
}

export default async function listFolderEntries(event, data) {

  const {page, perpage, folderId, searchType} = data;
  const {db, models} = this.params;
  const {Entry} = models;
  const offset = (page - 1) * perpage;
  const searchKeyword = (data.searchKeyword || '').trim();

  if (isEmpty(searchKeyword)) {
    const entries = await Entry.find({folderId}, {skip: offset, limit: perpage, order: 'id'}) || [];
    const total = await Entry.count({folderId});
    this.resolve({data: entries, total});
    return;
  }

  if ('page-num' === searchType) {
    const {entries, total} = await searchData({db, field: 'page-num', searchKeyword, folderId, perpage, offset});
    this.resolve({data: entries, total});
    return;
  }

  const {entries, total} = await searchSourceEntry({db, searchKeyword, folderId, perpage, offset});
  this.resolve({data: entries, total});
}
<|endoftext|>


<commit_before>var argv, http, url;
argv = require("optimist").default("port", 80).alias("p", "port").argv;
http = require("http");
url = require("url");
http.createServer(function (req, res) {
    var parsedUrl, proxyUrl;
    // Enable Cross-Origin Resource Sharing (CORS).
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD, OPTIONS");
    parsedUrl = url.parse(req.url, true);
    if (parsedUrl.query.hasOwnProperty("url")) {
        proxyUrl = url.parse(parsedUrl.query.url);
        var proxyOptions = {
            "host": proxyUrl.host,
            "port": proxyUrl.port || 80,
            "path": proxyUrl.pathname,
            "method": req.method,
            "headers": {}
        };
        // Copy some useful HTTP headers.
        if (req.headers["accept"]) proxyOptions.headers["accept"] = req.headers["accept"];
        // url.parse does not parse localhost correctly.
        if (proxyOptions.host.indexOf("localhost") !== -1) {
            proxyOptions.host = proxyOptions.host.split(":")[0];
        }
        // url.parse does not parse complex pathnames correctly.
        proxyOptions.path += req.url.split(proxyOptions.path)[1];
        var proxyReq = http.request(proxyOptions, function (proxyRes) {
            var contentType;
            contentType = proxyRes.headers["content-type"] || "text/plain";
            res.writeHead(200, contentType);
            proxyRes.on("data", function (chunk) {
                res.write(chunk);
            });
            proxyRes.on("end", function () {
                res.end();
            });
        });
        proxyReq.on("error", function (e) {
            res.writeHead(500);
            res.end("Captain, we crashed: " + e.code + "\n");
        });
        proxyReq.end();
    } else {
        res.writeHead(400);
        res.end("\"url\", did you pass it?\n");
    }
}).listen(argv.port);
console.log("Server running at http://127.0.0.1:" + argv.port + "/");
<commit_msg>Response headers have to be provided as an object.<commit_after>var argv, http, url;
argv = require("optimist").default("port", 80).alias("p", "port").argv;
http = require("http");
url = require("url");
http.createServer(function (req, res) {
    var parsedUrl, proxyUrl;
    // Enable Cross-Origin Resource Sharing (CORS).
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD, OPTIONS");
    parsedUrl = url.parse(req.url, true);
    if (parsedUrl.query.hasOwnProperty("url")) {
        proxyUrl = url.parse(parsedUrl.query.url);
        var proxyOptions = {
            "host": proxyUrl.host,
            "port": proxyUrl.port || 80,
            "path": proxyUrl.pathname,
            "method": req.method,
            "headers": {}
        };
        // Copy some useful HTTP headers.
        if (req.headers["accept"]) proxyOptions.headers["accept"] = req.headers["accept"];
        // url.parse does not parse localhost correctly.
        if (proxyOptions.host.indexOf("localhost") !== -1) {
            proxyOptions.host = proxyOptions.host.split(":")[0];
        }
        // url.parse does not parse complex pathnames correctly.
        proxyOptions.path += req.url.split(proxyOptions.path)[1];
        var proxyReq = http.request(proxyOptions, function (proxyRes) {
            var resHeaders;
            resHeaders = {};
            if (proxyRes.headers.hasOwnProperty("content-type")) resHeaders["Content-Type"] = proxyRes.headers["content-type"];
            res.writeHead(200, resHeaders);
            proxyRes.on("data", function (chunk) {
                res.write(chunk);
            });
            proxyRes.on("end", function () {
                res.end();
            });
        });
        proxyReq.on("error", function (e) {
            res.writeHead(500);
            res.end("Captain, we crashed: " + e.code + "\n");
        });
        proxyReq.end();
    } else {
        res.writeHead(400);
        res.end("\"url\", did you pass it?\n");
    }
}).listen(argv.port);
console.log("Server running at http://127.0.0.1:" + argv.port + "/");
<|endoftext|>


<commit_before>// Panda configuration file

var config = module.exports = {
    // ### Environment ###
    development: {
        app: {
            urlFormat: "/:slug"
        }
    },
    production: {
        url: process.env.APP_URL,
        database: {
            type: 'memory',
            connection: {
                uri: process.env.MONGOLAB_URI
            }
        },
        server: {
            host: '0.0.0.0',
            port: process.env.PORT
        },
        app: {
            urlFormat: '/:slug'
        }
    }
}<commit_msg>Configuration updates<commit_after>// Panda configuration file

var config = module.exports = {

    // ### Development Environment ###
    development: {
        app: {
            postUrl: "/:slug"
        },
        database: {
            type: 'mongo',
            connection: {
                uri: 'mongodb://localhost'
            }
        }
    },

    // ### Production Environment ###
    production: {
        url: process.env.APP_URL,
        database: {
            type: 'mongo',
            connection: {
                uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL
            }
        },
        server: {
            host: '0.0.0.0'
        },
        app: {
            postUrl: '/:slug'
        }
    }

};<|endoftext|>