<commit_before>/**
 * Created by nuintun on 2015/5/4.
 */

'use strict';

// import lib
var util = require('./util');
var acorn = require('acorn');

// the parse function
function parse(src, options){
  if (!options) options = {};

  return acorn.parse(src, {
    sourceType: options.sourceType,
    ranges: util.defined(options.ranges, false),
    locations: util.defined(options.locations, null),
    ecmaVersion: util.defined(options.ecmaVersion, 6),
    allowHashBang: util.defined(options.allowHashBang, true),
    allowReserved: util.defined(options.allowReserved, true),
    allowReturnOutsideFunction: util.defined(options.allowReturnOutsideFunction, true),
    allowImportExportEverywhere: util.defined(options.allowImportExportEverywhere, true)
  });
}

// executes visitor on the object and its children (recursively).
function traverse(object, visitor){
  var key;
  var child;

  if (visitor.call(null, object) !== false) {
    for (key in object) {
      if (object.hasOwnProperty(key)) {
        child = object[key];

        if (child !== null && typeof child === 'object') {
          traverse(child, visitor);
        }
      }
    }
  }
}

// the tree walk function
function walk(src, options, callback){
  var syntax;

  // parse ast
  try {
    syntax = parse(src, options);
  } catch (error) {
    // parse ast wrong, do nothing
  }

  // if parse success
  if (syntax) {
    traverse(syntax, callback);
  }

  return syntax;
}

// the is require function
function isRequire(node, word, flag){
  if (node.type === 'CallExpression') {
    node = node.callee;

    if (flag && node.type === 'MemberExpression') {
      return node.object.type === 'Identifier' && node.object.name === word
        && ((node.property.type === 'Identifier' && node.property.name === flag)
        || (node.property.type === 'Literal' && node.property.value === flag));
    } else {
      return node.type === 'Identifier' && node.name === word;
    }
  }
}

// exports
module.exports = function (src, replace, options){
  var offset = 0;
  var modules = [];

  if (replace && util.object(replace)) {
    options = replace;
    replace = undefined;
  }

  options = options || {};

  if (!util.string(src)) return modules;
  if (!util.string(options.word)) options.word = 'require';
  if (!(new RegExp('\\b' + options.word + '\\b')).test(src)) return modules;
  if (replace && !util.fn(replace)) replace = util.noop;

  // the handle function
  var handle = function (node, flag){
    var update;
    var value = node.value;

    // push modules in to array
    modules.push({
      flag: flag,
      path: value
    });

    // replace code
    if (replace) {
      update = replace(value, flag);

      if (util.string(update)) {
        src = src.substring(0, node.start + offset + 1) + update + src.substring(node.end + offset - 1);
        offset += update.length - value.length;
      }
    }
  };

  // walk code
  walk(src, options.parse, function (node){
    if (isRequire(node, options.word, options.flag)) {
      var args = node.arguments;
      var flag = node.callee.property ? options.flag : null;

      // when arguments length > 0
      if (args.length) {
        args = args[0];

        if (args.type === 'Literal') {
          handle(args, flag);
        } else if (args.type === 'ArrayExpression') {
          args.elements.forEach(function (args){
            if (args.type === 'Literal') {
              handle(args, flag);
            }
          });
        }
      }
    }
  });

  return replace ? src : modules;
};
<commit_msg>adjust code style<commit_after>/**
 * Created by nuintun on 2015/5/4.
 */

'use strict';

// import lib
var util = require('./util');
var acorn = require('acorn');

// the parse function
function parse(src, options){
  if (!options) options = {};

  return acorn.parse(src, {
    sourceType: options.sourceType,
    ranges: util.defined(options.ranges, false),
    locations: util.defined(options.locations, null),
    ecmaVersion: util.defined(options.ecmaVersion, 6),
    allowHashBang: util.defined(options.allowHashBang, true),
    allowReserved: util.defined(options.allowReserved, true),
    allowReturnOutsideFunction: util.defined(options.allowReturnOutsideFunction, true),
    allowImportExportEverywhere: util.defined(options.allowImportExportEverywhere, true)
  });
}

// executes visitor on the object and its children (recursively).
function traverse(object, visitor){
  var key;
  var child;

  if (visitor.call(null, object) !== false) {
    for (key in object) {
      if (object.hasOwnProperty(key)) {
        child = object[key];

        if (child !== null && typeof child === 'object') {
          traverse(child, visitor);
        }
      }
    }
  }
}

// the tree walk function
function walk(src, options, callback){
  var syntax;

  // parse ast
  try {
    syntax = parse(src, options);
  } catch (error) {
    // parse ast wrong, do nothing
  }

  // if parse success
  if (syntax) {
    traverse(syntax, callback);
  }

  return syntax;
}

// the is require function
function isRequire(node, word, flag){
  if (node.type === 'CallExpression') {
    node = node.callee;

    if (flag && node.type === 'MemberExpression') {
      return node.object.type === 'Identifier' && node.object.name === word
        && ((node.property.type === 'Identifier' && node.property.name === flag)
        || (node.property.type === 'Literal' && node.property.value === flag));
    } else {
      return node.type === 'Identifier' && node.name === word;
    }
  }
}

// exports
module.exports = function (src, replace, options){
  var deps = [];
  var offset = 0;

  if (replace && util.object(replace)) {
    options = replace;
    replace = undefined;
  }

  options = options || {};

  if (!util.string(src)) return deps;
  if (!util.string(options.word)) options.word = 'require';
  if (!(new RegExp('\\b' + options.word + '\\b')).test(src)) return deps;
  if (replace && !util.fn(replace)) replace = util.noop;

  // the handle function
  var handle = function (node, flag){
    var update;
    var value = node.value;

    // push deps in to array
    deps.push({
      flag: flag,
      path: value
    });

    // replace code
    if (replace) {
      update = replace(value, flag);

      if (util.string(update)) {
        src = src.substring(0, node.start + offset + 1) + update + src.substring(node.end + offset - 1);
        offset += update.length - value.length;
      }
    }
  };

  // walk code
  walk(src, options.parse, function (node){
    if (isRequire(node, options.word, options.flag)) {
      var args = node.arguments;
      var flag = node.callee.property ? options.flag : null;

      // when arguments length > 0
      if (args.length) {
        args = args[0];

        if (args.type === 'Literal') {
          handle(args, flag);
        } else if (args.type === 'ArrayExpression') {
          args.elements.forEach(function (args){
            if (args.type === 'Literal') {
              handle(args, flag);
            }
          });
        }
      }
    }
  });

  return replace ? src : deps;
};
<|endoftext|>


<commit_before>/* parser.js
 * Copyright 2014 Cubane Canada, Inc.
 *
 * Released under the MIT license -- see MIT-LICENSE for details
 */
