<commit_before>'use strict';

var Tree2Json = require('broccoli-tree-to-json'),
  RSVP = require('rsvp'),
  path = require('path'),
  fs = require('fs'),
  nano = require('nano'),
  lodash = require('lodash'),
  mktemp = require('mktemp'),
  mkdirp = require('mkdirp');

/**
 *
 * Synchronize CouchDB design documents.
 * Options include
 *  * `url`: the couchdb url (http://host:123/db)
 *  * `username`: optional. used to authenticate with couchdb
 *  * `password`: required if username is present.
 *  * `initDesign`:optional. Set to true if the directory structure should be created from the existing database design documents
 *
 * @param inputTree {string|tree} the input tree to monitor
 * @param options {Object} couchdb connection options
 * @return {CouchDBVersioning}
 * @constructor
 * @alias module:index
 */
function CouchDBVersioning(inputTree, options) {
  if (!(this instanceof CouchDBVersioning)) return new CouchDBVersioning(inputTree, options);

  this.srcDir = inputTree;
  this.revDir = inputTree + '/.rev';
  this.options = options;
  this.inputTree = new Tree2Json(inputTree + '/_design');

  this.initPromise = this.init(options)
    .catch(function (err) {
      console.trace('CouchDB Init ERROR:', new Date(), err);
    });
}

CouchDBVersioning.prototype.init = function (options) {
  return RSVP.all([this.initDesign(options),
    this.initTmpDir(),
    this.initRevCache()])
    .catch(function (err) {
      console.log('CouchDB Versioning initialization error:', err);
    });
};

CouchDBVersioning.prototype.initDesign = function (options) {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    if (options.initDesign) {
      mkdirp(path.join(self.srcDir, '_design'), function (err, made) {
        if (err) reject(err);
        else resolve(self.initExistingDesigns());
      });
    } else resolve();
  });
};

CouchDBVersioning.prototype.initConnection = function () {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    var connection = nano(self.options.url);

    if (self.options.username) {
      connection.auth(self.options.username, self.options.password, function (err, body, headers) {
        if (err) reject(err);
        else {
          self.connection = nano({url: self.options.url, cookie: headers['set-cookie'][0]});
          resolve();
        }
      });
    } else {
      self.connection = connection;
      resolve(connection);
    }
  });
};

CouchDBVersioning.prototype.initTmpDir = function () {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    mktemp.createDir(path.join((process.env.TMPDIR || 'tmp'), 'XXXXXXXX.tmp'), function (err, path) {
      if (err) {
        console.warn('CouchDBVersioning WARN:', new Date(), 'Could not create temp dir');
        resolve();
      }
      else {
        self.tempDir = path;
        resolve(path)
      }
    });
  });
};

CouchDBVersioning.prototype.initRevCache = function () {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    mkdirp(self.revDir, function (err, made) {
      if (err) reject(err);
      else resolve();
    });
  });
};

function getFiles(destDir) {
  return new RSVP.Promise(function (resolve, reject) {
    fs.readdir(destDir, function (err, files) {
      if (err) reject(err);
      else resolve(files);
    });
  })
}

function readFile(dir, file) {
  return new RSVP.Promise(function (resolve, reject) {
    fs.readFile(path.join(dir, file), function (err, data) {
      if (err) reject(err);
      else resolve(JSON.parse(data.toString()));
    });
  });
}

function reportError(docName, date, localRev, serverRev, nag) {
  console.log(nag ? 'NAG:' : 'ERROR:', date, docName + '._rev Conflict: local is', localRev, 'server is', serverRev);
}

CouchDBVersioning.prototype.updateDesign = function (existingDesigns, design) {
  var self = this;
  return RSVP.all(Object.keys(design).map(function (key) {
    return new RSVP.Promise(function (resolve, reject) {
      var designDoc = design[key];
      var designName = '_design/' + key;
      var existing = existingDesigns[key] || {_id: designName};
      designDoc._id = existing._id;

      return self.getRev(key)
        .then(function (rev) {
          var docName;
          var serverRevNum = 0, localRevNum;
          if (existing._rev) {
            serverRevNum = parseInt(existing._rev.split('-')[0]);
          }
          localRevNum = parseInt(rev.split('-')[0]);

          /*
           NOTE - Messing with _revs is a really bad idea.
           But as a development tool this is a special case.
           Generally development revs will outpace production revs, so we're allowing
           updates when local revs are equal or greater
           */
          if (localRevNum >= serverRevNum) {
            //fake out the rev for the equality test and update
            designDoc._rev = existing._rev;
            if (!lodash.isEqual(designDoc, existing)) {
              return new RSVP.Promise(function (resolve, reject) {
                self.connection.insert(designDoc, designName, function (err, body) {
                  if (err)reject(err);
                  else {
                    resolve(self.updateRev(key, body.rev));
                  }
                });
              }).catch(function (err) {
                  reject(err);
                });
            }
          } else {
            docName = '_design/' + key;
            reportError(docName, new Date(), rev, existing._rev);
            //nag
            setInterval(reportError, 10000, docName, new Date(), rev, existing._rev, true);
          }
        });
    });
  }));
};

CouchDBVersioning.prototype.getRev = function (key) {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    fs.readFile(path.join(self.revDir, key + '.txt'), function (err, data) {
      if (err) reject(err);
      else resolve(data.toString());
    });
  });
};

CouchDBVersioning.prototype.updateRev = function (key, rev) {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    var filePath = path.join(self.revDir, key + '.txt');
    fs.writeFile(filePath, rev, function (err, data) {
      if (err) {
        //HEROKU deploys won't update the rev (read only dirs), so this shouldn't be fatal
        console.warn('CouchDBVersioning WARN:', new Date(), 'could not update', filePath, '. :', err);
      }
      else resolve();
    });
  });
};

CouchDBVersioning.prototype.getExistingDesigns = function () {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    self.connection.get('_all_docs', {startkey: '_design', endkey: '_design0', include_docs: true},
      function (err, body) {
        var existing = {};
        if (err) reject(err);
        else {
          body.rows.forEach(function (row) {
            existing[row.id.split('/')[1]] = row.doc
          });
          resolve(existing);
        }
      });
  });
};

CouchDBVersioning.prototype.updateDocument = function (destDir, fileName) {
  var self = this;
  return readFile(destDir, fileName)
    .then(function (json) {
      if ('_design.json' === fileName) {
        return self.getExistingDesigns()
          .then(function (existing) {
            return self.updateDesign(existing, json);
          });
      }
    });
};

CouchDBVersioning.prototype.updateCouch = function (destDir) {
  var self = this;
  return getFiles(destDir)
    .then(function (files) {
      return RSVP.all(files.map(function (fileName) {
        return self.updateDocument(destDir, fileName);
      }));
    });
};

CouchDBVersioning.prototype.read = function (readTree) {
  var self = this;
  return this.initPromise
    .then(function () {
      return RSVP.all([self.initConnection(), readTree(self.inputTree)]);
    }).then(function (resolutions) {
      return self.updateCouch(resolutions[1]);
    }).then(function () {
      return self.tempDir;
    }).catch(function (err) {
      console.trace('CouchDBVersioning: ERROR:', new Date(), err);
      return self.tempDir;
    });
};

CouchDBVersioning.prototype.cleanup = function () {
  this.inputTree.cleanup();
  if (this.tempDir) fs.rmdirSync(this.tempDir);
};

CouchDBVersioning.prototype.writeDir = function (filePath, json) {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    mkdirp(filePath, function (err, made) {
      var promises;
      if (err) reject(err);
      else {
        promises = Object.keys(json).map(function (key) {
          var val = json[key];
          var subPath = path.join(filePath, key);
          var result;
          if (val instanceof Array || typeof val !== 'object') {
            result = self.writeFile(subPath, val);
          } else {
            result = self.writeDir(subPath, val);
          }
          return result;
        });
        resolve(RSVP.all(promises));
      }
    });
  });
};

var JS_PATH = new RegExp(path.sep + '((map)|(reduce))$');
var SPECIAL_VALUES = new RegExp(path.sep + '_rev$');
var IGNORED_VALUES = new RegExp(path.sep + '_id$');
CouchDBVersioning.prototype.writeFile = function (filePath, data) {
  var elems;
  if (IGNORED_VALUES.test(filePath)) return false;
  if (SPECIAL_VALUES.test(filePath)) {
    elems = filePath.split(path.sep);
    return this.updateRev(elems[elems.length - 2], data)
  }
  return new RSVP.Promise(function (resolve, reject) {
    var extension = JS_PATH.test(filePath) ? '.js' : '.txt';
    fs.writeFile(filePath + extension, data, function (err, data) {
      if (err) reject(err);
      else resolve();
    });
  });
};

CouchDBVersioning.prototype.initExistingDesigns = function () {
  var self = this;
  return this.initConnection()
    .then(function () {
      return self.getExistingDesigns();
    }).then(function (existing) {
      return RSVP.all(Object.keys(existing).map(function (designName) {
        return self.writeDir(path.join(self.srcDir, '_design', designName), existing[designName]);
      }));
    }).catch(function (err) {
      console.trace('CouchDBVersionin: ERROR:', new Date(), err);
    });
};

module.exports = CouchDBVersioning;<commit_msg>* remove the nag. It prevents heroku from deploying<commit_after>'use strict';

var Tree2Json = require('broccoli-tree-to-json'),
  RSVP = require('rsvp'),
  path = require('path'),
  fs = require('fs'),
  nano = require('nano'),
  lodash = require('lodash'),
  mktemp = require('mktemp'),
  mkdirp = require('mkdirp');

/**
 *
 * Synchronize CouchDB design documents.
 * Options include
 *  * `url`: the couchdb url (http://host:123/db)
 *  * `username`: optional. used to authenticate with couchdb
 *  * `password`: required if username is present.
 *  * `initDesign`:optional. Set to true if the directory structure should be created from the existing database design documents
 *
 * @param inputTree {string|tree} the input tree to monitor
 * @param options {Object} couchdb connection options
 * @return {CouchDBVersioning}
 * @constructor
 * @alias module:index
 */
function CouchDBVersioning(inputTree, options) {
  if (!(this instanceof CouchDBVersioning)) return new CouchDBVersioning(inputTree, options);

  this.srcDir = inputTree;
  this.revDir = inputTree + '/.rev';
  this.options = options;
  this.inputTree = new Tree2Json(inputTree + '/_design');

  this.initPromise = this.init(options)
    .catch(function (err) {
      console.trace('CouchDB Init ERROR:', new Date(), err);
    });
}

CouchDBVersioning.prototype.init = function (options) {
  return RSVP.all([this.initDesign(options),
    this.initTmpDir(),
    this.initRevCache()])
    .catch(function (err) {
      console.log('CouchDB Versioning initialization error:', err);
    });
};

CouchDBVersioning.prototype.initDesign = function (options) {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    if (options.initDesign) {
      mkdirp(path.join(self.srcDir, '_design'), function (err, made) {
        if (err) reject(err);
        else resolve(self.initExistingDesigns());
      });
    } else resolve();
  });
};

CouchDBVersioning.prototype.initConnection = function () {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    var connection = nano(self.options.url);

    if (self.options.username) {
      connection.auth(self.options.username, self.options.password, function (err, body, headers) {
        if (err) reject(err);
        else {
          self.connection = nano({url: self.options.url, cookie: headers['set-cookie'][0]});
          resolve();
        }
      });
    } else {
      self.connection = connection;
      resolve(connection);
    }
  });
};

