<commit_before>/**
 * Copyright (C) 2014 Glayzzle (BSD3 License)
 * @authors https://github.com/glayzzle/php-parser/graphs/contributors
 * @url http://glayzzle.com
 */

module.exports = function(api, tokens, EOF) {
  return {
    /**
     * reading a class
     * <ebnf>
     * class ::= class_scope? T_CLASS T_STRING (T_EXTENDS NAMESPACE_NAME)? (T_IMPLEMENTS (NAMESPACE_NAME ',')* NAMESPACE_NAME)? '{' CLASS_BODY '}'
     * </ebnf>
     */
    read_class: function(flag) {
      this.expect(tokens.T_CLASS)
        .next()
        .expect(tokens.T_STRING)
      ;
      var propName = this.text()
        , propExtends = false
        , propImplements = false
      ;
      if (this.next().token == tokens.T_EXTENDS) {
        propExtends = this.next().read_namespace_name();
      }
      if (this.token == tokens.T_IMPLEMENTS) {
        propImplements = this.next().read_list(
          this.read_namespace_name,
          ','
        );
      }
      return [
        'class'
        ,propName
        ,flag
        ,propExtends
        ,propImplements
        ,this.expect('{').next().read_class_body()
      ];
    }
    /**
     * Read the class visibility
     * <ebnf>
     *   class_scope ::= (T_FINAL | T_ABSTRACT)?
     * </ebnf>
     */
    ,read_class_scope: function() {
      var result = this.token;
      if (result == tokens.T_FINAL || result == tokens.T_ABSTRACT) {
        this.next();
        return result;
      }
      return 0;
    }
    /**
     * Reads a class body
     * <ebnf>
     *   class_body ::= (member_flags? (T_VAR | T_STRING | T_FUNCTION))*
     * </ebnf>
     */
    ,read_class_body: function() {
      var result = {
        'constants': []
        ,'properties': []
        ,'methods': []
        ,'use': {
          // list of traits
          traits: [],
          // list of alias
          adaptations: []
        }
      };

      while(this.token !== EOF && this.token !== '}') {

        // check T_USE trait
        if (this.token === tokens.T_USE) {
          this.next().read_trait_use_statement(result['use']);
          continue;
        }

        // check constant
        if (this.token === tokens.T_CONST) {
          result.constants.push(this.read_constant_list());
          this.expect(';').next();
          continue;
        }

        // read member flags
        var flags = this.read_member_flags(false);

        // jump over T_VAR then land on T_VARIABLE
        if (this.token === tokens.T_VAR) {
          this.next().expect(tokens.T_VARIABLE);
        }

        // reads a variable
        if (this.token === tokens.T_VARIABLE) {
          var variables = this.read_variable_list();
          this.expect(';').next();
          result.properties.push([flags].concat(variables));
        } else if (this.token === tokens.T_FUNCTION) {
          // reads a function
          result.methods.push([flags].concat(this.read_function(false, flags[2] === 1)));
        } else {
          // raise an error
          this.error([
            tokens.T_CONST,
            tokens.T_VARIABLE,
            tokens.T_FUNCTION
          ]);
        }
      }
      this.expect('}').next();
      return result;
    }
    /**
     * Reads variable list
     * <ebnf>
     *  variable_list ::= (variable_declaration ',')* variable_declaration
     * </ebnf>
     */
    ,read_variable_list: function() {
      return this.read_list(
        this.read_variable_declaration,
        ','
      );
    }
    /**
     * Reads a variable declaration
     * <ebnf>
     *  variable_declaration ::= T_VARIABLE '=' scalar
     * </ebnf>
     */
    ,read_variable_declaration: function() {
      var varName = this.text();
      this.expect(tokens.T_VARIABLE).next().expect([',', ';', '=']);
      if (this.token === ';' || this.token === ',') {
        return [varName, null];
      }
      if(this.token === '=') {
        return [varName, this.next().read_scalar()];
      }
    }
    /**
     * Reads constant list
     * <ebnf>
     *  constant_list ::= T_CONST (constant_declaration ',')* constant_declaration
     * </ebnf>
     */
    ,read_constant_list: function() {
      return this.expect(tokens.T_CONST)
        .next()
        .read_list(
          this.read_constant_declaration, ','
        )
      ;
    }
    /**
     * Reads a constant declaration
     * <ebnf>
     *  constant_declaration ::= T_STRING '=' scalar
     * </ebnf>
     */
    ,read_constant_declaration: function() {
      var name = this.text();
      var value = this.expect(tokens.T_STRING)
        .next()
        .expect('=')
        .next()
        .read_scalar()
      ;
      return [name, value];
    }
    /**
     * Read member flags
     * @return array
     *  1st index : 0 => public, 1 => protected, 2 => private
     *  2nd index : 0 => instance member, 1 => static member
     *  3rd index : 0 => normal, 1 => abstract member, 2 => final member
     */
    ,read_member_flags: function(asInterface) {
      var result = [-1, -1, -1];
      if (this.is('T_MEMBER_FLAGS')) {
        var idx = 0, val = 0;
        do {

          switch(this.token) {
            case tokens.T_PUBLIC:     idx = 0; val = 0; break;
            case tokens.T_PROTECTED:  idx = 0; val = 1; break;
            case tokens.T_PRIVATE:    idx = 0; val = 2; break;
            case tokens.T_STATIC:     idx = 1; val = 1; break;
            case tokens.T_ABSTRACT:   idx = 2; val = 1; break;
            case tokens.T_FINAL:      idx = 2; val = 2; break;
          }
          if (asInterface) {
            if (idx == 0 && val == 2) {
              this.expect([tokens.T_PUBLIC, tokens.T_PROTECTED]);
            } else if (idx == 2 && val == 1) {
              this.error();
            }
          }
          if (result[idx] != -1) this.error();
          result[idx] = val;
        } while(this.next().is('T_MEMBER_FLAGS'));
      }

      if (result[0] == -1) result[0] = 0;
      if (result[1] == -1) result[1] = 0;
      if (result[2] == -1) result[2] = 0;
      return result;
    }
    /**
     * reading an interface
     * <ebnf>
     * interface ::= class_scope? T_INTERFACE T_STRING (T_EXTENDS (NAMESPACE_NAME ',')* NAMESPACE_NAME)? '{' INTERFACE_BODY '}'
     * </ebnf>
     */
    ,read_interface: function(flag) {
      var name = this.expect(tokens.T_INTERFACE)
        .next()
        .expect(tokens.T_STRING)
        .text()
      ;
      var propExtends = false;
      if (this.next().token == tokens.T_EXTENDS) {
        propExtends =  this.next().read_list(
          this.read_namespace_name,
          ','
        );
      }
      return [
        'interface'
        , name
        , flag
        , propExtends
        , this.expect('{').next().read_interface_body()
      ];
    }
    /**
     * Reads an interface body
     * <ebnf>
     *   interface_body ::= (member_flags? (T_CONST | T_FUNCTION))*
     * </ebnf>
     */
    ,read_interface_body: function() {
      var result = {
        'constants': []
        ,'methods': []
      };
      while(this.token !== EOF && this.token !== '}') {
        // check constant
        if (this.token == tokens.T_CONST) {
          result.constants.push(this.read_constant_list());
          this.expect(';').next();
          continue;
        }
        // read member flags
        var flags = this.read_member_flags(true);

        // reads a function
        if (this.token === tokens.T_FUNCTION) {
          result.methods.push([flags].concat(this.read_function_declaration()));
          this.expect(';').next();
        } else {
          // raise an error
          this.error([
            tokens.T_CONST,
            tokens.T_FUNCTION
          ]);
        }
      }
      this.expect('}').next();
      return result;
    }
    /**
     * reading a trait
     * <ebnf>
     * trait ::= T_TRAIT T_STRING (T_EXTENDS (NAMESPACE_NAME ',')* NAMESPACE_NAME)? '{' FUNCTION* '}'
     * </ebnf>
     */
    ,read_trait: function(flag) {
      this.expect(tokens.T_TRAIT)
        .next()
        .expect(tokens.T_STRING)
      ;
      var propName = this.text(),
        propExtends = false,
        propImplements = false;
      if (this.next().token == tokens.T_EXTENDS) {
        propExtends = this.next().read_namespace_name();
      }
      if (this.token == tokens.T_IMPLEMENTS) {
        propImplements = this.next().read_list(
          this.read_namespace_name,
          ','
        );
      }
      return [
        'trait',
        propName,
        propExtends,
        propImplements,
        this.expect('{').next().read_class_body()
      ];
    }
    /**
     * reading a use statement
     * <ebnf>
     * trait_use_statement ::= namespace_name (',' namespace_name)* ('{' trait_use_alias '}')?
     * </ebnf>
     */
    ,read_trait_use_statement: function(result) {
      result.traits.push(this.read_namespace_name());
      while(this.token === ',') {
        result.traits.push(
          this.next().read_namespace_name()
        );
      }
      if (this.token === '{') {
        while(this.next()) {
          if (this.token === '}') break;
          result.adaptations.push(this.read_trait_use_alias());
          this.expect(';');
        }
        this.expect('}').next();
      } else {
        this.expect(';').next();
      }
    }
    /**
     * Reading trait alias
     * <ebnf>
     * trait_use_alias ::= namespace_name ( T_DOUBLE_COLON T_STRING )? (T_INSTEADOF namespace_name) | (T_AS member_flags? T_STRING)
     * </ebnf>
     */
    ,read_trait_use_alias: function() {
      var result = {
        origin: this.read_namespace_name(),
        act: false,
        target: false
      };
      if (this.token === tokens.T_DOUBLE_COLON) {
        result.origin = [
          result.origin,
          this.next().expect(tokens.T_STRING).text()
        ];
        this.next();
      }

      if (this.token === tokens.T_INSTEADOF) {
        result.act = 'instead';
        result.target = this.next().read_namespace_name();
      } else if (this.token === tokens.T_AS) {
        result.act = 'as';
        result.flags = this.next().read_member_flags();
        result.target = this.expect(tokens.T_STRING).text();
        this.next();
      } else {
        this.expect([
          tokens.T_AS,
          tokens.T_INSTEADOF
        ]);
      }
      return result;
    }
  };
};<commit_msg>fix constant_declaration : can be an expr, not just a scalar<commit_after>/**
 * Copyright (C) 2014 Glayzzle (BSD3 License)
 * @authors https://github.com/glayzzle/php-parser/graphs/contributors
 * @url http://glayzzle.com
 */

