<commit_before>'use strict';

var _ = require('highland');

var pg = require('pg');
var QueryStream = require('pg-query-stream');

var ls = require('./lightstreamer');

var utils = require('./utils');

var notify = require('./notification');

var dd = require('./data_dictionary');

// Postgres confg
var psql = process.env.DATABASE_URL;

if (utils.isReadOnly()) {
  console.log('Running in read-only mode.');

} else {
  console.log('Running in READ-WRITE mode.');
}

console.log('Connecting to', psql);

function selectMostRecentByIdx(idx, cb) {

  pg.connect(psql, function (err, client, done) {

    if (err) {

      console.error('Error requesting postgres client', err);

      notify.error(err);

      return cb(err);
    }

    client.query('select * from telemetry where idx = $1 and ts = ' +
      '(select max(ts) from telemetry where idx = $1) order by status desc',
      [idx],
      function (err2, res) {

        done();
        cb(err2, res);
      });
  });
}

function selectMostRecentByIdxIntervalAgoCount(idx, intervalAgo, count, cb) {

  pg.connect(psql, function (err, client, done) {

    var now = Date.now() / 1000 | 0;

    if (err) {

      console.error('Error requesting postgres client', err);

      notify.error(err);

      return cb(err);
    }

    count = count || 1;
    if (count < 1) {

      count = 1;
      intervalAgo = now;

    } else {

      intervalAgo = intervalAgo || now;

      if (intervalAgo < 1) {

        intervalAgo = now;
      }
    }

    client.query('with top_x as (select * ' +
      'from telemetry where idx = $1 and ts >= to_timestamp($2) ' +
      'order by ts desc, status desc limit $3) select * from top_x order by ts asc',
      [idx, now - intervalAgo, count],
      function (err2, res) {

        done();
        cb(err2, res);
      });
  });
}

function selectStatsByIdx(idx, cb) {

  pg.connect(psql, function (err, client, done) {

    if (err) {

      console.error('Error requesting postgres client', err);

      notify.error(err);

      return cb(err);
    }

    client.query('select avg(lag_avg) as lag_avg,' +
      ' avg(lag_stddev) as lag_stddev, avg(value_avg) as val_avg,' +
      ' avg(value_stddev) as val_stddev from telemetry_session_stats where idx = $1',
      [idx],
      function (err2, res) {

        done();
        cb(err2, res);
      });
  });
}

exports.selectStatsByIdx = selectStatsByIdx;

var previousSessionId = 0;

ls.dataStream.fork().each(function (data) {

  if (!utils.isReadOnly()) {

    pg.connect(psql, function (err, client, done) {

      if (err) {

        notify.error(err);

        return console.error('Error requesting postgres client', err);
      }

      client.query('insert into telemetry ' +
        '(idx, value, value_calibrated, ts, status, session_id) ' +
        'values ($1, $2, $3, to_timestamp($4), $5, $6)',
        [data.k, data.v, data.cv, data.t, data.s, data.sid],

        function (err2) {
          // suppress logging unique constraint violations
          // this can happen during normal ops
          // this occurs during a lightstreamer re-connect typically
          if (err2 && err2.code !== '23505') {

            done();

            notify.error(err2);

            return console.error('Error inserting data', err2);
          }

          if (previousSessionId !== data.sid) {

            client.query('insert into session (session_id) values ($1)',
            [data.sid],

            function (err3) {

              done();

              previousSessionId = data.sid;

              if (err3 && err3.code !== '23505') {

                notify.error(err3);

                return console.error('Error inserting data', err3);
              }

            });

          } else {

            done();
          }

        });
    });
  }
});

function addTelemetryStats(data, cb) {

  if (!Array.isArray(data)) {

    data = [data];
  }

  selectStatsByIdx(data[0].k, function (err, res) {

    if (err || res.rows.length === 0) {
      // keep chugging along, even if there was an error
      data = data.map(function (d) {

        d.lm = 0;
        d.ld = 0;
        d.vm = 0;
        d.vd = 0;

        return d;
      });

      if (err) {

        console.error(err);

        notify.error(err);
      }

      return cb(null, data);
    }

    data = data.map(function (d) {

      d.lm = res.rows[0].lag_avg || 0;
      d.ld = res.rows[0].lag_stddev || 0;
      d.vm = res.rows[0].val_avg || 0;
      d.vd = res.rows[0].val_stddev || 0;

      return d;
    });

    cb(null, data);
  });

}

exports.addTelemetryStats = addTelemetryStats;

function getTelemetryData(idx) {

  return _.wrapCallback(function (params, next) {

    // unixtime of -1 indicates the client wants the latest record available
    if (params.count === -1) {

      selectMostRecentByIdx(idx, function (err, res) {

        if (err) {

          next(err);
          return;
        }

        next(null, res.rows);
      });

    } else {
      // get a list of records later than intervalAgo of a idx
      selectMostRecentByIdxIntervalAgoCount(idx, params.intervalAgo, params.count,
        function (err, res) {

          if (err) {

            next(err);
            return;
          }

          // if no records found, get the latest
          if (res.rows.length === 0) {

            selectMostRecentByIdx(idx, function (err2, res2) {

              if (err2) {

                next(err2);
                return;
              }

              next(null, res2.rows);
            });

          } else {

            next(null, res.rows);
          }
        });
    }
  });
}

exports.getTelemetryData = getTelemetryData;

function addStats(idx) {

  return _.wrapCallback(function (rows, next) {

    var data = rows.map(function (r) {
      return {
        k: idx,
        v: r.value,
        t: r.ts.getTime() / 1000 | 0,
        s: r.status,
        lm: 0,
        ld: 0,
        vm: 0,
        vd: 0
      };
    });

    addTelemetryStats(data, next);
  });
}

exports.addStats = addStats;

function getTelemetrySessionStatsGaps(cb) {

  pg.connect(psql, function (err, client, done) {

    var query, stream;

    if (err) {

      console.error('Error requesting postgres client', err);

      notify.error(err);

      return cb(err);
    }

    query = new QueryStream('select * from get_telemetry_session_stats_gaps($1)',
      [dd.list.length - 1]);

    stream = client.query(query);
    stream.on('end', done);

    cb(err, stream);
  });
}

exports.getTelemetrySessionStatsGaps = getTelemetrySessionStatsGaps;

function getTelemetrySessionStatsBySessionIdIdx(sessionId, idx, cb) {

  pg.connect(psql, function (err, client, done) {

    if (err) {

      console.error('Error requesting postgres client', err);

      notify.error(err);

      return cb(err);
    }

    client.query('select * from get_telemetry_session_stats($1, $2)',
      [sessionId, idx],
      function (err2, res) {

        done();
        cb(err2, res);
      });
  });
}

exports.getTelemetrySessionStatsBySessionIdIdx = getTelemetrySessionStatsBySessionIdIdx;

function saveTelemetrySessionStatsBySessionIdIdx(
    session_id,
    idx,
    value_count,
    value_min,
    value_max,
    value_avg,
    value_stddev,
    lag_min,
    lag_max,
    lag_avg,
    lag_stddev,
    ts_min,
    ts_max,
    cb) {

  if (!utils.isReadOnly()) {

    pg.connect(psql, function (err, client, done) {

      if (err) {

        console.error('Error requesting postgres client', err);

        notify.error(err);

        return cb(err);
      }

      client.query('insert into telemetry_session_stats(' +
      'idx, session_id, value_count, value_min, value_max,' +
      'value_avg, value_stddev, lag_min, lag_max, lag_avg,' +
      'lag_stddev, ts_min, ts_max) values ($1, $2, $3, $4,' +
      '$5, $6, $7, $8, $9, $10, $11, $12, $13)',
      [
        idx,
        session_id,
        value_count,
        value_min,
        value_max,
        value_avg,
        value_stddev,
        lag_min,
        lag_max,
        lag_avg,
        lag_stddev,
        ts_min,
        ts_max
      ],
      function (err2, res) {

        done();
        cb(err2, res);
      });
    });
  }
}

exports.saveTelemetrySessionStatsBySessionIdIdx = saveTelemetrySessionStatsBySessionIdIdx;
<commit_msg>limit get latest telemetry entry to just one result<commit_after>'use strict';

var _ = require('highland');

var pg = require('pg');
var QueryStream = require('pg-query-stream');

var ls = require('./lightstreamer');

var utils = require('./utils');

var notify = require('./notification');

var dd = require('./data_dictionary');

// Postgres confg
var psql = process.env.DATABASE_URL;

if (utils.isReadOnly()) {
  console.log('Running in read-only mode.');

} else {
  console.log('Running in READ-WRITE mode.');
}

console.log('Connecting to', psql);

function selectMostRecentByIdx(idx, cb) {

  pg.connect(psql, function (err, client, done) {

    if (err) {

      console.error('Error requesting postgres client', err);

      notify.error(err);

      return cb(err);
    }

    client.query('select * from telemetry where idx = $1 and ts = ' +
      '(select max(ts) from telemetry where idx = $1) ' +
      'order by status desc limit 1',
      [idx],
      function (err2, res) {

        done();
        cb(err2, res);
      });
  });
}

function selectMostRecentByIdxIntervalAgoCount(idx, intervalAgo, count, cb) {

  pg.connect(psql, function (err, client, done) {

    var now = Date.now() / 1000 | 0;

    if (err) {

      console.error('Error requesting postgres client', err);

      notify.error(err);

      return cb(err);
    }

    count = count || 1;
    if (count < 1) {

      count = 1;
      intervalAgo = now;

    } else {

      intervalAgo = intervalAgo || now;

      if (intervalAgo < 1) {

        intervalAgo = now;
      }
    }

    client.query('with top_x as (select * ' +
      'from telemetry where idx = $1 and ts >= to_timestamp($2) ' +
      'order by ts desc, status desc limit $3) select * from top_x order by ts asc',
      [idx, now - intervalAgo, count],
      function (err2, res) {

        done();
        cb(err2, res);
      });
  });
}

function selectStatsByIdx(idx, cb) {

  pg.connect(psql, function (err, client, done) {

    if (err) {

      console.error('Error requesting postgres client', err);

      notify.error(err);

      return cb(err);
    }

    client.query('select avg(lag_avg) as lag_avg,' +
      ' avg(lag_stddev) as lag_stddev, avg(value_avg) as val_avg,' +
      ' avg(value_stddev) as val_stddev from telemetry_session_stats where idx = $1',
      [idx],
      function (err2, res) {

        done();
        cb(err2, res);
      });
  });
}

exports.selectStatsByIdx = selectStatsByIdx;

var previousSessionId = 0;