CouchDBVersioning.prototype.initTmpDir = function () {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    mktemp.createDir(path.join((process.env.TMPDIR || 'tmp'), 'XXXXXXXX.tmp'), function (err, path) {
      if (err) {
        console.warn('CouchDBVersioning WARN:', new Date(), 'Could not create temp dir');
        resolve();
      }
      else {
        self.tempDir = path;
        resolve(path)
      }
    });
  });
};

CouchDBVersioning.prototype.initRevCache = function () {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    mkdirp(self.revDir, function (err, made) {
      if (err) reject(err);
      else resolve();
    });
  });
};

function getFiles(destDir) {
  return new RSVP.Promise(function (resolve, reject) {
    fs.readdir(destDir, function (err, files) {
      if (err) reject(err);
      else resolve(files);
    });
  })
}

function readFile(dir, file) {
  return new RSVP.Promise(function (resolve, reject) {
    fs.readFile(path.join(dir, file), function (err, data) {
      if (err) reject(err);
      else resolve(JSON.parse(data.toString()));
    });
  });
}

function reportError(docName, date, localRev, serverRev, nag) {
  console.log(nag ? 'NAG:' : 'ERROR:', date, docName + '._rev Conflict: local is', localRev, 'server is', serverRev);
}

CouchDBVersioning.prototype.updateDesign = function (existingDesigns, design) {
  var self = this;
  return RSVP.all(Object.keys(design).map(function (key) {
    return new RSVP.Promise(function (resolve, reject) {
      var designDoc = design[key];
      var designName = '_design/' + key;
      var existing = existingDesigns[key] || {_id: designName};
      designDoc._id = existing._id;

      return self.getRev(key)
        .then(function (rev) {
          var docName;
          var serverRevNum = 0, localRevNum;
          if (existing._rev) {
            serverRevNum = parseInt(existing._rev.split('-')[0]);
          }
          localRevNum = parseInt(rev.split('-')[0]);

          /*
           NOTE - Messing with _revs is a really bad idea.
           But as a development tool this is a special case.
           Generally development revs will outpace production revs, so we're allowing
           updates when local revs are equal or greater
           */
          if (localRevNum >= serverRevNum) {
            //fake out the rev for the equality test and update
            designDoc._rev = existing._rev;
            if (!lodash.isEqual(designDoc, existing)) {
              return new RSVP.Promise(function (resolve, reject) {
                self.connection.insert(designDoc, designName, function (err, body) {
                  if (err)reject(err);
                  else {
                    resolve(self.updateRev(key, body.rev));
                  }
                });
              }).catch(function (err) {
                  reject(err);
                });
            }
          } else {
            docName = '_design/' + key;
            reportError(docName, new Date(), rev, existing._rev);
          }
        });
    });
  }));
};

CouchDBVersioning.prototype.getRev = function (key) {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    fs.readFile(path.join(self.revDir, key + '.txt'), function (err, data) {
      if (err) reject(err);
      else resolve(data.toString());
    });
  });
};

CouchDBVersioning.prototype.updateRev = function (key, rev) {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    var filePath = path.join(self.revDir, key + '.txt');
    fs.writeFile(filePath, rev, function (err, data) {
      if (err) {
        //HEROKU deploys won't update the rev (read only dirs), so this shouldn't be fatal
        console.warn('CouchDBVersioning WARN:', new Date(), 'could not update', filePath, '. :', err);
      }
      else resolve();
    });
  });
};

CouchDBVersioning.prototype.getExistingDesigns = function () {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    self.connection.get('_all_docs', {startkey: '_design', endkey: '_design0', include_docs: true},
      function (err, body) {
        var existing = {};
        if (err) reject(err);
        else {
          body.rows.forEach(function (row) {
            existing[row.id.split('/')[1]] = row.doc
          });
          resolve(existing);
        }
      });
  });
};

CouchDBVersioning.prototype.updateDocument = function (destDir, fileName) {
  var self = this;
  return readFile(destDir, fileName)
    .then(function (json) {
      if ('_design.json' === fileName) {
        return self.getExistingDesigns()
          .then(function (existing) {
            return self.updateDesign(existing, json);
          });
      }
    });
};

CouchDBVersioning.prototype.updateCouch = function (destDir) {
  var self = this;
  return getFiles(destDir)
    .then(function (files) {
      return RSVP.all(files.map(function (fileName) {
        return self.updateDocument(destDir, fileName);
      }));
    });
};

CouchDBVersioning.prototype.read = function (readTree) {
  var self = this;
  return this.initPromise
    .then(function () {
      return RSVP.all([self.initConnection(), readTree(self.inputTree)]);
    }).then(function (resolutions) {
      return self.updateCouch(resolutions[1]);
    }).then(function () {
      return self.tempDir;
    }).catch(function (err) {
      console.trace('CouchDBVersioning: ERROR:', new Date(), err);
      return self.tempDir;
    });
};

CouchDBVersioning.prototype.cleanup = function () {
  this.inputTree.cleanup();
  if (this.tempDir) fs.rmdirSync(this.tempDir);
};

CouchDBVersioning.prototype.writeDir = function (filePath, json) {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    mkdirp(filePath, function (err, made) {
      var promises;
      if (err) reject(err);
      else {
        promises = Object.keys(json).map(function (key) {
          var val = json[key];
          var subPath = path.join(filePath, key);
          var result;
          if (val instanceof Array || typeof val !== 'object') {
            result = self.writeFile(subPath, val);
          } else {
            result = self.writeDir(subPath, val);
          }
          return result;
        });
        resolve(RSVP.all(promises));
      }
    });
  });
};

var JS_PATH = new RegExp(path.sep + '((map)|(reduce))$');
var SPECIAL_VALUES = new RegExp(path.sep + '_rev$');
var IGNORED_VALUES = new RegExp(path.sep + '_id$');
CouchDBVersioning.prototype.writeFile = function (filePath, data) {
  var elems;
  if (IGNORED_VALUES.test(filePath)) return false;
  if (SPECIAL_VALUES.test(filePath)) {
    elems = filePath.split(path.sep);
    return this.updateRev(elems[elems.length - 2], data)
  }
  return new RSVP.Promise(function (resolve, reject) {
    var extension = JS_PATH.test(filePath) ? '.js' : '.txt';
    fs.writeFile(filePath + extension, data, function (err, data) {
      if (err) reject(err);
      else resolve();
    });
  });
};

CouchDBVersioning.prototype.initExistingDesigns = function () {
  var self = this;
  return this.initConnection()
    .then(function () {
      return self.getExistingDesigns();
    }).then(function (existing) {
      return RSVP.all(Object.keys(existing).map(function (designName) {
        return self.writeDir(path.join(self.srcDir, '_design', designName), existing[designName]);
      }));
    }).catch(function (err) {
      console.trace('CouchDBVersionin: ERROR:', new Date(), err);
    });
};

module.exports = CouchDBVersioning;<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';

/* system libs */
var moment = require('moment');

/* app libs */
var queue = require('../lib/queue');
var helpers = require('../lib/helpers')();

/* database models */
var Fanpage = require('../models/fanpage');
var User = require('../models/user');

/* constantes */
var timeout = 1;
var lastRun = 0;
var nextRun = moment().unix();

/* job tasks */

/* add page info to the queue */
var syncPageRatings = function(page, args) {
    var url = page.id + '/ratings';

    if (args) {
        args += '&';
    } else {
        args = '';
    }

    args += 'limit=25';
    args += '&access_token=' + page.access_token;

    queue.add(page, url, args, syncPageRatingsCallback, [ 'reviewer{id}', 'rating' ]);
}

/* parse page info callback response */
var syncPageRatingsCallback = function(page, ratings) {

    if (ratings.data) {
        for (var i = 0; i < ratings.data.length; i++) {
            var cur = ratings.data[i];

            Fanpage.update({ _id: page.id }, {
                /* page ratings */
                $addToSet: { ratings: { reviewer: cur.reviewer.id, rating: cur.rating } },

                /* job status */
                'jobs.page_ratings': Date.now()
            }, function(err) {
                if (err) {
                    throw 'Error updating output from sync page ratings: ' + err;
                }
            });
        }
    }

    /* queue next page */
    if (ratings.paging && ratings.paging.next && ratings.paging.cursors && ratings.paging.cursors.after) {
        syncPageRatings(page, 'after=' + ratings.paging.cursors.after);
    }
};

/* start syncing page contents */
var startSyncing = function (records, callback) {
    var i,
        cur;

    if (!callback) {
        throw 'No callback has been supplied for "startSyncing"';
    }

    for (i = 0; i < records.length; i += 1) {
        cur = records[i];

        User.findOne({ 'fanpages.id': cur._id }, { fanpages: { $elemMatch: { id: cur._id } } }, function (err, owner) {
            if (err) {
                throw err;
            }

            if (owner.fanpages.length === 1 && owner.fanpages[0].access_token) {
                syncPageRatings(owner.fanpages[0]);
            }
        });
    }
};

/* job interface */
var job = {

    /* job name */
    jobName: 'Page ratings',

    /* expose timeout */
    nextRun: function () {
        return nextRun;
    },

    /* check if job must be run */
    checkConditions: function (callback) {
        if (!callback) {
            throw 'No callback has been supplied for "checkConditions"!';
        }

        Fanpage.find({ $and: [ { 'billing.expiration': { $gt: new Date() } }, { 'error': { $exists: false } }, { 'jobs.new_site_created': { $exists: true, $ne: null }, $or: [ { 'jobs.update_profile_picture': { $exists: false } }, { 'jobs.update_profile_picture': { $lt: new Date((new Date()) - (1000 * 60 * 10)) } } ] } ] }, function (err, records) {
            if (err) {
                console.log('Database error: ' + err);
            } else {
                var status = (records && records.length !== 0);
                callback(job, status, records);
            }
        });
    },

    /* trigger job's work */
    doWork: function (records, callback) {
        nextRun = moment().unix() + timeout;
        startSyncing(records, callback);
    }

};

module.exports = job;<commit_msg>Corrigindo condição para execução do job de sincronização de page ratings.<commit_after>/*jslint node: true */
'use strict';

/* system libs */
var moment = require('moment');

/* app libs */
var queue = require('../lib/queue');
var helpers = require('../lib/helpers')();

/* database models */
var Fanpage = require('../models/fanpage');
var User = require('../models/user');

/* constantes */
var timeout = 1;
var lastRun = 0;
var nextRun = moment().unix();

/* job tasks */

/* add page info to the queue */
var syncPageRatings = function(page, args) {
    var url = page.id + '/ratings';

    if (args) {
        args += '&';
    } else {
        args = '';
    }

    args += 'limit=25';
    args += '&access_token=' + page.access_token;

    queue.add(page, url, args, syncPageRatingsCallback, [ 'reviewer{id}', 'rating' ]);
}