module.exports = function(api, tokens, EOF) {
  return {
    /**
     * reading a class
     * <ebnf>
     * class ::= class_scope? T_CLASS T_STRING (T_EXTENDS NAMESPACE_NAME)? (T_IMPLEMENTS (NAMESPACE_NAME ',')* NAMESPACE_NAME)? '{' CLASS_BODY '}'
     * </ebnf>
     */
    read_class: function(flag) {
      this.expect(tokens.T_CLASS)
        .next()
        .expect(tokens.T_STRING)
      ;
      var propName = this.text()
        , propExtends = false
        , propImplements = false
      ;
      if (this.next().token == tokens.T_EXTENDS) {
        propExtends = this.next().read_namespace_name();
      }
      if (this.token == tokens.T_IMPLEMENTS) {
        propImplements = this.next().read_list(
          this.read_namespace_name,
          ','
        );
      }
      return [
        'class'
        ,propName
        ,flag
        ,propExtends
        ,propImplements
        ,this.expect('{').next().read_class_body()
      ];
    }
    /**
     * Read the class visibility
     * <ebnf>
     *   class_scope ::= (T_FINAL | T_ABSTRACT)?
     * </ebnf>
     */
    ,read_class_scope: function() {
      var result = this.token;
      if (result == tokens.T_FINAL || result == tokens.T_ABSTRACT) {
        this.next();
        return result;
      }
      return 0;
    }
    /**
     * Reads a class body
     * <ebnf>
     *   class_body ::= (member_flags? (T_VAR | T_STRING | T_FUNCTION))*
     * </ebnf>
     */
    ,read_class_body: function() {
      var result = {
        'constants': []
        ,'properties': []
        ,'methods': []
        ,'use': {
          // list of traits
          traits: [],
          // list of alias
          adaptations: []
        }
      };

      while(this.token !== EOF && this.token !== '}') {

        // check T_USE trait
        if (this.token === tokens.T_USE) {
          this.next().read_trait_use_statement(result['use']);
          continue;
        }

        // check constant
        if (this.token === tokens.T_CONST) {
          result.constants.push(this.read_constant_list());
          this.expect(';').next();
          continue;
        }

        // read member flags
        var flags = this.read_member_flags(false);

        // jump over T_VAR then land on T_VARIABLE
        if (this.token === tokens.T_VAR) {
          this.next().expect(tokens.T_VARIABLE);
        }

        // reads a variable
        if (this.token === tokens.T_VARIABLE) {
          var variables = this.read_variable_list();
          this.expect(';').next();
          result.properties.push([flags].concat(variables));
        } else if (this.token === tokens.T_FUNCTION) {
          // reads a function
          result.methods.push([flags].concat(this.read_function(false, flags[2] === 1)));
        } else {
          // raise an error
          this.error([
            tokens.T_CONST,
            tokens.T_VARIABLE,
            tokens.T_FUNCTION
          ]);
        }
      }
      this.expect('}').next();
      return result;
    }
    /**
     * Reads variable list
     * <ebnf>
     *  variable_list ::= (variable_declaration ',')* variable_declaration
     * </ebnf>
     */
    ,read_variable_list: function() {
      return this.read_list(
        this.read_variable_declaration,
        ','
      );
    }
    /**
     * Reads a variable declaration
     * <ebnf>
     *  variable_declaration ::= T_VARIABLE '=' scalar
     * </ebnf>
     */
    ,read_variable_declaration: function() {
      var varName = this.text();
      this.expect(tokens.T_VARIABLE).next().expect([',', ';', '=']);
      if (this.token === ';' || this.token === ',') {
        return [varName, null];
      }
      if(this.token === '=') {
        return [varName, this.next().read_scalar()];
      }
    }
    /**
     * Reads constant list
     * <ebnf>
     *  constant_list ::= T_CONST (constant_declaration ',')* constant_declaration
     * </ebnf>
     */
    ,read_constant_list: function() {
      return this.expect(tokens.T_CONST)
        .next()
        .read_list(
          this.read_constant_declaration, ','
        )
      ;
    }
    /**
     * Reads a constant declaration
     * <ebnf>
     *  constant_declaration ::= T_STRING '=' expr
     * </ebnf>
     */
    ,read_constant_declaration: function() {
      var name = this.text();
      var value = this.expect(tokens.T_STRING)
        .next()
        .expect('=')
        .next()
        .read_expr()
      ;
      return [name, value];
    }
    /**
     * Read member flags
     * @return array
     *  1st index : 0 => public, 1 => protected, 2 => private
     *  2nd index : 0 => instance member, 1 => static member
     *  3rd index : 0 => normal, 1 => abstract member, 2 => final member
     */
    ,read_member_flags: function(asInterface) {
      var result = [-1, -1, -1];
      if (this.is('T_MEMBER_FLAGS')) {
        var idx = 0, val = 0;
        do {

          switch(this.token) {
            case tokens.T_PUBLIC:     idx = 0; val = 0; break;
            case tokens.T_PROTECTED:  idx = 0; val = 1; break;
            case tokens.T_PRIVATE:    idx = 0; val = 2; break;
            case tokens.T_STATIC:     idx = 1; val = 1; break;
            case tokens.T_ABSTRACT:   idx = 2; val = 1; break;
            case tokens.T_FINAL:      idx = 2; val = 2; break;
          }
          if (asInterface) {
            if (idx == 0 && val == 2) {
              this.expect([tokens.T_PUBLIC, tokens.T_PROTECTED]);
            } else if (idx == 2 && val == 1) {
              this.error();
            }
          }
          if (result[idx] != -1) this.error();
          result[idx] = val;
        } while(this.next().is('T_MEMBER_FLAGS'));
      }

      if (result[0] == -1) result[0] = 0;
      if (result[1] == -1) result[1] = 0;
      if (result[2] == -1) result[2] = 0;
      return result;
    }
    /**
     * reading an interface
     * <ebnf>
     * interface ::= class_scope? T_INTERFACE T_STRING (T_EXTENDS (NAMESPACE_NAME ',')* NAMESPACE_NAME)? '{' INTERFACE_BODY '}'
     * </ebnf>
     */
    ,read_interface: function(flag) {
      var name = this.expect(tokens.T_INTERFACE)
        .next()
        .expect(tokens.T_STRING)
        .text()
      ;
      var propExtends = false;
      if (this.next().token == tokens.T_EXTENDS) {
        propExtends =  this.next().read_list(
          this.read_namespace_name,
          ','
        );
      }
      return [
        'interface'
        , name
        , flag
        , propExtends
        , this.expect('{').next().read_interface_body()
      ];
    }
    /**
     * Reads an interface body
     * <ebnf>
     *   interface_body ::= (member_flags? (T_CONST | T_FUNCTION))*
     * </ebnf>
     */
    ,read_interface_body: function() {
      var result = {
        'constants': []
        ,'methods': []
      };
      while(this.token !== EOF && this.token !== '}') {
        // check constant
        if (this.token == tokens.T_CONST) {
          result.constants.push(this.read_constant_list());
          this.expect(';').next();
          continue;
        }
        // read member flags
        var flags = this.read_member_flags(true);

        // reads a function
        if (this.token === tokens.T_FUNCTION) {
          result.methods.push([flags].concat(this.read_function_declaration()));
          this.expect(';').next();
        } else {
          // raise an error
          this.error([
            tokens.T_CONST,
            tokens.T_FUNCTION
          ]);
        }
      }
      this.expect('}').next();
      return result;
    }
    /**
     * reading a trait
     * <ebnf>
     * trait ::= T_TRAIT T_STRING (T_EXTENDS (NAMESPACE_NAME ',')* NAMESPACE_NAME)? '{' FUNCTION* '}'
     * </ebnf>
     */
    ,read_trait: function(flag) {
      this.expect(tokens.T_TRAIT)
        .next()
        .expect(tokens.T_STRING)
      ;
      var propName = this.text(),
        propExtends = false,
        propImplements = false;
      if (this.next().token == tokens.T_EXTENDS) {
        propExtends = this.next().read_namespace_name();
      }
      if (this.token == tokens.T_IMPLEMENTS) {
        propImplements = this.next().read_list(
          this.read_namespace_name,
          ','
        );
      }
      return [
        'trait',
        propName,
        propExtends,
        propImplements,
        this.expect('{').next().read_class_body()
      ];
    }
    /**
     * reading a use statement
     * <ebnf>
     * trait_use_statement ::= namespace_name (',' namespace_name)* ('{' trait_use_alias '}')?
     * </ebnf>
     */
    ,read_trait_use_statement: function(result) {
      result.traits.push(this.read_namespace_name());
      while(this.token === ',') {
        result.traits.push(
          this.next().read_namespace_name()
        );
      }
      if (this.token === '{') {
        while(this.next()) {
          if (this.token === '}') break;
          result.adaptations.push(this.read_trait_use_alias());
          this.expect(';');
        }
        this.expect('}').next();
      } else {
        this.expect(';').next();
      }
    }
    /**
     * Reading trait alias
     * <ebnf>
     * trait_use_alias ::= namespace_name ( T_DOUBLE_COLON T_STRING )? (T_INSTEADOF namespace_name) | (T_AS member_flags? T_STRING)
     * </ebnf>
     */
    ,read_trait_use_alias: function() {
      var result = {
        origin: this.read_namespace_name(),
        act: false,
        target: false
      };
      if (this.token === tokens.T_DOUBLE_COLON) {
        result.origin = [
          result.origin,
          this.next().expect(tokens.T_STRING).text()
        ];
        this.next();
      }

      if (this.token === tokens.T_INSTEADOF) {
        result.act = 'instead';
        result.target = this.next().read_namespace_name();
      } else if (this.token === tokens.T_AS) {
        result.act = 'as';
        result.flags = this.next().read_member_flags();
        result.target = this.expect(tokens.T_STRING).text();
        this.next();
      } else {
        this.expect([
          tokens.T_AS,
          tokens.T_INSTEADOF
        ]);
      }
      return result;
    }
  };
};<|endoftext|>


<commit_before>/*globals exports */

'use strict';

exports.format = format;

function format (reports) {
    var formatted = '# Complexity report ~ ' + (new Date()).toLocaleDateString() + '\n\n', i;

    for (i = 0; i < reports.length; i += 1) {
        formatted += formatModule(reports[i]) + '\n\n';
    }

    return formatted;
}