ls.dataStream.fork().each(function (data) {

  if (!utils.isReadOnly()) {

    pg.connect(psql, function (err, client, done) {

      if (err) {

        notify.error(err);

        return console.error('Error requesting postgres client', err);
      }

      client.query('insert into telemetry ' +
        '(idx, value, value_calibrated, ts, status, session_id) ' +
        'values ($1, $2, $3, to_timestamp($4), $5, $6)',
        [data.k, data.v, data.cv, data.t, data.s, data.sid],

        function (err2) {
          // suppress logging unique constraint violations
          // this can happen during normal ops
          // this occurs during a lightstreamer re-connect typically
          if (err2 && err2.code !== '23505') {

            done();

            notify.error(err2);

            return console.error('Error inserting data', err2);
          }

          if (previousSessionId !== data.sid) {

            client.query('insert into session (session_id) values ($1)',
            [data.sid],

            function (err3) {

              done();

              previousSessionId = data.sid;

              if (err3 && err3.code !== '23505') {

                notify.error(err3);

                return console.error('Error inserting data', err3);
              }

            });

          } else {

            done();
          }

        });
    });
  }
});

function addTelemetryStats(data, cb) {

  if (!Array.isArray(data)) {

    data = [data];
  }

  selectStatsByIdx(data[0].k, function (err, res) {

    if (err || res.rows.length === 0) {
      // keep chugging along, even if there was an error
      data = data.map(function (d) {

        d.lm = 0;
        d.ld = 0;
        d.vm = 0;
        d.vd = 0;

        return d;
      });

      if (err) {

        console.error(err);

        notify.error(err);
      }

      return cb(null, data);
    }

    data = data.map(function (d) {

      d.lm = res.rows[0].lag_avg || 0;
      d.ld = res.rows[0].lag_stddev || 0;
      d.vm = res.rows[0].val_avg || 0;
      d.vd = res.rows[0].val_stddev || 0;

      return d;
    });

    cb(null, data);
  });

}

exports.addTelemetryStats = addTelemetryStats;

function getTelemetryData(idx) {

  return _.wrapCallback(function (params, next) {

    // unixtime of -1 indicates the client wants the latest record available
    if (params.count === -1) {

      selectMostRecentByIdx(idx, function (err, res) {

        if (err) {

          next(err);
          return;
        }

        next(null, res.rows);
      });

    } else {
      // get a list of records later than intervalAgo of a idx
      selectMostRecentByIdxIntervalAgoCount(idx, params.intervalAgo, params.count,
        function (err, res) {

          if (err) {

            next(err);
            return;
          }

          // if no records found, get the latest
          if (res.rows.length === 0) {

            selectMostRecentByIdx(idx, function (err2, res2) {

              if (err2) {

                next(err2);
                return;
              }

              next(null, res2.rows);
            });

          } else {

            next(null, res.rows);
          }
        });
    }
  });
}

exports.getTelemetryData = getTelemetryData;

function addStats(idx) {

  return _.wrapCallback(function (rows, next) {

    var data = rows.map(function (r) {
      return {
        k: idx,
        v: r.value,
        t: r.ts.getTime() / 1000 | 0,
        s: r.status,
        lm: 0,
        ld: 0,
        vm: 0,
        vd: 0
      };
    });

    addTelemetryStats(data, next);
  });
}

exports.addStats = addStats;

function getTelemetrySessionStatsGaps(cb) {

  pg.connect(psql, function (err, client, done) {

    var query, stream;

    if (err) {

      console.error('Error requesting postgres client', err);

      notify.error(err);

      return cb(err);
    }

    query = new QueryStream('select * from get_telemetry_session_stats_gaps($1)',
      [dd.list.length - 1]);

    stream = client.query(query);
    stream.on('end', done);

    cb(err, stream);
  });
}

exports.getTelemetrySessionStatsGaps = getTelemetrySessionStatsGaps;

function getTelemetrySessionStatsBySessionIdIdx(sessionId, idx, cb) {

  pg.connect(psql, function (err, client, done) {

    if (err) {

      console.error('Error requesting postgres client', err);

      notify.error(err);

      return cb(err);
    }

    client.query('select * from get_telemetry_session_stats($1, $2)',
      [sessionId, idx],
      function (err2, res) {

        done();
        cb(err2, res);
      });
  });
}

exports.getTelemetrySessionStatsBySessionIdIdx = getTelemetrySessionStatsBySessionIdIdx;

function saveTelemetrySessionStatsBySessionIdIdx(
    session_id,
    idx,
    value_count,
    value_min,
    value_max,
    value_avg,
    value_stddev,
    lag_min,
    lag_max,
    lag_avg,
    lag_stddev,
    ts_min,
    ts_max,
    cb) {

  if (!utils.isReadOnly()) {

    pg.connect(psql, function (err, client, done) {

      if (err) {

        console.error('Error requesting postgres client', err);

        notify.error(err);

        return cb(err);
      }

      client.query('insert into telemetry_session_stats(' +
      'idx, session_id, value_count, value_min, value_max,' +
      'value_avg, value_stddev, lag_min, lag_max, lag_avg,' +
      'lag_stddev, ts_min, ts_max) values ($1, $2, $3, $4,' +
      '$5, $6, $7, $8, $9, $10, $11, $12, $13)',
      [
        idx,
        session_id,
        value_count,
        value_min,
        value_max,
        value_avg,
        value_stddev,
        lag_min,
        lag_max,
        lag_avg,
        lag_stddev,
        ts_min,
        ts_max
      ],
      function (err2, res) {

        done();
        cb(err2, res);
      });
    });
  }
}

exports.saveTelemetrySessionStatsBySessionIdIdx = saveTelemetrySessionStatsBySessionIdIdx;
<|endoftext|>


<commit_before>var markdownpdf = require("markdown-pdf");

var write = function(inputFile, outFile) {
  outFile = outFile || "resume.pdf";
  markdownpdf().from(inputFile).to(outFile, function() {
    console.log(outFile + " created");
  });
}

module.exports.write = write;
<commit_msg>set default pdf name to 'resume.pdf'<commit_after>var markdownpdf = require('markdown-pdf');

var write = function(inputFile, outFile) {
  outFile = outFile + '.pdf' || 'resume.pdf';
  markdownpdf().from(inputFile).to(outFile, function() {
    console.log(outFile + ' created');
  });
}

module.exports.write = write;
<|endoftext|>


<commit_before>jQuery(document).ready(function($){
  $('notices_primary').infinitescroll({
    nextSelector    : "li.nav_next a",
    loadingImg      : $('address .url')[0].href+'plugins/InfiniteScroll/ajax-loader.gif',
    text            : "Loading the next set of posts...",
    donetext        : "Congratulations, you\'ve reached the end of the Internet.",
    navSelector     : "div.pagination",
    contentSelector : "#notices_primary",
    itemSelector    : "ol.notices"
    },function(){
        NoticeAttachments();
    });
});

<commit_msg>Corrected the Infinite Scroll CSS Selectors<commit_after>jQuery(document).ready(function($){
  $('notices_primary').infinitescroll({
    debug: true,
    nextSelector    : "li.nav_next a",
    loadingImg      : $('address .url')[0].href+'plugins/InfiniteScroll/ajax-loader.gif',
    text            : "Loading the next set of posts...",
    donetext        : "Congratulations, you\'ve reached the end of the Internet.",
    navSelector     : "div.pagination",
    contentSelector : "#notices_primary ol.notices",
    itemSelector    : "#notices_primary ol.notices li"
    },function(){
        NoticeAttachments();
    });
});

<|endoftext|>


<commit_before>/**
 * @module ogs.vgl
 */

/**
 * Create a new instance of class viewer
 *
 * @class
 * @param canvas
 * @returns {vglModule.viewer}
 */
vglModule.viewer = function(canvas) {

  if (!(this instanceof vglModule.viewer)) {
    return new vglModule.viewer(canvas);
  }

  vglModule.object.call(this);

  /** @private */
  var m_that = this;

  /** @private */
  var m_canvas = canvas;

  /** @private */
  var m_ready = false;

  /** @private */
  var m_interactorStyle = null;

  /** @private */
  var m_renderer = vglModule.renderer();

  /** @private */
  var m_renderWindow = vglModule.renderWindow(m_canvas);
  m_renderWindow.addRenderer(m_renderer);

  this.canvas = function() {
    return m_canvas;
  };

  this.renderWindow = function() {
    return m_renderWindow;
  };

  this.init = function() {
    if (m_renderWindow !== null) {
      m_renderWindow.createWindow();
      m_ready = true;
    }
    else {
      console.log("[ERROR] No render window attached");
    }
  };

  this.interactorStyle = function() {
    return m_interactorStyle;
  };

  this.setInteractorStyle = function(style) {
    if (style !== m_interactorStyle) {
      m_interactorStyle = style;
      m_interactorStyle.setViewer(this);
      this.modified();
    }
  };

  this.handleMouseDown = function(event) {
    if (m_ready === true) {
      var fixedEvent = $.event.fix(event || window.event);
      fixedEvent.preventDefault();
      fixedEvent.state = 'down';
      fixedEvent.type = vglModule.command.mousePressEvent;
      $(m_that).trigger(fixedEvent);
    }

    return true;
  };

  this.handleMouseUp = function(event) {
    if (m_ready === true) {
      var fixedEvent = $.event.fix(event || window.event);
      fixedEvent.preventDefault();
      fixedEvent.state = 'up';
      fixedEvent.type = vglModule.command.mousePressEvent;
      $(m_that).trigger(fixedEvent);
    }

    return true;
  };

  this.handleMouseMove = function(event) {
    if (m_ready === true) {
      var fixedEvent = $.event.fix(event || window.event);
      fixedEvent.preventDefault();
      fixedEvent.type = vglModule.command.mouseMoveEvent;
      $(m_that).trigger(fixedEvent);
    }

    return true;
  };

  this.handleKeyPress = function(event) {
    if (m_ready === true) {
      var fixedEvent = $.event.fix(event || window.event);
      fixedEvent.preventDefault();
      fixedEvent.type = vglModule.command.keyPressEvent;
      $(m_that).trigger(fixedEvent);
    }

    return true;
  };

  this.handleContextMenu = function(event) {
    if (m_ready === true) {
      var fixedEvent = $.event.fix(event || window.event);
      fixedEvent.preventDefault();
      fixedEvent.type = vglModule.command.contextMenuEvent;
      $(m_that).trigger(fixedEvent);
    }

    return false;
  };

  this.relMouseCoords = function(event) {
    var totalOffsetX = 0,
        totalOffsetY = 0,
        canvasX = 0,
        canvasY = 0,
        currentElement = m_canvas;

    do {
      totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
      totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
    } while (currentElement = currentElement.offsetParent);

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    return {
      x: canvasX,
      y: canvasY
    };
  };

  this.render = function() {
    m_renderWindow.render();
  };

  return this;
};

inherit(vglModule.viewer, vglModule.object);<commit_msg>Only prevent default action on right mouse click<commit_after>/**
 * @module ogs.vgl
 */

/**
 * Create a new instance of class viewer
 *
 * @class
 * @param canvas
 * @returns {vglModule.viewer}
 */