/* parse page info callback response */
var syncPageRatingsCallback = function(page, ratings) {

    if (ratings.data) {
        for (var i = 0; i < ratings.data.length; i++) {
            var cur = ratings.data[i];

            Fanpage.update({ _id: page.id }, {
                /* page ratings */
                $addToSet: { ratings: { reviewer: cur.reviewer.id, rating: cur.rating } },

                /* job status */
                'jobs.page_ratings': Date.now()
            }, function(err) {
                if (err) {
                    throw 'Error updating output from sync page ratings: ' + err;
                }
            });
        }
    }

    /* queue next page */
    if (ratings.paging && ratings.paging.next && ratings.paging.cursors && ratings.paging.cursors.after) {
        syncPageRatings(page, 'after=' + ratings.paging.cursors.after);
    }
};

/* start syncing page contents */
var startSyncing = function (records, callback) {
    var i,
        cur;

    if (!callback) {
        throw 'No callback has been supplied for "startSyncing"';
    }

    for (i = 0; i < records.length; i += 1) {
        cur = records[i];

        User.findOne({ 'fanpages.id': cur._id }, { fanpages: { $elemMatch: { id: cur._id } } }, function (err, owner) {
            if (err) {
                throw err;
            }

            if (owner.fanpages.length === 1 && owner.fanpages[0].access_token) {
                syncPageRatings(owner.fanpages[0]);
            }
        });
    }
};

/* job interface */
var job = {

    /* job name */
    jobName: 'Page ratings',

    /* expose timeout */
    nextRun: function () {
        return nextRun;
    },

    /* check if job must be run */
    checkConditions: function (callback) {
        if (!callback) {
            throw 'No callback has been supplied for "checkConditions"!';
        }

        Fanpage.find({ $and: [ { 'billing.expiration': { $gt: new Date() } }, { 'error': { $exists: false } }, { 'jobs.new_site_created': { $exists: true, $ne: null }, $or: [ { 'jobs.page_ratings': { $exists: false } }, { 'jobs.page_ratings': { $lt: new Date((new Date()) - (1000 * 60 * 10)) } } ] } ] }, function (err, records) {
            if (err) {
                console.log('Database error: ' + err);
            } else {
                var status = (records && records.length !== 0);
                callback(job, status, records);
            }
        });
    },

    /* trigger job's work */
    doWork: function (records, callback) {
        nextRun = moment().unix() + timeout;
        startSyncing(records, callback);
    }

};

module.exports = job;<|endoftext|>


<commit_before>'use strict';

const extend = require('xtend');
const choo = require('choo');
const html = require('choo/html');
const app = choo();

app.model({
  state: {
    todos: [],
  },
  reducers: {
    addTodo: (state, data) => {
      const todo = extend(data, {
        completed: false,
      });
      const newTodos = state.todos.slice();
      newTodos.push(data);
      return {
        todos: newTodos,
      };
  },
  },
});

const hTodoLi = (todo) => html`

    <input type="checkbox" ${todo.completed ? 'checked' : ''} />
    ${todo.title}

`;

const view = (state, prevState, send) => {
  const onTaskSubmition = (e) => {
    const userInput = e.target.children[0];
    send('addTodo', { title: userInput.value });
    userInput.value = '';
    e.preventDefault();
  };

  return html`

ChooDo

      <form onsubmit=${onTaskSubmition}>

        <input type="text" placeholder="Write your next task here..." id="title" autofocus>
      </form>

        ${state.todos.map(hTodoLi)}

`;
}

app.router([
  ['/', view],
]);

const tree = app.start();
document.body.appendChild(tree);
<commit_msg>Avoid task completion reseting completion status<commit_after>'use strict';

const extend = require('xtend');
const choo = require('choo');
const html = require('choo/html');
const app = choo();

app.model({
  state: {
    todos: [],
  },
  reducers: {
    addTodo: (state, data) => {
      const todo = extend(data, {
        completed: false,
      });
      const newTodos = state.todos.slice();
      newTodos.push(data);
      return {
        todos: newTodos,
      };
    },

    updateTodo: (state, data) => {
      const newTodos = state.todos.slice();
      const oldTask = newTodos[data.index];
      const newTask = extend(oldTask, data.update);
      newTodos[data.index] = newTask;
      return { todos : newTodos };
    },
  },
});

const view = (state, prevState, send) => {
  const onTaskSubmition = (e) => {
    const userInput = e.target.children[0];
    send('addTodo', { title: userInput.value });
    userInput.value = '';
    e.preventDefault();
  };

  const onTaskChecked = (e, index) => {
    const update = { completed: e.target.checked }
    send('updateTodo', { index: index, update: update })
  };

  const hTodoLi = (todo, index) => {
    const checked = todo.completed ? 'checked' : '';
    const onChange = (e) => onTaskChecked(e, index);

    return html`

        <input type="checkbox" ${ checked } onchange=${ onChange } />
        ${todo.title}

`;
  };

  return html`

ChooDo

      <form onsubmit=${ onTaskSubmition }>

        <input type="text" placeholder="Write your next task here..." id="title" autofocus>
      </form>

        ${state.todos.map(hTodoLi)}

`;
}

app.router([
  ['/', view],
]);

const tree = app.start();
document.body.appendChild(tree);
<|endoftext|>


<commit_before>var _ = require('lodash');
var async = require('async-chainable');
var asyncExec = require('async-chainable-exec');
var barcodeReader = require('quagga').default;
var events = require('events');
var fs = require('fs');
var temp = require('temp');
var pdfImage = require('pdf-image').PDFImage;
var rimraf = require('rimraf');
var pdftk = require('node-pdftk');
var util = require('util');

/**
 * PDFDicer functions that gives the all functionality.
 */
function PDFDicer(options) {
	var dicer = this;

	dicer.settings = _.defaults(options, {
		profile: 'quagga', // Default profile to use
		areas: [
			{ top: "0%", right: "0%", left: "0%", bottom: "0%" }
		],
		imageFormat: 'png',
		magickOptions: { // Options passed to ImageMagick when converting pdf -> page output format
			'-quality': 100,
			'-density': 150,
			'-background': 'white',
			'-alpha': 'remove',
			'-gaussian-blur': '0x1',
		},
		bardecode: {
			bin: '/opt/bardecoder/bin/bardecode',
			checkEvaluation: true,
			serial: '',
		},
		quagga: { // Options passed to Quagga
			numOfWorkers: 0, // Always 0 in Node backend
			locate: false, // We have to indicate the location of the barcode
			inputStream: {
				size: false, // Force full image resolution
			},
			decoder: {
				readers: ['code_128_reader'],
				multiple: false,
			},
		},
		filter: page => true,
		temp: {
			prefix: 'pdfdicer-',
		},
		tempClean: true,
		threads: {
			pages: 1,
			areas: 1,
		},
	});

	dicer.profile = name => {
		switch (name) {
			case 'quagga':
				_.merge(dicer.settings, {
					profile: 'quagga',
					driver: 'quagga',
					imageFormat: 'png',
				});
				break;
			case 'bardecode':
				_.merge(dicer.settings, {
					profile: 'bardecode',
					driver: 'bardecode',
					imageFormat: 'tif',
				});
				break;
			default:
				throw new Error(`Unknown profile: ${name}`);
		}

		return this;
	};

	/**
	* Convenience function to quickly set a setting
	* @param {string} key The key of the setting to set, dotted notation is supported
	* @param {*} value The value to set to
	* @return {Object} This chainable object
	*/
	dicer.set = (key, value) => {
		_.set(dicer.settings, key, value);
		return dicer;
	};

	/**
	* Shortcut function to set the areas used by the split function
	* @param {array} areas The areas array to set. Each option should have `top`, `right`, `left`, `bottom` which are either percentages or absolute values
	* @return {Object} This chainable object
	*/
	dicer.areas = areas => {
		_.merge(this.settings.areas, areas);
		return this;
	};

	/**
	 * Take an input file and split it into many PDF files based on configured options
	 * @param {string} input The input path to process (ends in .pdf usually)
	 * @param {Object} [options] Optional options which override the defaults
	 * @param {function} callback Callback function to fire on completion or error
	 * @return {PDFDicer} This chainable object
	 *
	 * @emits stage Fired at each stage of the process. ENUM: 'init', 'readPDF', 'readPages', 'extracted', 'filtering', 'loadRange', 'preSplit'
	 * @emits tempDir The temp dir used for storage
	 * @emits pageConverted  Fired with each page and pageOffset extracted as they are extracted
	 * @emits pagesConverted Fired with an array of all extracted page collection
	 * @emits pageAnalyze Fired before each page gets analyzed with the page object
	 * @emits pageAnalyzed Fired after each page has been analyzed with the page object
	 * @emits barcodeFiltered Fired when a specific barcode is filtered out of the input. Emitted as (page)
	 * @emits barcodePassed Fired when a barcode passes a filter test. Emitted as (page)
	 * @emits pagesAnalyzed Fired after all pages have been analyzed with the page collection
	 * @emits rangeExtracted Fired after the splitted range has been calculated from the original input pdf
	 * @emits split Fired after each pdf has been separated in the range and it gives you the pdf resultant
	 * @emits splitted Fired after pdf have been separated in the range
	 */
	dicer.split = function(input, options, callback) {
		// Argument mangling {{{
		if (_.isFunction(options)) { // Called as: input, callback
			callback = options;
			options = {};
		} else if (!_.isFunction(callback)) {
			throw new Error('Callback required as the final parameter of pdfDicer.convert()');
		}
		// }}}

		var settings = _.defaults({}, options, this.settings);

		async()
			// Sanity checks {{{
			.then(function(next) {
				dicer.emit('stage', 'init');
				if (!_.isString(input)) return next('Unknown input type');
				next();
			})
			// }}}
			// Check file exists {{{
			.then(function(next) {
				fs.access(input, err => next(err ? 'File not found' : null));
			})
			// }}}
			// Prepare (temp directory) {{{
			.then('tempDir', function(next) {
				temp.mkdir(settings.temp, next);
			})
			// }}}
			// Build the PDF processing instance {{{
			// More information about image processing on https://www.imagemagick.org/script/command-line-options.php
			.then('pdf', function(next) {
				dicer.emit('tempDir', this.tempDir);
				next(null, new pdfImage(input, {
					outputDirectory: this.tempDir,
					convertOptions: settings.magickOptions,
				}));
			})
			// }}}
			// Set output image format {{{
			.then(function(next) {
				this.pdf.setConvertExtension(settings.imageFormat);
				next();
			})
			// }}}
			// Extract info about the input file {{{
			.then('info', function(next) {
				dicer.emit('stage', 'readPDF');
				this.pdf.getInfo()
					.catch(e => next(e))
					.then(data => next(null, data), next)
			})
			// }}}
			// Convert the file into images {{{
			.set('pages', {})
			.then(function(next) {
				dicer.emit('stage', 'readPages');
				async()
					.set('pdf', this.pdf)
					.set('pages', this.pages)
					.forEach(0, parseInt(this.info.Pages) - 1, function(next, pageNumber) {
						this.pdf.convertPage(pageNumber)
							.then(path => {
								this.pages[pageNumber] = {
									path: path,
								},
								dicer.emit('pageConverted', this.pages[pageNumber], pageNumber);
								next();
							})
							.catch(next)
					})
					.end(next);
			})
			// }}}
			// Post conversion emitters {{{
			.then(function(next) {
				dicer.emit('pagesConverted', this.pages);
				dicer.emit('stage', 'extracted');
				next();
			})
			// }}}
			// Read each page and extract a barcode if there is one {{{
			.limit(settings.threads.pages)
			.forEach('pages', function(nextPage, page, pageOffset) {
				page.number = parseInt(pageOffset) + 1;
				page.barcode = false;
				dicer.emit('pageAnalyze', page);
				if (settings.driver == 'quagga') {
					async()
						.limit(settings.threads.areas)
						.forEach(settings.areas, function(nextArea, area) {
							var hasAreas = Object.values(area).filter(a => a === '0%').length !== 4;
							var options = {
								src: page.path
							};
							options.locate = hasAreas;
							if (hasAreas) {
								options.inputStream = {
									area: area,
								};
							}

							barcodeReader.decodeSingle(Object.assign({}, settings.quagga, options), function(res) {
								if (!page.barcode && res && res.codeResult) page.barcode = res.codeResult.code;
								nextArea();
							});
						})
						.then(function(next) {
							dicer.emit('pageAnalyzed', page);
							next();
						})
						.end(nextPage);
				} else if (settings.driver == 'bardecode') {
					var runCommand = [
						settings.bardecode.bin,
						page.path,
					];
					if (settings.bardecode.serial) runCommand.push('-K', settings.bardecode.serial); // Append serial number if we have one

					async()
						.use(asyncExec)
						.exec('response', runCommand)
						.then('response', function(next) {
							var firstExtracted = _(this.response)
								.filter(i => ! /^EVALUATION MODE/.test(i))
								.first();

							if (firstExtracted) page.barcode = firstExtracted;

							if (settings.bardecode.checkEvaluation && /\?\?\?$/.test(page.barcode)) console.warn('You are using an evaluation version of Bardecode - the last three digits of the barcode are obscured!');

							next();
						})
						.then(function(next) {
							dicer.emit('pageAnalyzed', page);
							next();
						})
						.end(nextPage);
				} else {
					throw new Error(`Unknown page decoder: ${settings.driver}`);
				}
			})
			// }}}
			// Filter page barcodes {{{
			.then(function(next) {
				dicer.emit('stage', 'filtering');
				if (!_.isFunction(settings.filter)) return next();

				_.forEach(this.pages, page => {
					var res = settings.filter(page);
					if (!res) {
						dicer.emit('barcodeFiltered', page);
						page.barcode = false;
					} else {
						dicer.emit('barcodePassed', page);
					}
				});
				next();
			})
			// }}}
			// Post pages analyzed emitters {{{
			.then(function(next) {
				dicer.emit('pagesAnalyzed', this.pages);
				next();
			})
			// }}}
			// Build range to split the pdf {{{
			.set('range', new Object())
			.then(function(next) {
				dicer.emit('stage', 'loadRange');
				var memBarcodeID = '';
				var rangeCount = 1;
				var index = 0;

				try {
					for (var key in this.pages) {
						if (this.pages.hasOwnProperty(key)) {
							var page = this.pages[key];
							memBarcodeID = (page.barcode === false) ? memBarcodeID : page.barcode.split('-')[0];

							if (this.range[memBarcodeID] == null) {
								this.range[memBarcodeID] = new Object();
								this.range[memBarcodeID].barcode = new Object();
								try {
									this.range[memBarcodeID].barcode.id = page.barcode.substring(page.barcode.lastIndexOf("/") + 1, page.barcode.length);
								} catch (error) {
									// The barcode scanner is not able to find the barcode information.
									this.range[memBarcodeID].barcode.id = page.barcode;
								}
								this.range[memBarcodeID].barcode.start = page.barcode;
								this.range[memBarcodeID].pages = 1;
								this.range[memBarcodeID].from = index + 1;
							} else {
								this.range[memBarcodeID].pages++;
								if (page.barcode !== false)
									this.range[memBarcodeID].barcode.end = page.barcode;
							}
						}
						index++;
					}
				} catch (error) {
					console.error('[PDF-DICER] Error', error);
					return next(error);
				}

				next();
			})
			// }}}
			// Emits the data with the range to split the pdf {{{
			.then(function(next) {
				dicer.emit('rangeExtracted', this.range);
				next();
			})
			// }}}
			// Update stage {{{
			.then(function(next) {
				dicer.emit('stage', 'preSplit');
				next();
			})
			// }}}
			// Gives the resultant split pdfs {{{
			.forEach('range', function(nextRange, range, rangeIndex) {
				range.to = range.from + range.pages - 1;

				pdftk
					.input(input)
					.cat(`${range.from}-${range.to}`)
					.output()
					.then(buffer => {
						dicer.emit('split', range, buffer);
						nextRange();
					})
					.catch(nextRange);
			})
			// }}}
			// Emits the end signal for the functionality {{{
			.then(function(next) {
				dicer.emit('splitted');
				next();
			})
			// }}}
			// Clean up the temp directory {{{
			.then(function(next) {
				if (!settings.tempClean) return next();
				rimraf(this.tempDir, next);
			})
			// }}}
			.end(callback);

		return this;
	};

	dicer.profile(dicer.settings.profile); // Load default profile
};