function formatModule (report) {
    return [
        '##',
        report.module,
        '\n\n',
        '* Maintainability index: ', report.maintainability, '\n',
        '* Aggregate cyclomatic complexity: ', report.aggregate.complexity.cyclomatic,
        formatFunctions(report.functions)
    ].join('');
}

function formatFunctions (report) {
    var formatted = '', i;

    for (i = 0; i < report.length; i += 1) {
        formatted += '\n\n' + formatFunction(report[i]);
    }

    return formatted;
}

function formatFunction (report) {
    return [
        '  * Function: **', report.name, '**\n',
        '    * Line No.: ', report.line, '\n',
        '    * Physical SLOC: ', report.complexity.sloc.physical, '\n',
        '    * Logical SLOC: ', report.complexity.sloc.logical, '\n',
        '    * Cyclomatic complexity: ', report.complexity.cyclomatic, '\n',
        '    * Halstead difficulty: ', report.complexity.halstead.difficulty, '\n',
        '    * Halstead volume: ', report.complexity.halstead.volume, '\n',
        '    * Halstead effort: ', report.complexity.halstead.effort
    ].join('');
}

<commit_msg>Tweak markdown format.<commit_after>/*globals exports */

'use strict';

exports.format = format;

function format (reports) {
    var formatted = '# Complexity report ~ ' + (new Date()).toLocaleDateString() + '\n\n', i;

    for (i = 0; i < reports.length; i += 1) {
        formatted += formatModule(reports[i]) + '\n\n';
    }

    return formatted;
}

function formatModule (report) {
    return [
        '##',
        report.module,
        '\n\n',
        '* Maintainability index: ', report.maintainability, '\n',
        '* Aggregate cyclomatic complexity: ', report.aggregate.complexity.cyclomatic,
        formatFunctions(report.functions)
    ].join('');
}

function formatFunctions (report) {
    var formatted = '', i;

    for (i = 0; i < report.length; i += 1) {
        formatted += '\n\n' + formatFunction(report[i]);
    }

    return formatted;
}

function formatFunction (report) {
    return [
        '    * Function: **', report.name, '**\n',
        '        * Line No.: ', report.line, '\n',
        '        * Physical SLOC: ', report.complexity.sloc.physical, '\n',
        '        * Logical SLOC: ', report.complexity.sloc.logical, '\n',
        '        * Cyclomatic complexity: ', report.complexity.cyclomatic, '\n',
        '        * Halstead difficulty: ', report.complexity.halstead.difficulty, '\n',
        '        * Halstead volume: ', report.complexity.halstead.volume, '\n',
        '        * Halstead effort: ', report.complexity.halstead.effort
    ].join('');
}

<|endoftext|>


<commit_before>/* global ajax */
//TODO: need to make sure it is passing back headers and auto parsing json.
utils.ajax.http = (function () {
    /**
     * Module dependencies.
     */
    var serialize = function(obj) {
        var str = [];
        for(var p in obj)
            if (obj.hasOwnProperty(p)) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
        return str.join("&");
    };

    var win = window,
        CORSxhr = (function () {
            var xhr;

            if (win.XMLHttpRequest && ('withCredentials' in new win.XMLHttpRequest())) {
                xhr = win.XMLHttpRequest;

            } else if (win.XDomainRequest) {
                xhr = win.XDomainRequest;
            }

            return xhr;
        }()),
        methods = ['head', 'get', 'post', 'put', 'delete'],
        i = 0,
        methodsLength = methods.length,
        result = {};

    function Request(options) {
        this.init(options);
    }

    Request.prototype.init = function (options) {
        var that = this;

        that.xhr = new CORSxhr();
        that.method = options.method;
        that.url = options.url;
        that.success = options.success;
        that.error = options.error;
        that.data = options.data;
        that.headers = options.headers;

        if (options.credentials === true) {
            that.xhr.withCredentials = true;
        }

        that.send();

        return that;
    };

    Request.prototype.send = function () {
        var that = this;

        // serialize data if GET
        if(that.method === 'GET' && that.data) {
            var concat = that.url.indexOf('?') > -1 ? '&' : '?';
            that.url += concat + serialize(that.data);
        } else {
            that.data = JSON.stringify(that.data);
        }

        // Success callback
        if (that.success !== undefined) {
            that.xhr.onload = function () {
                var headers = parseResponseHeaders(this.getAllResponseHeaders());
                var response = this.responseText;
                if (headers.contentType && headers.contentType.indexOf('application/json') !== -1) {
                    response = JSON.parse(response);
                }
                that.success.call(this, {
                    data:response,
                    request: {
                        method: that.method,
                        url: that.url,
                        data: that.data,
                        headers: that.headers
                    },
                    headers:headers,
                    status:this.status});
            };
        }

        // Error callback
        if (that.error !== undefined) {
            that.xhr.error = function () {
                that.error.call(this, this.responseText);
            };
        }

        that.xhr.open(that.method, that.url, true);

        if (that.headers !== undefined) {
            that.setHeaders();
        }

        // Send
        that.xhr.send(that.data, true);

        return that;
    };

    Request.prototype.setHeaders = function () {
        var that = this,
            headers = that.headers,
            key;

        for (key in headers) {
            if (headers.hasOwnProperty(key)) {
                that.xhr.setRequestHeader(key, headers[key]);
            }
        }

        return that;
    };

    function parseResponseHeaders(str) {
        var list = str.split("\n");
        var headers = {};
        var parts;
        var i = 0, len = list.length;
        while (i < len) {
            parts = list[i].split(': ');
            if (parts[0] && parts[1]) {
                parts[0] = parts[0].split('-').join('').split('');
                parts[0][0] = parts[0][0].toLowerCase();
                headers[parts[0].join('')] = parts[1];
            }
            i += 1;
        }
        return headers;
    }

    function addDefaults(options, defaults) {
        for(var i in defaults) {
            if(defaults.hasOwnProperty(i) && options[i] === undefined) {
                if (typeof defaults[i] === 'object') {
                    options[i] = {};
                    addDefaults(options[i], defaults[i]);
                } else {
                    options[i] = defaults[i];
                }
            }
        }
        return options;
    }

    /**
     * Public Methods
     */
    for (i; i < methodsLength; i += 1) {
        /* jshint ignore:start */
        (function () {
            var method = methods[i];
            result[method] = function (url, success) {
                var options = {};

                if (url === undefined) {
                    throw new Error('CORS: url must be defined');
                }

                if (typeof url === 'object') {
                    options = url;

                } else {
                    if (typeof success === 'function') {
                        options.success = success;
                    }

                    options.url = url;
                }

                options.method = method.toUpperCase();
                addDefaults(options, result.defaults);
                return new Request(options).xhr;
            };
        }());
        /* jshint ignore:end */
    }
    result.defaults = {
        headers: {}
    };
    return result;
}());<commit_msg>added mock data to http.<commit_after>/* global ajax */
utils.ajax.http = (function () {
    /**
     * Module dependencies.
     */
    var serialize = function (obj) {
        var str = [];
        for (var p in obj)
            if (obj.hasOwnProperty(p)) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
        return str.join("&");
    };

    var win = window,
        CORSxhr = (function () {
            var xhr;

            if (win.XMLHttpRequest && ('withCredentials' in new win.XMLHttpRequest())) {
                xhr = win.XMLHttpRequest;

            } else if (win.XDomainRequest) {
                xhr = win.XDomainRequest;
            }

            return xhr;
        }()),
        methods = ['head', 'get', 'post', 'put', 'delete'],
        i = 0,
        methodsLength = methods.length,
        result = {},
        mockMode,
        mockRegistry = [];

    function Request(options) {
        this.init(options);
    }

    Request.prototype.init = function (options) {
        var that = this;

        that.xhr = new CORSxhr();
        that.method = options.method;
        that.url = options.url;
        that.success = options.success;
        that.error = options.error;
        that.data = options.data;
        that.headers = options.headers;

        if (options.credentials === true) {
            that.xhr.withCredentials = true;
        }

        that.send();

        return that;
    };

    Request.prototype.send = function () {
        var that = this;

        // serialize data if GET
        if (that.method === 'GET' && that.data) {
            var concat = that.url.indexOf('?') > -1 ? '&' : '?';
            that.url += concat + serialize(that.data);
        } else {
            that.data = JSON.stringify(that.data);
        }

        // Success callback
        if (that.success !== undefined) {
            that.xhr.onload = function () {
                var headers = parseResponseHeaders(this.getAllResponseHeaders());
                var response = this.responseText;
                if (headers.contentType && headers.contentType.indexOf('application/json') !== -1) {
                    response = JSON.parse(response);
                }
                that.success.call(this, {
                    data: response,
                    request: {
                        method: that.method,
                        url: that.url,
                        data: that.data,
                        headers: that.headers
                    },
                    headers: headers,
                    status: this.status
                });
            };
        }

        // Error callback
        if (that.error !== undefined) {
            that.xhr.error = function () {
                that.error.call(this, this.responseText);
            };
        }

        that.xhr.open(that.method, that.url, true);

        if (that.headers !== undefined) {
            that.setHeaders();
        }

        // Send
        that.xhr.send(that.data, true);

        return that;
    };

    Request.prototype.setHeaders = function () {
        var that = this,
            headers = that.headers,
            key;

        for (key in headers) {
            if (headers.hasOwnProperty(key)) {
                that.xhr.setRequestHeader(key, headers[key]);
            }
        }

        return that;
    };

    function parseResponseHeaders(str) {
        var list = str.split("\n");
        var headers = {};
        var parts;
        var i = 0, len = list.length;
        while (i < len) {
            parts = list[i].split(': ');
            if (parts[0] && parts[1]) {
                parts[0] = parts[0].split('-').join('').split('');
                parts[0][0] = parts[0][0].toLowerCase();
                headers[parts[0].join('')] = parts[1];
            }
            i += 1;
        }
        return headers;
    }

    function addDefaults(options, defaults) {
        for (var i in defaults) {
            if (defaults.hasOwnProperty(i) && options[i] === undefined) {
                if (typeof defaults[i] === 'object') {
                    options[i] = {};
                    addDefaults(options[i], defaults[i]);
                } else {
                    options[i] = defaults[i];
                }
            }
        }
        return options;
    }

    function findAdapter(options) {
        var i, len = mockRegistry.length, mock, result;
        for (i = 0; i < len; i += 1) {
            mock = mockRegistry[i];
            if (mock.type === "string" || mock.type === "object") {
                result = options.url.match(mock.matcher);
            } else if (mock.type === "function") {
                result = mock.matcher(options);
            }
            if (result) {
                result = mock.adapter;
            }
        }
        return result;
    }

    /**
     * Public Methods
     */
    for (i; i < methodsLength; i += 1) {
        /* jshint ignore:start */
        (function () {
            var method = methods[i];
            result[method] = function (url, success) {
                var options = {}, adapter, adapterResult;

                if (url === undefined) {
                    throw new Error('CORS: url must be defined');
                }

                if (typeof url === 'object') {
                    options = url;

                } else {
                    if (typeof success === 'function') {
                        options.success = success;
                    }

                    options.url = url;
                }

                options.method = method.toUpperCase();
                addDefaults(options, result.defaults);
                if (mockMode) {
                    adapter = findAdapter(options);
                    if (adapter) {
                        adapterResult = adapter(options);
                        if (adapterResult === true) {
                            options.method = "GET";
                            return new Request(options).xhr;
                        }
                        return adapterResult;
                    } else if (window.console && console.warn) {
                        console.warn("No adapter found for " + options.url + ". Adapter required in mock mode.");
                    }
                }
                return new Request(options).xhr;
            };
        }());
        /* jshint ignore:end */
    }
    result.mock = function (enable) {
        mockMode = !!enable;
    };
    /**
     * registerMock
     * @param {string|regEx|fn} matcher
     * @param {constructor} adapter
     */
    result.registerMock = function (matcher, adapter) {
        mockRegistry.push({matcher: matcher, type: typeof matcher, adapter: adapter});
    };
    result.defaults = {
        headers: {}
    };
    return result;
}());<|endoftext|>