vglModule.viewer = function(canvas) {

  if (!(this instanceof vglModule.viewer)) {
    return new vglModule.viewer(canvas);
  }

  vglModule.object.call(this);

  /** @private */
  var m_that = this;

  /** @private */
  var m_canvas = canvas;

  /** @private */
  var m_ready = false;

  /** @private */
  var m_interactorStyle = null;

  /** @private */
  var m_renderer = vglModule.renderer();

  /** @private */
  var m_renderWindow = vglModule.renderWindow(m_canvas);
  m_renderWindow.addRenderer(m_renderer);

  this.canvas = function() {
    return m_canvas;
  };

  this.renderWindow = function() {
    return m_renderWindow;
  };

  this.init = function() {
    if (m_renderWindow !== null) {
      m_renderWindow.createWindow();
      m_ready = true;
    }
    else {
      console.log("[ERROR] No render window attached");
    }
  };

  this.interactorStyle = function() {
    return m_interactorStyle;
  };

  this.setInteractorStyle = function(style) {
    if (style !== m_interactorStyle) {
      m_interactorStyle = style;
      m_interactorStyle.setViewer(this);
      this.modified();
    }
  };

  this.handleMouseDown = function(event) {
    if (m_ready === true) {
      var fixedEvent = $.event.fix(event || window.event);
      // Only prevent default action for right mouse button
      if (event.button == 2)
        fixedEvent.preventDefault();
      fixedEvent.state = 'down';
      fixedEvent.type = vglModule.command.mousePressEvent;
      $(m_that).trigger(fixedEvent);
    }

    return true;
  };

  this.handleMouseUp = function(event) {
    if (m_ready === true) {
      var fixedEvent = $.event.fix(event || window.event);
      fixedEvent.preventDefault();
      fixedEvent.state = 'up';
      fixedEvent.type = vglModule.command.mousePressEvent;
      $(m_that).trigger(fixedEvent);
    }

    return true;
  };

  this.handleMouseMove = function(event) {
    if (m_ready === true) {
      var fixedEvent = $.event.fix(event || window.event);
      fixedEvent.preventDefault();
      fixedEvent.type = vglModule.command.mouseMoveEvent;
      $(m_that).trigger(fixedEvent);
    }

    return true;
  };

  this.handleKeyPress = function(event) {
    if (m_ready === true) {
      var fixedEvent = $.event.fix(event || window.event);
      fixedEvent.preventDefault();
      fixedEvent.type = vglModule.command.keyPressEvent;
      $(m_that).trigger(fixedEvent);
    }

    return true;
  };

  this.handleContextMenu = function(event) {
    if (m_ready === true) {
      var fixedEvent = $.event.fix(event || window.event);
      fixedEvent.preventDefault();
      fixedEvent.type = vglModule.command.contextMenuEvent;
      $(m_that).trigger(fixedEvent);
    }

    return false;
  };

  this.relMouseCoords = function(event) {
    var totalOffsetX = 0,
        totalOffsetY = 0,
        canvasX = 0,
        canvasY = 0,
        currentElement = m_canvas;

    do {
      totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
      totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
    } while (currentElement = currentElement.offsetParent);

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    return {
      x: canvasX,
      y: canvasY
    };
  };

  this.render = function() {
    m_renderWindow.render();
  };

  return this;
};

inherit(vglModule.viewer, vglModule.object);<|endoftext|>


<commit_before>import { EyeFilterMenu } from "buttons";
import { FormattedMessage as T, injectIntl, defineMessages } from "react-intl";
import { Tooltip } from "shared";
import { TextInput } from "../../../inputs";
import TxHistory from "TxHistory";
import { LoadingMoreTransactionsIndicator, NoMoreTransactionsIndicator, NoTransactions } from "indicators";
import InfiniteScroll from "react-infinite-scroller";
import "style/HistoryPage.less";

const messages = defineMessages({
  filterByAddrPlaceholder: {
    id: "txhistory.filterByAddrPlaceholder",
    defaultMessage: "Filter by Address"
  },
});

const Page = ({
  sortTypes,
  txTypes,
  transactions,
  tsDate,
  selectedSortOrderKey,
  selectedTxTypeKey,
  searchText,
  loadMoreThreshold,
  noMoreTransactions,
  intl,
  onChangeSelectedType,
  onChangeSortType,
  onChangeSearchText,
  onLoadMoreTransactions,
}) => (
  <InfiniteScroll
    hasMore={!noMoreTransactions}
    loadMore={onLoadMoreTransactions}
    initialLoad={loadMoreThreshold > 90}
    useWindow={false}
    threshold={loadMoreThreshold}
  >

        <T id="history.title" m="Transaction History" />

            <TextInput
              type="text"
              placeholder={intl.formatMessage(messages.filterByAddrPlaceholder)}
              value={searchText}
              onChange={(e) => onChangeSearchText(e.target.value)}
            />

          <Tooltip tipWidth={ 300 } text={<T id="transactions.sortby.tooltip" m="Sort By" />}>
            <EyeFilterMenu
              labelKey="label"
              keyField="value"
              options={sortTypes}
              selected={selectedSortOrderKey}
              onChange={onChangeSortType}
              className="sort-by"
            />
          </Tooltip>
          <Tooltip tipWidth={ 300 } text={<T id="transactions.txtypes.tooltip" m="Transaction Type" />}>
            <EyeFilterMenu
              labelKey="label"
              keyField="key"
              options={txTypes}
              selected={selectedTxTypeKey}
              onChange={onChangeSelectedType}
            />
          </Tooltip>

      {transactions.length > 0
        ? <TxHistory {...{ transactions, tsDate }} />
        : null }

    {!noMoreTransactions
      ? <LoadingMoreTransactionsIndicator />
      : transactions.length > 0
        ? <NoMoreTransactionsIndicator />
        : <NoTransactions />
    }
  </InfiniteScroll>
);