util.inherits(PDFDicer, events.EventEmitter);

module.exports = PDFDicer;
<commit_msg>Extra debug config for Quagga<commit_after>var _ = require('lodash');
var async = require('async-chainable');
var asyncExec = require('async-chainable-exec');
var barcodeReader = require('quagga').default;
var events = require('events');
var fs = require('fs');
var temp = require('temp');
var pdfImage = require('pdf-image').PDFImage;
var rimraf = require('rimraf');
var pdftk = require('node-pdftk');
var util = require('util');

/**
 * PDFDicer functions that gives the all functionality.
 */
function PDFDicer(options) {
	var dicer = this;

	dicer.settings = _.defaults(options, {
		profile: 'quagga', // Default profile to use
		areas: [
			{ top: "0%", right: "0%", left: "0%", bottom: "0%" }
		],
		imageFormat: 'png',
		magickOptions: { // Options passed to ImageMagick when converting pdf -> page output format
			'-quality': 100,
			'-density': 150,
			'-background': 'white',
			'-alpha': 'remove',
			'-gaussian-blur': '0x1',
		},
		bardecode: {
			bin: '/opt/bardecoder/bin/bardecode',
			checkEvaluation: true,
			serial: '',
		},
		quagga: { // Options passed to Quagga
			numOfWorkers: 0, // Always 0 in Node backend
			locate: false, // We have to indicate the location of the barcode
			inputStream: {
				size: false, // Force full image resolution
			},
			decoder: {
				readers: ['code_128_reader'],
				multiple: false,
				debug: {
					drawBoundingBox: true,
					showFrequency: true,
					drawScanline: true,
					showPattern: true
				}
			},
			locator: {
				debug: {
					showCanvas: true,
					showPatches: true,
					showFoundPatches: true,
					showSkeleton: true,
					showLabels: true,
					showPatchLabels: true,
					showRemainingPatchLabels: true,
					boxFromPatches: {
						showTransformed: true,
						showTransformedBox: true,
						showBB: true
					}
				},
				halfSample: true,
				patchSize: "medium" // x-small, small, medium, large, x-large
			}
		},
		filter: page => true,
		temp: {
			prefix: 'pdfdicer-',
		},
		tempClean: true,
		threads: {
			pages: 1,
			areas: 1,
		},
	});

	dicer.profile = name => {
		switch (name) {
			case 'quagga':
				_.merge(dicer.settings, {
					profile: 'quagga',
					driver: 'quagga',
					imageFormat: 'png',
				});
				break;
			case 'bardecode':
				_.merge(dicer.settings, {
					profile: 'bardecode',
					driver: 'bardecode',
					imageFormat: 'tif',
				});
				break;
			default:
				throw new Error(`Unknown profile: ${name}`);
		}

		return this;
	};

	/**
	* Convenience function to quickly set a setting
	* @param {string} key The key of the setting to set, dotted notation is supported
	* @param {*} value The value to set to
	* @return {Object} This chainable object
	*/
	dicer.set = (key, value) => {
		_.set(dicer.settings, key, value);
		return dicer;
	};

	/**
	* Shortcut function to set the areas used by the split function
	* @param {array} areas The areas array to set. Each option should have `top`, `right`, `left`, `bottom` which are either percentages or absolute values
	* @return {Object} This chainable object
	*/
	dicer.areas = areas => {
		_.merge(this.settings.areas, areas);
		return this;
	};

	/**
	 * Take an input file and split it into many PDF files based on configured options
	 * @param {string} input The input path to process (ends in .pdf usually)
	 * @param {Object} [options] Optional options which override the defaults
	 * @param {function} callback Callback function to fire on completion or error
	 * @return {PDFDicer} This chainable object
	 *
	 * @emits stage Fired at each stage of the process. ENUM: 'init', 'readPDF', 'readPages', 'extracted', 'filtering', 'loadRange', 'preSplit'
	 * @emits tempDir The temp dir used for storage
	 * @emits pageConverted  Fired with each page and pageOffset extracted as they are extracted
	 * @emits pagesConverted Fired with an array of all extracted page collection
	 * @emits pageAnalyze Fired before each page gets analyzed with the page object
	 * @emits pageAnalyzed Fired after each page has been analyzed with the page object
	 * @emits barcodeFiltered Fired when a specific barcode is filtered out of the input. Emitted as (page)
	 * @emits barcodePassed Fired when a barcode passes a filter test. Emitted as (page)
	 * @emits pagesAnalyzed Fired after all pages have been analyzed with the page collection
	 * @emits rangeExtracted Fired after the splitted range has been calculated from the original input pdf
	 * @emits split Fired after each pdf has been separated in the range and it gives you the pdf resultant
	 * @emits splitted Fired after pdf have been separated in the range
	 */
	dicer.split = function(input, options, callback) {
		// Argument mangling {{{
		if (_.isFunction(options)) { // Called as: input, callback
			callback = options;
			options = {};
		} else if (!_.isFunction(callback)) {
			throw new Error('Callback required as the final parameter of pdfDicer.convert()');
		}
		// }}}

		var settings = _.defaults({}, options, this.settings);

		async()
			// Sanity checks {{{
			.then(function(next) {
				dicer.emit('stage', 'init');
				if (!_.isString(input)) return next('Unknown input type');
				next();
			})
			// }}}
			// Check file exists {{{
			.then(function(next) {
				fs.access(input, err => next(err ? 'File not found' : null));
			})
			// }}}
			// Prepare (temp directory) {{{
			.then('tempDir', function(next) {
				temp.mkdir(settings.temp, next);
			})
			// }}}
			// Build the PDF processing instance {{{
			// More information about image processing on https://www.imagemagick.org/script/command-line-options.php
			.then('pdf', function(next) {
				dicer.emit('tempDir', this.tempDir);
				next(null, new pdfImage(input, {
					outputDirectory: this.tempDir,
					convertOptions: settings.magickOptions,
				}));
			})
			// }}}
			// Set output image format {{{
			.then(function(next) {
				this.pdf.setConvertExtension(settings.imageFormat);
				next();
			})
			// }}}
			// Extract info about the input file {{{
			.then('info', function(next) {
				dicer.emit('stage', 'readPDF');
				this.pdf.getInfo()
					.catch(e => next(e))
					.then(data => next(null, data), next)
			})
			// }}}
			// Convert the file into images {{{
			.set('pages', {})
			.then(function(next) {
				dicer.emit('stage', 'readPages');
				async()
					.set('pdf', this.pdf)
					.set('pages', this.pages)
					.forEach(0, parseInt(this.info.Pages) - 1, function(next, pageNumber) {
						this.pdf.convertPage(pageNumber)
							.then(path => {
								this.pages[pageNumber] = {
									path: path,
								},
								dicer.emit('pageConverted', this.pages[pageNumber], pageNumber);
								next();
							})
							.catch(next)
					})
					.end(next);
			})
			// }}}
			// Post conversion emitters {{{
			.then(function(next) {
				dicer.emit('pagesConverted', this.pages);
				dicer.emit('stage', 'extracted');
				next();
			})
			// }}}
			// Read each page and extract a barcode if there is one {{{
			.limit(settings.threads.pages)
			.forEach('pages', function(nextPage, page, pageOffset) {
				page.number = parseInt(pageOffset) + 1;
				page.barcode = false;
				dicer.emit('pageAnalyze', page);
				if (settings.driver == 'quagga') {
					async()
						.limit(settings.threads.areas)
						.forEach(settings.areas, function(nextArea, area) {
							var hasAreas = Object.values(area).filter(a => a === '0%').length !== 4;
							var options = {
								src: page.path
							};
							options.locate = hasAreas;
							if (hasAreas) {
								options.inputStream = {
									area: area,
								};
							}

							barcodeReader.decodeSingle(Object.assign({}, settings.quagga, options), function(res) {
								if (!page.barcode && res && res.codeResult) page.barcode = res.codeResult.code;
								nextArea();
							});
						})
						.then(function(next) {
							dicer.emit('pageAnalyzed', page);
							next();
						})
						.end(nextPage);
				} else if (settings.driver == 'bardecode') {
					var runCommand = [
						settings.bardecode.bin,
						page.path,
					];
					if (settings.bardecode.serial) runCommand.push('-K', settings.bardecode.serial); // Append serial number if we have one

					async()
						.use(asyncExec)
						.exec('response', runCommand)
						.then('response', function(next) {
							var firstExtracted = _(this.response)
								.filter(i => ! /^EVALUATION MODE/.test(i))
								.first();

							if (firstExtracted) page.barcode = firstExtracted;

							if (settings.bardecode.checkEvaluation && /\?\?\?$/.test(page.barcode)) console.warn('You are using an evaluation version of Bardecode - the last three digits of the barcode are obscured!');

							next();
						})
						.then(function(next) {
							dicer.emit('pageAnalyzed', page);
							next();
						})
						.end(nextPage);
				} else {
					throw new Error(`Unknown page decoder: ${settings.driver}`);
				}
			})
			// }}}
			// Filter page barcodes {{{
			.then(function(next) {
				dicer.emit('stage', 'filtering');
				if (!_.isFunction(settings.filter)) return next();

				_.forEach(this.pages, page => {
					var res = settings.filter(page);
					if (!res) {
						dicer.emit('barcodeFiltered', page);
						page.barcode = false;
					} else {
						dicer.emit('barcodePassed', page);
					}
				});
				next();
			})
			// }}}
			// Post pages analyzed emitters {{{
			.then(function(next) {
				dicer.emit('pagesAnalyzed', this.pages);
				next();
			})
			// }}}
			// Build range to split the pdf {{{
			.set('range', new Object())
			.then(function(next) {
				dicer.emit('stage', 'loadRange');
				var memBarcodeID = '';
				var rangeCount = 1;
				var index = 0;

				try {
					for (var key in this.pages) {
						if (this.pages.hasOwnProperty(key)) {
							var page = this.pages[key];
							memBarcodeID = (page.barcode === false) ? memBarcodeID : page.barcode.split('-')[0];

							if (this.range[memBarcodeID] == null) {
								this.range[memBarcodeID] = new Object();
								this.range[memBarcodeID].barcode = new Object();
								try {
									this.range[memBarcodeID].barcode.id = page.barcode.substring(page.barcode.lastIndexOf("/") + 1, page.barcode.length);
								} catch (error) {
									// The barcode scanner is not able to find the barcode information.
									this.range[memBarcodeID].barcode.id = page.barcode;
								}
								this.range[memBarcodeID].barcode.start = page.barcode;
								this.range[memBarcodeID].pages = 1;
								this.range[memBarcodeID].from = index + 1;
							} else {
								this.range[memBarcodeID].pages++;
								if (page.barcode !== false)
									this.range[memBarcodeID].barcode.end = page.barcode;
							}
						}
						index++;
					}
				} catch (error) {
					console.error('[PDF-DICER] Error', error);
					return next(error);
				}

				next();
			})
			// }}}
			// Emits the data with the range to split the pdf {{{
			.then(function(next) {
				dicer.emit('rangeExtracted', this.range);
				next();
			})
			// }}}
			// Update stage {{{
			.then(function(next) {
				dicer.emit('stage', 'preSplit');
				next();
			})
			// }}}
			// Gives the resultant split pdfs {{{
			.forEach('range', function(nextRange, range, rangeIndex) {
				range.to = range.from + range.pages - 1;

				pdftk
					.input(input)
					.cat(`${range.from}-${range.to}`)
					.output()
					.then(buffer => {
						dicer.emit('split', range, buffer);
						nextRange();
					})
					.catch(nextRange);
			})
			// }}}
			// Emits the end signal for the functionality {{{
			.then(function(next) {
				dicer.emit('splitted');
				next();
			})
			// }}}
			// Clean up the temp directory {{{
			.then(function(next) {
				if (!settings.tempClean) return next();
				rimraf(this.tempDir, next);
			})
			// }}}
			.end(callback);

		return this;
	};

	dicer.profile(dicer.settings.profile); // Load default profile
};