<commit_before>import TreefulNode from './treeful-node';

let _treefulInstance = null;

class Treeful {
	constructor() {
		if(_treefulInstance) {
			return _treefulInstance;
		}
		_treefulInstance = this;

		let _tree = {};
		let _ids = [];

		this.addRootNode = () => {
			//CHECK TO MAKE SURE ROOT NODE ISNT CREATED
			const branch = {};
			branch['root'] = new TreefulNode('root');
			_tree = Object.assign({}, branch);
			_ids.push('root');
		};

		this.addNode = (id, data = null, parent = 'root') => {
			//if id is not a string? if data is a function? if parent doens't exist?
			if(_ids.indexOf(id) > -1) {
				throw new Error('Cannot use duplicate node IDs');
				return;
			}
			const node = new TreefulNode(id, data);
			const branch = {};
			branch[id] = node;
			_tree = Object.assign(_tree, branch);
			_ids.push(id);
			_tree[parent].addNode(node);
			return this;
		};

		this.setData = (id, data) => {
			//MAKE SURE THAT THERE IS NO TYPE MUTATION (except null)
			_tree[id].setData(data);
		};

		this.getData = id => {
			//if id is invalid? not found?
			return _tree[id].getData();
		}

		this.getTree = () => _tree['root'];

		this.subscribe = (id, callback) => {
			//if id is invalid? not found?
			_tree[id].subscribe(callback);
		};

		this.destroy = () => {
			_tree = {};
			_ids = [];
			_treefulInstance = null;
		};

		this.addRootNode();
	}
};

export default new Treeful();<commit_msg>added type checking<commit_after>import TreefulNode from './treeful-node';

let _treefulInstance = null;

class Treeful {
	constructor() {
		if(_treefulInstance) {
			return _treefulInstance;
		}
		_treefulInstance = this;
		let _tree;

		this.addNode = (id, data = null, parent = 'root') => {
			checkIdType(id);
			checkDuplicate(id);
			checkDataType(data);
			checkIdExists(parent);

			const node = new TreefulNode(id, data);
			const branch = {};
			branch[id] = node;
			_tree = Object.assign(_tree, branch);
			_tree[parent].addNode(node);

			return this;
		};

		this.setData = (id, data) => {
			checkIdType(id);
			checkIdExists(id);
			checkDataType(data);
			checkTypeMutation(id, data);

			_tree[id].setData(data);
		};

		this.getData = id => {
			checkIdType(id);
			checkIdExists(id);

			return _tree[id].getData();
		};

		this.subscribe = (id, callback) => {
			checkIdType(id);
			checkIdExists(id);
			checkCallbackType(callback);

			_tree[id].subscribe(callback);
		};

		this.destroy = () => {
			init();
		};

		const init = () => {
			_tree = {};
			addRootNode();
		};

		const addRootNode = () => {
			const branch = {};
			branch['root'] = new TreefulNode('root');
			_tree = Object.assign({}, branch);
		};

		const checkIdExists = id => {
			if(Object.keys(_tree).indexOf(id) < 0) {
				throw new Error('Node with id \'' + id + '\' is not found.');
			}
		};

		const checkIdType = id => {
			if(!isType(id, 'string')) {
				throw new TypeError('Id must be a string.');
			}
		};

		const checkDataType = data => {
			if(isType(data, 'function')) {
				throw new TypeError('Data cannot be a function.');
			}
		};

		const checkDuplicate = id => {
			if(Object.keys(_tree).indexOf(id) > -1) {
				throw new Error('Cannot use duplicate id \'' + id + '\'.');
			}
		};

		const checkCallbackType = callback => {
			if(!isType(callback, 'function')) {
				throw new TypeError('Callback must be a function.');
			}
		};

		const checkTypeMutation = (id, data) => {
			if(!isType(this.getData(id), null) && !isType(data, getType(this.getData(id)))) {
				throw new Error('Data type cannot be mutated from ' + getType(this.getData(id)) + ' to ' + getType(data) + '.');
			}
		};

		const getType = e => {
			return {}.toString.call(e).toLowerCase().split(' ')[1].replace(']', '');
		};

		const isType = (e, type) => {
			return {}.toString.call(e).toLowerCase().indexOf(type) > -1;
		};

		init();
	}
};

export default new Treeful();<|endoftext|>


<commit_before>import * as dotenv from 'dotenv';
dotenv.config({ debug: true });

console.log('process.env.ENVIRONMENT', process.env.ENVIRONMENT);
console.log('process.env.API', process.env.API);

const baseBundleId = 'gov.dts.ugrc.utahwvcr';
const bundleIds = {
  development: `${baseBundleId}.dev`,
  staging: `${baseBundleId}.staging`,
  production: baseBundleId,
};
const bundleId = bundleIds[process.env.ENVIRONMENT];
const names = {
  development: 'WVC (Dev)',
  staging: 'WVC (Staging)',
  production: 'WVC Reporter',
};
const name = names[process.env.ENVIRONMENT];
console.log('bundleId', bundleId);

// perhaps this bump could be automated using a combo of app.config.json and this file?
const buildNumber = 574;

export default {
  name,
  slug: 'wildlife-vehicle-collision-reporter',
  description: 'A mobile application for reporting and removing animal carcasses.',
  scheme: bundleId.replaceAll('.', '-'),
  githubUrl: 'https://github.com/agrc/roadkill-mobile',
  version: '3.0.0',
  orientation: 'portrait',
  icon: process.env.ENVIRONMENT === 'production' ? './assets/icon.png' : `./assets/icon_${process.env.ENVIRONMENT}.png`,
  splash: {
    image:
      process.env.ENVIRONMENT === 'production'
        ? './assets/splash.png'
        : `./assets/splash_${process.env.ENVIRONMENT}.png`,
    resizeMode: 'contain',
    backgroundColor: '#ffffff',
  },
  assetBundlePatterns: ['**/*'],
  // hermes was causing issues with environment variables. For some reason
  // it was making the prod app point to the staging api
  // wait until upgrade to expo 47 to try again
  // jsEngine: 'hermes',
  ios: {
    bundleIdentifier: bundleId,
    googleServicesFile: process.env.GOOGLE_SERVICES_IOS,
    buildNumber: buildNumber.toString(),
    supportsTablet: true,
    config: {
      usesNonExemptEncryption: false,
      googleMapsApiKey: process.env.GOOGLE_MAPS_API_KEY_IOS,
    },
    infoPlist: {
      NSLocationAlwaysUsageDescription:
        'The app uses your location in the background for tracking routes. *Note* this is only applicable for agency employees or contractors. Background location is not used for public users.',
      NSLocationWhenInUseUsageDescription:
        'The app uses your location to help record the location of the animal that you are reporting.',
      UIBackgroundModes: ['location'],
    },
  },
  android: {
    package: bundleId,
    googleServicesFile: process.env.GOOGLE_SERVICES_ANDROID,
    versionCode: buildNumber,
    softwareKeyboardLayoutMode: 'pan',
    adaptiveIcon: {
      foregroundImage:
        process.env.ENVIRONMENT === 'production'
          ? './assets/adaptive-icon.png'
          : `./assets/adaptive-icon_${process.env.ENVIRONMENT}.png`,
      backgroundColor: '#FFFFFF',
    },
    permissions: [
      'ACCESS_FINE_LOCATION',
      'ACCESS_COARSE_LOCATION',
      'ACCESS_BACKGROUND_LOCATION',
      'FOREGROUND_SERVICE',
      'READ_EXTERNAL_STORAGE',
      'WRITE_EXTERNAL_STORAGE',
    ],
    config: {
      googleMaps: {
        apiKey: process.env.GOOGLE_MAPS_API_KEY_ANDROID,
      },
    },
  },
  hooks: {
    postPublish: [
      {
        file: 'sentry-expo/upload-sourcemaps',
        config: {
          organization: 'utah-ugrc',
          project: 'roadkill',
          authToken: process.env.SENTRY_AUTH_TOKEN,
        },
      },
    ],
  },
  plugins: [
    'sentry-expo',
    'expo-notifications',
    [
      'expo-image-picker',
      {
        photosPermission: 'The app accesses to your photos to allow you to submit a photo of the animal.',
        cameraPermission: 'The app accesses your camera to allow you to capture and submit a photo of the animal.',
      },
    ],
    [
      'react-native-fbsdk-next',
      {
        appID: process.env.FACEBOOK_OAUTH_CLIENT_ID,
        clientToken: process.env.FACEBOOK_OAUTH_CLIENT_TOKEN,
        displayName: `Utah ${name}`,
        advertiserIDCollectionEnabled: false,
        autoLogAppEventsEnabled: false,
      },
    ],
    [
      'expo-build-properties',
      {
        ios: {
          // required for react-native-maps, expo default for sdk 46 is 12.0
          // ref: https://github.com/react-native-maps/react-native-maps/blob/master/docs/installation.md#enabling-google-maps
          deploymentTarget: '13.0',

          // this will be needed when expo-firebase-analytics (7.2+) and react-native-maps (1.3.2+) are bumped
          // it fixes firebase but breaks maps
          // waiting on https://github.com/react-native-maps/react-native-maps/discussions/4389
          // // https://docs.expo.dev/versions/latest/sdk/firebase-analytics/#additional-configuration-for-ios
          // useFrameworks: 'static',
        },
      },
    ],
  ],
  extra: {
    eas: {
      projectId: '648c99de-696c-4704-8723-7f8838dc6896',
    },
  },

  // required for eas update command
  runtimeVersion: '1.0.0',
  updates: {
    url: 'https://u.expo.dev/648c99de-696c-4704-8723-7f8838dc6896',
  },
};
<commit_msg>build(front): these log statements broke the android build<commit_after>import * as dotenv from 'dotenv';
dotenv.config();