(function () {
    'use strict';

    var parser = exports,
        util = require('util'),
        stream = require('stream');

    /**
     Parser for MDL/Symyx CTfile formats

     Usage:
         var molfile = require('molfile');

         var parsed = molfile.parseMol(string);

     @module molfile
     @class  molfile

     */

    /**
     Return parser version string.

     @method getVersion
     @return {String} parser version
     */
    parser.getVersion = function getVersion() {
        return {
            moduleVersion: '0.0.2'
        };
    };

    /**
     * Parse the count line of a V2000 format molFile.  Returns an object:
     *
     *     {
     *       'atoms': 15,
     *       'bonds': 14,
     *       'chiral': 1,
     *       'mLines': 999,
     *       'version': ' V2000'
     *     }
     *
     * Note that mLines should always be 999 for modern molfiles,
     * to signal the mLines value is ignored.  M lines are read until 'M  END'.
     *
     * Note that version will contain leading spaces if the version string
     * is shorter than the 6 bytes alloted.
     *
     * @method parseCountLine
     * @param {String} line count line to parse
     * @return {Object} data from the line
     */
    parser.parseCountLine = function parseCountLine(line) {
        var parsed = {};

        parsed.atoms = parseInt(line.slice(0, 3), 10);
        parsed.bonds = parseInt(line.slice(3, 6), 10);
        // atom lists: 6-9
        // obsolete:   9-12
        parsed.chiral = parseInt(line.slice(12, 15), 10);
        // stexts:    15-18
        // obsolete:  18-21
        // obsolete:  21-24
        // obsolete:  24-27
        // obsolete:  27-30
        parsed.mLines = parseInt(line.slice(30, 33), 10);
        parsed.version = line.slice(33, 39);

        if (parsed.version !== " V2000") {
            throw new Error("Unsupported molfile version '" + parsed.version + "'");
        }

        return parsed;
    };

    /**
     Parses an atom line.  Return value is an object:

          {
             'x': 0.0,
             'y': 0.0,
             'z': 0.0,
             'elname': 'Hf'
             'massDiff': 0,
             'chargeCode': 0,
             'valenceCode': 0,
           }

     Note that massDiff, chargeCode and valenceCode should be ignored if there
     are isotope, charge, or radical entries in the property table which
     follows the atom and bond tables.

     It is easier to read the isotope, charge, and radical information
     from the properties than to interpret the codes.

     Mass difference is an integral difference from the periodic table mass,
     and is in the range -3..4

     Charge code should be interpreted as follows:

     | Code   |  Meaning |
     |-------|---------|
     |      0 | no charge (0)|
     |      1 |       +3 |
     |      2 |       +2 |
     |      3 |       +1 |
     |      4 | doublet (radical) |
     |      5 |       -1 |
     |      6 |       -2 |
     |      7 |       -3 |

     Valence code should be interpreted as follows:

     | Code   |  Meaning |
     |-------|---------|
     |      0 | default valence |
     |   1-14 | valence = code |
     |    15 |  valence = 0 |

     @method parseAtomLine
     @param {String} line the line to parse
     @return {Object} data from the line
     */
    parser.parseAtomLine = function (line) {
        var parsed = { x: 0, y: 0, z: 0 };

        parsed.x = parseFloat(line.slice(0, 10));
        parsed.y = parseFloat(line.slice(10, 20));
        parsed.z = parseFloat(line.slice(20, 30));
        // 31 is declared as a space
        parsed.elname = line.slice(31, 34).trim();
        parsed.massDiff = parseInt(line.slice(34, 36), 10);
        parsed.chargeCode = parseInt(line.slice(36, 39), 10);
        // several obsolete fields
        parsed.valenceCode = parseInt(line.slice(48, 51), 10);
        // more obsolete fields

        return parsed;
    };

    /**
     Parses a bond line.  Return value is an object:

          {
            'from': 3,
            'to': 4,
            'bondType': 1
          }

     bondType is a code, and should be interpreted as follows:

     | Code | Meaning |
     |------|---------|
     | 1 | single |
     | 2 | double |
     | 3 | triple |
     | 4 | aromatic |
     | 5 | single or double |
     | 6 | single or aromatic |
     | 7 | double or aromatic |
     | 8 | any |

     Codes 5-8 are can only be present when the file describes a
     search.  They are never present in a molecule description.

     @method parseBondLine
     @param {String} line the line to parse
     @return {Object} data from the line
     */
    parser.parseBondLine = function (line) {
        var parsed = { from: 0, to: 0, bondType: 0 };

        parsed.from = parseInt(line.slice(0, 3), 10);
        parsed.to = parseInt(line.slice(3, 6), 10);
        parsed.bondType = parseInt(line.slice(6, 9), 10);
        // several other fields, all obsolete

        return parsed;
    };

    parser.addKeyValue = function addKeyValue(values, part) {
        var key = parseInt(part.slice(0, 4), 10),
            value = parseInt(part.slice(4, 8), 10);
        values[key] = value;
    };

    /**
     Parses a property line

     @method parseProperty
     @param {String} line the line to parse
     @return {Object} data from the line
     */
    parser.parseProperty = function parseProperty(line) {
        if (/^M {2}END$/.test(line)) {
            return null;
        }

        var parsed = {},
            values = {},
            i,
            slices = [],
            offset;

        parsed.mode = line.slice(3, 6);
        parsed[parsed.mode] = values;
        parsed.count = parseInt(line.slice(6, 9), 10);

        for (i = 0; i < parsed.count; i += 1) {
            offset = 9 + i * 8;
            slices.push(line.slice(offset, offset + 8));
        }

        slices.forEach(function (slice) {
            parser.addKeyValue(values, slice);
        });

        return parsed;
    };

    parser.makeDate = function makeDate(line) {
        var month = parseInt(line.slice(0, 2), 10),
            day = line.slice(2, 4),
            year = parseInt(line.slice(4, 6), 10),
            hour = line.slice(6, 8),
            minute = line.slice(8, 10);

        if (year < 80) {
            year += 2000;
        }

        return new Date(year, month - 1, day, hour, minute);
    };

    parser.parseMolHeader = function parseMolHeader(header) {
        var parsed = {},
            lines = header.split('\n');

        parsed.name = lines[0];
        parsed.initials = lines[1].slice(0, 2);
        parsed.software = lines[1].slice(2, 10);
        parsed.date = parser.makeDate(lines[1].slice(10, 20));
        parsed.comment = lines[2];

        return parsed;
    };

    parser.parseDataItem = function parseDataItem(string) {
        var parsed = {},
            match,
            from,
            to;

        match = /<([\-A-Za-z_\.]+)>/.exec(string);
        parsed.name = match ? match[1] : '';

        from = string.indexOf('\n');
        to = string.length;
        parsed.value = string.slice(from + 1, to);

        return parsed;
    };

    parser.splitDataItems = function splitDataItems(string) {
        // between M  END and $$$, split on double newline
        return string.split('\n\n');
    };

    /**
     Prescan the molfile data, find the newlines and boundaries of various
     blocks.  Returns an object:

         {
           newlines: [],     // offset of each newline
           firstM: 120,      // beginning of properties
           lastM: 154,       // end of properties
           firstAngle: 230,  // beginning of data
           sectionEnd: 500   // end of data
         }

     @method prescanMol
     @param {String} mol the molfile data
     @return {Object} object containing useful offsets
     */
    parser.prescanMol = function prescanMol(mol) {
        var scan = { newlines: [] },
            start = 0,
            len = mol.length,
            found = -1,
            line;

        while (start < len) {
            found = mol.indexOf('\n', start);
            if (found === -1) {
                break;
            }
            scan.newlines.push(found);

            line = mol.slice(start, found);

            if (line.match(/^M {2}END/)) {
                scan.lastM = start;
            }
            if (line.match(/^M/) && !scan.firstM) {
                scan.firstM = start;
            }
            if (line.match(/^>/) && !scan.firstAngle) {
                scan.firstAngle = start;
            } else if (line.match(/^\$\$\$/)) {
                scan.sectionEnd = start;
            }

            start = found + 1;
        }

        return scan;
    };

    function getAtoms(mol, scan, parsed) {
        var begin = scan.newlines[3] + 1,
            end = scan.newlines[3 + parsed.countLine.atoms],
            atomLines = mol.slice(begin, end);

        return atomLines.split('\n');
    }

    function getBonds(mol, scan, parsed) {
        var startLine = 3 + parsed.countLine.atoms,
            begin = scan.newlines[startLine] + 1,
            end = scan.newlines[startLine + parsed.countLine.bonds];

        return mol.slice(begin, end).split('\n');
    }

    function getProperties(mol, scan) {
        var begin = scan.firstM,
            end = scan.lastM;

        return mol.slice(begin, end).split('\n');
    }

    function getData(mol, scan) {
        var begin = scan.firstAngle,
            end = scan.sectionEnd;

        return mol.slice(begin, end).split('\n\n');
    }

    function squashProperty(accum, property) {
        var mode = property.mode,
            source,
            target;

        if (!accum[mode]) {
            accum[mode] = property[mode];
        } else {
            target = accum[mode];
            source = property[mode];

            Object.keys(source).forEach(function (key) {
                target[key] = source[key];
            });
        }

        return accum;
    }
    parser.squashProperty = squashProperty;

    function squashData(accum, data) {
        if (data.name) {
            accum[data.name] = data.value;
        }

        return accum;
    }

    /**
     Parses a V2000 molfile record and returns an Object containing
     the data therein.

          {
              atoms: [
                { x: 0.0, y: 0.0, z: 0.0, elname: 'Hf' }
                ...
              ],
              bonds: [
                  { 3, 4, 1 },
                  ...
              }
              properties: {
                  CHG: {
                     3: -1
                  }
                  ISO: {
                  }
                  RAD: {
                  }
              }
              data: {
                ID: 'zwitterions_2'
             }
           }

     @method parseMol
     @param {String} mol the complete molfile, including newlines
     @return {Object} an object representing the contents of the molfile
     */
    parser.parseMol = function parseMol(mol) {
        var parsed = {},
            scan = parser.prescanMol(mol),
            headerEnd = scan.newlines[2] + 1,
            countLineEnd = scan.newlines[3] + 1;

        parsed.header = parser.parseMolHeader(mol.slice(0, headerEnd));

        parsed.countLine = parser.parseCountLine(mol.slice(headerEnd, countLineEnd));

        parsed.atoms = getAtoms(mol, scan, parsed).map(parser.parseAtomLine);

        parsed.bonds = getBonds(mol, scan, parsed).map(parser.parseBondLine);

        // now read properties
        parsed.properties = getProperties(mol, scan).map(parser.parseProperty)
            .reduce(squashProperty, {});

        parsed.data = getData(mol, scan).map(parser.parseDataItem)
            .reduce(squashData, {});

        return parsed;
    };

    /**
     A Transform stream that splits an SDF file into individual MOL
     file segments and pushes the segments to the output of the stream

     @class SDFTransform
     */

    /**
     Constructs a new SDFTransform

     @constructor
     @method SDFTransform
     @return {SDFTransform}
     */
    function SDFTransform() {
        stream.Transform.call(this);

        this.buffer = "";
    }
    util.inherits(SDFTransform, stream.Transform);

    /*jslint nomen:true, unparam:true*/
    SDFTransform.prototype._transform = function (chunk, unused, callback) {
        this.buffer += chunk;

        var parts = this.buffer.split(/\$\$\$\$\r?\n/m);

        // remove last (partial) sdf file
        this.buffer = parts.pop();

        parts.forEach(function (part) {
            this.push(part);
        }.bind(this));

        callback(null);
    };

    SDFTransform.prototype._flush = function (callback) {
        if (this.buffer.length > 1) {
            this.push(this.buffer);
        }

        callback(null);
    };
    /*jslint nomen:false, unparam:true*/

    parser.SDFTransform = SDFTransform;

    /**
     A Writable stream that splits an SDF file into individual MOL file segments
     suitable for passing to parseMol.

     Output is via callback.  See SDFTransform for output via Streams API

     @class SDFSplitter
     */

    /**

     @constructor
     @method SDFSplitter
     @param {Function} callback function to call with molfile data
     @return {SDFSplitter} a Writable stream which calls the supplied callback
     once per molfile in the supplied SDFSplitter stream
     */
    function SDFSplitter(handler) {
        parser.SDFTransform.call(this);

        this.on('data', function (chunk) {
            handler(String(chunk));
        });
    }
    util.inherits(SDFSplitter, SDFTransform);

    parser.SDFSplitter = SDFSplitter;

}());
<commit_msg>publish: bump version<commit_after>/* parser.js
 * Copyright 2014 Cubane Canada, Inc.
 *
 * Released under the MIT license -- see MIT-LICENSE for details
 */