util.inherits(PDFDicer, events.EventEmitter);

module.exports = PDFDicer;
<|endoftext|>


<commit_before>/**
 * Created by Jayant Bhawal on 19-03-2016.
 */
var express = require('express');
var app = express();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
var compression = require('compression');
var dummyjson = require('dummy-json');
var Firebase = require("firebase");
var moment = require('moment');

var firebaseRef = new Firebase("https://harpoon.firebaseio.com/");

var randomInt = function(min, max) {
	min = (typeof(min) == "number")?min:parseInt(min);
	max = (typeof(max) == "number")?max:parseInt(max);
	return Math.floor(Math.random() * (max - min)) + min;
};

var parseMoment = function (str) {
	switch (str){
		case 'now':	return moment().format('X'); break;
		case 'tomorrow':	return moment().add(1,'d').format('X'); break;
		case 'yesterday':	return moment().subtract(1,'d').format('X'); break;
		default:
			str = str.replace(/(\\"|\\')/g, function (v) {
				return v.replace("\\","");
			});
			return eval(str);
	}
};
var customHelpers = {
	random: function () {
		var args = Array.prototype.slice.call(arguments);
		args.pop();
		if(args && args.length && Array.isArray(args)){
			return args[Math.floor(Math.random()*args.length)];
		}
		else{
			return 0;
		}
	},
	momentstr: function () {
		var args = Array.prototype.slice.call(arguments);
		args.pop();
		if(args && args.length && Array.isArray(args)){
			var dateStr = "";
			args.forEach(function (arg, i) {
				if(dateStr.length){
					dateStr += " ";
				}
				dateStr += parseMoment(arg);
			});
			return dateStr;
		}
		else{
			return moment().format('X');
		}
	},
	moment: function () {
		var args = Array.prototype.slice.call(arguments);
		args.pop();
		if(args && args.length && args.length < 3 && Array.isArray(args)){
			var dateStr = "";
			if(args.length == 1){
				dateStr += parseMoment(args[0]);
			}
			else if(args.length == 2){
				dateStr += randomInt(parseMoment(args[0]),parseMoment(args[1]));
			}
			return dateStr;
		}
		else{
			return moment().format('X');
		}
	},
	eval: function () {
		var args = Array.prototype.slice.call(arguments);
		args.pop();
		if(args && args.length && args.length < 3 && Array.isArray(args)){
			var evalStr = "";
			args.forEach(function (arg, i) {
				if(evalStr.length){
					evalStr += " ";
				}
				arg = arg.replace(/(\\"|\\')/g, function (v) {
					return v.replace("\\","");
				});
				evalStr += eval(arg);
			});
			return evalStr;
		}
		else{
			return "nothing to eval";
		}
	},
	objectId: function () {
		var ID = (Math.random().toString(16)).substr(2,8);
		ID += (Math.random().toString(16)).substr(2,8);
		ID += (Math.random().toString(16)).substr(2,8);		//24 characters
		ID += (Math.random().toString(16)).substr(2,24 - ID.length);
		return ID;
	},
	avatar: function () {
		var imageNumber = Math.round(Math.random()*96)
		var men = "//randomuser.me/api/portraits/men/"+imageNumber+".jpg";
		var women = "//randomuser.me/api/portraits/women/"+imageNumber+".jpg";
		if(typeof arguments[0] == "string"){
			switch(arguments[0]){
				case "male": avatar = men; break;
				case "female": avatar = women; break;
				//No default
			}
		}
		else{
			var avatar = (Math.round(Math.random()))?men:women;
		}
		return avatar;
	}
	//TODO: Make a `this` helper.
};

var port = process.env.PORT || 8080;

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  // res.header("Access-Control-Allow-Headers", "*");
  next();
});

app.use(compression({level: 6}));	//6 is default
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(__dirname + '/app'));
app.use(express.static(__dirname));

app.get("/", function (req, res) {
	res.sendFile(__dirname + "/app/index.html");
});
app.get("/:title", function (req, res) {
	var token = req.get('X-Auth-Token');
	if(token){
		var path = "users/"+token+"/templates/"+req.params.title+"/code";
		firebaseRef.child(path).once("value", function (snap) {
			var data = snap.val();
			if(data){
				data = dummyjson.parse(data,{helpers: customHelpers});
				res.send(data);
			}
			else{
				res.send("{}");
			}
		});
	}
	else{
		res.status(403).send("Missing required header.");
	}
});
app.post("/generate", function (req, res) {
	var data = dummyjson.parse(req.body.template,{helpers: customHelpers});
	res.send(data);
});

http.listen(port, "0.0.0.0", function () {
	console.log('Harpoon server running on localhost:' + port);
});
<commit_msg>Minor changes.<commit_after>/**
 * Created by Jayant Bhawal on 19-03-2016.
 */
var express = require('express');
var app = express();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
var compression = require('compression');
var dummyjson = require('dummy-json');
var Firebase = require("firebase");
var moment = require('moment');

var firebaseRef = new Firebase("https://harpoon.firebaseio.com/");

var randomInt = function (min, max) {
	min = (typeof(min) == "number") ? min : parseInt(min);
	max = (typeof(max) == "number") ? max : parseInt(max);
	return Math.floor(Math.random() * (max - min)) + min;
};