export default injectIntl(Page);
<commit_msg>[history] Show filter when no transactions are present (#1711)<commit_after>import { EyeFilterMenu } from "buttons";
import { FormattedMessage as T, injectIntl, defineMessages } from "react-intl";
import { Tooltip } from "shared";
import { TextInput } from "../../../inputs";
import TxHistory from "TxHistory";
import { LoadingMoreTransactionsIndicator, NoMoreTransactionsIndicator, NoTransactions } from "indicators";
import InfiniteScroll from "react-infinite-scroller";
import "style/HistoryPage.less";

const messages = defineMessages({
  filterByAddrPlaceholder: {
    id: "txhistory.filterByAddrPlaceholder",
    defaultMessage: "Filter by Address"
  },
});

const Page = ({
  sortTypes,
  txTypes,
  transactions,
  tsDate,
  selectedSortOrderKey,
  selectedTxTypeKey,
  searchText,
  loadMoreThreshold,
  noMoreTransactions,
  intl,
  onChangeSelectedType,
  onChangeSortType,
  onChangeSearchText,
  onLoadMoreTransactions,
}) => (
  <InfiniteScroll
    hasMore={!noMoreTransactions}
    loadMore={onLoadMoreTransactions}
    initialLoad={loadMoreThreshold > 90}
    useWindow={false}
    threshold={loadMoreThreshold}
  >

        <T id="history.title" m="Transaction History" />

            <TextInput
              type="text"
              placeholder={intl.formatMessage(messages.filterByAddrPlaceholder)}
              value={searchText}
              onChange={(e) => onChangeSearchText(e.target.value)}
            />

          <Tooltip tipWidth={ 300 } text={<T id="transactions.sortby.tooltip" m="Sort By" />}>
            <EyeFilterMenu
              labelKey="label"
              keyField="value"
              options={sortTypes}
              selected={selectedSortOrderKey}
              onChange={onChangeSortType}
              className="sort-by"
            />
          </Tooltip>
          <Tooltip tipWidth={ 300 } text={<T id="transactions.txtypes.tooltip" m="Transaction Type" />}>
            <EyeFilterMenu
              labelKey="label"
              keyField="key"
              options={txTypes}
              selected={selectedTxTypeKey}
              onChange={onChangeSelectedType}
            />
          </Tooltip>

      {transactions.length > 0
        ? <TxHistory {...{ transactions, tsDate }} />
        : null }

    {!noMoreTransactions
      ? <LoadingMoreTransactionsIndicator />
      : transactions.length > 0
        ? <NoMoreTransactionsIndicator />
        : <NoTransactions />
    }
  </InfiniteScroll>
);

export default injectIntl(Page);
<|endoftext|>


<commit_before><commit_msg>put less-loader in correct position<commit_after><|endoftext|>


<commit_before>/*
 * fis
 * http://web.baidu.com/
 */

'use strict';

function deploy(dest, file){
    console.log('deploy [' + file.realpath + '] to [' + dest.to + file.release + ']');
}

module.exports = function(dest, collection, fis){
    var settings = fis.config.get('deploy', {});
    var dests = [];
    dest.split(/,/g).forEach(function(d){
        if(settings[d]){
            var from = settings[d].from;
            if(from){
                settings[d].from = '/' + from.replace(/^\//, '');
            } else {
                settings[d].from = '/';
            }
            dests.push(settings[d]);
        } else if(/^output\b/.test(d)){ //local
            dests.push({
                from : '/',
                to   : '/' + d
            });
        } else {
            fis.log.error('invalid deploy destination options [' + d + ']');
        }
    });
    fis.util.map(collection, function(subpath, file){
        dests.forEach(function(d){
            if(subpath.indexOf(d.from) === 0){
                deploy(d, file);
            }
        });
    });
};<commit_msg>修复kernel.cache的bug<commit_after>/*
 * fis
 * http://web.baidu.com/
 */

'use strict';

function deploy(dest, file){
    console.log('deploy [' + file.realpath + '] to [' + dest.to + file.release + ']');
}

module.exports = function(dest, collection, fis){
    var settings = fis.config.get('deploy', {});
    var dests = [];
    dest.split(/,/g).forEach(function(d){
        if(settings[d]){
            var from = settings[d].from;
            if(from){
                settings[d].from = '/' + from.replace(/^\//, '');
            } else {
                settings[d].from = '/';
            }
            dests.push(settings[d]);
        } else if(/^output\b/.test(d)){ //local
            dests.push({
                from : '/',
                to   : '/' + d
            });
        } else {
            fis.log.error('invalid deploy destination options [' + d + ']');
        }
    });
    fis.util.map(collection, function(subpath, file){
        dests.forEach(function(d){
            if(file.release.indexOf(d.from) === 0){
                deploy(d, file);
            }
        });
    });
};<|endoftext|>


<commit_before>var liveworld = function() {
    $(function() {
        $("#embed-globe").popover({
            container: "body"
        });
    });
    var liveDurationMins = parseInt($('#world-time-select').find(":selected").val());
    var selectedLanguage = $('#world-language-select').find(":selected").val();
    var selectedEventType = $('#world-event-select').find(":selected").val();
    var transformedEvents = [];
    $("#world-time-select").change(function() {
        liveDurationMins = $(this).find(":selected").val();
        loadData();
    });

    $("#world-language-select").change(function() {
        selectedLanguage = $(this).find(":selected").val();
        loadData();
    });

    $("#world-event-select").change(function() {
        selectedEventType = $(this).find(":selected").val();
        loadData();
    });

    var width = $("#live-world").parent().parent().width();
    var height = width;
    var speed = -1e-3;
    var start = Date.now();

    var sphere = {
        type: "Sphere"
    };

    var projection = d3.geo.orthographic()
        .scale(width / 2.1)
        .clipAngle(90)
        .translate([width / 2, height / 2]);

    var graticule = d3.geo.graticule();

    var canvas = d3.select("#live-world").append("canvas")
        .attr("width", width)
        .attr("height", height);

    var context = canvas.node().getContext("2d");

    var path = d3.geo.path()
        .projection(projection)
        .context(context);

    //d3.select(self.frameElement).style("height", height + "px");

    var getEventType = function(eventFromServer) {
        return _.contains(eventFromServer.actionTags, "Build") ? "Build" : "wtf";
    };

    var url = function() {
        return (location.hostname == "localhost") ?
            "http://localhost:5000/live/devbuild/" :
            "http://quantifieddev.herokuapp.com/live/devbuild/";
    }

    var getLiveEventsUrl = function() {
        var liveDevBuildUrl = url() + liveDurationMins;

        var langQuery = (selectedLanguage !== "all") ? "lang=" + selectedLanguage : "";
        var eventQuery = (selectedEventType !== "all") ? "eventType=" + selectedEventType : "";

        if (langQuery && eventQuery) {
            liveDevBuildUrl += "?" + langQuery + "&" + eventQuery;
        } else if (langQuery) {
            liveDevBuildUrl += "?" + langQuery;
        } else if (eventQuery) {
            liveDevBuildUrl += "?" + eventQuery;
        };

        return liveDevBuildUrl;
    }

    var loadData = function() {
        var liveDevBuildUrl = getLiveEventsUrl();

        d3.json(liveDevBuildUrl, function(error, events) {
            var data = events;
            transformedEvents = [];
            var buildLocations = [];
            var wtfLocations = [];
            var isBuildLocationUnique = function(singleEvent) {
                return singleEvent.type === "Build" && !(_.findWhere(buildLocations, singleEvent.location))
            }
            var isWtfLocationUnique = function(singleEvent) {
                return singleEvent.type === "wtf" && !(_.findWhere(wtfLocations, singleEvent.location))
            }
            for (var i = events.length - 1; i >= 0; i--) {
                var eventFromServer = events[i].payload;
                var singleEvent = {
                    id: i,
                    location: {
                        lon: eventFromServer.location.long,
                        lat: eventFromServer.location.lat
                    },
                    type: getEventType(eventFromServer), // "wtf" or "Build"
                    language: eventFromServer.properties.Language != undefined ? eventFromServer.properties.Language[0] : ""
                }
                if (isBuildLocationUnique(singleEvent)) {
                    transformedEvents.push(singleEvent);
                    buildLocations.push(singleEvent.location);
                }
                if (isWtfLocationUnique(singleEvent)) {
                    transformedEvents.push(singleEvent);
                    wtfLocations.push(singleEvent.location);
                }
            };
            createCircles();
        })
    };

    loadData();
    setInterval(function() {
            loadData()
        },
        60000);

    var CircleSize = function(transformedEvent) {
        var size = Math.random(1, 0.7) * 0.7;
        return function() {
            size += 0.03;
            if (size > 2.1) {
                size = 0.3;
            }
            return size;
        }
    };

    var eventsToDraw;

    var createCircles = function() {
        eventsToDraw = transformedEvents.map(function(transformedEvent) {
            var circleSize = new CircleSize(transformedEvent);

            var draw = function(context) {
                var circle = d3.geo.circle().angle(circleSize()).origin([transformedEvent.location.lon, transformedEvent.location.lat]);
                circlePoints = [circle()];
                context.beginPath();
                path({
                    type: "GeometryCollection",
                    geometries: circlePoints
                });
                context.fillStyle = transformedEvent.type === "Build" ? "rgba(0, 0, 255, .5)" : "rgba(255, 0, 0, .5)";
                context.fill();
                context.lineWidth = .2;
                context.strokeStyle = "#FFF";
                context.stroke();
            }

            return draw;
        });
        animateCircles();
    }

    var animateCircles = function() {
        d3.json("/topo/world-110m.json", function(error, topo) {
            var land = topojson.feature(topo, topo.objects.land),
                grid = graticule();

            var redrawGlobe = function() {
                var λ = (speed * (Date.now() - start) * 2),
                    φ = -15;

                context.clearRect(0, 0, width, height);

                context.beginPath();
                path(sphere);
                context.lineWidth = 3;
                context.strokeStyle = "#000";
                context.stroke();
                context.fillStyle = "#fff";
                context.fill();

                context.save();
                context.translate(width / 2, 0);
                context.scale(-1, 1);
                context.translate(-width / 2, 0);
                projection.rotate([λ + 180, -φ]);

                context.beginPath();
                path(land);
                context.fillStyle = "#dadac4";
                context.fill();

                context.beginPath();
                path(grid);
                context.lineWidth = .5;
                context.strokeStyle = "rgba(0,0,119,.2)";
                context.stroke();

                context.restore();
                projection.rotate([λ, φ]);

                context.beginPath();
                path(grid);
                context.lineWidth = .5;
                context.strokeStyle = "rgba(0,119,119,.2)";
                context.stroke();

                context.beginPath();
                path(land);
                context.fillStyle = "rgba(0,100,0,.5)";
                context.fill();
                context.lineWidth = .5;
                context.strokeStyle = "#060";
                context.stroke();

                if (eventsToDraw != undefined) {
                    eventsToDraw.forEach(function(drawCompile) {
                        drawCompile(context);
                    });
                }
                setTimeout(redrawGlobe, 1000);
            };
            redrawGlobe();
        });
    }

};
$(document).ready(liveworld);<commit_msg>- On click of globe, quantifieddev website is opened<commit_after>var liveworld = function() {
    $(function() {
        $("#embed-globe").popover({
            container: "body"
        });
    });
    $("#live-world").click(function(){
        window.open('http://quantifieddev.org');
    });
    var liveDurationMins = parseInt($('#world-time-select').find(":selected").val());
    var selectedLanguage = $('#world-language-select').find(":selected").val();
    var selectedEventType = $('#world-event-select').find(":selected").val();
    var transformedEvents = [];
    $("#world-time-select").change(function() {
        liveDurationMins = $(this).find(":selected").val();
        loadData();
    });

    $("#world-language-select").change(function() {
        selectedLanguage = $(this).find(":selected").val();
        loadData();
    });

    $("#world-event-select").change(function() {
        selectedEventType = $(this).find(":selected").val();
        loadData();
    });

    var width = $("#live-world").parent().parent().width();
    var height = width;
    var speed = -1e-3;
    var start = Date.now();

    var sphere = {
        type: "Sphere"
    };

    var projection = d3.geo.orthographic()
        .scale(width / 2.1)
        .clipAngle(90)
        .translate([width / 2, height / 2]);

    var graticule = d3.geo.graticule();

    var canvas = d3.select("#live-world").append("canvas")
        .attr("width", width)
        .attr("height", height);

    var context = canvas.node().getContext("2d");

    var path = d3.geo.path()
        .projection(projection)
        .context(context);

    //d3.select(self.frameElement).style("height", height + "px");

    var getEventType = function(eventFromServer) {
        return _.contains(eventFromServer.actionTags, "Build") ? "Build" : "wtf";
    };

    var url = function() {
        return (location.hostname == "localhost") ?
            "http://localhost:5000/live/devbuild/" :
            "http://quantifieddev.herokuapp.com/live/devbuild/";
    }

    var getLiveEventsUrl = function() {
        var liveDevBuildUrl = url() + liveDurationMins;

        var langQuery = (selectedLanguage !== "all") ? "lang=" + selectedLanguage : "";
        var eventQuery = (selectedEventType !== "all") ? "eventType=" + selectedEventType : "";

        if (langQuery && eventQuery) {
            liveDevBuildUrl += "?" + langQuery + "&" + eventQuery;
        } else if (langQuery) {
            liveDevBuildUrl += "?" + langQuery;
        } else if (eventQuery) {
            liveDevBuildUrl += "?" + eventQuery;
        };

        return liveDevBuildUrl;
    }

    var loadData = function() {
        var liveDevBuildUrl = getLiveEventsUrl();

        d3.json(liveDevBuildUrl, function(error, events) {
            var data = events;
            transformedEvents = [];
            var buildLocations = [];
            var wtfLocations = [];
            var isBuildLocationUnique = function(singleEvent) {
                return singleEvent.type === "Build" && !(_.findWhere(buildLocations, singleEvent.location))
            }
            var isWtfLocationUnique = function(singleEvent) {
                return singleEvent.type === "wtf" && !(_.findWhere(wtfLocations, singleEvent.location))
            }
            for (var i = events.length - 1; i >= 0; i--) {
                var eventFromServer = events[i].payload;
                var singleEvent = {
                    id: i,
                    location: {
                        lon: eventFromServer.location.long,
                        lat: eventFromServer.location.lat
                    },
                    type: getEventType(eventFromServer), // "wtf" or "Build"
                    language: eventFromServer.properties.Language != undefined ? eventFromServer.properties.Language[0] : ""
                }
                if (isBuildLocationUnique(singleEvent)) {
                    transformedEvents.push(singleEvent);
                    buildLocations.push(singleEvent.location);
                }
                if (isWtfLocationUnique(singleEvent)) {
                    transformedEvents.push(singleEvent);
                    wtfLocations.push(singleEvent.location);
                }
            };
            createCircles();
        })
    };

    loadData();
    setInterval(function() {
            loadData()
        },
        60000);

    var CircleSize = function(transformedEvent) {
        var size = Math.random(1, 0.7) * 0.7;
        return function() {
            size += 0.03;
            if (size > 2.1) {
                size = 0.3;
            }
            return size;
        }
    };

    var eventsToDraw;

    var createCircles = function() {
        eventsToDraw = transformedEvents.map(function(transformedEvent) {
            var circleSize = new CircleSize(transformedEvent);

            var draw = function(context) {
                var circle = d3.geo.circle().angle(circleSize()).origin([transformedEvent.location.lon, transformedEvent.location.lat]);
                circlePoints = [circle()];
                context.beginPath();
                path({
                    type: "GeometryCollection",
                    geometries: circlePoints
                });
                context.fillStyle = transformedEvent.type === "Build" ? "rgba(0, 0, 255, .5)" : "rgba(255, 0, 0, .5)";
                context.fill();
                context.lineWidth = .2;
                context.strokeStyle = "#FFF";
                context.stroke();
            }

            return draw;
        });
        animateCircles();
    }

    var animateCircles = function() {
        d3.json("/topo/world-110m.json", function(error, topo) {
            var land = topojson.feature(topo, topo.objects.land),
                grid = graticule();

            var redrawGlobe = function() {
                var λ = (speed * (Date.now() - start) * 2),
                    φ = -15;

                context.clearRect(0, 0, width, height);

                context.beginPath();
                path(sphere);
                context.lineWidth = 3;
                context.strokeStyle = "#000";
                context.stroke();
                context.fillStyle = "#fff";
                context.fill();

                context.save();
                context.translate(width / 2, 0);
                context.scale(-1, 1);
                context.translate(-width / 2, 0);
                projection.rotate([λ + 180, -φ]);

                context.beginPath();
                path(land);
                context.fillStyle = "#dadac4";
                context.fill();

                context.beginPath();
                path(grid);
                context.lineWidth = .5;
                context.strokeStyle = "rgba(0,0,119,.2)";
                context.stroke();

                context.restore();
                projection.rotate([λ, φ]);

                context.beginPath();
                path(grid);
                context.lineWidth = .5;
                context.strokeStyle = "rgba(0,119,119,.2)";
                context.stroke();

                context.beginPath();
                path(land);
                context.fillStyle = "rgba(0,100,0,.5)";
                context.fill();
                context.lineWidth = .5;
                context.strokeStyle = "#060";
                context.stroke();

                if (eventsToDraw != undefined) {
                    eventsToDraw.forEach(function(drawCompile) {
                        drawCompile(context);
                    });
                }
                setTimeout(redrawGlobe, 1000);
            };
            redrawGlobe();
        });
    }

};
$(document).ready(liveworld);<|endoftext|>


<commit_before>// Tests for the calculator.
exports.config = {
  directConnet = true,

  specs: [
    'spec.js'
  ],

  capabilities: {
    'browserName': 'chrome'
  },
};
<commit_msg>Fix direct connect in config<commit_after>// Tests for the calculator.
exports.config = {
  directConnet: true,

  specs: [
    'spec.js'
  ],

  capabilities: {
    'browserName': 'chrome'
  },
};
<|endoftext|>


<commit_before>if (typeof jQuery === 'undefined') { throw new Error('Starscream JavaScript requires jQuery') }

   var j$ = jQuery.noConflict();

j$(document).ready(function () {
    // style all buttons
    j$('button').addClass("btn btn-default");
    //style all form controls
    j$('input').addClass("form-control");
    // try to style the select lists
    j$('select').addClass("dropdown-toggle");
    //try text areas
    j$('textarea').addClass("form-control");

    //redo the detail table into an unordered list
    j$('div.pbSubsection table').each(function () {
        var list = j$("
").addClass("list-group");

        j$(this).find("tr").each(function () {
            var p = j$(this).children().map(function () {
                if (j$(this).find('table').length > 0) {
                    var subList = j$("
").addClass("list-group");
                    subList.attr("id", j$(this).find('table').attr("id")) // assign the id from the table
                    // remove the flow ".empty" table cells
                    j$(".empty").remove();
                    j$("td:empty").remove();

                    var sP = j$(this).find('table').children().map(function () {
                        var tmpPara = "
" + j$(this).html().trim() + "
";
                        tmpPara.addClass(this.attr("class"));

                        if (tmpPara.trim() ===  "

"){
                            tmpPara = "";
                        }
                        return tmpPara;
                    });

                    subList.append("
" + j$.makeArray(sP).join("") + "
");

                    return j$('
').append(j$('
').append(subList)).html();
                }
                else {
                    return "
" + j$(this).html().trim() + "
";
                }
            });

            list.append("
" + j$.makeArray(p).join("") + "
");
        });
        // remove empty paragraphs
        list.find('p:empty').remove();
        list.j$('p').each(function(index, item) {
            if(j$.trim($(item).text()) === "") {
                j$(item).slideUp(); // $(item).remove();
            }
        });

        j$(this).replaceWith(list);
    });
});<commit_msg>Don't delete paragraphs with embedded children<commit_after>if (typeof jQuery === 'undefined') { throw new Error('Starscream JavaScript requires jQuery') }

   var j$ = jQuery.noConflict();

j$(document).ready(function () {
    // style all buttons
    j$('button').addClass("btn btn-default");
    //style all form controls
    j$('input').addClass("form-control");
    // try to style the select lists
    j$('select').addClass("dropdown-toggle");
    //try text areas
    j$('textarea').addClass("form-control");

    //redo the detail table into an unordered list
    j$('div.pbSubsection table').each(function () {
        var list = j$("
").addClass("list-group");

        j$(this).find("tr").each(function () {
            var p = j$(this).children().map(function () {
                if (j$(this).find('table').length > 0) {
                    var subList = j$("
").addClass("list-group");
                    subList.attr("id", j$(this).find('table').attr("id")) // assign the id from the table
                    // remove the flow ".empty" table cells
                    j$(".empty").remove();
                    j$("td:empty").remove();

                    var sP = j$(this).find('table').children().map(function () {
                        var tmpPara = "
" + j$(this).html().trim() + "
";
                        tmpPara.addClass(this.attr("class"));

                        if (tmpPara.trim() ===  "

"){
                            tmpPara = "";
                        }
                        return tmpPara;
                    });

                    subList.append("
" + j$.makeArray(sP).join("") + "
");

                    return j$('
').append(j$('
').append(subList)).html();
                }
                else {
                    return "
" + j$(this).html().trim() + "
";
                }
            });

            list.append("
" + j$.makeArray(p).join("") + "
");
        });
        // remove empty paragraphs
        list.find('p:empty').remove();
        list.find('p').each(function(index, item) {
            if(j$.trim(j$(item).text()) === "" && j$(item).children().length() === 0) {
                j$(item).slideUp();
                j$(item).remove();
            }
        });

        j$(this).replaceWith(list);
    });
});<|endoftext|>


<commit_before>const _ = require('lodash');
const nconf = require('nconf');
const Promise = require('bluebird');
const JSDOM = require('jsdom').JSDOM;
const debug = require('debug')('datathon');
const moment = require('moment');

const utils = require('../lib/utils');
const mongo = require('../lib/mongo');
const l = require('../parsers/components/linkontime');

const cfgFile = "config/content.json";
nconf.argv().env().file({ file: cfgFile });

const cName = 'finalized';
const CHUNK = nconf.get('amount') ? _.parseInt(nconf.get('amount')) : 500;

let max = null;
const until = nconf.get('unti');
if(!until) {
    max = new Date("2018-11-30");
    debug("Using the default, running until %s", max);
}
else {
    max = new Date(until);
    debug("Using the requested date, running until %s", max);
}

const since = nconf.get('since');
if(!since) {
    console.log("`since` variable is required");
    process.exit(1);
}
let last = new Date(since);
let total = null;
let progressive = 0;
let initial = 0;
const executedAt = moment();

return mongo
    .readLimit(cName, {}, { savingTime: -1 }, 1, 0)
    .then(_.first)
    .then(function(lastSaved) {
        if(lastSaved) {
            debug("Last reference found to %s", lastSaved.savingTime);
            last = new Date(lastSaved.savingTime);
        }
        else {
            debug("Starting `since` %s", last);
        }
        return last;
    })
    .tap(function(last) {
        return mongo.count(cName, {})
            .tap(function(before) {
                debug("previously found %d, chunk size configured (with `amount`) is %d", before, CHUNK);
                initial = before;
            });
    })
    .tap(function(last) {
        return mongo.count(nconf.get('schema').htmls, {
                savingTime: { $gt: last, $lte: max }
        })
        .tap(function(amount) {
            total = (amount - initial);
            debug("The amount of htmls between %s and %s is: %d, still TODO %d",
                last, max, amount, total);
        });
    })
    .then(infiniteLoop);

function infiniteLoop(last) {
    let start = moment();
    return mongoPipeline(last)
        .map(enhanceRedact)
        .then(_.compact)
        .tap(massSave)
        .then(function(elements) {
            if(!_.size(elements)) {
                console.log("0 elements found");
                process.exit(1);
            }
            let end = moment();
            var secs = moment.duration(end - start).asSeconds();
            debug("exec %d secs 1st [%s] last [%s]",
                secs,
                _.first(elements) ? moment(_.first(elements).savingTime).format() : "NONE",
                _.last(elements) ? moment(_.last(elements).savingTime).format() : "NONE"
            );
            return new Date(_.last(elements).savingTime);
        })
        .then(infiniteLoop)
        .catch(function(error) {
            console.log("Fatal");
            console.error(error);
        });
};

function massSave(elements) {
    let copyable = new Object(elements);
    return Promise.map(elements, function(e) {
        return mongo
            .count(cName, { id: e.id })
            .tap(function(a) {
                if(a > 0)
                    copyable = _.reject(copyable, { id: e.id });
            });
    }, { concurrency: 5 })
    .then(function() {
        progressive += _.size(copyable);
        const runfor = moment.duration(moment() - executedAt).asSeconds();
        const pps = _.round(progressive / runfor, 0)
        const estim = (total - progressive) / pps;
        const stillwaitfor = moment.duration({ seconds: estim }).humanize();
        debug("Saving %d objects, total %d (still TODO %d) run since %s (%d secs) PPS %d ETA %s",
            _.size(copyable), progressive, total - progressive,
            moment.duration(executedAt - moment()).humanize(),
            runfor, pps, stillwaitfor
        );
        if(_.size(copyable))
            return mongo.writeMany(cName, copyable);
    });
};

function enhanceRedact(e) {
    try {
        _.unset(e, '_id');
        e.impressionOrder = _.first(e.impressionOrder);
        e.impressionTime = _.first(e.impressionTime);
        e.pseudo = utils.pseudonymizeUser(e.userId);
        const jsdom = new JSDOM(e.html).window.document;
        e.attributions = attributeOffsets(jsdom, e.html);
        e.details = l({jsdom}).linkedtime;
        _.unset(e, 'html');
        _.unset(e, 'userId');
    } catch(error) {
        console.error(error);
        return null;
    }
    return e;
};

function mongoPipeline(lastSaved) {

    if(moment(lastSaved).isAfter(max)) {
        debug("Execution completed, reach %s", max);
        process.exit(1);
    }

    return mongo.aggregate(nconf.get('schema').htmls, [{
        /* I use savingTime despite we use the impressionTime, because
         * savingTime is indexes, impressionTime ensure differencies */
            $match: {
                savingTime: { $gt: lastSaved }
            }},
            { $sort: {
                savingTime: 1
            }},
            { $limit: CHUNK },
            { $lookup: {
                from: "impressions2",
                localField: "id",
                foreignField: "htmlId",
                as: "impre"
            }},
            { $project: {
                html: true,
                utype: true,
                permaLink: true,
                id: true,
                timelineId: true,
                userId: true,
                savingTime: true,

                impressionOrder: '$impre.impressionOrder',
                impressionTime: '$impre.impressionTime',
            }}
        ]);
};

function attributeOffsets(jsdom, htmlstring) {

    let retval = []
    // { h: 'h5' || 'h6', offset: <Int>, name: <String>, display: <String> }
    const h5s = jsdom.querySelectorAll('h5');
    const h6s = jsdom.querySelectorAll('h6');

    function finder(initialO, h) {
        let linked = h.firstChild && h.firstChild.querySelector && h.firstChild.querySelector('a');
        if(linked) {
            let name = h.firstChild.querySelector('a').textContent;
            let display = h.textContent;
            let offset = htmlstring.indexOf(h.outerHTML);
            if(name) {
                retval.push(_.extend(initialO, {
                    offset,
                    name,
                    display
                }));
            }
        }
    };

    _.each(h5s, _.partial(finder, { h: 'h5' }));
    _.each(h6s, _.partial(finder, { h: 'h6' }));

    return retval;
};

<commit_msg>last tweaks<commit_after>const _ = require('lodash');
const nconf = require('nconf');
const Promise = require('bluebird');
const JSDOM = require('jsdom').JSDOM;
const debug = require('debug')('datathon');
const moment = require('moment');

const utils = require('../lib/utils');
const mongo = require('../lib/mongo');
const l = require('../parsers/components/linkontime');

const cfgFile = "config/content.json";
nconf.argv().env().file({ file: cfgFile });

const cName = 'finalized';
const CHUNK = nconf.get('amount') ? _.parseInt(nconf.get('amount')) : 500;

let max = null;
const until = nconf.get('unti');
if(!until) {
    max = new Date("2018-11-30");
    debug("`until` not set: using the default %s", max);
}
else {
    max = new Date(until);
    debug("`until` set, it will stop when reach %s", max);
}

const since = nconf.get('since');
let last = new Date(since);
let total = null;
let progressive = 0;
let initial = 0;
const executedAt = moment();

return mongo
    .readLimit(cName, {}, { savingTime: -1 }, 1, 0)
    .then(_.first)
    .then(function(lastSaved) {
        if(lastSaved) {
            if(since) {
                debug("Last reference found to %s but since %s request overrides",
                    lastSaved.savingTime, since);
                last = new Date(since);
            } else {
                debug("Last reference found to %s, and since not configured", lastSaved.savingTime);
                last = new Date(lastSaved.savingTime);
            }
        }
        else if(!since) {
            debug("When last reference don't exist, `since` is mandatory");
            process.exit(1);
        }
        else {
            last = new Date(since);
            debug("Starting `since` %s", last);
        }
        return last;
    })
    .tap(function(last) {
        return mongo.count(cName, {})
            .tap(function(before) {
                debug("previously found %d, chunk size configured (with `amount`) is %d", before, CHUNK);
                initial = before;
            });
    })
    .tap(function(last) {
        return mongo.count(nconf.get('schema').htmls, {
                savingTime: { $gt: last, $lte: max }
        })
        .tap(function(amount) {
            total = (amount - initial);
            debug("The # of htmls between %s and %s is: %d, still TBD %d",
                moment(last).format(), moment(max).format(), amount, total);
        });
    })
    .then(infiniteLoop);

function infiniteLoop(last) {
    let start = moment();
    return mongoPipeline(last)
        .map(enhanceRedact)
        .then(_.compact)
        .tap(massSave)
        .then(function(elements) {
            if(!_.size(elements)) {
                console.log("0 elements found");
                process.exit(1);
            }
            let end = moment();
            var secs = moment.duration(end - start).asSeconds();
            debug("exec %d secs 1st [%s] last [%s]",
                secs,
                _.first(elements) ? moment(_.first(elements).savingTime).format() : "NONE",
                _.last(elements) ? moment(_.last(elements).savingTime).format() : "NONE"
            );
            return new Date(_.last(elements).savingTime);
        })
        .then(infiniteLoop)
        .catch(function(error) {
            console.log("Fatal");
            console.error(error);
        });
};

function massSave(elements) {
    let copyable = new Object(elements);
    return Promise.map(elements, function(e) {
        return mongo
            .count(cName, { id: e.id })
            .tap(function(a) {
                if(a > 0)
                    copyable = _.reject(copyable, { id: e.id });
            });
    }, { concurrency: 5 })
    .then(function() {
        progressive += _.size(copyable);
        const runfor = moment.duration(moment() - executedAt).asSeconds();
        const pps = _.round(progressive / runfor, 0)
        const estim = (total - progressive) / pps;
        const stillwaitfor = moment.duration({ seconds: estim }).humanize();
        debug("Saving %d objects, total %d (still TBD %d) run since %s (%d secs) PPS %d ETA %s",
            _.size(copyable), progressive, total - progressive,
            moment.duration(executedAt - moment()).humanize(),
            runfor, pps, stillwaitfor
        );
        if(_.size(copyable))
            return mongo.writeMany(cName, copyable);
    });
};

function enhanceRedact(e) {
    try {
        _.unset(e, '_id');
        e.impressionOrder = _.first(e.impressionOrder);
        e.impressionTime = _.first(e.impressionTime);
        e.pseudo = utils.pseudonymizeUser(e.userId);
        const jsdom = new JSDOM(e.html).window.document;
        e.attributions = attributeOffsets(jsdom, e.html);
        e.details = l({jsdom}).linkedtime;
        _.unset(e, 'html');
        _.unset(e, 'userId');
    } catch(error) {
        console.error(error);
        return null;
    }
    return e;
};

function mongoPipeline(lastSaved) {

    if(moment(lastSaved).isAfter(max)) {
        debug("Execution completed, reach %s", max);
        process.exit(1);
    }

    return mongo.aggregate(nconf.get('schema').htmls, [{
        /* I use savingTime despite we use the impressionTime, because
         * savingTime is indexes, impressionTime ensure differencies */
            $match: {
                savingTime: { $gt: lastSaved }
            }},
            { $sort: {
                savingTime: 1
            }},
            { $limit: CHUNK },
            { $lookup: {
                from: "impressions2",
                localField: "id",
                foreignField: "htmlId",
                as: "impre"
            }},
            { $project: {
                html: true,
                utype: true,
                permaLink: true,
                id: true,
                timelineId: true,
                userId: true,
                savingTime: true,

                impressionOrder: '$impre.impressionOrder',
                impressionTime: '$impre.impressionTime',
            }}
        ]);
};

function attributeOffsets(jsdom, htmlstring) {

    let retval = []
    // { h: 'h5' || 'h6', offset: <Int>, name: <String>, display: <String> }
    const h5s = jsdom.querySelectorAll('h5');
    const h6s = jsdom.querySelectorAll('h6');

    function finder(initialO, h) {
        let linked = h.firstChild && h.firstChild.querySelector && h.firstChild.querySelector('a');
        if(linked) {
            let name = h.firstChild.querySelector('a').textContent;
            let display = h.textContent;
            let offset = htmlstring.indexOf(h.outerHTML);
            if(name) {
                retval.push(_.extend(initialO, {
                    offset,
                    name,
                    display
                }));
            }
        }
    };

    _.each(h5s, _.partial(finder, { h: 'h5' }));
    _.each(h6s, _.partial(finder, { h: 'h6' }));

    return retval;
};

<|endoftext|>


<commit_before>/*
 * Copyright 2014 Ambris
 *
 * Project : Very simple PDF viewer jQuery plugin
 * Version : 0.1
 * author: Richard Stefan (richard.stefan@ambris.com)
 *
 * Licensed under the Apache License, Version 2.0(the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http: //www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function($) {

    var customStyle = {
        width: '100px',
        height: '100px',
        overflow: 'scroll',
        position: 'absolute',
        top: '-9999px'
    };

    var $scrollDiv = $("
").css(customStyle);
    var scrollDiv = $scrollDiv.get(0);
    $("body").append($scrollDiv);

    var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
    var scrollbarHeight = scrollDiv.offsetHeight - scrollDiv.clientHeight;
    document.body.removeChild(scrollDiv);

    $.scrollbar = {
        width: function() {
            return scrollbarWidth;
        },

        height: function() {
            return scrollbarHeight;
        }
    };
})(jQuery);

(function($) {
    $.pdfviewer = function(element, options) {

        var defaults = {
            href: '', // for demonstration purpose
            scale: 1.0,
            autoFit: false,
            toolbar_template: '
' +
                '<button id="pdf-prev">Previous</button>' +
                '<button id="pdf-next">Next</button>' +
                'Page:/' +
                '<button id="pdf-autofit-height">Adjust Height</button>' +
                '<button id="pdf-autofit-width">Adjust Width</button>' +
                '<button id="pdf-autofit">Auto fit</button>' +
                '
',
            viewer_template: '
<canvas id="pdf-the-canvas"></canvas>
',

            onPrevPage: function() {
                return true;
            },
            onNextPage: function() {
                return true;
            },
            onDocumentLoaded: function() {},
            onBeforeRenderPage: function(num) {
                return true;
            },
            onRenderedPage: function(num) {}
        }

        var plugin = this;

        plugin.settings = {};

        var $element = $(element), // reference to the jQuery version of DOM element
            element = element, // reference to the actual DOM element
            elt_width = $element.innerWidth(),
            elt_heigth = $element.innerHeight();

        var pdfDoc = null,
            pageNum = 1,
            pageRendering = false,
            pageNumPending = null,
            scale = 1.0,
            canvas = null,
            ctx = null;

        plugin.init = function() {

            options = options || {};
            options.href = options.href || $element.data('href');

            plugin.settings = $.extend({}, defaults, options);

            $element.html(build());

            if (!PDFJS) {
                console.log('pdf.js not loaded. Add "pdf.js" to your page.');
                return this;
            }

            PDFJS.disableWorker = true;

            scale = plugin.settings.scale;
            canvas = $('#pdf-the-canvas', element).get(0);
            ctx = canvas.getContext('2d');

            $('#pdf-prev', element).on('click', plugin.prevPage);
            $('#pdf-next', element).on('click', plugin.nextPage);
            $('#pdf-autofit-height', element).on('click', plugin.autoFitScaleByHeight);
            $('#pdf-autofit-width', element).on('click', plugin.autoFitScaleByWidth);
            $('#pdf-autofit', element).on('click', plugin.autoFit);

            /**
             * Asynchronously downloads PDF.
             */
            PDFJS.getDocument(plugin.settings.href).then(function(pdfDoc_) {
                pdfDoc = pdfDoc_;
                plugin.settings.onDocumentLoaded.call(element);

                $('#pdf-page-count', element).text(pdfDoc.numPages);

                // Initial/first page rendering
                plugin.renderPage(pageNum);
            });
        };

        // public methods
        /**
         * Get page info from document, resize canvas accordingly, and render page.
         * @param num Page number.
         */
        plugin.renderPage = function(num) {

            if (!plugin.settings.onBeforeRenderPage.call(element, num)) return;

            pageRendering = true;
            // Using promise to fetch the page
            pdfDoc.getPage(num).then(function(page) {
                var viewport = page.getViewport(scale);
                canvas.height = viewport.height;
                canvas.width = viewport.width;

                $('.pdf-canvas').css('margin-top', $('.pdf-toolbar').height() + 1);
                if (canvas.width < $(canvas).parent().width() - 20)
                    $(canvas).css('margin-left', (($(canvas).parent().width() - canvas.width) / 2));
                else
                    $(canvas).css('margin-left', 0);

                // Render PDF page into canvas context
                var renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                };
                var renderTask = page.render(renderContext);

                // Wait for rendering to finish
                renderTask.promise.then(function() {
                    pageRendering = false;

                    plugin.settings.onRenderedPage.call(element, num);

                    if (pageNumPending !== null) {
                        // New page rendering is pending
                        plugin.renderPage(pageNumPending);
                        pageNumPending = null;
                    }
                });
            });

            // Update page counters
            $('#pdf-page-num', element).text(pageNum);
        };

        plugin.currentPage = function() {
            return pageNum;
        };

        plugin.pages = function() {
            return pdfDoc.numPages;
        };

        /**
         * Displays previous page.
         */
        plugin.prevPage = function() {
            if (!plugin.settings.onPrevPage.call(element)) return;

            if (pageNum <= 1) {
                return;
            }
            pageNum--;
            queueRenderPage(pageNum);
        };

        /**
         * Displays next page.
         */
        plugin.nextPage = function() {
            if (!plugin.settings.onNextPage.call(element)) return;

            if (pageNum >= pdfDoc.numPages) {
                return;
            }
            pageNum++;
            queueRenderPage(pageNum);
        }

        plugin.autoFit = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentHeight = $(canvas).parent().height();
                var parentWidth = $(canvas).parent().width();
                var viewport = page.getViewport(1.0);

                if (parentHeight <= parentWidth)
                    plugin.autoFitScaleByHeight();
                else
                    plugin.autoFitScaleByWidth();
            });
        }

        plugin.autoFitScaleByHeight = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentHeight = $(canvas).parent().height() - 1;
                var parentWidth = $(canvas).parent().width() - 1;

                var viewport = page.getViewport(1.0);
                scale = parentHeight / viewport.height;

                if (scale * viewport.width >= parentWidth)
                    scale = (parentHeight - $.scrollbar.height()) / viewport.height;

                queueRenderPage(pageNum);
            });
        }

        plugin.autoFitScaleByWidth = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentWidth = $(canvas).parent().width() - 1;
                var parentHeight = $(canvas).parent().height() - 1;

                var viewport = page.getViewport(1.0);
                scale = parentWidth / viewport.width;

                if (scale * viewport.height >= parentHeight)
                    scale = (parentWidth - $.scrollbar.width()) / viewport.width;

                queueRenderPage(pageNum);
            });
        }

        // private methods
        var build = function() {
            return plugin.settings.toolbar_template + plugin.settings.viewer_template;
        }

        /**
         * If another page rendering in progress, waits until the rendering is
         * finised. Otherwise, executes rendering immediately.
         */
        var queueRenderPage = function(num) {
            if (pageRendering) {
                pageNumPending = num;
            } else {
                plugin.renderPage(num);
            }
        }

        plugin.init();
    }

    $.fn.pdfviewer = function(options) {

        return this.each(function() {

            if (undefined == $(this).data('pdfviewer')) {

                var plugin = new $.pdfviewer(this, options);

                // in the jQuery version of the element
                // store a reference to the plugin object
                // you can later access the plugin and its methods and properties like
                // element.data('pdfviewer').publicMethod(arg1, arg2, ... argn) or
                // element.data('pdfviewer').settings.propertyName
                $(this).data('pdfviewer', plugin);

            }

        });

    }

})(jQuery);<commit_msg>add support for HiDPI devices<commit_after>/*
 * Copyright 2014 Ambris
 *
 * Project : Very simple PDF viewer jQuery plugin
 * Version : 0.1
 * author: Richard Stefan (richard.stefan@ambris.com)
 *
 * Licensed under the Apache License, Version 2.0(the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http: //www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function($) {

    var customStyle = {
        width: '100px',
        height: '100px',
        overflow: 'scroll',
        position: 'absolute',
        top: '-9999px'
    };

    var $scrollDiv = $("
").css(customStyle);
    var scrollDiv = $scrollDiv.get(0);
    $("body").append($scrollDiv);

    var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
    var scrollbarHeight = scrollDiv.offsetHeight - scrollDiv.clientHeight;
    document.body.removeChild(scrollDiv);

    $.scrollbar = {
        width: function() {
            return scrollbarWidth;
        },

        height: function() {
            return scrollbarHeight;
        }
    };
})(jQuery);

(function($) {
    $.pdfviewer = function(element, options) {

        var defaults = {
            href: '', // for demonstration purpose
            scale: 1.0,
            autoFit: false,
            toolbar_template: '
' +
                '<button id="pdf-prev">Previous</button>' +
                '<button id="pdf-next">Next</button>' +
                'Page:/' +
                '<button id="pdf-autofit-height">Adjust Height</button>' +
                '<button id="pdf-autofit-width">Adjust Width</button>' +
                '<button id="pdf-autofit">Auto fit</button>' +
                '
',
            viewer_template: '
<canvas id="pdf-the-canvas"></canvas>
',

            onPrevPage: function() {
                return true;
            },
            onNextPage: function() {
                return true;
            },
            onDocumentLoaded: function() {},
            onBeforeRenderPage: function(num) {
                return true;
            },
            onRenderedPage: function(num) {}
        }

        var plugin = this;

        plugin.settings = {};

        var $element = $(element), // reference to the jQuery version of DOM element
            element = element, // reference to the actual DOM element
            elt_width = $element.innerWidth(),
            elt_heigth = $element.innerHeight();

        var pdfDoc = null,
            pageNum = 1,
            pageRendering = false,
            pageNumPending = null,
            scale = 1.0,
            canvas = null,
            ctx = null;

        plugin.init = function() {

            options = options || {};
            options.href = options.href || $element.data('href');

            plugin.settings = $.extend({}, defaults, options);

            $element.html(build());

            if (!PDFJS) {
                console.log('pdf.js not loaded. Add "pdf.js" to your page.');
                return this;
            }

            PDFJS.disableWorker = true;

            scale = plugin.settings.scale;
            canvas = $('#pdf-the-canvas', element).get(0);
            ctx = canvas.getContext('2d');

            $('#pdf-prev', element).on('click', plugin.prevPage);
            $('#pdf-next', element).on('click', plugin.nextPage);
            $('#pdf-autofit-height', element).on('click', plugin.autoFitScaleByHeight);
            $('#pdf-autofit-width', element).on('click', plugin.autoFitScaleByWidth);
            $('#pdf-autofit', element).on('click', plugin.autoFit);

            /**
             * Asynchronously downloads PDF.
             */
            PDFJS.getDocument(plugin.settings.href).then(function(pdfDoc_) {
                pdfDoc = pdfDoc_;
                plugin.settings.onDocumentLoaded.call(element);

                $('#pdf-page-count', element).text(pdfDoc.numPages);

                // Initial/first page rendering
                plugin.renderPage(pageNum);
            });
        };

        // public methods
        /**
         * Get page info from document, resize canvas accordingly, and render page.
         * @param num Page number.
         */
        plugin.renderPage = function(num) {

            if (!plugin.settings.onBeforeRenderPage.call(element, num)) return;

            pageRendering = true;
            // Using promise to fetch the page
            pdfDoc.getPage(num).then(function(page) {
                var viewport = page.getViewport(scale);
                canvas.height = viewport.height;
                canvas.width = viewport.width;

                $('.pdf-canvas').css('margin-top', $('.pdf-toolbar').height() + 1);
                if (canvas.width < $(canvas).parent().width() - 20)
                    $(canvas).css('margin-left', (($(canvas).parent().width() - canvas.width) / 2));
                else
                    $(canvas).css('margin-left', 0);

                // now default all the dimension info
                // finally query the various pixel ratios
                var devicePixelRatio = window.devicePixelRatio || 1,
                    backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                    ctx.mozBackingStorePixelRatio ||
                    ctx.msBackingStorePixelRatio ||
                    ctx.oBackingStorePixelRatio ||
                    ctx.backingStorePixelRatio || 1,

                    ratio = devicePixelRatio / backingStoreRatio;

                // upscale the canvas if the two ratios don't match
                if (devicePixelRatio !== backingStoreRatio) {

                    var oldWidth = canvas.width;
                    var oldHeight = canvas.height;

                    canvas.width = oldWidth * ratio;
                    canvas.height = oldHeight * ratio;

                    canvas.style.width = oldWidth + 'px';
                    canvas.style.height = oldHeight + 'px';

                    // now scale the context to counter
                    // the fact that we've manually scaled
                    // our canvas element
                    ctx.scale(ratio, ratio);

                }

                // Render PDF page into canvas context
                var renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                };
                var renderTask = page.render(renderContext);

                // Wait for rendering to finish
                renderTask.promise.then(function() {
                    pageRendering = false;

                    plugin.settings.onRenderedPage.call(element, num);

                    if (pageNumPending !== null) {
                        // New page rendering is pending
                        plugin.renderPage(pageNumPending);
                        pageNumPending = null;
                    }
                });
            });

            // Update page counters
            $('#pdf-page-num', element).text(pageNum);
        };

        plugin.currentPage = function() {
            return pageNum;
        };

        plugin.pages = function() {
            return pdfDoc.numPages;
        };

        /**
         * Displays previous page.
         */
        plugin.prevPage = function() {
            if (!plugin.settings.onPrevPage.call(element)) return;

            if (pageNum <= 1) {
                return;
            }
            pageNum--;
            queueRenderPage(pageNum);
        };

        /**
         * Displays next page.
         */
        plugin.nextPage = function() {
            if (!plugin.settings.onNextPage.call(element)) return;

            if (pageNum >= pdfDoc.numPages) {
                return;
            }
            pageNum++;
            queueRenderPage(pageNum);
        }

        plugin.autoFit = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentHeight = $(canvas).parent().height();
                var parentWidth = $(canvas).parent().width();
                var viewport = page.getViewport(1.0);

                if (parentHeight <= parentWidth)
                    plugin.autoFitScaleByHeight();
                else
                    plugin.autoFitScaleByWidth();
            });
        }

        plugin.autoFitScaleByHeight = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentHeight = $(canvas).parent().height() - 1;
                var parentWidth = $(canvas).parent().width() - 1;

                var viewport = page.getViewport(1.0);
                scale = parentHeight / viewport.height;

                if (scale * viewport.width >= parentWidth)
                    scale = (parentHeight - $.scrollbar.height()) / viewport.height;

                queueRenderPage(pageNum);
            });
        }

        plugin.autoFitScaleByWidth = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentWidth = $(canvas).parent().width() - 1;
                var parentHeight = $(canvas).parent().height() - 1;

                var viewport = page.getViewport(1.0);
                scale = parentWidth / viewport.width;

                if (scale * viewport.height >= parentHeight)
                    scale = (parentWidth - $.scrollbar.width()) / viewport.width;

                queueRenderPage(pageNum);
            });
        }

        // private methods
        var build = function() {
            return plugin.settings.toolbar_template + plugin.settings.viewer_template;
        }

        /**
         * If another page rendering in progress, waits until the rendering is
         * finised. Otherwise, executes rendering immediately.
         */
        var queueRenderPage = function(num) {
            if (pageRendering) {
                pageNumPending = num;
            } else {
                plugin.renderPage(num);
            }
        }

        plugin.init();
    }

    $.fn.pdfviewer = function(options) {

        return this.each(function() {

            if (undefined == $(this).data('pdfviewer')) {

                var plugin = new $.pdfviewer(this, options);

                // in the jQuery version of the element
                // store a reference to the plugin object
                // you can later access the plugin and its methods and properties like
                // element.data('pdfviewer').publicMethod(arg1, arg2, ... argn) or
                // element.data('pdfviewer').settings.propertyName
                $(this).data('pdfviewer', plugin);

            }

        });

    }

})(jQuery);<|endoftext|>