(function () {
    'use strict';

    var parser = exports,
        util = require('util'),
        stream = require('stream');

    /**
     Parser for MDL/Symyx CTfile formats

     Usage:
         var molfile = require('molfile');

         var parsed = molfile.parseMol(string);

     @module molfile
     @class  molfile

     */

    /**
     Return parser version string.

     @method getVersion
     @return {String} parser version
     */
    parser.getVersion = function getVersion() {
        return {
            moduleVersion: '0.0.3'
        };
    };

    /**
     * Parse the count line of a V2000 format molFile.  Returns an object:
     *
     *     {
     *       'atoms': 15,
     *       'bonds': 14,
     *       'chiral': 1,
     *       'mLines': 999,
     *       'version': ' V2000'
     *     }
     *
     * Note that mLines should always be 999 for modern molfiles,
     * to signal the mLines value is ignored.  M lines are read until 'M  END'.
     *
     * Note that version will contain leading spaces if the version string
     * is shorter than the 6 bytes alloted.
     *
     * @method parseCountLine
     * @param {String} line count line to parse
     * @return {Object} data from the line
     */
    parser.parseCountLine = function parseCountLine(line) {
        var parsed = {};

        parsed.atoms = parseInt(line.slice(0, 3), 10);
        parsed.bonds = parseInt(line.slice(3, 6), 10);
        // atom lists: 6-9
        // obsolete:   9-12
        parsed.chiral = parseInt(line.slice(12, 15), 10);
        // stexts:    15-18
        // obsolete:  18-21
        // obsolete:  21-24
        // obsolete:  24-27
        // obsolete:  27-30
        parsed.mLines = parseInt(line.slice(30, 33), 10);
        parsed.version = line.slice(33, 39);

        if (parsed.version !== " V2000") {
            throw new Error("Unsupported molfile version '" + parsed.version + "'");
        }

        return parsed;
    };

    /**
     Parses an atom line.  Return value is an object:

          {
             'x': 0.0,
             'y': 0.0,
             'z': 0.0,
             'elname': 'Hf'
             'massDiff': 0,
             'chargeCode': 0,
             'valenceCode': 0,
           }

     Note that massDiff, chargeCode and valenceCode should be ignored if there
     are isotope, charge, or radical entries in the property table which
     follows the atom and bond tables.

     It is easier to read the isotope, charge, and radical information
     from the properties than to interpret the codes.

     Mass difference is an integral difference from the periodic table mass,
     and is in the range -3..4

     Charge code should be interpreted as follows:

     | Code   |  Meaning |
     |-------|---------|
     |      0 | no charge (0)|
     |      1 |       +3 |
     |      2 |       +2 |
     |      3 |       +1 |
     |      4 | doublet (radical) |
     |      5 |       -1 |
     |      6 |       -2 |
     |      7 |       -3 |

     Valence code should be interpreted as follows:

     | Code   |  Meaning |
     |-------|---------|
     |      0 | default valence |
     |   1-14 | valence = code |
     |    15 |  valence = 0 |

     @method parseAtomLine
     @param {String} line the line to parse
     @return {Object} data from the line
     */
    parser.parseAtomLine = function (line) {
        var parsed = { x: 0, y: 0, z: 0 };

        parsed.x = parseFloat(line.slice(0, 10));
        parsed.y = parseFloat(line.slice(10, 20));
        parsed.z = parseFloat(line.slice(20, 30));
        // 31 is declared as a space
        parsed.elname = line.slice(31, 34).trim();
        parsed.massDiff = parseInt(line.slice(34, 36), 10);
        parsed.chargeCode = parseInt(line.slice(36, 39), 10);
        // several obsolete fields
        parsed.valenceCode = parseInt(line.slice(48, 51), 10);
        // more obsolete fields

        return parsed;
    };

    /**
     Parses a bond line.  Return value is an object:

          {
            'from': 3,
            'to': 4,
            'bondType': 1
          }

     bondType is a code, and should be interpreted as follows:

     | Code | Meaning |
     |------|---------|
     | 1 | single |
     | 2 | double |
     | 3 | triple |
     | 4 | aromatic |
     | 5 | single or double |
     | 6 | single or aromatic |
     | 7 | double or aromatic |
     | 8 | any |

     Codes 5-8 are can only be present when the file describes a
     search.  They are never present in a molecule description.

     @method parseBondLine
     @param {String} line the line to parse
     @return {Object} data from the line
     */
    parser.parseBondLine = function (line) {
        var parsed = { from: 0, to: 0, bondType: 0 };

        parsed.from = parseInt(line.slice(0, 3), 10);
        parsed.to = parseInt(line.slice(3, 6), 10);
        parsed.bondType = parseInt(line.slice(6, 9), 10);
        // several other fields, all obsolete

        return parsed;
    };

    parser.addKeyValue = function addKeyValue(values, part) {
        var key = parseInt(part.slice(0, 4), 10),
            value = parseInt(part.slice(4, 8), 10);
        values[key] = value;
    };

    /**
     Parses a property line

     @method parseProperty
     @param {String} line the line to parse
     @return {Object} data from the line
     */
    parser.parseProperty = function parseProperty(line) {
        if (/^M {2}END$/.test(line)) {
            return null;
        }

        var parsed = {},
            values = {},
            i,
            slices = [],
            offset;

        parsed.mode = line.slice(3, 6);
        parsed[parsed.mode] = values;
        parsed.count = parseInt(line.slice(6, 9), 10);

        for (i = 0; i < parsed.count; i += 1) {
            offset = 9 + i * 8;
            slices.push(line.slice(offset, offset + 8));
        }

        slices.forEach(function (slice) {
            parser.addKeyValue(values, slice);
        });

        return parsed;
    };

    parser.makeDate = function makeDate(line) {
        var month = parseInt(line.slice(0, 2), 10),
            day = line.slice(2, 4),
            year = parseInt(line.slice(4, 6), 10),
            hour = line.slice(6, 8),
            minute = line.slice(8, 10);

        if (year < 80) {
            year += 2000;
        }

        return new Date(year, month - 1, day, hour, minute);
    };

    parser.parseMolHeader = function parseMolHeader(header) {
        var parsed = {},
            lines = header.split('\n');

        parsed.name = lines[0];
        parsed.initials = lines[1].slice(0, 2);
        parsed.software = lines[1].slice(2, 10);
        parsed.date = parser.makeDate(lines[1].slice(10, 20));
        parsed.comment = lines[2];

        return parsed;
    };

    parser.parseDataItem = function parseDataItem(string) {
        var parsed = {},
            match,
            from,
            to;

        match = /<([\-A-Za-z_\.]+)>/.exec(string);
        parsed.name = match ? match[1] : '';

        from = string.indexOf('\n');
        to = string.length;
        parsed.value = string.slice(from + 1, to);

        return parsed;
    };

    parser.splitDataItems = function splitDataItems(string) {
        // between M  END and $$$, split on double newline
        return string.split('\n\n');
    };

    /**
     Prescan the molfile data, find the newlines and boundaries of various
     blocks.  Returns an object:

         {
           newlines: [],     // offset of each newline
           firstM: 120,      // beginning of properties
           lastM: 154,       // end of properties
           firstAngle: 230,  // beginning of data
           sectionEnd: 500   // end of data
         }

     @method prescanMol
     @param {String} mol the molfile data
     @return {Object} object containing useful offsets
     */
    parser.prescanMol = function prescanMol(mol) {
        var scan = { newlines: [] },
            start = 0,
            len = mol.length,
            found = -1,
            line;

        while (start < len) {
            found = mol.indexOf('\n', start);
            if (found === -1) {
                break;
            }
            scan.newlines.push(found);

            line = mol.slice(start, found);

            if (line.match(/^M {2}END/)) {
                scan.lastM = start;
            }
            if (line.match(/^M/) && !scan.firstM) {
                scan.firstM = start;
            }
            if (line.match(/^>/) && !scan.firstAngle) {
                scan.firstAngle = start;
            } else if (line.match(/^\$\$\$/)) {
                scan.sectionEnd = start;
            }

            start = found + 1;
        }

        return scan;
    };

    function getAtoms(mol, scan, parsed) {
        var begin = scan.newlines[3] + 1,
            end = scan.newlines[3 + parsed.countLine.atoms],
            atomLines = mol.slice(begin, end);

        return atomLines.split('\n');
    }

    function getBonds(mol, scan, parsed) {
        var startLine = 3 + parsed.countLine.atoms,
            begin = scan.newlines[startLine] + 1,
            end = scan.newlines[startLine + parsed.countLine.bonds];

        return mol.slice(begin, end).split('\n');
    }

    function getProperties(mol, scan) {
        var begin = scan.firstM,
            end = scan.lastM;

        return mol.slice(begin, end).split('\n');
    }

    function getData(mol, scan) {
        var begin = scan.firstAngle,
            end = scan.sectionEnd;

        return mol.slice(begin, end).split('\n\n');
    }

    function squashProperty(accum, property) {
        var mode = property.mode,
            source,
            target;

        if (!accum[mode]) {
            accum[mode] = property[mode];
        } else {
            target = accum[mode];
            source = property[mode];

            Object.keys(source).forEach(function (key) {
                target[key] = source[key];
            });
        }

        return accum;
    }
    parser.squashProperty = squashProperty;

    function squashData(accum, data) {
        if (data.name) {
            accum[data.name] = data.value;
        }

        return accum;
    }

    /**
     Parses a V2000 molfile record and returns an Object containing
     the data therein.

          {
              atoms: [
                { x: 0.0, y: 0.0, z: 0.0, elname: 'Hf' }
                ...
              ],
              bonds: [
                  { 3, 4, 1 },
                  ...
              }
              properties: {
                  CHG: {
                     3: -1
                  }
                  ISO: {
                  }
                  RAD: {
                  }
              }
              data: {
                ID: 'zwitterions_2'
             }
           }

     @method parseMol
     @param {String} mol the complete molfile, including newlines
     @return {Object} an object representing the contents of the molfile
     */
    parser.parseMol = function parseMol(mol) {
        var parsed = {},
            scan = parser.prescanMol(mol),
            headerEnd = scan.newlines[2] + 1,
            countLineEnd = scan.newlines[3] + 1;

        parsed.header = parser.parseMolHeader(mol.slice(0, headerEnd));

        parsed.countLine = parser.parseCountLine(mol.slice(headerEnd, countLineEnd));

        parsed.atoms = getAtoms(mol, scan, parsed).map(parser.parseAtomLine);

        parsed.bonds = getBonds(mol, scan, parsed).map(parser.parseBondLine);

        // now read properties
        parsed.properties = getProperties(mol, scan).map(parser.parseProperty)
            .reduce(squashProperty, {});

        parsed.data = getData(mol, scan).map(parser.parseDataItem)
            .reduce(squashData, {});

        return parsed;
    };

    /**
     A Transform stream that splits an SDF file into individual MOL
     file segments and pushes the segments to the output of the stream

     @class SDFTransform
     */

    /**
     Constructs a new SDFTransform

     @constructor
     @method SDFTransform
     @return {SDFTransform}
     */
    function SDFTransform() {
        stream.Transform.call(this);

        this.buffer = "";
    }
    util.inherits(SDFTransform, stream.Transform);

    /*jslint nomen:true, unparam:true*/
    SDFTransform.prototype._transform = function (chunk, unused, callback) {
        this.buffer += chunk;

        var parts = this.buffer.split(/\$\$\$\$\r?\n/m);

        // remove last (partial) sdf file
        this.buffer = parts.pop();

        parts.forEach(function (part) {
            this.push(part);
        }.bind(this));

        callback(null);
    };

    SDFTransform.prototype._flush = function (callback) {
        if (this.buffer.length > 1) {
            this.push(this.buffer);
        }

        callback(null);
    };
    /*jslint nomen:false, unparam:true*/

    parser.SDFTransform = SDFTransform;

    /**
     A Writable stream that splits an SDF file into individual MOL file segments
     suitable for passing to parseMol.

     Output is via callback.  See SDFTransform for output via Streams API

     @class SDFSplitter
     */

    /**

     @constructor
     @method SDFSplitter
     @param {Function} callback function to call with molfile data
     @return {SDFSplitter} a Writable stream which calls the supplied callback
     once per molfile in the supplied SDFSplitter stream
     */
    function SDFSplitter(handler) {
        parser.SDFTransform.call(this);

        this.on('data', function (chunk) {
            handler(String(chunk));
        });
    }
    util.inherits(SDFSplitter, SDFTransform);

    parser.SDFSplitter = SDFSplitter;

}());
<|endoftext|>


<commit_before>var debug       = require('debug')('routes:api:v1');
var request     = require('superagent-promise');
var assert      = require('assert');
var base        = require('taskcluster-base');

/** API end-point for version v1/ */
var api = new base.API({
  title:      "Authentication API",
  description: [
    "Authentication related API end-points for taskcluster."
  ].join('\n')
});

// Export API
module.exports = api;

/** Get authorized scopes for a given client */
api.declare({
  method:     'get',
  route:      '/client/:clientId/scopes',
  name:       'inspect',
  input:      null,
  output:     "http://schemas.taskcluster.net/auth/v1/client-scopes-response.json#",
  scopes:     ['auth:inspect', 'auth:credentials'],
  title:      "Get Client Authorized Scopes",
  description: [
    "Returns the scopes the client is authorized to access and the date-time",
    "where the clients authorization is set to expire.",
    "",
    "This API end-point allows you inspect clients without getting access to",
    "credentials, as provide by the `getCredentials` request below."
  ].join('\n')
}, function(req, res) {
  return this.Client.load(req.params.clientId).then(function(client) {
    return res.reply({
      clientId:     client.clientId,
      scopes:       client.scopes,
      expires:      client.expires.toJSON()
    });
  });
});

/** Get credentials for a given client */
api.declare({
  method:     'get',
  route:      '/client/:clientId/credentials',
  name:       'getCredentials',
  input:      null,
  output:     "http://schemas.taskcluster.net/auth/v1/client-credentials-response.json#",
  scopes:     ['auth:credentials'],
  title:      "Get Client Credentials",
  description: [
    "Returns the clients `accessToken` as needed for verifying signatures.",
    "This API end-point also returns the list of scopes the client is",
    "authorized for and the date-time where the client authorization expires",
    "",
    "Remark, **if you don't need** the `accessToken` but only want to see what",
    "scopes a client is authorized for, you should use the `getScopes`",
    "function described above."
  ].join('\n')
}, function(req, res) {
  return this.Client.load(req.params.clientId).then(function(client) {
    return res.reply({
      clientId:     client.clientId,
      accessToken:  client.accessToken,
      scopes:       client.scopes,
      expires:      client.expires.toJSON()
    });
  });
});
<commit_msg>Fixed API<commit_after>var debug       = require('debug')('routes:api:v1');
var request     = require('superagent-promise');
var assert      = require('assert');
var base        = require('taskcluster-base');