var parseMoment = function (str) {
	switch (str) {
		case 'now':
			return moment().format('X');
			break;
		case 'tomorrow':
			return moment().add(1, 'd').format('X');
			break;
		case 'yesterday':
			return moment().subtract(1, 'd').format('X');
			break;
		default:
			str = str.replace(/(\\"|\\')/g, function (v) {
				return v.replace("\\", "");
			});
			return eval(str);
	}
};
var customHelpers = {
	random: function () {
		var args = Array.prototype.slice.call(arguments);
		args.pop();
		if (args && args.length && Array.isArray(args)) {
			return args[Math.floor(Math.random() * args.length)];
		}
		else {
			return 0;
		}
	},
	momentstr: function () {
		var args = Array.prototype.slice.call(arguments);
		args.pop();
		if (args && args.length && Array.isArray(args)) {
			var dateStr = "";
			args.forEach(function (arg, i) {
				if (dateStr.length) {
					dateStr += " ";
				}
				dateStr += parseMoment(arg);
			});
			return dateStr;
		}
		else {
			return moment().format('X');
		}
	},
	moment: function () {
		var args = Array.prototype.slice.call(arguments);
		args.pop();
		if (args && args.length && args.length < 3 && Array.isArray(args)) {
			var dateStr = "";
			if (args.length == 1) {
				dateStr += parseMoment(args[0]);
			}
			else if (args.length == 2) {
				dateStr += randomInt(parseMoment(args[0]), parseMoment(args[1]));
			}
			return dateStr;
		}
		else {
			return moment().format('X');
		}
	},
	eval: function () {
		var args = Array.prototype.slice.call(arguments);
		args.pop();
		if (args && args.length && args.length < 3 && Array.isArray(args)) {
			var evalStr = "";
			args.forEach(function (arg, i) {
				if (evalStr.length) {
					evalStr += " ";
				}
				arg = arg.replace(/(\\"|\\')/g, function (v) {
					return v.replace("\\", "");
				});
				evalStr += eval(arg);
			});
			return evalStr;
		}
		else {
			return "nothing to eval";
		}
	},
	objectId: function () {
		var ID = (Math.random().toString(16)).substr(2, 8);
		ID += (Math.random().toString(16)).substr(2, 8);
		ID += (Math.random().toString(16)).substr(2, 8);		//24 characters
		ID += (Math.random().toString(16)).substr(2, 24 - ID.length);
		return ID;
	},
	avatar: function () {
		var imageNumber = Math.round(Math.random() * 96)
		var men = "//randomuser.me/api/portraits/men/" + imageNumber + ".jpg";
		var women = "//randomuser.me/api/portraits/women/" + imageNumber + ".jpg";
		if (typeof arguments[0] == "string") {
			switch (arguments[0]) {
				case "male":
					avatar = men;
					break;
				case "female":
					avatar = women;
					break;
				//No default
			}
		}
		else {
			var avatar = (Math.round(Math.random())) ? men : women;
		}
		return avatar;
	}
	//TODO: Make a `this` helper.
};

var port = process.env.PORT || 8080;

app.use(function (req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", Object.keys(req.headers).join(","));
	console.log("H> ", Object.keys(req.headers).join(","));
	next();
});

app.use(compression({level: 6}));	//6 is default
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(__dirname + '/app'));
app.use(express.static(__dirname));

app.get("/", function (req, res) {
	res.sendFile(__dirname + "/app/index.html");
});
app.get("/:title", function (req, res) {
	var token = req.get('X-Auth-Token');
	if (token) {
		var path = "users/" + token + "/templates/" + req.params.title + "/code";
		firebaseRef.child(path).once("value", function (snap) {
			var data = snap.val();
			if (data) {
				data = dummyjson.parse(data, {helpers: customHelpers});
				res.send(data);
			}
			else {
				res.send("{}");
			}
		});
	}
	else {
		res.status(403).send("Missing required header.");
	}
});
app.post("/generate", function (req, res) {
	var data = dummyjson.parse(req.body.template, {helpers: customHelpers});
	res.send(data);
});

http.listen(port, "0.0.0.0", function () {
	console.log('Harpoon server running on localhost:' + port);
});
<|endoftext|>


<commit_before>module.exports = require('./lib/authn');<commit_msg>Correcting path<commit_after>module.exports = require('./lib/authz');
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const spawn = require('cross-spawn');
const script = process.argv[2];
const args = process.argv.slice(3);
const path = require('path');

switch (script) {
    case 'start':
    case 'test':
    case 'build':
    case 'eject':
        const result = spawn.sync(
            'node',
            [require.resolve('./scripts/' + script)].concat(args),
            { stdio: 'inherit' }
        );
        process.exit(result.status);
        break;
    default:
        console.log('Unknown script "' + script + '".');
        console.log('Perhaps you need to upgrade cycle-scripts?');
        break;
}
<commit_msg>Readd clean script<commit_after>#!/usr/bin/env node
'use strict';

const spawn = require('cross-spawn');
const script = process.argv[2];
const args = process.argv.slice(3);
const path = require('path');
const rimraf = require('rimraf');

const appPath = (...paths) => path.join(process.cwd(), ...paths);

switch (script) {
    case 'clean':
        rimraf.sync(appPath('.nyc_output'));
        rimraf.sync(appPath('build'));
        rimraf.sync(appPath('coverage'));
        break;
    case 'start':
    case 'test':
    case 'build':
    case 'eject':
        const result = spawn.sync(
            'node',
            [require.resolve('./scripts/' + script)].concat(args),
            { stdio: 'inherit' }
        );
        process.exit(result.status);
        break;
    default:
        console.log('Unknown script "' + script + '".');
        console.log('Perhaps you need to upgrade cycle-scripts?');
        break;
}
<|endoftext|>


<commit_before>var Promise = require('iou').Promise;

require('coffee-script').register();

var HTTP = require('http')
  , URL = require('url')

  , YARGS = require('yargs')
  , PATH = require('filepath')
  , REQUEST = require('request')

  , LIB = require('./lib')

exports.main = function () {
  var opts = parse_options()
    , argv = opts.argv
    , run_opts = Object.create(null)

  if (argv.help) {
    console.log(opts.help())
    process.exit(1);
  }

  run_opts.connection_uri = argv.serve;
  run_opts.target_uri = argv.target;
  run_opts.config_path = argv.config;

  exports.run(run_opts).then(print_output).catch(die);
};

// opts.connection_uri - The URI String of the dev_proxy server.
// opts.target_uri - The URI String of the target server.
// opts.config_path - The path String of the configuration file.
// callback - Callback Function is optional.
exports.run = function (opts, callback) {
  var state = Object.create(null)

  if (opts.config_path) {
    state.config_path =  PATH.newPath(opts.config_path);
  } else {
    state.config_path = PATH.newPath(__dirname).append('examples', 'rails');
  }

  state.connection_uri = opts.connection_uri;
  state.target_uri = opts.target_uri;

  function on_success(state) {
    if (typeof callback === 'function') {
      callback(null, state);
    }
    return state;
  }

  function on_error(err) {
    if (typeof callback === 'function') {
      callback(err);
    } else {
      return Promise.reject(err);
    }
  }

  var promise = Promise.resolve(state)
    .then(LIB.middleware.config_reader)
    .then(LIB.middleware.file_watcher)
    .then(LIB.middleware.path_matcher)
    .then(LIB.middleware.http_server)
    .then(on_success)
    .catch(on_error);

  return promise;
};

function parse_options() {
  return YARGS.usage('Run a little server that proxies to another server.')
    .alias('t', 'target')
    .describe('t', 'Target URI like "http://localhost:3000"')
    .alias('s', 'serve')
    .describe('s', 'Server URI like "http://192.168.1.102:8080"')
    .default('s', 'http://localhost:8080')
    .alias('c', 'config')
    .describe('c', 'Configuraiton file path')
    .alias('h', 'help')
    .describe('h', "Print this help text.")
}

function print_output(state) {
  console.log('STATE', state);
  console.log('Listening for connections on '+ state.hostname +':'+ state.port +' '+ state.family);
  console.log('Proxying requests to '+ state.target_uri);
  console.log('Press CTRL+c to stop.');
}

function die(err) {
  console.error(err.stack);
  process.exit(2);
}

/*
function create_proxy(target) {
  return function (req, res) {
    var buffer = LIB.cache_service.cache(req)
    req.pipe(REQUEST(target + req.url)).pipe(buffer).pipe(res);
  };
}
*/
<commit_msg>Better argument and error handling in main.<commit_after>var Promise = require('iou').Promise;

require('coffee-script').register();

var HTTP = require('http')
  , URL = require('url')

  , YARGS = require('yargs')
  , PATH = require('filepath')
  , REQUEST = require('request')

  , LIB = require('./lib')

exports.main = function () {
  var opts = parse_options()
    , argv = opts.argv
    , run_opts = Object.create(null)

  if (argv.help) {
    console.log(opts.help())
    process.exit(1);
  }

  run_opts.serve_uri = argv.serve;
  run_opts.target_uri = argv.target;
  run_opts.config_path = argv.config;

  exports.run(run_opts).then(print_output).catch(die);
};

// opts.serve_uri - The URI String of the dev_proxy server.
// opts.target_uri - The URI String of the target server.
// opts.config_path - The path String of the configuration file.
// callback - Callback Function is optional.
exports.run = function (opts, callback) {
  var state = Object.create(null)

  if (!opts.config_path) {
    throw new Error("You need to provide a config path.")
  }
  if (!opts.target_uri) {
    throw new Error("You need to provide a target uri.")
  }
  if (!opts.serve_uri) {
    throw new Error("You need to provide a serve uri.")
  }

  state.config_path =  PATH.newPath(opts.config_path);
  state.serve_uri = opts.serve_uri;
  state.target_uri = opts.target_uri;

  function on_success(state) {
    if (typeof callback === 'function') {
      callback(null, state);
    }
    return state;
  }

  function on_error(err) {
    if (typeof callback === 'function') {
      callback(err);
    } else {
      return Promise.reject(err);
    }
  }

  var promise = Promise.resolve(state)
    .then(LIB.middleware.config_reader)
    .then(LIB.middleware.file_watcher)
    .then(LIB.middleware.path_matcher)
    .then(LIB.middleware.http_server)
    .then(on_success)
    .catch(on_error);

  return promise;
};

function parse_options() {
  return YARGS.usage('Run a little server that reverse proxies to another server.')
    .alias('t', 'target')
    .describe('t', 'Target server URI like "http://localhost:3000". This is your webserver.')
    .alias('s', 'serve')
    .describe('s', 'Proxy server URI like "http://192.168.1.102:8080". This is the URL you want to point your web browser at.')
    .alias('c', 'config')
    .describe('c', 'Configuration file. See examples/rails.coffee for an example file.')
    .alias('h', 'help')
    .describe('h', "Print this help text.")
}

function print_output(state) {
  console.log('STATE', state);
  console.log('Listening for connections on '+ state.hostname +':'+ state.port +' '+ state.family);
  console.log('Proxying requests to '+ state.target_uri);
  console.log('Press CTRL+c to stop.');
}

function die(err) {
  console.error(err.stack);
  process.exit(2);
}

/*
function create_proxy(target) {
  return function (req, res) {
    var buffer = LIB.cache_service.cache(req)
    req.pipe(REQUEST(target + req.url)).pipe(buffer).pipe(res);
  };
}
*/
<|endoftext|>


<commit_before>module.exports.note = require('./lib/note');
module.exports.chord = require('./lib/chord');
module.exports.scale = require('./lib/scale');
module.exports.improv = require('./lib/improv');
module.exports.midi = require('./lib/midi');<commit_msg>Expose interval and duration modules<commit_after>module.exports.note = require('./lib/note');
module.exports.chord = require('./lib/chord');
module.exports.scale = require('./lib/scale');
module.exports.improv = require('./lib/improv');
module.exports.midi = require('./lib/midi');
module.exports.duration = require('./lib/duration');
module.exports.interval = require('./lib/interval');
<|endoftext|>