<commit_before>Parse.initialize("ONeIYsbSCtIJg6bo0M823t6Z8ZqmqEM4Zfgh2U5a", "A1lJ2mF6YV48qcO5KBkQ1XCEC2BDF3mAt1MlqqlB");

var user = Parse.User.current();
updateScores();

function onLogin() {
  console.log('Welcome!  Fetching your information.... ');

  FB.api("/me", function (response) {
    if (response && !response.error) {
      user.set("fbId", response.id);
      user.set("name", response.name);
      user.save();
    }
    //console.log(response);
  });

  FB.api("/me/friends",
    function (response) {
      if (response && !response.error) {
      var ids = [];
      var query = new Parse.Query(Parse.User);
      var relation = user.relation("friendsUsingApp");
      for (i = 0; false && i < response.data.keys(dictionary).length; i++) {
        ids[0] = response.data[i];
      }
      query.containsAll("fbId", ids);
      query.find({
        success: function(friends) {
          relation.add(friends);
          user.save();
        }
      });
      }
    }
  );

  fetchStatuses();
}

function updateScores() {
  var UserScores = Parse.Collection.extend({
    model: Parse.User
  });
  new UserScores().fetch({
    success: function(collection) {
      str = "";
      collection.each(function(object) {
        str += object.get("name") + "  :  " + object.get("correctAnswers") + "
";
      });
      $('#scoreboard').html(str);
    },
    error: function(collection, error) {
      // The collection could not be retrieved.
    }
  });
}