const baseBundleId = 'gov.dts.ugrc.utahwvcr';
const bundleIds = {
  development: `${baseBundleId}.dev`,
  staging: `${baseBundleId}.staging`,
  production: baseBundleId,
};
const bundleId = bundleIds[process.env.ENVIRONMENT];
const names = {
  development: 'WVC (Dev)',
  staging: 'WVC (Staging)',
  production: 'WVC Reporter',
};
const name = names[process.env.ENVIRONMENT];

// perhaps this bump could be automated using a combo of app.config.json and this file?
const buildNumber = 574;

export default {
  name,
  slug: 'wildlife-vehicle-collision-reporter',
  description: 'A mobile application for reporting and removing animal carcasses.',
  scheme: bundleId.replaceAll('.', '-'),
  githubUrl: 'https://github.com/agrc/roadkill-mobile',
  version: '3.0.0',
  orientation: 'portrait',
  icon: process.env.ENVIRONMENT === 'production' ? './assets/icon.png' : `./assets/icon_${process.env.ENVIRONMENT}.png`,
  splash: {
    image:
      process.env.ENVIRONMENT === 'production'
        ? './assets/splash.png'
        : `./assets/splash_${process.env.ENVIRONMENT}.png`,
    resizeMode: 'contain',
    backgroundColor: '#ffffff',
  },
  assetBundlePatterns: ['**/*'],
  // hermes was causing issues with environment variables. For some reason
  // it was making the prod app point to the staging api
  // wait until upgrade to expo 47 to try again
  // jsEngine: 'hermes',
  ios: {
    bundleIdentifier: bundleId,
    googleServicesFile: process.env.GOOGLE_SERVICES_IOS,
    buildNumber: buildNumber.toString(),
    supportsTablet: true,
    config: {
      usesNonExemptEncryption: false,
      googleMapsApiKey: process.env.GOOGLE_MAPS_API_KEY_IOS,
    },
    infoPlist: {
      NSLocationAlwaysUsageDescription:
        'The app uses your location in the background for tracking routes. *Note* this is only applicable for agency employees or contractors. Background location is not used for public users.',
      NSLocationWhenInUseUsageDescription:
        'The app uses your location to help record the location of the animal that you are reporting.',
      UIBackgroundModes: ['location'],
    },
  },
  android: {
    package: bundleId,
    googleServicesFile: process.env.GOOGLE_SERVICES_ANDROID,
    versionCode: buildNumber,
    softwareKeyboardLayoutMode: 'pan',
    adaptiveIcon: {
      foregroundImage:
        process.env.ENVIRONMENT === 'production'
          ? './assets/adaptive-icon.png'
          : `./assets/adaptive-icon_${process.env.ENVIRONMENT}.png`,
      backgroundColor: '#FFFFFF',
    },
    permissions: [
      'ACCESS_FINE_LOCATION',
      'ACCESS_COARSE_LOCATION',
      'ACCESS_BACKGROUND_LOCATION',
      'FOREGROUND_SERVICE',
      'READ_EXTERNAL_STORAGE',
      'WRITE_EXTERNAL_STORAGE',
    ],
    config: {
      googleMaps: {
        apiKey: process.env.GOOGLE_MAPS_API_KEY_ANDROID,
      },
    },
  },
  hooks: {
    postPublish: [
      {
        file: 'sentry-expo/upload-sourcemaps',
        config: {
          organization: 'utah-ugrc',
          project: 'roadkill',
          authToken: process.env.SENTRY_AUTH_TOKEN,
        },
      },
    ],
  },
  plugins: [
    'sentry-expo',
    'expo-notifications',
    [
      'expo-image-picker',
      {
        photosPermission: 'The app accesses to your photos to allow you to submit a photo of the animal.',
        cameraPermission: 'The app accesses your camera to allow you to capture and submit a photo of the animal.',
      },
    ],
    [
      'react-native-fbsdk-next',
      {
        appID: process.env.FACEBOOK_OAUTH_CLIENT_ID,
        clientToken: process.env.FACEBOOK_OAUTH_CLIENT_TOKEN,
        displayName: `Utah ${name}`,
        advertiserIDCollectionEnabled: false,
        autoLogAppEventsEnabled: false,
      },
    ],
    [
      'expo-build-properties',
      {
        ios: {
          // required for react-native-maps, expo default for sdk 46 is 12.0
          // ref: https://github.com/react-native-maps/react-native-maps/blob/master/docs/installation.md#enabling-google-maps
          deploymentTarget: '13.0',

          // this will be needed when expo-firebase-analytics (7.2+) and react-native-maps (1.3.2+) are bumped
          // it fixes firebase but breaks maps
          // waiting on https://github.com/react-native-maps/react-native-maps/discussions/4389
          // // https://docs.expo.dev/versions/latest/sdk/firebase-analytics/#additional-configuration-for-ios
          // useFrameworks: 'static',
        },
      },
    ],
  ],
  extra: {
    eas: {
      projectId: '648c99de-696c-4704-8723-7f8838dc6896',
    },
  },

  // required for eas update command
  runtimeVersion: '1.0.0',
  updates: {
    url: 'https://u.expo.dev/648c99de-696c-4704-8723-7f8838dc6896',
  },
};
<|endoftext|>


<commit_before>//
// This is NodeJS code
//
// Example:
//
//     node vendor/pragmarx/sdk/src/Services/Chat/NodeJS/socket.js
//     node app/Services/Chat/Server/NodeJs/socket.js
//
//

var port = 23172;

var server = require('http').Server();

var io = require('socket.io')(server);

var Redis = require('ioredis');

var redis = new Redis();

redis.subscribe('chat-channel');

redis.on('message', function(channel, message)
{
    message = JSON.parse(message);

    var text = '';

    if (typeof message.data != 'undefined' && message.data && typeof message.data.message != 'undefined')
    {
        if (typeof message.data.fullName != 'undefined' && message.data.fullName)
        {
            text += ' # '+message.data.fullName;
        }

        text += '> '+message.data.message;
    }

    console.log(channel + ': ' + message.event + text);

    io.emit(channel + ':' + message.event, message.data);
});

console.log('Listening port '+port+'...');

server.listen(port);
<commit_msg>Move to debug<commit_after>//
// This is NodeJS code
//
// Example:
//
//     node vendor/pragmarx/sdk/src/Services/Chat/NodeJS/socket.js
//     node app/Services/Chat/Server/NodeJs/socket.js
//
//

var port = 23172;

var server = require('http').Server();

var io = require('socket.io')(server);

var Redis = require('ioredis');

var redis = new Redis();

redis.subscribe('chat-channel');

redis.on('message', function(channel, message)
{
    message = JSON.parse(message);

    var text = '';

    if (typeof message.data != 'undefined' && message.data && typeof message.data.message != 'undefined')
    {
        if (typeof message.data.fullName != 'undefined' && message.data.fullName)
        {
            text += ' # '+message.data.fullName;
        }

        text += '> '+message.data.message;
    }

    debug(channel + ': ' + message.event + text);

    io.emit(channel + ':' + message.event, message.data);
});

debug('Listening port '+port+'...');

server.listen(port);
<|endoftext|>


<commit_before>'use strict';

const exec = require('cp-sugar').exec;
const pathJoin = require('path').join;
const readFile = require('fs').readFileSync;
const unlink = require('fs').unlinkSync;
const sep = require('path').sep;
const tempFolder = require('osenv').tmpdir();
const path = require('path');
const EOL = require('os').EOL;

// npm audit error codes
/**
 * Missing package-lock.json
 */
const EAUDITNOLOCK = 'EAUDITNOLOCK';

/**
 * Audit the project in directory projectDir
 * @param {(string | undefined)} projectDir - project directory to be analyzed by npm audit
 */
module.exports = function audit(projectDir) {
    try {
        const options = getDefaultOptionsFor(projectDir);
        process.chdir(options.directoryToAudit);
        const command = `npm audit --json > ${options.auditLogFilepath}`;

        return exec(command)
            .then(() => createResponseFromAuditLog(options.auditLogFilepath))
            .catch((err) =>
                createResponseFromAuditLogOrFromError(
                    options.auditLogFilepath,
                    err
                )
            )
            .then((response) => {
                if (packageLockHasBeenFound(response)) {
                    return removeIgnoredVulnerabilities(response, options);
                }

                const createLockFileCommand = `npm i --package-lock-only > ${
                    options.createLockLogFilepath
                }`;

                return exec(createLockFileCommand)
                    .then(() => exec(command))
                    .then(() =>
                        createResponseFromAuditLog(options.auditLogFilepath)
                    )
                    .catch((err) =>
                        createResponseFromAuditLogOrFromError(
                            options.auditLogFilepath,
                            err
                        )
                    )
                    .then((result) =>
                        processResult(result).whenErrorIs(EAUDITNOLOCK)
                    )
                    .then((result) =>
                        removePackageLockFrom(options.directoryToAudit, result)
                    )
                    .then((result) =>
                        removeIgnoredVulnerabilities(result, options)
                    );
            });
    } catch (error) {
        return Promise.reject(error.message);
    }
};

function packageLockHasNotBeenFound(response) {
    return response && response.error && response.error.code === EAUDITNOLOCK;
}

function packageLockHasBeenFound(response) {
    return !packageLockHasNotBeenFound(response);
}