<commit_before>var SerialPort = require('serialport').SerialPort;
var serialPort = new SerialPort('/dev/ttyAMA0', {
  baudrate: 115200
});
var express = require('express');
var bodyParser = require('body-parser')
var _gcodes = [];
serialPort.on('open', function () {
  console.log('serial opened!');
  serialPort.on('data', function (data) {
    if(data.toLowerCase().indexOf('ok')>-1){
      sendNext();
    }
  });
});
serialPort.on('close', function () {
  console.log('close');
})
function sendNext(){
  if(_gcodes.length>0){
    serialPort.write( _gcodes.shift()+"\n");
  }
}
var app = express();
app.use(express.static(__dirname+'/public'));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/gcode', (req, res) => {
    _gcodes = _gcodes.concat(req.body.data.split('\n'));
    sendNext();
    res.send('ok');
})
app.get('/move', (req, res) => {
    serialPort.write("G91\n");
    serialPort.write("G1 X"+req.query.x+" Y"+req.query.y+"\n");
    res.send('ok');
})
app.get('/laser', (req, res) => {
    serialPort.write("M3 P"+(req.query.status?5:0)+"\n");
    res.send('ok');
})
app.get('/setzero', (req, res) => {
    serialPort.write("G92 X0 Y0 Z0\n");
    res.send('ok');
})

app.listen(8000);
console.log("127.0.0.1:8000");
<commit_msg>update<commit_after>var SerialPort = require('serialport').SerialPort;
var serialPort = new SerialPort('/dev/ttyAMA0', {
  baudrate: 115200
});
var express = require('express');
var bodyParser = require('body-parser')
var _gcodes = [];
serialPort.on('open', function () {
  console.log('serial opened!');
  serialPort.on('data', function (data) {
    if(data.toString().toLowerCase().indexOf('ok')>-1){
      sendNext();
    }
  });
});
serialPort.on('close', function () {
  console.log('close');
})
function sendNext(){
  if(_gcodes.length>0){
    serialPort.write( _gcodes.shift()+"\n");
  }
}
var app = express();
app.use(express.static(__dirname+'/public'));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/gcode', (req, res) => {
    _gcodes = _gcodes.concat(req.body.data.split('\n'));
    sendNext();
    res.send('ok');
})
app.get('/move', (req, res) => {
    serialPort.write("G91\n");
    serialPort.write("G1 X"+req.query.x+" Y"+req.query.y+"\n");
    res.send('ok');
})
app.get('/laser', (req, res) => {
    serialPort.write("M3 P"+(req.query.status?5:0)+"\n");
    res.send('ok');
})
app.get('/setzero', (req, res) => {
    serialPort.write("G92 X0 Y0 Z0\n");
    res.send('ok');
})

app.listen(8000);
console.log("127.0.0.1:8000");
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const promisify = require('util').promisify
const writeFile = promisify(fs.writeFile)
const globby = require('globby')

;(async () => {
  // const posts = require('./dist/content/posts/index.json')
  const files = await globby('./dist/**/*.{css,mjs}')
  const headers = []

  for (const file of files) {
    const relative = path.relative('./dist', file)

    switch (path.extname(relative)) {
      case '.css':
        headers.push(`  Link: </${relative}> rel=preload as=style`)
        break

      case '.mjs':
        // headers.push(`  Link: </${relative}>; rel=modulepreload`)
        break
    }
  }

  const lines = []

  for (const path of ['/', '/posts/*']) {
    lines.push(path)

    // if (path === '/') {
    //   lines.push(`  Link: </content/posts/${posts[posts.length - 1].slug}.md>; rel=preload; as=fetch`)
    // }

    lines.push(...headers)
  }

  // for (const post of posts) {
  //   lines.push(`/posts/${post.slug}`, `  Link: </content/posts/${post.slug}.md>; rel=preload; as=fetch`)
  // }

  await writeFile('./dist/_headers', lines.join('\n'))
})()
<commit_msg>Try to get push to work<commit_after>const fs = require('fs')
const path = require('path')
const promisify = require('util').promisify
const writeFile = promisify(fs.writeFile)
const globby = require('globby')

;(async () => {
  // const posts = require('./dist/content/posts/index.json')
  const files = await globby('./dist/**/*.{css,mjs}')
  const headers = []

  for (const file of files) {
    const relative = path.relative('./dist', file)

    switch (path.extname(relative)) {
      case '.css':
        headers.push(`  Link: </${relative}>; rel=preload; as=style`)
        break

      case '.mjs':
        headers.push(`  Link: </${relative}>; rel=modulepreload`)
        break
    }
  }

  const lines = []

  for (const path of ['/index.html ']) {
    lines.push(path)

    // if (path === '/') {
    //   lines.push(`  Link: </content/posts/${posts[posts.length - 1].slug}.md>; rel=preload; as=fetch`)
    // }

    lines.push(...headers)
  }

  // for (const post of posts) {
  //   lines.push(`/posts/${post.slug}`, `  Link: </content/posts/${post.slug}.md>; rel=preload; as=fetch`)
  // }

  await writeFile('./dist/_headers', lines.join('\n'))
})()
<|endoftext|>


<commit_before>function init_postcodeBlock(blockId, address_table_id, zipcodes) {
    var city_field_td = cj(address_table_id + ' #address_'+blockId+'_city').parent();
    var postalcode_field_td = cj(address_table_id + ' #address_'+blockId+'_postal_code').parent();
    //postalcode_field_td.detach();
    city_field_td.parent().prepend(postalcode_field_td);
    var first_row = city_field_td.parent().parent().parent().parent().parent();
    first_row.before(zipcodes_getRowHtml(blockId, zipcodes));

    cj('#zipcode_lookup_'+blockId).select2({
        matcher: function(term, text) {
            // The text parameter looks like 2000 - Antewerpen.
            // So try to split it into a zipcode and a city part.
            // Split the zipcode text into a zipcode part
            // splitted[0] and a city part splitted[1].
            var splitted = text.split(" - ");
            if ((splitted[0].toUpperCase().indexOf(term.toUpperCase())==0) || (splitted[1].toUpperCase().indexOf(term.toUpperCase())==0)) {
                return true;
            }
            return false;
        }
    });
    zipcodes_addOnChange(blockId);
}

function zipcodes_getRowHtml(blockId, zipcodes) {
    var html = '
';
    html = html + 'Postcode lookup
';
    html = html + '<select type="text" class="crm-form-select" id="zipcode_lookup_'+blockId+'" style="width: 100%;" value="">';
    html = html + '<option value=""> - Lookup a postcode - </option>';
    for(var i = 0; i < zipcodes.length; i++) {
        html = html + '<option value="'+zipcodes[i]+'">'+zipcodes[i]+'</option>';
    }
    html = html + '</select>';
    html = html + '
';
    return html;
}

function zipcodes_addOnChange(blockId) {
    cj('#zipcode_lookup_'+blockId).change(function (e) {
        zipcodes_fill(blockId);
    });
}

function zipcodes_fill(blockId) {
    var value = cj('#zipcode_lookup_'+blockId).val();
    var values = value.split(' - ');
    if(values[0] && values[1]) {
        cj('#address_' + blockId + '_postal_code').val(values[0]);
        cj('#address_' + blockId + '_city').val(values[1]);
    }
}

/**
 *
 * remove all lookup widgets
 */
function zipcodes_reset() {
    cj('.zipcodes_input_row').remove();
}

/*
 * The code sniplet below makes sure that whenever a new address block is added
 * the reset functions are run
 */
cj(function() {
    cj.each(['show', 'hide'], function (i, ev) {
        var el = cj.fn[ev];
        cj.fn[ev] = function () {
          this.trigger(ev);
          return el.apply(this, arguments);
        };
      });
});<commit_msg>Fixed #1.<commit_after>function init_postcodeBlock(blockId, address_table_id, zipcodes) {
    var city_field_td = cj(address_table_id + ' #address_'+blockId+'_city').parent();
    var postalcode_field_td = cj(address_table_id + ' #address_'+blockId+'_postal_code').parent();
    //postalcode_field_td.detach();
    city_field_td.parent().prepend(postalcode_field_td);
    var first_row = city_field_td.parent().parent().parent().parent().parent();
    first_row.before(zipcodes_getRowHtml(blockId, zipcodes));

    cj('#zipcode_lookup_'+blockId).select2({
        matcher: function(term, text) {
            // The text parameter looks like 2000 - Antewerpen.
            // So try to split it into a zipcode and a city part.
            // Split the zipcode text into a zipcode part
            // splitted[0] and a city part splitted[1].
            var splitted = text.split(" - ");
            if ((splitted[0].toUpperCase().indexOf(term.toUpperCase())==0) || (splitted[1].toUpperCase().indexOf(term.toUpperCase())==0)) {
                return true;
            }
            return false;
        }
    });
    zipcodes_addOnChange(blockId);

  cj('#address_' + blockId + '_country_id').change(function(e) {
    console.log(cj('#address_' + blockId + '_country_id').val());
    if ((cj('#address_' + blockId + '_country_id').val()) == 1020) {
      cj('#zipcodes_input_row_'+blockId).removeClass('hiddenElement');
    } else {
      cj('#zipcodes_input_row_'+blockId).addClass('hiddenElement');
    }
  });
}

function zipcodes_getRowHtml(blockId, zipcodes) {
    var html = '
';
    html = html + 'Postcode lookup
';
    html = html + '<select type="text" class="crm-form-select" id="zipcode_lookup_'+blockId+'" style="width: 100%;" value="">';
    html = html + '<option value=""> - Lookup a postcode - </option>';
    for(var i = 0; i < zipcodes.length; i++) {
        html = html + '<option value="'+zipcodes[i]+'">'+zipcodes[i]+'</option>';
    }
    html = html + '</select>';
    html = html + '
';
    return html;
}

function zipcodes_addOnChange(blockId) {
    cj('#zipcode_lookup_'+blockId).change(function (e) {
        zipcodes_fill(blockId);
    });
}

function zipcodes_fill(blockId) {
    var value = cj('#zipcode_lookup_'+blockId).val();
    var values = value.split(' - ');
    if(values[0] && values[1]) {
        cj('#address_' + blockId + '_postal_code').val(values[0]);
        cj('#address_' + blockId + '_city').val(values[1]);
    }
}

/**
 *
 * remove all lookup widgets
 */
function zipcodes_reset() {
    cj('.zipcodes_input_row').remove();
}

/*
 * The code sniplet below makes sure that whenever a new address block is added
 * the reset functions are run
 */
cj(function() {
    cj.each(['show', 'hide'], function (i, ev) {
        var el = cj.fn[ev];
        cj.fn[ev] = function () {
          this.trigger(ev);
          return el.apply(this, arguments);
        };
      });
});<|endoftext|>


<commit_before>'use strict';

let mongoose = require('mongoose');
let encryption = require('../utilities/encryption');

var User = mongoose.model('User');

User.find({
  username: 'admin'
}, function (err, users) {
  if (users.length > 0 || err) {
    return;
  }

  let newSalt = encryption.generateSalt();
  User.create({
    username: 'admin',
    email: 'admin@admin.bg',
    salt: newSalt,
    hashPass: encryption.generateHashedPassword(newSalt, 'admin'),
    roles: ['admin'],
  }, function (err, result) {
    console.log(`Created ${result}`);
  });
});
<commit_msg>Initial seeding of games in the database added<commit_after>'use strict';