var pagesGrabbed = 0;
var postslist = [];

function fetchStatuses() {
  FB.api("/me/home", getPosts);
}

function getPosts(response){
  $('#statusPost').text("Loading your friends' statuses...");

  for (element in response.data){
    post = response.data[element]
    if(post.hasOwnProperty('message')&&!post.hasOwnProperty('to')&&!post.from.hasOwnProperty('category')){
      //console.log(post.from.name + ": " +post.message);
      //console.log(post);
      postslist.push({name:post.from.name, nameid:post.from.id, message:post.message, postid:post.id});
    }
  }
  if(pagesGrabbed < 4){
    nextPage = response.paging.next;
    pagesGrabbed++;
    $.get(nextPage, getPosts, "json");
  } else {
    updateText();
  }
}

var prevPosts = [];
var chosen = 10;
var alreadyChosen = true;
var score = 0;

function updateText() {
  alreadyChosen = false;
  $('#panel1').toggleClass('falsebox',false);
  $('#panel1').toggleClass('truebox',false);
  $('#panel2').toggleClass('falsebox',false);
  $('#panel2').toggleClass('truebox',false);
  $('#panel3').toggleClass('falsebox',false);
  $('#panel3').toggleClass('truebox',false);
  $('#panel4').toggleClass('falsebox',false);
  $('#panel4').toggleClass('truebox',false);
  var arr = [];
  for(var i = 0; i < 4; i++) {
    var addpost = function(){
		arr[i] = postslist[Math.floor((Math.random() * postslist.length))];
		for(var j = 0;j<i;j++){
			if(arr[i].nameid === arr[j].nameid){
				addpost();
			}
		}
    };
    addpost();
  }
  chosen = Math.floor((Math.random() * 4));
  for(var k = 0;k<prevPosts.length;k++){
		if(arr[chosen].postid===prevPosts[k])
			chosen = Math.floor((Math.random() * 4));
  }
  prevPosts.push(chosen);
  var message = arr[chosen].message;
  $('#statusPost').text(message);
  $('#img1').attr('src',"https://graph.facebook.com/" + arr[0].nameid + "/picture?type=large");
  $('#name1').text(arr[0].name);
  $('#img2').attr('src',"https://graph.facebook.com/" + arr[1].nameid + "/picture?type=large");
  $('#name2').text(arr[1].name);
  $('#img3').attr('src',"https://graph.facebook.com/" + arr[2].nameid + "/picture?type=large");
  $('#name3').text(arr[2].name);
  $('#img4').attr('src',"https://graph.facebook.com/" + arr[3].nameid + "/picture?type=large");
  $('#name4').text(arr[3].name);
  $('#next').prop('disabled', true);
}