/** API end-point for version v1/ */
var api = new base.API({
  title:      "Authentication API",
  description: [
    "Authentication related API end-points for taskcluster."
  ].join('\n')
});

// Export API
module.exports = api;

/** Get authorized scopes for a given client */
api.declare({
  method:     'get',
  route:      '/client/:clientId/scopes',
  name:       'inspect',
  input:      undefined,
  output:     "http://schemas.taskcluster.net/auth/v1/client-scopes-response.json#",
  scopes:     ['auth:inspect', 'auth:credentials'],
  title:      "Get Client Authorized Scopes",
  description: [
    "Returns the scopes the client is authorized to access and the date-time",
    "where the clients authorization is set to expire.",
    "",
    "This API end-point allows you inspect clients without getting access to",
    "credentials, as provide by the `getCredentials` request below."
  ].join('\n')
}, function(req, res) {
  return this.Client.load(req.params.clientId).then(function(client) {
    return res.reply({
      clientId:     client.clientId,
      scopes:       client.scopes,
      expires:      client.expires.toJSON()
    });
  });
});

/** Get credentials for a given client */
api.declare({
  method:     'get',
  route:      '/client/:clientId/credentials',
  name:       'getCredentials',
  input:      undefined,
  output:     "http://schemas.taskcluster.net/auth/v1/client-credentials-response.json#",
  scopes:     ['auth:credentials'],
  title:      "Get Client Credentials",
  description: [
    "Returns the clients `accessToken` as needed for verifying signatures.",
    "This API end-point also returns the list of scopes the client is",
    "authorized for and the date-time where the client authorization expires",
    "",
    "Remark, **if you don't need** the `accessToken` but only want to see what",
    "scopes a client is authorized for, you should use the `getScopes`",
    "function described above."
  ].join('\n')
}, function(req, res) {
  return this.Client.load(req.params.clientId).then(function(client) {
    return res.reply({
      clientId:     client.clientId,
      accessToken:  client.accessToken,
      scopes:       client.scopes,
      expires:      client.expires.toJSON()
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Created by mtorres on 7/05/17.
 */

var express = require('express');
var router = express.Router();
var db_conf = require('../db_conf');

var isAuthenticated = function (req, res, next) {
    if (req.isAuthenticated()){
        return next();
    }

    res.redirect('/');
};

// Ventas por periodo
router.get('/sales/data.json', isAuthenticated, function (req, res) {

    const period = {
        start_date : '',//req.query.start_date,
        end_date : '' //req.query.end_date
    };

    db_conf.db.manyOrNone('select fecha_venta, forma_pago, count(*) as conteo, sum(precio_venta) as total from ventas group by id_tienda, forma_pago, fecha_venta',[
        period.start_date, period.end_date
    ]).then(function (data) {

        res.jsonp({
            metadata : { period : period },
            data : data
        });

    }).catch(function (error) {
        console.log(error);
        res.jsonp(error);
    });

});

// Más vendidos
router.get('/best-selling/data.json').then(function(req, res){
    /* *
     * Query striing:
     * start_date
     * end_date
     * group_by: global, store
     */

});

// Saldos con proveedores
router.get('/suppliers/data.json', function(req, res){

    db_conf.db.manyOrNone('select * from suppliers').then(function (suppliers) {
        res.jsonp(suppliers );
    }).catch(function (error) {
        console.log(error);
        res.jsonp(error);
    })

});

// Top empleados
router.get('/employees/data.json').then(function (req, res) {
    /* *
    * Query string:
    * group_by: global, store
    * */

});

router.get('/barchart/data.json', function (req, res) {
    const data = [
        {letter: 'A', frequency: .08167},
        {letter: 'B', frequency: .01492},
        {letter: 'C', frequency: .02782},
        {letter: 'D', frequency: .04253},
        {letter: 'E', frequency: .12702},
        {letter: 'F', frequency: .02288},
        {letter: 'G', frequency: .02015},
        {letter: 'H', frequency: .06094},
        {letter: 'I', frequency: .06966},
        {letter: 'J', frequency: .00153},
        {letter: 'K', frequency: .00772},
        {letter: 'L', frequency: .04025},
        {letter: 'M', frequency: .02406},
        {letter: 'N', frequency: .06749},
        {letter: 'O', frequency: .07507},
        {letter: 'P', frequency: .01929},
        {letter: 'Q', frequency: .00095},
        {letter: 'R', frequency: .05987},
        {letter: 'S', frequency: .06327},
        {letter: 'T', frequency: .09056},
        {letter: 'U', frequency: .02758},
        {letter: 'V', frequency: .00978},
        {letter: 'W', frequency: .02360},
        {letter: 'X', frequency: .00150},
        {letter: 'Y', frequency: .01974},
        {letter: 'Z', frequency: .00074}
    ];
    res.jsonp(data)
});

module.exports = router;<commit_msg>charts<commit_after>/**
 * Created by mtorres on 7/05/17.
 */

var express = require('express');
var router = express.Router();
var db_conf = require('../db_conf');

var isAuthenticated = function (req, res, next) {
    if (req.isAuthenticated()){
        return next();
    }

    res.redirect('/');
};

// Ventas por periodo
router.get('/sales/data.json', isAuthenticated, function (req, res) {

    //por tienda ...
    const options = {
        start_date : '',//req.query.start_date,
        end_date : '' , //req.query.end_date
        aggregation : 'store'
    };

    db_conf.db.manyOrNone('select fecha_venta, forma_pago, count(*) as conteo, sum(precio_venta) as total from ventas group by id_tienda, forma_pago, fecha_venta',[
        options.start_date, options.end_date
    ]).then(function (data) {

        res.jsonp({
            metadata : { period : options },
            data : data
        });

    }).catch(function (error) {
        console.log(error);
        res.jsonp(error);
    });

});

// Más vendidos
router.get('/best-selling/data.json').then(function(req, res){
    /* *
     * Query string:
     * start_date
     * end_date
     * aggregation: global || store
     */

});

// Saldos con proveedores
router.get('/suppliers/data.json', function(req, res){

    db_conf.db.manyOrNone('select * from suppliers').then(function (suppliers) {
        res.jsonp(suppliers );
    }).catch(function (error) {
        console.log(error);
        res.jsonp(error);
    })

});

// Top empleados
router.get('/employees/data.json').then(function (req, res) {
    /* *
    * Query string:
    * start_date
    * end_date
    * aggregation: global || store
    * */

});

router.get('/barchart/data.json', function (req, res) {
    const data = [
        {letter: 'A', frequency: .08167},
        {letter: 'B', frequency: .01492},
        {letter: 'C', frequency: .02782},
        {letter: 'D', frequency: .04253},
        {letter: 'E', frequency: .12702},
        {letter: 'F', frequency: .02288},
        {letter: 'G', frequency: .02015},
        {letter: 'H', frequency: .06094},
        {letter: 'I', frequency: .06966},
        {letter: 'J', frequency: .00153},
        {letter: 'K', frequency: .00772},
        {letter: 'L', frequency: .04025},
        {letter: 'M', frequency: .02406},
        {letter: 'N', frequency: .06749},
        {letter: 'O', frequency: .07507},
        {letter: 'P', frequency: .01929},
        {letter: 'Q', frequency: .00095},
        {letter: 'R', frequency: .05987},
        {letter: 'S', frequency: .06327},
        {letter: 'T', frequency: .09056},
        {letter: 'U', frequency: .02758},
        {letter: 'V', frequency: .00978},
        {letter: 'W', frequency: .02360},
        {letter: 'X', frequency: .00150},
        {letter: 'Y', frequency: .01974},
        {letter: 'Z', frequency: .00074}
    ];
    res.jsonp(data)
});

module.exports = router;<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict';

const EventEmitter = require('events');
const async = require('async');
const _ = require('lodash');
const arrivals = require('arrivals');
const debug = require('debug')('phases');

module.exports = phaser;

function phaser(phaseSpecs) {
  let ee = new EventEmitter();

  let tasks = _.map(phaseSpecs, function(spec, i) {
    if (!spec.index) {
      spec.index = i;
    }

    if (spec.arrivalRate && !spec.rampTo) {
      spec.mode = spec.mode || 'uniform';
    }

    if (spec.pause) {
      return createPause(spec, ee);
    } else if (spec.rampTo && spec.arrivalRate) {
      return createRamp(spec, ee);
    } else if (spec.arrivalCount) {
      return createArrivalCount(spec, ee);
    } else if (spec.arrivalRate) {
      return createArrivalRate(spec, ee);
    } else {
      console.log('Unknown phase spec\n%j\nThis should not happen', spec);
    }
  });

  ee.run = function() {
    async.series(tasks, function(err) {
      if (err) {
        debug(err);
      }

      ee.emit('done');
    });
  };

  return ee;
}

function createPause(spec, ee) {
  const duration = spec.pause * 1000;
  const task = function(callback) {
    ee.emit('phaseStarted', spec);
    setTimeout(function() {
      ee.emit('phaseCompleted', spec);
      return callback(null);
    }, duration);
  };
  return task;
}

function createRamp(spec, ee) {
  const incBy = (spec.rampTo - spec.arrivalRate) / (spec.duration - 1);
  const stepCount = spec.duration;
  const arrivalRate = spec.arrivalRate;

  debug('rampTo: incBy = %s', incBy);
  let steps = _.map(_.range(0, stepCount), function(i) {
    return function(callback) {
      let tick = 1000 / (arrivalRate + i * incBy);
      debug('rampTo: tick = %s', tick);
      let p = arrivals.uniform.process(tick, 1000);
      p.on('arrival', function() {
        ee.emit('arrival');
      });
      p.on('finished', function() {
        return callback(null);
      });
      p.start();
    };
  });

  const task = function task(callback) {
    ee.emit('phaseStarted', spec);
    async.series(steps, function(err) {
      if (err) {
        debug(err);
      }
      ee.emit('phaseCompleted', spec);
      return callback(null);
    });
  };

  return task;
}

function createArrivalCount(spec, ee) {
  const task = function(callback) {
    ee.emit('phaseStarted', spec);
    const duration = spec.duration * 1000;
    const interval = duration / spec.arrivalCount;
    const p = arrivals.uniform.process(interval, duration);
    p.on('arrival', function() {
      ee.emit('arrival');
    });
    p.on('finished', function() {
      ee.emit('phaseCompleted', spec);
      return callback(null);
    });
    p.start();
  };

  return task;
}

function createArrivalRate(spec, ee) {
  const task = function(callback) {
    ee.emit('phaseStarted', spec);
    const ar = 1000 / spec.arrivalRate;
    const duration = spec.duration * 1000;
    debug('creating a %s process for arrivalRate', spec.mode);
    const p = arrivals[spec.mode].process(ar, duration);
    p.on('arrival', function() {
      ee.emit('arrival');
    });
    p.on('finished', function() {
      ee.emit('phaseCompleted', spec);
      return callback(null);
    });
    p.start();
  };

  return task;
}
<commit_msg>Make phase definitions with arrivalRate = 0 work<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict';

const EventEmitter = require('events');
const async = require('async');
const _ = require('lodash');
const isUndefined = _.isUndefined;
const arrivals = require('arrivals');
const debug = require('debug')('phases');

module.exports = phaser;

function phaser(phaseSpecs) {
  let ee = new EventEmitter();

  let tasks = _.map(phaseSpecs, function(spec, i) {
    if (isUndefined(spec.index)) {
      spec.index = i;
    }

    if (!isUndefined(spec.arrivalRate) && isUndefined(spec.rampTo)) {
      spec.mode = spec.mode || 'uniform';
    }

    if (!isUndefined(spec.pause)) {
      return createPause(spec, ee);
    }

    if (!isUndefined(spec.arrivalCount)) {
      return createArrivalCount(spec, ee);
    }

    if (!isUndefined(spec.arrivalRate)) {

      // If arrivalRate is zero, it's the same as a pause:
      if (spec.arrivalRate === 0) {
        return createPause(
          Object.assign(
            spec, { pause: spec.duration }),
          ee);
      }

      // If it's a ramp, create that:
      if (!isUndefined(spec.rampTo)) {
        return createRamp(spec, ee);
      }

      // Otherwise it's a plain arrival phase:
      return createArrivalRate(spec, ee);
    }

    console.log('Unknown phase spec\n%j\nThis should not happen', spec);
  });

  ee.run = function() {
    async.series(tasks, function(err) {
      if (err) {
        debug(err);
      }

      ee.emit('done');
    });
  };

  return ee;
}

function createPause(spec, ee) {
  const duration = spec.pause * 1000;
  const task = function(callback) {
    ee.emit('phaseStarted', spec);
    setTimeout(function() {
      ee.emit('phaseCompleted', spec);
      return callback(null);
    }, duration);
  };
  return task;
}

function createRamp(spec, ee) {
  const incBy = (spec.rampTo - spec.arrivalRate) / (spec.duration - 1);
  const stepCount = spec.duration;
  const arrivalRate = spec.arrivalRate;

  debug('rampTo: incBy = %s', incBy);
  let steps = _.map(_.range(0, stepCount), function(i) {
    return function(callback) {
      let tick = 1000 / (arrivalRate + i * incBy);
      debug('rampTo: tick = %s', tick);
      let p = arrivals.uniform.process(tick, 1000);
      p.on('arrival', function() {
        ee.emit('arrival');
      });
      p.on('finished', function() {
        return callback(null);
      });
      p.start();
    };
  });

  const task = function task(callback) {
    ee.emit('phaseStarted', spec);
    async.series(steps, function(err) {
      if (err) {
        debug(err);
      }
      ee.emit('phaseCompleted', spec);
      return callback(null);
    });
  };

  return task;
}

function createArrivalCount(spec, ee) {
  const task = function(callback) {
    ee.emit('phaseStarted', spec);
    const duration = spec.duration * 1000;
    const interval = duration / spec.arrivalCount;
    const p = arrivals.uniform.process(interval, duration);
    p.on('arrival', function() {
      ee.emit('arrival');
    });
    p.on('finished', function() {
      ee.emit('phaseCompleted', spec);
      return callback(null);
    });
    p.start();
  };

  return task;
}

function createArrivalRate(spec, ee) {
  const task = function(callback) {
    ee.emit('phaseStarted', spec);
    const ar = 1000 / spec.arrivalRate;
    const duration = spec.duration * 1000;
    debug('creating a %s process for arrivalRate', spec.mode);
    const p = arrivals[spec.mode].process(ar, duration);
    p.on('arrival', function() {
      ee.emit('arrival');
    });
    p.on('finished', function() {
      ee.emit('phaseCompleted', spec);
      return callback(null);
    });
    p.start();
  };

  return task;
}
<|endoftext|>


<commit_before>
/*
 * GET home page.
 */
var mongo = require('mongodb');
var appconf = require('konphyg')(__dirname + '/../config')('conf');

exports.byid = function(req, res){
  var event_id = req.params.id;
  var mongo_client = require('mongodb').MongoClient;
  var mongoUri = process.env.MONGOLAB_URI ||
    process.env.MONGOHQ_URL ||
    appconf.mongodb_url;

  mongo_client.connect(mongoUri, function (err, db) {
    var collection = db.collection('events');
    collection.findOne({event_id: event_id}, function(err, item) {
          if(err)
          {
              console.log(err);
              res.render('index', { title: "iCalGen.js" });
          }
          else
          {
              res.setHeader('Content-Type', 'text/calendar');
              res.setHeader('Content-Disposition', 'attachment; filename="event.ics"');
              res.send(item.ics_string);
          }
      });
  });
};
<commit_msg>Set event content to QR code<commit_after>
/*
 * GET home page.
 */
var mongo = require('mongodb');
var appconf = require('konphyg')(__dirname + '/../config')('conf');

exports.byid = function(req, res){
  var event_id = req.params.id;
  var mongo_client = require('mongodb').MongoClient;
  var mongoUri = process.env.MONGOLAB_URI ||
    process.env.MONGOHQ_URL ||
    appconf.mongodb_url;

  mongo_client.connect(mongoUri, function (err, db) {
    var collection = db.collection('events');
    collection.findOne({event_id: event_id}, function(err, item) {
          if(err)
          {
              console.log(err);
              res.render('index', { title: "iCalGen.js" });
          }
          else
          {
              //res.setHeader('Content-Type', 'text/calendar');
              //res.setHeader('Content-Disposition', 'attachment; filename="event.ics"');
              res.send(item.ics_string);
          }
      });
  });
};
<|endoftext|>


<commit_before>var request = require('request'),
	async = require("async"),
	moment = require('moment'),
	helper = require('../routes/helper');

exports.repoInfo = function(url, sucCb, errCb) {
	var issuesData = {};
	request({
		uri: url,
		method: 'GET',
		headers: {
			'User-Agent': 'request'
		}
	}, function (error, response, body) {
		if (!error) {
			var issues = JSON.parse(response.body);
			var openIssues = 0;
			var openedToday = 0;
			var openedWeek = 0;
			var openedWeekAgo = 0;
			var curDate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
			async.each(issues, function(issue, callback){
				// Open Issues
				if(issue.state == 'open'){
					openIssues+=1;
				}
				// Open Issues in Last 24 hours
				var issueCreated = new Date(issue.created_at);

				var issueCreated = moment(new Date(issue.created_at)).format("YYYY-MM-DD HH:mm:ss");

				var remainingHours = moment(curDate).diff(issueCreated, 'hours');
				if(remainingHours <= 24) {
					openedToday+=1;
				}
				var remainingDays = moment(curDate).diff(issueCreated, 'days');

				if(remainingDays>0 && remainingDays<8){
					openedWeek+=1;
				}
				if(remainingDays>7){
					openedWeekAgo+=1;
				}

				callback();
			}, function(err) {
				console.log('return err 1  - '+ typeof err);
				console.log('return err val 1  - '+ err);
				var link = response.headers.link;
				var soFarData = {};
				soFarData['openIssues'] = 0;
				soFarData['openedToday'] = 0;
				soFarData['openedWeek'] = 0;
				soFarData['openedWeekAgo'] = 0;
				if(link) {
					var re = /\<((?:(?!\>).)+)/img;
					// console.log("split", link.split(re));
					z = link.replace(/[>";<]/g,"").split(re);
					// console.log('z = '+ z);
					nextUrl = z[0].split(", ")[0].split(" ")[0];
					lastUrl = z[0].split(", ")[1].split(" ")[0];
					nextPageNum = z[0].split(", ")[0].split(" ")[0].split("page=")[1];
					lastPageNum = z[0].split(", ")[1].split(" ")[0].split("page=")[1];

					soFarData['openIssues']+=openIssues;
					soFarData['openedToday']+=openedToday;
					soFarData['openedWeek']+=openedWeek;
					soFarData['openedWeekAgo']+=openedWeekAgo;
					for (var i = nextPageNum; i <= lastPageNum; i++) {
						 var nextUrl = z[0].split(", ")[0].split(" ")[0].split("page=")[0] + 'page=' + i;
						// console.log('soFarData 1 - '+ JSON.stringify(soFarData));
						console.log('nextUrl 1 - '+ nextUrl);
						var subData = helper.subRepoInfo(nextUrl, soFarData);
						if(i == lastPageNum) {
							console.log('last page');
							return sucCb(soFarData);
						}
					};
				} else {
					// Nothing
				}
			});
		} else {
			console.log('error - '+ error);
			return errCb(error);
		}
	});
}

exports.subRepoInfo = function(subUrl, soFarData) {
	request({
		uri: subUrl,
		method: 'GET',
		headers: {
			'access_token': token,
			'User-Agent': 'request'
		}
	}, function (error, response, body) {
		if (!error) {
			request({
				uri: subUrl,
				method: 'GET',
				headers: {
					'User-Agent': 'request'
				}
			}, function (error, response, body) {
				if (!error) {
					var issues = JSON.parse(response.body);
					console.log('response headers - '+ JSON.parse(response.headers));
					var openIssues = 0;
					var openedToday = 0;
					var openedWeek = 0;
					var openedWeekAgo = 0;
					var curDate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
					async.each(issues, function(issue, callback){
						// Open Issues
						if(issue.state == 'open'){
							soFarData['openIssues']+=1;
						}
						// Open Issues in Last 24 hours
						var issueCreated = new Date(issue.created_at);

						var issueCreated = moment(new Date(issue.created_at)).format("YYYY-MM-DD HH:mm:ss");

						var remainingHours = moment(curDate).diff(issueCreated, 'hours');
						if(remainingHours <= 24) {
							soFarData['openedToday']+=1;
						}
						var remainingDays = moment(curDate).diff(issueCreated, 'days');

						if(remainingDays>0 && remainingDays<8){
							soFarData['openedWeek']+=1;
						}
						if(remainingDays>7){
							soFarData['openedWeekAgo']+=1;
						}
						callback();
					},
					function(err) {
						console.log('return err 2 - '+ err);
						// Final return
						console.log('soFarData - '+ JSON.stringify(soFarData));
						return soFarData;
					});
				} else {
					console.log('error - '+ error);
					return error;
				}
			});
		} else {
			console.log('error - '+ error);
			return error;
		}
	});
}

module.exports = exports;<commit_msg>token removed<commit_after>var request = require('request'),
	async = require("async"),
	moment = require('moment'),
	helper = require('../routes/helper');

exports.repoInfo = function(url, sucCb, errCb) {
	var issuesData = {};
	request({
		uri: url,
		method: 'GET',
		headers: {
			'User-Agent': 'request'
		}
	}, function (error, response, body) {
		if (!error) {
			var issues = JSON.parse(response.body);
			var openIssues = 0;
			var openedToday = 0;
			var openedWeek = 0;
			var openedWeekAgo = 0;
			var curDate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
			async.each(issues, function(issue, callback){
				// Open Issues
				if(issue.state == 'open'){
					openIssues+=1;
				}
				// Open Issues in Last 24 hours
				var issueCreated = new Date(issue.created_at);

				var issueCreated = moment(new Date(issue.created_at)).format("YYYY-MM-DD HH:mm:ss");

				var remainingHours = moment(curDate).diff(issueCreated, 'hours');
				if(remainingHours <= 24) {
					openedToday+=1;
				}
				var remainingDays = moment(curDate).diff(issueCreated, 'days');

				if(remainingDays>0 && remainingDays<8){
					openedWeek+=1;
				}
				if(remainingDays>7){
					openedWeekAgo+=1;
				}

				callback();
			}, function(err) {
				console.log('return err 1  - '+ typeof err);
				console.log('return err val 1  - '+ err);
				var link = response.headers.link;
				var soFarData = {};
				soFarData['openIssues'] = 0;
				soFarData['openedToday'] = 0;
				soFarData['openedWeek'] = 0;
				soFarData['openedWeekAgo'] = 0;
				if(link) {
					var re = /\<((?:(?!\>).)+)/img;
					// console.log("split", link.split(re));
					z = link.replace(/[>";<]/g,"").split(re);
					// console.log('z = '+ z);
					nextUrl = z[0].split(", ")[0].split(" ")[0];
					lastUrl = z[0].split(", ")[1].split(" ")[0];
					nextPageNum = z[0].split(", ")[0].split(" ")[0].split("page=")[1];
					lastPageNum = z[0].split(", ")[1].split(" ")[0].split("page=")[1];

					soFarData['openIssues']+=openIssues;
					soFarData['openedToday']+=openedToday;
					soFarData['openedWeek']+=openedWeek;
					soFarData['openedWeekAgo']+=openedWeekAgo;
					for (var i = nextPageNum; i <= lastPageNum; i++) {
						 var nextUrl = z[0].split(", ")[0].split(" ")[0].split("page=")[0] + 'page=' + i;
						// console.log('soFarData 1 - '+ JSON.stringify(soFarData));
						console.log('nextUrl 1 - '+ nextUrl);
						var subData = helper.subRepoInfo(nextUrl, soFarData);
						if(i == lastPageNum) {
							console.log('last page');
							return sucCb(soFarData);
						}
					};
				} else {
					// Nothing
				}
			});
		} else {
			console.log('error - '+ error);
			return errCb(error);
		}
	});
}

exports.subRepoInfo = function(subUrl, soFarData) {
	request({
		uri: subUrl,
		method: 'GET',
		headers: {
			'User-Agent': 'request'
		}
	}, function (error, response, body) {
		if (!error) {
			request({
				uri: subUrl,
				method: 'GET',
				headers: {
					'User-Agent': 'request'
				}
			}, function (error, response, body) {
				if (!error) {
					var issues = JSON.parse(response.body);
					console.log('response headers - '+ JSON.parse(response.headers));
					var openIssues = 0;
					var openedToday = 0;
					var openedWeek = 0;
					var openedWeekAgo = 0;
					var curDate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
					async.each(issues, function(issue, callback){
						// Open Issues
						if(issue.state == 'open'){
							soFarData['openIssues']+=1;
						}
						// Open Issues in Last 24 hours
						var issueCreated = new Date(issue.created_at);

						var issueCreated = moment(new Date(issue.created_at)).format("YYYY-MM-DD HH:mm:ss");

						var remainingHours = moment(curDate).diff(issueCreated, 'hours');
						if(remainingHours <= 24) {
							soFarData['openedToday']+=1;
						}
						var remainingDays = moment(curDate).diff(issueCreated, 'days');

						if(remainingDays>0 && remainingDays<8){
							soFarData['openedWeek']+=1;
						}
						if(remainingDays>7){
							soFarData['openedWeekAgo']+=1;
						}
						callback();
					},
					function(err) {
						console.log('return err 2 - '+ err);
						// Final return
						console.log('soFarData - '+ JSON.stringify(soFarData));
						return soFarData;
					});
				} else {
					console.log('error - '+ error);
					return error;
				}
			});
		} else {
			console.log('error - '+ error);
			return error;
		}
	});
}

module.exports = exports;<|endoftext|>


<commit_before>const Issuer = require('../models/issuer');
const Program = require('../models/program');
const Badge = require('../models/badge');
const phrases = require('../lib/phrases');
const logger = require('../lib/logger');
/*
 * Administrative Pages
 */

exports.issuerIndex = function (req, res) {
  return res.render('admin/issuer-index.html', {
    page: 'issuer-index',
    badges: req.badges,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.issueBadge = function (req, res) {
  return res.render('admin/issue-badge.html', {
    page: 'issue-badge',
    badge: req.badge,
    results: req.flash('results').pop(),
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.login = function (req, res) {
  return res.render('admin/login.html', {
    page: 'login',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.newBadgeForm = function (req, res) {
  return res.render('admin/create-or-edit-badge.html', {
    page: 'new-badge',
    badge: new Badge,
    issuers: req.issuers,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.editBadgeForm = function (req, res) {
  return res.render('admin/create-or-edit-badge.html', {
    page: 'edit-badge',
    editing: true,
    badge: req.badge,
    issuers: req.issuers,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.newIssuerForm = function (req, res) {
  return res.render('admin/create-or-edit-issuer.html', {
    page: 'new-issuer',
    issuer: new Issuer,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.newProgramForm = function (req, res) {
  return res.render('admin/create-or-edit-program.html', {
    page: 'new-program',
    program: new Program,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.editProgramForm = function (req, res) {
  return res.render('admin/create-or-edit-program.html', {
    page: 'edit-program',
    editing: true,
    program:  req.program,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.editIssuerForm = function (req, res) {
  return res.render('admin/create-or-edit-issuer.html', {
    page: 'edit-issuer',
    editing: true,
    issuer: req.issuer,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.newBehaviorForm = function (req, res) {
  return res.render('admin/new-behavior.html', {
    page: 'new-behavior',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    badgeShortName: req.query['for']
  });
};

exports.badgeIndex = function (req, res) {
  return res.render('admin/badge-index.html', {
    page: 'home',
    issuers: req.issuers,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    badges: req.badges,
    behaviors: req.behaviors
  });
};

exports.showBadge = function (req, res) {
  return res.render('admin/show-badge.html', {
    page: 'edit-badge',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    defaultBehavior: req.query['behavior'],
    badge: req.badge,
    behaviors: req.behaviors
  });
};

exports.criteria = function criteria(req, res) {
  return res.render('public/criteria.html', {
    badge: req.badge,
    user: req.session.user,
  });
}

exports.all = function all(req, res) {
  return res.render('public/all.html', {
    badges: req.badges,
    user: req.session.user,
  });
};

exports.claim = function claim(req, res) {
  return res.render('public/claim.html', {
    csrf: req.session._csrf,
    code: req.query.code,
    missing: req.query.missing,
    user: req.session.user,
  });
};

exports.confirmClaim = function confirmClaim(req, res) {
  return res.render('public/confirm-claim.html', {
    csrf: req.session._csrf,
    code: req.body.code,
    claim: req.claim,
    badge: req.badge,
    user: req.session.user,
  });
};

exports.manageClaimCodes = function (req, res) {
  return res.render('admin/manage-claim-codes.html', {
    page: 'edit-badge',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    badge: req.badge,
    codes: req.badge.claimCodes,
    exampleCode: phrases(1)
  });
};

exports.showFlushDbForm = function (req, res) {
  return res.render('admin/flush-user-info.html', {
    page: 'flush',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf
  });
};

exports.userList = function userList(req, res, next) {
  return res.render('admin/user-list.html', {
    page: 'user-list',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    users: req.users
  });
};

exports.stats = function stats(req, res, next) {
  return res.render('admin/stats.html', {
    page: 'stats',
    stats: req.stats,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    users: req.users
  });
};

exports.notFound = function notFound(req, res, next) {
  res.status(404);
  return res.render('public/404.html', {});
};

exports.nextError = function nextError(req, res, next) {
  return next(new Error('some error'));
};

exports.errorHandler = function (err, req, res, next) {
  logger.error('there was an error at ' + req.url, err);
  res.status(500);
  return res.render('public/500.html');
};
<commit_msg>Add CSRF to all render routes.<commit_after>const Issuer = require('../models/issuer');
const Program = require('../models/program');
const Badge = require('../models/badge');
const phrases = require('../lib/phrases');
const logger = require('../lib/logger');
/*
 * Administrative Pages
 */

exports.issuerIndex = function (req, res) {
  return res.render('admin/issuer-index.html', {
    page: 'issuer-index',
    badges: req.badges,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.issueBadge = function (req, res) {
  return res.render('admin/issue-badge.html', {
    page: 'issue-badge',
    badge: req.badge,
    results: req.flash('results').pop(),
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.login = function (req, res) {
  return res.render('admin/login.html', {
    page: 'login',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.newBadgeForm = function (req, res) {
  return res.render('admin/create-or-edit-badge.html', {
    page: 'new-badge',
    badge: new Badge,
    issuers: req.issuers,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.editBadgeForm = function (req, res) {
  return res.render('admin/create-or-edit-badge.html', {
    page: 'edit-badge',
    editing: true,
    badge: req.badge,
    issuers: req.issuers,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.newIssuerForm = function (req, res) {
  return res.render('admin/create-or-edit-issuer.html', {
    page: 'new-issuer',
    issuer: new Issuer,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.newProgramForm = function (req, res) {
  return res.render('admin/create-or-edit-program.html', {
    page: 'new-program',
    program: new Program,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.editProgramForm = function (req, res) {
  return res.render('admin/create-or-edit-program.html', {
    page: 'edit-program',
    editing: true,
    program:  req.program,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.editIssuerForm = function (req, res) {
  return res.render('admin/create-or-edit-issuer.html', {
    page: 'edit-issuer',
    editing: true,
    issuer: req.issuer,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
  });
};

exports.newBehaviorForm = function (req, res) {
  return res.render('admin/new-behavior.html', {
    page: 'new-behavior',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    badgeShortName: req.query['for']
  });
};

exports.badgeIndex = function (req, res) {
  return res.render('admin/badge-index.html', {
    page: 'home',
    issuers: req.issuers,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    badges: req.badges,
    behaviors: req.behaviors
  });
};

exports.showBadge = function (req, res) {
  return res.render('admin/show-badge.html', {
    page: 'edit-badge',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    defaultBehavior: req.query['behavior'],
    badge: req.badge,
    behaviors: req.behaviors
  });
};

exports.criteria = function criteria(req, res) {
  return res.render('public/criteria.html', {
    badge: req.badge,
    user: req.session.user,
    csrf: req.session._csrf,
  });
}

exports.all = function all(req, res) {
  return res.render('public/all.html', {
    badges: req.badges,
    user: req.session.user,
    csrf: req.session._csrf,
  });
};

exports.claim = function claim(req, res) {
  return res.render('public/claim.html', {
    csrf: req.session._csrf,
    code: req.query.code,
    missing: req.query.missing,
    user: req.session.user,
  });
};

exports.confirmClaim = function confirmClaim(req, res) {
  return res.render('public/confirm-claim.html', {
    csrf: req.session._csrf,
    code: req.body.code,
    claim: req.claim,
    badge: req.badge,
    user: req.session.user,
  });
};

exports.manageClaimCodes = function (req, res) {
  return res.render('admin/manage-claim-codes.html', {
    page: 'edit-badge',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    badge: req.badge,
    codes: req.badge.claimCodes,
    exampleCode: phrases(1)
  });
};

exports.showFlushDbForm = function (req, res) {
  return res.render('admin/flush-user-info.html', {
    page: 'flush',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf
  });
};

exports.userList = function userList(req, res, next) {
  return res.render('admin/user-list.html', {
    page: 'user-list',
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    users: req.users
  });
};

exports.stats = function stats(req, res, next) {
  return res.render('admin/stats.html', {
    page: 'stats',
    stats: req.stats,
    user: req.session.user,
    access: req.session.access,
    csrf: req.session._csrf,
    users: req.users
  });
};

exports.notFound = function notFound(req, res, next) {
  res.status(404);
  return res.render('public/404.html', {});
};

exports.nextError = function nextError(req, res, next) {
  return next(new Error('some error'));
};

exports.errorHandler = function (err, req, res, next) {
  logger.error('there was an error at ' + req.url, err);
  res.status(500);
  return res.render('public/500.html');
};
<|endoftext|>


<commit_before>module.exports = function(app, passport) {
  app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));

  app.get('/auth/facebook/callback',
  passport.authenticate('facebook', {
    failureRedirect : '/'
  }), function(req, res) {
    return res.status(200).send(req.user);
  });

  app.get('/profile', function(req, res) {
    return res.send(200);
  });
};<commit_msg>Add artist and genre routes using the controllers<commit_after>var artistController = require('../controllers/artist-controller');
var genreController = require('../controllers/genre-controller');

module.exports = function(app, passport) {
  app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));

  app.get('/auth/facebook/callback',
  passport.authenticate('facebook', {
    failureRedirect : '/'
  }), function(req, res) {
    return res.status(200).send(req.user);
  });

  app.get('/profile', function(req, res) {
    return res.send(200);
  });

  app.post('/api/artist/:id/like', artistController.likeArtist);
  app.get('/api/artist/recommendation', artistController.getArtistRecommendations);

  app.get('/api/genre', genreController.getGenres);
  app.get('/api/genre/artists', genreController.getArtistsByGenre);
};<|endoftext|>


<commit_before>var PLR_SHADOW = -5
var PLR_FORCE = 0.8;
var PLR_RADIUS = 20

class Player {
    constructor(menu, image) {
        var shape = new planck.Circle(PLR_RADIUS / PHY_SCALE)
        var body = menu.world.createBody({
            'type': 'dynamic'
        })
        this.world = menu.world
        body.createFixture({
            'shape': shape,
            'restitution': 0.9,
            'm_radius': PLR_RADIUS / PHY_SCALE
        }).setUserData(this)
        body.setLinearDamping(0.3);
        body.setAwake(true);
        body.setActive(true);
        this.body = body;
        this.image = image;
        this.pawn = makeImage('img/pawn.png')
        this.ball = false
        this.boost_dt = 0
    }
    take_ball(ball) {
        if (ball.owned) {
            ball.owned.ball = false;
        }
        ball.body.setActive(false);
        this.ball = ball
        ball.owned = this
    }
    distance_from(coords) {
        return Math.sqrt(Math.pow(coords.x - this.pos.x, 2) + Math.pow(coords.y - this.pos.y, 2))
    }
    set_position(x, y, randomicity = 0, rotation = 0) {
        let temp = new planck.Vec2(x / PHY_SCALE + (Math.random() * randomicity - randomicity / 2), -y / PHY_SCALE + (Math.random() * randomicity - randomicity / 2))
        this.body.setLinearVelocity({
            x: 0,
            y: 0
        }, 0.0);
        this.body.setTransform(temp, rotation);
    }
    destroy() {
        this.world.destroyBody(this.body)
        this.body = null
        this.image = null
        this.world = null
    }

    targets(coords, coord2, delta) {
        var x = coords[0] - this.pos.x
        var y = coords[1] - this.pos.y
        var distance = Math.sqrt(Math.pow(Math.abs(x), 2) + Math.pow(Math.abs(y), 2))
        var angle = Math.acos(x / distance)
        var myangle = (Math.PI / 2 + this.body.getAngle()) % (2 * Math.PI)
        var sync = Math.abs(angle - myangle) < (delta / 360 * (2 * Math.PI))
        return [sync, angle]
    }
    push(dt) {
        if (!!this.ball) {
            // shooting ball
            this.ball.shot(dt)
            let angle = this.body.getAngle()
            let [x, y] = [Math.sin(-angle), Math.cos(-angle)]
            let temp = new planck.Vec2(this.pos.x + x, this.pos.y + y)
            this.ball.body.setTransform(temp, angle)
            this.ball.body.setActive(true)
            temp = this.body.getLinearVelocity()
            this.ball.body.setLinearVelocity(temp)
            this.ball.body.applyLinearImpulse(this.ball.body.getWorldVector(new planck.Vec2(0, 3 * PLR_FORCE)), this.ball.pos, true)
            this.ball = false
        } else {
            if (dt < this.boost_dt + 2000) // 2s min between 2 boosts
                return
            this.body.applyLinearImpulse(this.body.getWorldVector(new planck.Vec2(0, 5 * PLR_FORCE)), this.pos, true)
        }
        this.boost_dt = dt
    }
    forward(delta) {
        let force = PLR_FORCE * delta
        this.body.applyLinearImpulse(this.body.getWorldVector(new planck.Vec2(0, force)), this.pos, true)
    }
    backward(delta) {
        let force = PLR_FORCE * delta
        this.body.applyLinearImpulse(this.body.getWorldVector(new planck.Vec2(0, -force / 1.25)), this.pos, true)
    }
    left(delta) {
        let angle = 0.37 * delta
        this.body.setTransform(this.pos, this.body.getAngle() + angle)

    }
    right(delta) {
        let angle = 0.37 * delta
        this.body.setTransform(this.pos, this.body.getAngle() - angle)
    }
    draw(dt, delta) {
        this.pos = this.body.getPosition();
        app.display.context.save()
        let x = PHY_SCALE * (this.pos.x)
        let y = -PHY_SCALE * (this.pos.y)
        app.display.context.translate(x, y)
        app.display.blit(this.image, -PLR_RADIUS, -PLR_RADIUS)
        app.display.context.rotate(-this.body.getAngle())
        app.display.context.translate(0, -PLR_RADIUS / 2)
        if (this.ball) {
            app.display.blit(this.ball.image, -this.ball.image.width / 2, -this.ball.image.height / 2)
            let angle = this.body.getAngle()
            let [x, y] = [Math.sin(-angle), Math.cos(-angle)]
            this.ball.pos = new planck.Vec2(this.pos.x + x, this.pos.y + y)
        }
        app.display.context.translate(0, -PLR_RADIUS / 2)
        app.display.blit(this.pawn, -this.pawn.width / 2, -this.pawn.height / 2)
        app.display.context.restore()
    }
}
<commit_msg>targets works with planck<commit_after>var PLR_SHADOW = -5
var PLR_FORCE = 0.8;
var PLR_RADIUS = 20

class Player {
    constructor(menu, image) {
        var shape = new planck.Circle(PLR_RADIUS / PHY_SCALE)
        var body = menu.world.createBody({
            'type': 'dynamic'
        })
        this.world = menu.world
        body.createFixture({
            'shape': shape,
            'restitution': 0.9,
            'm_radius': PLR_RADIUS / PHY_SCALE
        }).setUserData(this)
        body.setLinearDamping(0.3);
        body.setAwake(true);
        body.setActive(true);
        this.body = body;
        this.image = image;
        this.pawn = makeImage('img/pawn.png')
        this.ball = false
        this.boost_dt = 0
    }
    take_ball(ball) {
        if (ball.owned) {
            ball.owned.ball = false;
        }
        ball.body.setActive(false);
        this.ball = ball
        ball.owned = this
    }
    distance_from(coords) {
        return Math.sqrt(Math.pow(coords.x - this.pos.x, 2) + Math.pow(coords.y - this.pos.y, 2))
    }
    set_position(x, y, randomicity = 0, rotation = 0) {
        let temp = new planck.Vec2(x / PHY_SCALE + (Math.random() * randomicity - randomicity / 2), -y / PHY_SCALE + (Math.random() * randomicity - randomicity / 2))
        this.body.setLinearVelocity({
            x: 0,
            y: 0
        }, 0.0);
        this.body.setTransform(temp, rotation);
    }
    destroy() {
        this.world.destroyBody(this.body)
        this.body = null
        this.image = null
        this.world = null
    }

    targets(coords, coord2, delta) {
        var x = coords.x - this.pos.x
        var y = coords.y - this.pos.y
        var distance = Math.sqrt(Math.pow(Math.abs(x), 2) + Math.pow(Math.abs(y), 2))
        var angle = Math.acos(x / distance)
        var myangle = (Math.PI / 2 + this.body.getAngle()) % (2 * Math.PI)
        var sync = Math.abs(angle - myangle) < (delta / 360 * (2 * Math.PI))
        return [sync, angle]
    }
    push(dt) {
        if (!!this.ball) {
            // shooting ball
            this.ball.shot(dt)
            let angle = this.body.getAngle()
            let [x, y] = [Math.sin(-angle), Math.cos(-angle)]
            let temp = new planck.Vec2(this.pos.x + x, this.pos.y + y)
            this.ball.body.setTransform(temp, angle)
            this.ball.body.setActive(true)
            temp = this.body.getLinearVelocity()
            this.ball.body.setLinearVelocity(temp)
            this.ball.body.applyLinearImpulse(this.ball.body.getWorldVector(new planck.Vec2(0, 3 * PLR_FORCE)), this.ball.pos, true)
            this.ball = false
        } else {
            if (dt < this.boost_dt + 2000) // 2s min between 2 boosts
                return
            this.body.applyLinearImpulse(this.body.getWorldVector(new planck.Vec2(0, 5 * PLR_FORCE)), this.pos, true)
        }
        this.boost_dt = dt
    }
    forward(delta) {
        let force = PLR_FORCE * delta
        this.body.applyLinearImpulse(this.body.getWorldVector(new planck.Vec2(0, force)), this.pos, true)
    }
    backward(delta) {
        let force = PLR_FORCE * delta
        this.body.applyLinearImpulse(this.body.getWorldVector(new planck.Vec2(0, -force / 1.25)), this.pos, true)
    }
    left(delta) {
        let angle = 0.37 * delta
        this.body.setTransform(this.pos, this.body.getAngle() + angle)

    }
    right(delta) {
        let angle = 0.37 * delta
        this.body.setTransform(this.pos, this.body.getAngle() - angle)
    }
    draw(dt, delta) {
        this.pos = this.body.getPosition();
        app.display.context.save()
        let x = PHY_SCALE * (this.pos.x)
        let y = -PHY_SCALE * (this.pos.y)
        app.display.context.translate(x, y)
        app.display.blit(this.image, -PLR_RADIUS, -PLR_RADIUS)
        app.display.context.rotate(-this.body.getAngle())
        app.display.context.translate(0, -PLR_RADIUS / 2)
        if (this.ball) {
            app.display.blit(this.ball.image, -this.ball.image.width / 2, -this.ball.image.height / 2)
            let angle = this.body.getAngle()
            let [x, y] = [Math.sin(-angle), Math.cos(-angle)]
            this.ball.pos = new planck.Vec2(this.pos.x + x, this.pos.y + y)
        }
        app.display.context.translate(0, -PLR_RADIUS / 2)
        app.display.blit(this.pawn, -this.pawn.width / 2, -this.pawn.height / 2)
        app.display.context.restore()
    }
}
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var request = require('request');
var url = require('url');
var spotify_api_url = 'https://lit-wildwood-6408.herokuapp.com/playlist/search?q=';

//https://api.spotify.com/v1/search?q=katy+perry&type=artist,track,album&limit=10

/* GET search listing. */
router.get('/', function(req, res, next){

	var search_result = {results:[]}

	var parsedUrl = url.parse(req.url, true);
	var queryAsObject = parsedUrl.query;
	var query = queryAsObject.query.replace(" ","+");
	console.log(query)

	var query_url = spotify_api_url+query+'&type=artist,track,album&limit=10';

	console.log(query_url)
	request(query_url, function(err, response, body){
		if(!err && response.statusCode == 200){
			data = JSON.parse(body);

			//var track_uri = data.tracks.items[0].uri +"";
			var items = data.tracks.items;
			var result = {}

			for(var i=0; i<items.length; i++){
				result.img_url = data.tracks.items[i].album.images[0].url
				result.name = data.tracks.items[i].name
				result.artist = data.tracks.items[i].artists[0].name
				result.track_uri = data.tracks.items[i].uri
				search_result.results.push(result)
				result = {}
			}

			res.send(search_result);

		}else{
			search_result = err
			res.send(search_result);
		}
	});

});

module.exports = router;
<commit_msg>Mesagge sended if nothing found<commit_after>var express = require('express');
var router = express.Router();
var request = require('request');
var url = require('url');
var spotify_api_url = 'https://lit-wildwood-6408.herokuapp.com/playlist/search?q=';

//https://api.spotify.com/v1/search?q=katy+perry&type=artist,track,album&limit=10

/* GET search listing. */
router.get('/', function(req, res, next){

	var search_result = {results:[]}

	var parsedUrl = url.parse(req.url, true);
	var queryAsObject = parsedUrl.query;
	var query = queryAsObject.query.replace(" ","+");
	console.log(query)

	var query_url = spotify_api_url+query+'&type=artist,track,album&limit=10';

	console.log(query_url)
	request(query_url, function(err, response, body){
		if(!err && response.statusCode == 200){
			data = JSON.parse(body);

			//var track_uri = data.tracks.items[0].uri +"";
			var items = data.tracks.items;
			var result = {}
			if (items.length > 0) {
				for(var i=0; i<items.length; i++){
					result.img_url = data.tracks.items[i].album.images[0].url
					result.name = data.tracks.items[i].name
					result.artist = data.tracks.items[i].artists[0].name
					result.track_uri = data.tracks.items[i].uri
					search_result.results.push(result)
					result = {}
				}

				res.send(search_result);

			} else{
				res.send("No se han encontrado resultados o no estan permitidos");
			}

		}else{
			search_result = err
			res.send(search_result);
		}
	});

});

module.exports = router;
<|endoftext|>


<commit_before>const fs = require('mz/fs');
const JSZip = require('jszip');
const path = require('path');
const semver = require('semver');
const { parseChangelogMarkdown } = require('./changelogMarkdownParser');

function readInfoFromComposerJson(composerJsonString) {
    const composerJson = JSON.parse(composerJsonString);

    return {
        version: composerJson.version,
        shopwareCompatibility: composerJson.require['shopware/core'],
        label: {
            en: composerJson.extra.label['en-GB'],
            de: composerJson.extra.label['de-DE'],
        },
    };
}

function readInfoFromPluginJson(pluginJsonString) {
    const pluginJson = JSON.parse(pluginJsonString);
    const minimumVersion = pluginJson.compatibility.minimumVersion || '0.0.0';
    const maximumVersion = pluginJson.compatibility.maximumVersion || '99.99.99';

    return {
        version: pluginJson.currentVersion,
        shopwareCompatibility: `${minimumVersion} - ${maximumVersion}`,
        label: pluginJson.label,
    };
}

module.exports = class Plugin {
    static async readFromZipFile(zipFilePath) {
        if (!await fs.exists(zipFilePath)) {
            throw new Error(`File ${zipFilePath} does not exist`);
        }

        const data = await fs.readFile(zipFilePath);
        const zip = await JSZip.loadAsync(data);

        const sw5RootDirectory = zip.folder(/^(Backend|Frontend|Core)\/\w+\//)[0];
        const sw6RootDirectory = zip.folder(/^\w+\//)[0];

        const plugin = new Plugin();
        let rootDirectory;
        if (sw5RootDirectory) {
            rootDirectory = sw5RootDirectory.name;
            plugin.technicalName = rootDirectory.split('/')[1];
            plugin.shopwareMajorVersion = 5;
            Object.assign(plugin, readInfoFromPluginJson(
                await zip.file(path.join(rootDirectory, 'plugin.json')).async('string'),
            ));
        } else if (sw6RootDirectory) {
            rootDirectory = sw6RootDirectory.name;
            plugin.technicalName = rootDirectory.split('/')[0];
            plugin.shopwareMajorVersion = 6;
            Object.assign(plugin, readInfoFromComposerJson(
                await zip.file(path.join(rootDirectory, 'composer.json')).async('string'),
            ));
        } else {
            throw new Error('Could not detect whether plugin targets Shopware 5 or Shopware 6.');
        }

        const parsedChangelog = parseChangelogMarkdown(
            await zip.file(path.join(rootDirectory, 'CHANGELOG.md')).async('string'),
        );
        plugin.releaseNotes = parsedChangelog[plugin.version];

        return plugin;
    }

    isCompatibleWithShopwareVersion(shopwareVersion) {
        return semver.satisfies(shopwareVersion, this.shopwareCompatibility);
    }
};
<commit_msg>Add compatibility with Shopware's new 4-digit version numbers (#34)<commit_after>const fs = require('mz/fs');
const JSZip = require('jszip');
const path = require('path');
const semver = require('semver');
const { parseChangelogMarkdown } = require('./changelogMarkdownParser');

function readInfoFromComposerJson(composerJsonString) {
    const composerJson = JSON.parse(composerJsonString);

    return {
        version: composerJson.version,
        shopwareCompatibility: composerJson.require['shopware/core'],
        label: {
            en: composerJson.extra.label['en-GB'],
            de: composerJson.extra.label['de-DE'],
        },
    };
}

function readInfoFromPluginJson(pluginJsonString) {
    const pluginJson = JSON.parse(pluginJsonString);
    const minimumVersion = pluginJson.compatibility.minimumVersion || '0.0.0';
    const maximumVersion = pluginJson.compatibility.maximumVersion || '99.99.99';

    return {
        version: pluginJson.currentVersion,
        shopwareCompatibility: `${minimumVersion} - ${maximumVersion}`,
        label: pluginJson.label,
    };
}

module.exports = class Plugin {
    static async readFromZipFile(zipFilePath) {
        if (!await fs.exists(zipFilePath)) {
            throw new Error(`File ${zipFilePath} does not exist`);
        }

        const data = await fs.readFile(zipFilePath);
        const zip = await JSZip.loadAsync(data);

        const sw5RootDirectory = zip.folder(/^(Backend|Frontend|Core)\/\w+\//)[0];
        const sw6RootDirectory = zip.folder(/^\w+\//)[0];

        const plugin = new Plugin();
        let rootDirectory;
        if (sw5RootDirectory) {
            rootDirectory = sw5RootDirectory.name;
            plugin.technicalName = rootDirectory.split('/')[1];
            plugin.shopwareMajorVersion = 5;
            Object.assign(plugin, readInfoFromPluginJson(
                await zip.file(path.join(rootDirectory, 'plugin.json')).async('string'),
            ));
        } else if (sw6RootDirectory) {
            rootDirectory = sw6RootDirectory.name;
            plugin.technicalName = rootDirectory.split('/')[0];
            plugin.shopwareMajorVersion = 6;
            Object.assign(plugin, readInfoFromComposerJson(
                await zip.file(path.join(rootDirectory, 'composer.json')).async('string'),
            ));
        } else {
            throw new Error('Could not detect whether plugin targets Shopware 5 or Shopware 6.');
        }

        const parsedChangelog = parseChangelogMarkdown(
            await zip.file(path.join(rootDirectory, 'CHANGELOG.md')).async('string'),
        );
        plugin.releaseNotes = parsedChangelog[plugin.version];

        return plugin;
    }

    isCompatibleWithShopwareVersion(shopwareMarketingVersion) {
        if (!shopwareMarketingVersion) {
            return false;
        }

        if (this.shopwareMajorVersion === 6) {
            if (!shopwareMarketingVersion.startsWith('6.')) {
                return false;
            }

            const shopwareVersion = this.getShopware6Semver(shopwareMarketingVersion);
            const pluginShopwareCompatibility = this.getShopware6Semver(this.shopwareCompatibility);

            return semver.satisfies(shopwareVersion, pluginShopwareCompatibility);
        }

        if (this.shopwareMajorVersion === 5) {
            if (!shopwareMarketingVersion.startsWith('5.')) {
                return false;
            }

            return semver.satisfies(shopwareMarketingVersion, this.shopwareCompatibility);
        }

        throw new Error(
            'The scs-commander is incompatible with the given Shopware version number'
            + ` (${shopwareMarketingVersion}).`,
        );
    }

    getShopware6Semver(version) {
        if (!version.startsWith('6.')) {
            throw new Error(`"${version}" is not a valid Shopware 6 version number.`);
        }

        const numberOfVersionComponents = version.split('.').length;
        if (numberOfVersionComponents === 4) {
            // "New", 4-component version (e.g. `6.3.0.0`). Hence just drop the first component.
            return version.substring(2);
        }

        if (numberOfVersionComponents === 3) {
            // Legacy version (e.g. `6.1.0`). Hence drop the first component and add a patch version of `0`.
            return `${version.substring(2)}.0`;
        }

        throw new Error('The given shopware version format is unknown.');
    }
};
<|endoftext|>


<commit_before>
/*
 * GET submit page
 * */

// TODO: This should be an input form that lets users populate:
// * title
// * summary
// * submitter
// * body or filename(s) (multiple files)
exports.submit = function(req, res) {
    res.render( 'submit',
            {title: 'submit to '+GLOBAL.group+' research',
             group: GLOBAL.group} );
};

exports.submission = function(req, res) {
    GLOBAL.db.get( 'SELECT * FROM posts WHERE id=?;', req.params['id'],
            function(err, row) {
                if ( !row ) {
                    // TODO: 404 handler, with contextual message.
                }
                //console.log(row);
                res.render( 'submission', { title: GLOBAL.group + ': ' + row['title'],
                                            subtitle: row['title'],
                                            summary: row['summary'],
                                            body: row['body'] }
                    );
            } );
};

<commit_msg>begin new submit_post() for app.post('/submit', submit_post);<commit_after>
/*
 * GET submit page
 * */

// TODO: This should be an input form that lets users populate:
// * title
// * summary
// * submitter
// * body or filename(s) (multiple files)
exports.submit = function ( req, res ) {
    res.render( 'submit',
            {title: 'submit to '+GLOBAL.group+' research',
             group: GLOBAL.group} );
};

exports.submit_post = function ( req, res ) {
//    GLOBAL.db.run( 'INSERT INTO posts (time, submitter, title, summary) VALUES ' +
//            '()')
};

exports.submission = function(req, res) {
    GLOBAL.db.get( 'SELECT * FROM posts WHERE id=?;', req.params['id'],
            function(err, row) {
                if ( !row ) {
                    // TODO: 404 handler, with contextual message.
                }
                //console.log(row);
                res.render( 'submission', { title: GLOBAL.group + ': ' + row['title'],
                                            subtitle: row['title'],
                                            summary: row['summary'],
                                            body: row['body'] }
                    );
            } );
};

<|endoftext|>