let mongoose = require('mongoose');
let encryption = require('../utilities/encryption');

var User = mongoose.model('User');
var Game = mongoose.model('Game');

User.find({
  username: 'admin'
}, function (err, users) {
  if (users.length > 0 || err) {
    return;
  }

  let newSalt = encryption.generateSalt();
  User.create({
    username: 'admin',
    email: 'admin@admin.bg',
    salt: newSalt,
    hashPass: encryption.generateHashedPassword(newSalt, 'admin'),
    roles: ['admin'],
  }, function (err, result) {
    console.log(`Created ${result}`);
  });
});

Game.find({}).exec(function(err, collection) {
  if (err) {
    console.log('Cannot find games: ' + err);
    return;
  }

  if (collection.length === 0) {
    console.log('Seeding games...');
    Game.create({name: 'FIFA 11', featured: true, dateAdded: new Date('10/1/2016'), mainPageImage: "images/fifa-16.jpg"});
    Game.create({name: 'Bloodborne', featured: true, dateAdded: new Date('10/1/2016'), mainPageImage: "images/bloodborne.jpg"});
    Game.create({name: 'Call of Duty', featured: false, dateAdded: new Date('13/1/2016'),  mainPageImage: "images/call-of-duty1.jpg"});
    console.log('Initial games seeded!');
  }
});
<|endoftext|>


<commit_before>module.exports = {
  "parser": "babel-eslint",
  "extends": [
    require.resolve("eslint-config-standard"),
  ],
  "rules": {
    // disable eslint rules
    "no-underscore-dangle": 0, // why not?
    "require-jsdoc": 0, // flow type is better
    "valid-jsdoc": 0,

    // enable eslint rules
    "func-style": [2, "declaration", { "allowArrowFunctions": true }],
    "no-invalid-this": 0, // this doesn't even work on node streams

    // disable airbnb rules
    "camelcase": 0, // who cares
    "consistent-return": 0, // unnecessary
    "default-case": 0, // don't always need one
    "no-nested-ternary": 0, // why not?!
    "no-param-reassign": 0, // i do this all the time
    "no-shadow": 0, // necessary w/ callbacks sometimes
    "no-use-before-define": [2, "nofunc"], // function declarations!
    "react/jsx-closing-bracket-location": 0, // i don't get it
    "strict": 0, // doesn't work inside modules

    // enable airbnb rules
    "func-names": 0, // use arrow functions instead, but it doesn't really work as expected
    "object-curly-spacing": [2, "always"], // yes please

    // disable google rules
    "max-len": 0, // what is this? 1999?
    "no-eq-null": 0, // checks whether it's undefined
    "no-implicit-coercion": 0, // no, it's awesome!
    "no-inline-comments": 0, // wtf?
    "no-warning-comments": 0, // wtf?

    // enable google rules
    "operator-assignment": 2,
    "max-nested-callbacks": [2, 3],
    "no-negated-condition": 2,
    "quote-props": [2, "as-needed"],

    // unset standard rules
    "comma-dangle": 0, // who cares
    "no-loop-func": 2, // if need to do it, write an eslint comment

    // custom rules
    "arrow-parens": 0, // [2, "as-needed"] doesn't work w/ async functions
    "no-cond-assign": [2, "except-parens"],
    "no-console": 2,
    "no-var": 2,
    "object-shorthand": [2, "always"],
    "operator-linebreak": [2, "before", {
      "overrides": {
        "=": "after"
      }
    }],
    "prefer-arrow-callback": 2,
    "prefer-const": 2,
    "prefer-spread": 2,
    "prefer-template": 0, // doesn't make sense all the time
    "radix": 0,
    "require-yield": 0, // doesn't make sense for Koa routes w/o async stuff
  }
}
<commit_msg>no-return-assign: 0<commit_after>module.exports = {
  "parser": "babel-eslint",
  "extends": [
    require.resolve("eslint-config-standard"),
  ],
  "rules": {
    // disable eslint rules
    "no-underscore-dangle": 0, // why not?
    "require-jsdoc": 0, // flow type is better
    "valid-jsdoc": 0,

    // enable eslint rules
    "func-style": [2, "declaration", { "allowArrowFunctions": true }],
    "no-invalid-this": 0, // this doesn't even work on node streams

    // disable airbnb rules
    "camelcase": 0, // who cares
    "consistent-return": 0, // unnecessary
    "default-case": 0, // don't always need one
    "no-nested-ternary": 0, // why not?!
    "no-param-reassign": 0, // i do this all the time
    "no-shadow": 0, // necessary w/ callbacks sometimes
    "no-use-before-define": [2, "nofunc"], // function declarations!
    "react/jsx-closing-bracket-location": 0, // i don't get it
    "strict": 0, // doesn't work inside modules

    // enable airbnb rules
    "func-names": 0, // use arrow functions instead, but it doesn't really work as expected
    "object-curly-spacing": [2, "always"], // yes please

    // disable google rules
    "max-len": 0, // what is this? 1999?
    "no-eq-null": 0, // checks whether it's undefined
    "no-implicit-coercion": 0, // no, it's awesome!
    "no-inline-comments": 0, // wtf?
    "no-warning-comments": 0, // wtf?

    // enable google rules
    "operator-assignment": 2,
    "max-nested-callbacks": [2, 3],
    "no-negated-condition": 2,
    "quote-props": [2, "as-needed"],

    // unset standard rules
    "comma-dangle": 0, // who cares
    "no-loop-func": 2, // if need to do it, write an eslint comment
    "no-return-assign": 0, // no reason to block this. saves SLOC

    // custom rules
    "arrow-parens": 0, // [2, "as-needed"] doesn't work w/ async functions
    "no-cond-assign": [2, "except-parens"],
    "no-console": 2,
    "no-var": 2,
    "object-shorthand": [2, "always"],
    "operator-linebreak": [2, "before", {
      "overrides": {
        "=": "after"
      }
    }],
    "prefer-arrow-callback": 2,
    "prefer-const": 2,
    "prefer-spread": 2,
    "prefer-template": 0, // doesn't make sense all the time
    "radix": 0,
    "require-yield": 0, // doesn't make sense for Koa routes w/o async stuff
  }
}
<|endoftext|>


<commit_before>/*global setTimeout, State, Config, Phaser*/

State.GameSplash = function (game) {
	"use strict";
	this.game = game;
};
State.GameSplash.prototype = {
	preload: function () {
		"use strict";
		var progressBar = this.game.add.sprite(Config.gameSplash.progressBar.x, Config.gameSplash.progressBar.y, 'progress-bar');
		var sprite = this.game.add.sprite(Config.gameSplash.x, Config.gameSplash.y, 'game-splash');
		this.game.load.setPreloadSprite(progressBar);
		this.game.load.onLoadComplete.add(function () {this.game.add.tween(sprite).to({alpha : 0}, Config.gameSplash.millis, Phaser.Easing.Linear.None).start(); setTimeout(function () {this.game.state.start('Menu');}, Config.gameSplash.millis);}, this);

		this.loadAssets();
	},
	create: function () {
		"use strict";
	},
	update: function () {
		"use strict";
		Config.global.screen.resize(this.game);
	},
	loadAssets: function () {

		//Credits
		this.game.load.image('credits', Config.credits.dir);

		//HowToPlay
		this.game.load.image('how-to-play', Config.howToPlay.dir);

		//Menu
		this.game.load.image('menu-background',  Config.menu.dir);
		this.game.load.spritesheet('button-play', Config.menu.buttonPlay.dir, Config.menu.buttonPlay.width, Config.menu.buttonPlay.height);
		this.game.load.spritesheet('button-credits', Config.menu.buttonCredits.dir, Config.menu.buttonCredits.width, Config.menu.buttonCredits.height);
		this.game.load.spritesheet('button-how-to-play', Config.menu.buttonHowToPlay.dir, Config.menu.buttonHowToPlay.width, Config.menu.buttonHowToPlay.height);

		//TileMap
		this.load.tilemap('fase01', Config.tilemap.fase01.dir, null, Phaser.Tilemap.TILED_JSON);
		this.game.load.image('tiles', Config.tilemap.tiles.tileset.dir);

		this.game.load.image('coin', Config.tilemap.tiles.coins.dir);

		this.game.load.image('powerlife', Config.tilemap.tiles.powerlifes.dir);

		this.game.load.image('powerstar', Config.tilemap.tiles.powerstars.dir);

		//Player
		this.game.load.spritesheet('oscar', Config.player.dir, Config.player.width, Config.player.height);

		//Background
		this.game.load.image('game-background', Config.background.game.dir);
	}
};<commit_msg>Implemetacao de inimigo<commit_after>/*global setTimeout, State, Config, Phaser*/

State.GameSplash = function (game) {
	"use strict";
	this.game = game;
};
State.GameSplash.prototype = {
	preload: function () {
		"use strict";
		var progressBar = this.game.add.sprite(Config.gameSplash.progressBar.x, Config.gameSplash.progressBar.y, 'progress-bar');
		var sprite = this.game.add.sprite(Config.gameSplash.x, Config.gameSplash.y, 'game-splash');
		this.game.load.setPreloadSprite(progressBar);
		this.game.load.onLoadComplete.add(function () {this.game.add.tween(sprite).to({alpha : 0}, Config.gameSplash.millis, Phaser.Easing.Linear.None).start(); setTimeout(function () {this.game.state.start('Menu');}, Config.gameSplash.millis);}, this);

		this.loadAssets();
	},
	create: function () {
		"use strict";
	},
	update: function () {
		"use strict";
		Config.global.screen.resize(this.game);
	},
	loadAssets: function () {

		//Credits
		this.game.load.image('credits', Config.credits.dir);

		//HowToPlay
		this.game.load.image('how-to-play', Config.howToPlay.dir);

		//Menu
		this.game.load.image('menu-background',  Config.menu.dir);
		this.game.load.spritesheet('button-play', Config.menu.buttonPlay.dir, Config.menu.buttonPlay.width, Config.menu.buttonPlay.height);
		this.game.load.spritesheet('button-credits', Config.menu.buttonCredits.dir, Config.menu.buttonCredits.width, Config.menu.buttonCredits.height);
		this.game.load.spritesheet('button-how-to-play', Config.menu.buttonHowToPlay.dir, Config.menu.buttonHowToPlay.width, Config.menu.buttonHowToPlay.height);

		//TileMap
		this.load.tilemap('fase01', Config.tilemap.fase01.dir, null, Phaser.Tilemap.TILED_JSON);
		this.game.load.image('tiles', Config.tilemap.tiles.tileset.dir);

		this.game.load.image('coin', Config.tilemap.tiles.coins.dir);

		this.game.load.image('powerlife', Config.tilemap.tiles.powerlifes.dir);

		this.game.load.image('powerstar', Config.tilemap.tiles.powerstars.dir);

		//Player
		this.game.load.spritesheet('oscar', Config.player.dir, Config.player.width, Config.player.height);

		//Enemy
		this.game.load.spritesheet('enemy', Config.enemy.dir, Config.enemy.width, Config.enemy.height);

		//Background
		this.game.load.image('game-background', Config.background.game.dir);
	}
};<|endoftext|>