function correctAns(num){
	if(!alreadyChosen){
		if(num===chosen){
			if(num===0){
				$('#panel1').toggleClass('truebox',true);
			}
			else if(num===1){
				$('#panel2').toggleClass('truebox',true);
			}
			else if(num===2){
				$('#panel3').toggleClass('truebox',true);
			}
			else if(num===3){
				$('#panel4').toggleClass('truebox',true);
			}
			//increment the score of the current user
			score+=10;
			user.increment("correctAnswers");
		}
		else if(num!==chosen){
			if(num===0){
			$('#panel1').toggleClass('falsebox',true);
			}
			else if(num===1){
			$('#panel2').toggleClass('falsebox',true);
			}
			else if(num===2){
			$('#panel3').toggleClass('falsebox',true);
			}
			else if(num===3){
			  $('#panel4').toggleClass('falsebox',true);
			}
			if(chosen===0){
			  $('#panel1').toggleClass('truebox',true);
			}
			else if(chosen===1){
			  $('#panel2').toggleClass('truebox',true);
			}
			else if(chosen===2){
			  $('#panel3').toggleClass('truebox',true);
			}
			else if(chosen===3){
			  $('#panel4').toggleClass('truebox',true);
			}
			//increment statusesShown
			score-=5;
		}
		user.increment("statusesShown");
		user.save();
	}
  $('#scorelabel').text(score);
  $('#next').prop('disabled', false);
  alreadyChosen = true;
  chosen = 10;
  updateScores();
}