function createResponseFromAuditLog(logFilePath) {
    try {
        const response = JSON.parse(readFile(logFilePath).toString());
        return response;
    } catch (err) {
        return {
            error: {
                summary: err.message,
            },
        };
    }
}

function createResponseFromAuditLogOrFromError(logFilePath, err) {
    try {
        const response = JSON.parse(readFile(logFilePath).toString());
        return response;
    } catch (err2) {
        // prettier-ignore
        return {
            error: {
                summary: err && err.message
                    ? err.message
                    : err2.message,
            },
        };
    }
}

/**
 * Middleware that intercept any input error object.
 * This middleware may modify the inital error message
 * @param {Object} result -  result of the npm audit command
 */
function processResult(result) {
    return {
        whenErrorIs: (errorCode) => {
            if (
                errorCode === EAUDITNOLOCK &&
                packageLockHasNotBeenFound(result)
            ) {
                const summary = result.error.summary || '';
                result.error.summary = `package.json file is missing or is badly formatted. ${summary}`;
                return result;
            }
            return result;
        },
    };
}

/**
 * Middleware that removes the auto-generated package-lock.json
 * @param {string} projectDir - folder where the package-lock.json file has been generated
 * @param {*} response - result of the npm audit command (eventually modified by previous middlewares execution)
 * @returns input response if file removal is ok
 * In case of error it adds or updates into the input response object the property 'internalErrors'
 */
function removePackageLockFrom(projectDir, response) {
    try {
        const file = pathJoin(projectDir, 'package-lock.json');
        unlink(file);
        return response;
    } catch (error) {
        if (error.code === 'ENOENT') {
            return response;
        }
        if (response) {
            response.internalErrors = response.internalErrors || [];
            response.internalErrors.push(error);
            return response;
        }
        return response;
    }
}

/**
 * exported for testing purposes
 */
module.exports.removePackageLockFrom = removePackageLockFrom;

/**
 * Remove, from npm audit command response, the vulnerabilities defined in .auditignore file
 * @param {*} response - result of the npm audit command (eventually modified by previous middlewares execution)
 * @param {DefaultOptions} options - options
 */
function removeIgnoredVulnerabilities(response, options) {
    try {
        const ignoredVulnerabilities = getIgnoredVulnerabilities(options);
        if (ignoredVulnerabilities && ignoredVulnerabilities.length === 0) {
            return response;
        }
        const filteredResponse = JSON.parse(JSON.stringify(response, null, 2));

        filteredResponse.actions = filteredResponse.actions
            .map((action) => {
                action.resolves = action.resolves.filter(
                    (resolve) =>
                        ignoredVulnerabilities.indexOf(`${resolve.id}`) < 0
                );
                return action;
            })
            .filter((action) => action.resolves.length > 0);

        ignoredVulnerabilities.forEach(
            (ignoredVulnerability) =>
                delete filteredResponse.advisories[ignoredVulnerability]
        );

        const vulnerabilitiesMetadata = {
            info: 0,
            low: 0,
            moderate: 0,
            high: 0,
            critical: 0,
        };

        const severities = {};
        const advisories = filteredResponse.advisories;
        for (const key in advisories) {
            if (advisories.hasOwnProperty(key)) {
                const advisory = advisories[key];
                severities[`${advisory.id}`] = advisory.severity;
            }
        }

        filteredResponse.actions.forEach((action) => {
            action.resolves.forEach((resolve) => {
                vulnerabilitiesMetadata[severities[`${resolve.id}`]] += 1;
            });
        });

        filteredResponse.metadata.vulnerabilities = vulnerabilitiesMetadata;

        return filteredResponse;
    } catch (error) {
        if (response) {
            response.internalErrors = response.internalErrors || [];
            response.internalErrors.push(error);
            return response;
        }
        return response;
    }
}

/**
 * exported for testing purposes
 */
module.exports.removeIgnoredVulnerabilities = removeIgnoredVulnerabilities;

/**
 * @typedef DefaultOptions
 * @type {Object}
 * @property {string} directoryToAudit - Folder to audit. Defaults to process.cwd()
 * @property {string} auditLogFilepath - Path of the file that will receive all output of the npm-audit command.
 * @property {string} createLockLogFilepath - Path of the file that will receive all output of the 'npm i --package-lock-only' command.
 */

/**
 * Get default options of this module
 * @param {string} projectDir - path to the directory that will be analyzed by npm audit
 * @returns {DefaultOptions}
 */
function getDefaultOptionsFor(projectDir) {
    const directoryToAudit = projectDir || process.cwd();
    const projectName = directoryToAudit.split(sep).pop() || '';
    const auditLogFilename = `npm-audit-${projectName.trim()}.log`;
    const auditLogFilepath = path.resolve(tempFolder, auditLogFilename);
    const createLockLogFilename = `npm-audit-${projectName.trim()}-create-lock.log`;
    const createLockLogFilepath = path.resolve(
        tempFolder,
        createLockLogFilename
    );

    return {
        directoryToAudit,
        auditLogFilepath,
        createLockLogFilepath,
    };
}

function getIgnoredVulnerabilities(options) {
    try {
        const auditIgnoreFile = pathJoin(
            options.directoryToAudit,
            '.auditignore'
        );
        const content = readFile(auditIgnoreFile).toString();
        return content
            .split(EOL)
            .filter((vulnerabilityUri) => vulnerabilityUri.includes('https://'))
            .map((vulnerabilityUri) => vulnerabilityUri.split('/').pop())
            .map((id) => id.replace('\n', ''))
            .map((id) => id.replace('\r', ''))
            .map((id) => id.trim());
    } catch (error) {
        return [];
    }
}

/**
 * exported for testing purposes
 */
module.exports.getNpmAuditOptions = getNpmAuditOptions;

/**
 * Get all command-line options defined in the audit.opts file.
 * This method is for the moment restricted to read the --audit-level option only
 * @param {DefaultOptions} options - default options of this module
 * @returns {NpmAuditOptions}
 */
function getNpmAuditOptions(options) {
    try {
        const auditOptionsFile = pathJoin(
            options.directoryToAudit,
            'audit.opts'
        );
        const content = readFile(auditOptionsFile).toString();

        return content
            .split(EOL)
            .filter((commandLineOption) =>
                commandLineOption.includes('--audit-level')
            )
            .map((commandLineOption) =>
                commandLineOption.replace(/[\n,\r]/g, '')
            )
            .map((commandLineOption) => commandLineOption.replace(/[\t]/g, ' '))
            .map((commandLineOption) => commandLineOption.trim())
            .reduce((result, commandLineOption) => {
                const keyValue = getNpmAuditOptionFrom(commandLineOption);
                if (keyValue.key) {
                    result[keyValue.key] = keyValue.value;
                }
                enforceValidValueForAuditLevelIn(result);
                return result;
            }, defaultNpmAuditOptions);
    } catch (error) {
        return defaultNpmAuditOptions;
    }
}

/**
 * @enum {string}
 */
const auditLevel = {
    low: 'low',
    moderate: 'moderate',
    high: 'high',
    critical: 'critical',
};
/**
 * exported for testing purposes
 */
module.exports.auditLevel = auditLevel;

/**
 * @typedef NpmAuditOptions
 * @type {Object}
 * @property {string} ['--audit-level'] - audit level option
 */

/**
 * Default options used when they are missing in audit.opts file
 * or when the audit.opts file is missing.
 * @type {NpmAuditOptions}
 */
const defaultNpmAuditOptions = {
    '--audit-level': auditLevel.low,
};

/**
 * @typedef KeyValue
 * @type {Object}
 * @property {string} key - key part of the key-value object
 * @property {string} value - value part of the key-value object
 */
/**
 * Extract the key and value of an npm-audit command-line option
 * @param {string} option - npm audit comman-line option
 * @returns {KeyValue}
 */
function getNpmAuditOptionFrom(option) {
    if (!option) {
        return {
            key: undefined,
            value: undefined,
        };
    }
    if (option.includes('=')) {
        const parts = option.split('=').map((part) => part.trim());
        return {
            key: parts[0],
            value: parts[1] ? parts[1] : true,
        };
    }
    const parts = option.split(' ').filter((part) => part && part.length > 0);
    return {
        key: parts[0],
        value: parts[1] ? parts[1] : true,
    };
}

function enforceValidValueForAuditLevelIn(npmAuditOptions) {
    if (npmAuditOptions && npmAuditOptions['--audit-level']) {
        const value = npmAuditOptions['--audit-level'];
        // prettier-ignore
        switch (value) {
        case auditLevel.low:
        case auditLevel.moderate:
        case auditLevel.high:
        case auditLevel.critical:
            return;
        default:
            npmAuditOptions['--audit-level'] = auditLevel.low;
            return;
        }
    }
}
<commit_msg>fix(audit): handle all possible line breaking in audit.opts<commit_after>'use strict';

const exec = require('cp-sugar').exec;
const pathJoin = require('path').join;
const readFile = require('fs').readFileSync;
const unlink = require('fs').unlinkSync;
const sep = require('path').sep;
const tempFolder = require('osenv').tmpdir();
const path = require('path');
const EOL = require('os').EOL;

// npm audit error codes
/**
 * Missing package-lock.json
 */
const EAUDITNOLOCK = 'EAUDITNOLOCK';

/**
 * Audit the project in directory projectDir
 * @param {(string | undefined)} projectDir - project directory to be analyzed by npm audit
 */
module.exports = function audit(projectDir) {
    try {
        const options = getDefaultOptionsFor(projectDir);
        process.chdir(options.directoryToAudit);
        const command = `npm audit --json > ${options.auditLogFilepath}`;

        return exec(command)
            .then(() => createResponseFromAuditLog(options.auditLogFilepath))
            .catch((err) =>
                createResponseFromAuditLogOrFromError(
                    options.auditLogFilepath,
                    err
                )
            )
            .then((response) => {
                if (packageLockHasBeenFound(response)) {
                    return removeIgnoredVulnerabilities(response, options);
                }

                const createLockFileCommand = `npm i --package-lock-only > ${
                    options.createLockLogFilepath
                }`;

                return exec(createLockFileCommand)
                    .then(() => exec(command))
                    .then(() =>
                        createResponseFromAuditLog(options.auditLogFilepath)
                    )
                    .catch((err) =>
                        createResponseFromAuditLogOrFromError(
                            options.auditLogFilepath,
                            err
                        )
                    )
                    .then((result) =>
                        processResult(result).whenErrorIs(EAUDITNOLOCK)
                    )
                    .then((result) =>
                        removePackageLockFrom(options.directoryToAudit, result)
                    )
                    .then((result) =>
                        removeIgnoredVulnerabilities(result, options)
                    );
            });
    } catch (error) {
        return Promise.reject(error.message);
    }
};