<commit_msg>Friends are properly added to the relation key in Parse, called "friendsUsingApp"<commit_after>Parse.initialize("ONeIYsbSCtIJg6bo0M823t6Z8ZqmqEM4Zfgh2U5a", "A1lJ2mF6YV48qcO5KBkQ1XCEC2BDF3mAt1MlqqlB");

var user = Parse.User.current();
updateScores();

function onLogin() {
  console.log('Welcome!  Fetching your information.... ');

  FB.api("/me", function (response) {
    if (response && !response.error) {
      user.set("fbId", response.id);
      user.set("name", response.name);
      user.save();
    }
    //console.log(response);
  });

  FB.api("/me/friends",
    function (response) {
      if (response && !response.error) {
        console.log("friends----");
        console.log(response);

        var ids = [];
        var query = new Parse.Query(Parse.User);
        var relation = user.relation("friendsUsingApp");
        //get size of dictionaries

        for (i = 0; i < response.data.length; i++) {
          ids[i] = response.data[i].id;
        }
        console.log(ids);
        console.log("gerodfksdjflsdjf");
        query.containedIn("fbId", ids);
        query.find({
          success: function(friends) {
            console.log(friends);
            console.log("SUCCESS");
            relation.add(friends);
            user.save();
          }
        });
      }
    }
  );

  fetchStatuses();
}

function updateScores() {
  var UserScores = Parse.Collection.extend({
    model: Parse.User
  });
  new UserScores().fetch({
    success: function(collection) {
      str = "";
      collection.each(function(object) {
        str += object.get("name") + "  :  " + object.get("correctAnswers") + "
";
      });
      $('#scoreboard').html(str);
    },
    error: function(collection, error) {
      // The collection could not be retrieved.
    }
  });
}

var pagesGrabbed = 0;
var postslist = [];

function fetchStatuses() {
  FB.api("/me/home", getPosts);
}

function getPosts(response){
  $('#statusPost').text("Loading your friends' statuses...");

  for (element in response.data){
    post = response.data[element]
    if(post.hasOwnProperty('message')&&!post.hasOwnProperty('to')&&!post.from.hasOwnProperty('category')){
      //console.log(post.from.name + ": " +post.message);
      //console.log(post);
      postslist.push({name:post.from.name, nameid:post.from.id, message:post.message, postid:post.id});
    }
  }
  if(pagesGrabbed < 4){
    nextPage = response.paging.next;
    pagesGrabbed++;
    $.get(nextPage, getPosts, "json");
  } else {
    updateText();
  }
}

var prevPosts = [];
var chosen = 10;
var alreadyChosen = true;
var score = 0;

function updateText() {
  alreadyChosen = false;
  $('#panel1').toggleClass('falsebox',false);
  $('#panel1').toggleClass('truebox',false);
  $('#panel2').toggleClass('falsebox',false);
  $('#panel2').toggleClass('truebox',false);
  $('#panel3').toggleClass('falsebox',false);
  $('#panel3').toggleClass('truebox',false);
  $('#panel4').toggleClass('falsebox',false);
  $('#panel4').toggleClass('truebox',false);
  var arr = [];
  for(var i = 0; i < 4; i++) {
    var addpost = function(){
		arr[i] = postslist[Math.floor((Math.random() * postslist.length))];
		for(var j = 0;j<i;j++){
			if(arr[i].nameid === arr[j].nameid){
				addpost();
			}
		}
    };
    addpost();
  }
  chosen = Math.floor((Math.random() * 4));
  for(var k = 0;k<prevPosts.length;k++){
		if(arr[chosen].postid===prevPosts[k])
			chosen = Math.floor((Math.random() * 4));
  }
  prevPosts.push(chosen);
  var message = arr[chosen].message;
  $('#statusPost').text(message);
  $('#img1').attr('src',"https://graph.facebook.com/" + arr[0].nameid + "/picture?type=large");
  $('#name1').text(arr[0].name);
  $('#img2').attr('src',"https://graph.facebook.com/" + arr[1].nameid + "/picture?type=large");
  $('#name2').text(arr[1].name);
  $('#img3').attr('src',"https://graph.facebook.com/" + arr[2].nameid + "/picture?type=large");
  $('#name3').text(arr[2].name);
  $('#img4').attr('src',"https://graph.facebook.com/" + arr[3].nameid + "/picture?type=large");
  $('#name4').text(arr[3].name);
  $('#next').prop('disabled', true);
}

function correctAns(num){
	if(!alreadyChosen){
		if(num===chosen){
			if(num===0){
				$('#panel1').toggleClass('truebox',true);
			}
			else if(num===1){
				$('#panel2').toggleClass('truebox',true);
			}
			else if(num===2){
				$('#panel3').toggleClass('truebox',true);
			}
			else if(num===3){
				$('#panel4').toggleClass('truebox',true);
			}
			//increment the score of the current user
			score+=10;
			user.increment("correctAnswers");
		}
		else if(num!==chosen){
			if(num===0){
			$('#panel1').toggleClass('falsebox',true);
			}
			else if(num===1){
			$('#panel2').toggleClass('falsebox',true);
			}
			else if(num===2){
			$('#panel3').toggleClass('falsebox',true);
			}
			else if(num===3){
			  $('#panel4').toggleClass('falsebox',true);
			}
			if(chosen===0){
			  $('#panel1').toggleClass('truebox',true);
			}
			else if(chosen===1){
			  $('#panel2').toggleClass('truebox',true);
			}
			else if(chosen===2){
			  $('#panel3').toggleClass('truebox',true);
			}
			else if(chosen===3){
			  $('#panel4').toggleClass('truebox',true);
			}
			//increment statusesShown
			score-=5;
		}
		user.increment("statusesShown");
		user.save();
	}
  $('#scorelabel').text(score);
  $('#next').prop('disabled', false);
  alreadyChosen = true;
  chosen = 10;
  updateScores();
}

<|endoftext|>