function packageLockHasNotBeenFound(response) {
    return response && response.error && response.error.code === EAUDITNOLOCK;
}

function packageLockHasBeenFound(response) {
    return !packageLockHasNotBeenFound(response);
}

function createResponseFromAuditLog(logFilePath) {
    try {
        const response = JSON.parse(readFile(logFilePath).toString());
        return response;
    } catch (err) {
        return {
            error: {
                summary: err.message,
            },
        };
    }
}

function createResponseFromAuditLogOrFromError(logFilePath, err) {
    try {
        const response = JSON.parse(readFile(logFilePath).toString());
        return response;
    } catch (err2) {
        // prettier-ignore
        return {
            error: {
                summary: err && err.message
                    ? err.message
                    : err2.message,
            },
        };
    }
}

/**
 * Middleware that intercept any input error object.
 * This middleware may modify the inital error message
 * @param {Object} result -  result of the npm audit command
 */
function processResult(result) {
    return {
        whenErrorIs: (errorCode) => {
            if (
                errorCode === EAUDITNOLOCK &&
                packageLockHasNotBeenFound(result)
            ) {
                const summary = result.error.summary || '';
                result.error.summary = `package.json file is missing or is badly formatted. ${summary}`;
                return result;
            }
            return result;
        },
    };
}

/**
 * Middleware that removes the auto-generated package-lock.json
 * @param {string} projectDir - folder where the package-lock.json file has been generated
 * @param {*} response - result of the npm audit command (eventually modified by previous middlewares execution)
 * @returns input response if file removal is ok
 * In case of error it adds or updates into the input response object the property 'internalErrors'
 */
function removePackageLockFrom(projectDir, response) {
    try {
        const file = pathJoin(projectDir, 'package-lock.json');
        unlink(file);
        return response;
    } catch (error) {
        if (error.code === 'ENOENT') {
            return response;
        }
        if (response) {
            response.internalErrors = response.internalErrors || [];
            response.internalErrors.push(error);
            return response;
        }
        return response;
    }
}

/**
 * exported for testing purposes
 */
module.exports.removePackageLockFrom = removePackageLockFrom;

/**
 * Remove, from npm audit command response, the vulnerabilities defined in .auditignore file
 * @param {*} response - result of the npm audit command (eventually modified by previous middlewares execution)
 * @param {DefaultOptions} options - options
 */
function removeIgnoredVulnerabilities(response, options) {
    try {
        const ignoredVulnerabilities = getIgnoredVulnerabilities(options);
        if (ignoredVulnerabilities && ignoredVulnerabilities.length === 0) {
            return response;
        }
        const filteredResponse = JSON.parse(JSON.stringify(response, null, 2));

        filteredResponse.actions = filteredResponse.actions
            .map((action) => {
                action.resolves = action.resolves.filter(
                    (resolve) =>
                        ignoredVulnerabilities.indexOf(`${resolve.id}`) < 0
                );
                return action;
            })
            .filter((action) => action.resolves.length > 0);

        ignoredVulnerabilities.forEach(
            (ignoredVulnerability) =>
                delete filteredResponse.advisories[ignoredVulnerability]
        );

        const vulnerabilitiesMetadata = {
            info: 0,
            low: 0,
            moderate: 0,
            high: 0,
            critical: 0,
        };

        const severities = {};
        const advisories = filteredResponse.advisories;
        for (const key in advisories) {
            if (advisories.hasOwnProperty(key)) {
                const advisory = advisories[key];
                severities[`${advisory.id}`] = advisory.severity;
            }
        }

        filteredResponse.actions.forEach((action) => {
            action.resolves.forEach((resolve) => {
                vulnerabilitiesMetadata[severities[`${resolve.id}`]] += 1;
            });
        });

        filteredResponse.metadata.vulnerabilities = vulnerabilitiesMetadata;

        return filteredResponse;
    } catch (error) {
        if (response) {
            response.internalErrors = response.internalErrors || [];
            response.internalErrors.push(error);
            return response;
        }
        return response;
    }
}

/**
 * exported for testing purposes
 */
module.exports.removeIgnoredVulnerabilities = removeIgnoredVulnerabilities;

/**
 * @typedef DefaultOptions
 * @type {Object}
 * @property {string} directoryToAudit - Folder to audit. Defaults to process.cwd()
 * @property {string} auditLogFilepath - Path of the file that will receive all output of the npm-audit command.
 * @property {string} createLockLogFilepath - Path of the file that will receive all output of the 'npm i --package-lock-only' command.
 */

/**
 * Get default options of this module
 * @param {string} projectDir - path to the directory that will be analyzed by npm audit
 * @returns {DefaultOptions}
 */
function getDefaultOptionsFor(projectDir) {
    const directoryToAudit = projectDir || process.cwd();
    const projectName = directoryToAudit.split(sep).pop() || '';
    const auditLogFilename = `npm-audit-${projectName.trim()}.log`;
    const auditLogFilepath = path.resolve(tempFolder, auditLogFilename);
    const createLockLogFilename = `npm-audit-${projectName.trim()}-create-lock.log`;
    const createLockLogFilepath = path.resolve(
        tempFolder,
        createLockLogFilename
    );

    return {
        directoryToAudit,
        auditLogFilepath,
        createLockLogFilepath,
    };
}

function getIgnoredVulnerabilities(options) {
    try {
        const auditIgnoreFile = pathJoin(
            options.directoryToAudit,
            '.auditignore'
        );
        const content = readFile(auditIgnoreFile).toString();
        return content
            .split(EOL)
            .filter((vulnerabilityUri) => vulnerabilityUri.includes('https://'))
            .map((vulnerabilityUri) => vulnerabilityUri.split('/').pop())
            .map((id) => id.replace('\n', ''))
            .map((id) => id.replace('\r', ''))
            .map((id) => id.trim());
    } catch (error) {
        return [];
    }
}

/**
 * exported for testing purposes
 */
module.exports.getNpmAuditOptions = getNpmAuditOptions;

/**
 * Get all command-line options defined in the audit.opts file.
 * This method is for the moment restricted to read the --audit-level option only
 * @param {DefaultOptions} options - default options of this module
 * @returns {NpmAuditOptions}
 */
function getNpmAuditOptions(options) {
    try {
        const auditOptionsFile = pathJoin(
            options.directoryToAudit,
            'audit.opts'
        );
        const content = readFile(auditOptionsFile).toString();

        return content
            .split(/EOL|\n|\r/)
            .filter((commandLineOption) =>
                commandLineOption.includes('--audit-level')
            )
            .map((commandLineOption) => commandLineOption.replace(/[\t]/g, ' '))
            .map((commandLineOption) => commandLineOption.trim())
            .reduce((result, commandLineOption) => {
                const keyValue = getNpmAuditOptionFrom(commandLineOption);
                if (keyValue.key) {
                    result[keyValue.key] = keyValue.value;
                }
                enforceValidValueForAuditLevelIn(result);
                return result;
            }, defaultNpmAuditOptions);
    } catch (error) {
        return defaultNpmAuditOptions;
    }
}

/**
 * @enum {string}
 */
const auditLevel = {
    low: 'low',
    moderate: 'moderate',
    high: 'high',
    critical: 'critical',
};
/**
 * exported for testing purposes
 */
module.exports.auditLevel = auditLevel;

/**
 * @typedef NpmAuditOptions
 * @type {Object}
 * @property {string} ['--audit-level'] - audit level option
 */

/**
 * Default options used when they are missing in audit.opts file
 * or when the audit.opts file is missing.
 * @type {NpmAuditOptions}
 */
const defaultNpmAuditOptions = {
    '--audit-level': auditLevel.low,
};

/**
 * @typedef KeyValue
 * @type {Object}
 * @property {string} key - key part of the key-value object
 * @property {string} value - value part of the key-value object
 */
/**
 * Extract the key and value of an npm-audit command-line option
 * @param {string} option - npm audit comman-line option
 * @returns {KeyValue}
 */
function getNpmAuditOptionFrom(option) {
    if (!option) {
        return {
            key: undefined,
            value: undefined,
        };
    }
    if (option.includes('=')) {
        const parts = option.split('=').map((part) => part.trim());
        return {
            key: parts[0],
            value: parts[1] ? parts[1] : true,
        };
    }
    const parts = option.split(' ').filter((part) => part && part.length > 0);
    return {
        key: parts[0],
        value: parts[1] ? parts[1] : true,
    };
}

function enforceValidValueForAuditLevelIn(npmAuditOptions) {
    if (npmAuditOptions && npmAuditOptions['--audit-level']) {
        const value = npmAuditOptions['--audit-level'];
        // prettier-ignore
        switch (value) {
        case auditLevel.low:
        case auditLevel.moderate:
        case auditLevel.high:
        case auditLevel.critical:
            return;
        default:
            npmAuditOptions['--audit-level'] = auditLevel.low;
            return;
        }
    }
}
<|endoftext|>


<commit_before>/*
* Global vars
*/

var $w;
var $h;
var $slides;
var $components;
var $portraits;
var $play;
var $video;
var $navButton;
var $nav;
var anchors;
var is_touch = Modernizr.touch;
var active_counter = null;
var begin = moment();

var breakSlidesForMobile = function() {
    /*
    * break slides into multiple slides if the screen is too small
    */
    $w = $(window).width();
    $h = $(window).height();
};

var setUpFullPage = function() {
    // clear all anchors
    anchors = [];

    // get the anchors

   _.each($slides, function(section) {
        var anchor = $(section).data('anchor');
        if (anchor === undefined) {
            return false;
        }
        anchors.push(anchor);
    });

   console.log(anchors);

    $.fn.fullpage({
        autoScrolling: false,
        anchors: anchors,
        menu: '.nav',
        verticalCentered: false,
        fixedElements: '.primary-navigation, .nav',
        scrollOverflow: true,
        resize: false,
        css3: true,
        loopHorizontal: false,
        afterSlideLoad: lazyLoad,
        afterRender: onPageLoad
    });
};

var onPageLoad = function() {
    // always get the home stuff
    lazyLoad('_', 0, 'home', 0);

    $('.section.active').find('.controlArrow').hide();

    // fade in
    $('body').css('opacity', 1);

    // find the title and fade in
    $('.section.active').find('.text').addClass('fade').css('opacity', 1);
};

var lazyLoad = function(anchorLink, index, slideAnchor, slideIndex) {
    var thisSlide = $slides[slideIndex];
    var nextSlide = $slides[slideIndex + 1];

    slides = [thisSlide, nextSlide];

    getBackgroundImages(slides)

    // hide slide/section nav on titlecards
    if ($slides.first().hasClass('active') === true) {
        $slides.find('.controlArrow').hide();
    }

    if (slideAnchor === 'dashboard') {
        onStartCounts();
    }
};

var getBackgroundImages = function(slides) {
    console.log(slides);
    _.each($(slides), function(slide) {
        var image = 'assets/img/' + $(slide).data('bgimage');

        if (image !== 'assets/img/undefined' && $(slide).css('background-image') === 'none') {
            $(slide).css('background-image', 'url(' + image + ')');
        }
    });
};

var gotoNextSlide = function() {
    $.fn.fullpage.moveSlideRight();
}

var showNav = function() {
    //$nav.height($h);
    $navButton.find('i').toggleClass('fa-bars').toggleClass('fa-times');
    $nav.toggleClass('active');
    if ($nav.hasClass('active')) {
        $nav.css('display', 'block');
        var fade = _.debounce(fadeInNav, 1);
        fade();
    }
    else {
        $nav.css('opacity', 0);
        var fade = _.debounce(fadeOutNav, 500);
        fade();
    }
}

var fadeInNav = function() {
    $nav.css('opacity', 1);
};

var fadeOutNav = function() {
    $nav.css('display', 'none');
};

var revealVideo = function() {
    /*
    * Show the video.
    */

    var text = $(this).parents('.text');
    $(text).hide();
    $(text).parent().css('background-image', '');
    $(text).next().css('display', 'table-cell');
    var player = text.siblings('#player');
    initPlayer(player);
};

var initPlayer = function(player) {

    /*
    * Setup JWPlayer.
    */

    jwplayer('player').setup({
        modes: [{
            type: 'flash',
            src: 'http://www.npr.org/templates/javascript/jwplayer/player.swf',
            config: {
                skin: 'http://media.npr.org/templates/javascript/jwplayer/skins/mle/npr-video-archive/npr-video-archive.zip',
                file: 'http://pd.npr.org/npr-mp4/npr/nprvid/2014/03/20140324_nprvid_juniorrough-n.mp4',
                image: '../assets/img/junior/junior.jpg',
                'hd.file': 'http://pd.npr.org/npr-mp4/npr/nprvid/2014/03/20140324_nprvid_juniorrough-n.mp4'
            }
        }, {
            type: 'html5',
            config: {
                levels: [
                    {
                        file: 'http://pd.npr.org/npr-mp4/npr/nprvid/2014/03/20140324_nprvid_juniorrough-n.mp4',
                        image: '../assets/img/junior/junior.jpg'
                    }
                ]
            }
        }],
        bufferlength: '5',
        controlbar: 'over',
        icons: 'true',
        autostart: false,
        width: '100%',
        height: $h - 50
    });
    jwplayer('player').play();

};

var onUpdateCounts = function(e) {
    /*
    * Updates the count based on elapsed time and known rates.
    */
    var now = moment();
    var elapsed_seconds = (now - begin) / 1000;
    var RATES = [
        ['marijuana', 0.08844],
        ['cocaine', 0.01116],
        ['illegal-entry', 0.01065],
        ['vehicles', 2.15096],
        ['pedestrians', 1.30102]
    ]

    _.each(RATES, function(count, i){
        var count_category = count[0];
        var count_number = count[1];
        var count_unit = count[2];

        $('#' + count_category + ' span.number').html(Math.round(count_number * elapsed_seconds));
    });

};

var onStartCounts = function(e) {
    active_counter = setInterval(onUpdateCounts,500);
}

$(document).ready(function() {

    /*
    * Define vars
    */

    $slides = $('.slide');
    $play_video = $('.btn-video');
    $video = $('.video');
    $components = $('.component');
    $portraits = $('.section[data-anchor="people"] .slide')
    $navButton = $('.primary-navigation-btn');
    $nav = $('.nav');
    $titleCardButton = $('.btn-play');

    // init chapters

    breakSlidesForMobile();
    setUpFullPage();

    // handlers

    $play_video.on('click', revealVideo);
    $navButton.on('click', showNav);
    $titleCardButton.on('click', gotoNextSlide);

    // Redraw slides if the window resizes
    $(window).resize(breakSlidesForMobile);

});<commit_msg>height of video<commit_after>/*
* Global vars
*/

var $w;
var $h;
var $slides;
var $components;
var $portraits;
var $play;
var $video;
var $navButton;
var $nav;
var anchors;
var is_touch = Modernizr.touch;
var active_counter = null;
var begin = moment();

var breakSlidesForMobile = function() {
    /*
    * break slides into multiple slides if the screen is too small
    */
    $w = $(window).width();
    $h = $(window).height();
};

var setUpFullPage = function() {
    // clear all anchors
    anchors = [];

    // get the anchors

   _.each($slides, function(section) {
        var anchor = $(section).data('anchor');
        if (anchor === undefined) {
            return false;
        }
        anchors.push(anchor);
    });

   console.log(anchors);

    $.fn.fullpage({
        autoScrolling: false,
        anchors: anchors,
        menu: '.nav',
        verticalCentered: false,
        fixedElements: '.primary-navigation, .nav',
        scrollOverflow: true,
        resize: false,
        css3: true,
        loopHorizontal: false,
        afterSlideLoad: lazyLoad,
        afterRender: onPageLoad
    });
};

var onPageLoad = function() {
    // always get the home stuff
    lazyLoad('_', 0, 'home', 0);

    $('.section.active').find('.controlArrow').hide();

    // fade in
    $('body').css('opacity', 1);

    // find the title and fade in
    $('.section.active').find('.text').addClass('fade').css('opacity', 1);
};

var lazyLoad = function(anchorLink, index, slideAnchor, slideIndex) {
    var thisSlide = $slides[slideIndex];
    var nextSlide = $slides[slideIndex + 1];

    slides = [thisSlide, nextSlide];

    getBackgroundImages(slides)

    // hide slide/section nav on titlecards
    if ($slides.first().hasClass('active') === true) {
        $slides.find('.controlArrow').hide();
    }

    if (slideAnchor === 'dashboard') {
        onStartCounts();
    }
};

var getBackgroundImages = function(slides) {
    console.log(slides);
    _.each($(slides), function(slide) {
        var image = 'assets/img/' + $(slide).data('bgimage');

        if (image !== 'assets/img/undefined' && $(slide).css('background-image') === 'none') {
            $(slide).css('background-image', 'url(' + image + ')');
        }
    });
};

var gotoNextSlide = function() {
    $.fn.fullpage.moveSlideRight();
}

var showNav = function() {
    //$nav.height($h);
    $navButton.find('i').toggleClass('fa-bars').toggleClass('fa-times');
    $nav.toggleClass('active');
    if ($nav.hasClass('active')) {
        $nav.css('display', 'block');
        var fade = _.debounce(fadeInNav, 1);
        fade();
    }
    else {
        $nav.css('opacity', 0);
        var fade = _.debounce(fadeOutNav, 500);
        fade();
    }
}

var fadeInNav = function() {
    $nav.css('opacity', 1);
};

var fadeOutNav = function() {
    $nav.css('display', 'none');
};

var revealVideo = function() {
    /*
    * Show the video.
    */

    var text = $(this).parents('.text');
    $(text).hide();
    $(text).parent().css('background-image', '');
    $(text).next().css('display', 'table-cell');
    var player = text.siblings('#player');
    initPlayer(player);
};

var initPlayer = function(player) {

    /*
    * Setup JWPlayer.
    */

    jwplayer('player').setup({
        modes: [{
            type: 'flash',
            src: 'http://www.npr.org/templates/javascript/jwplayer/player.swf',
            config: {
                skin: 'http://media.npr.org/templates/javascript/jwplayer/skins/mle/npr-video-archive/npr-video-archive.zip',
                file: 'http://pd.npr.org/npr-mp4/npr/nprvid/2014/03/20140324_nprvid_juniorrough-n.mp4',
                image: '../assets/img/junior/junior.jpg',
                'hd.file': 'http://pd.npr.org/npr-mp4/npr/nprvid/2014/03/20140324_nprvid_juniorrough-n.mp4'
            }
        }, {
            type: 'html5',
            config: {
                levels: [
                    {
                        file: 'http://pd.npr.org/npr-mp4/npr/nprvid/2014/03/20140324_nprvid_juniorrough-n.mp4',
                        image: '../assets/img/junior/junior.jpg'
                    }
                ]
            }
        }],
        bufferlength: '5',
        controlbar: 'over',
        icons: 'true',
        autostart: false,
        width: '100%',
        height: $h - 70
    });
    jwplayer('player').play();

};

var onUpdateCounts = function(e) {
    /*
    * Updates the count based on elapsed time and known rates.
    */
    var now = moment();
    var elapsed_seconds = (now - begin) / 1000;
    var RATES = [
        ['marijuana', 0.08844],
        ['cocaine', 0.01116],
        ['illegal-entry', 0.01065],
        ['vehicles', 2.15096],
        ['pedestrians', 1.30102]
    ]

    _.each(RATES, function(count, i){
        var count_category = count[0];
        var count_number = count[1];
        var count_unit = count[2];

        $('#' + count_category + ' span.number').html(Math.round(count_number * elapsed_seconds));
    });

};

var onStartCounts = function(e) {
    active_counter = setInterval(onUpdateCounts,500);
}

$(document).ready(function() {

    /*
    * Define vars
    */

    $slides = $('.slide');
    $play_video = $('.btn-video');
    $video = $('.video');
    $components = $('.component');
    $portraits = $('.section[data-anchor="people"] .slide')
    $navButton = $('.primary-navigation-btn');
    $nav = $('.nav');
    $titleCardButton = $('.btn-play');

    // init chapters

    breakSlidesForMobile();
    setUpFullPage();

    // handlers

    $play_video.on('click', revealVideo);
    $navButton.on('click', showNav);
    $titleCardButton.on('click', gotoNextSlide);

    // Redraw slides if the window resizes
    $(window).resize(breakSlidesForMobile);

});<|endoftext|>