<commit_before>module.exports = {
  "env": {
    "node": true
  },

  "rules": {

    /**
     * Possible Errors
     * The following rules point out areas where you might have made mistakes.
     */

    // disallow or enforce trailing commas
    "comma-dangle": [1, "never"],

    // disallow assignment in conditional expressions
    "no-cond-assign": 2,

    // disallow use of console (off by default in the node environment)
    "no-console": 2,

    // disallow use of constant expressions in conditions
    "no-constant-condition": 1,

    // disallow control characters in regular expressions
    "no-control-regex": 2,

    // disallow use of debugger
    "no-debugger": 2,

    // disallow duplicate arguments in functions
    "no-dupe-args": 2,

    // disallow duplicate keys when creating object literals
    "no-dupe-keys": 2,

    // disallow a duplicate case label.
    "no-duplicate-case": 2,

    // disallow empty statements
    "no-empty": 2,

    // disallow the use of empty character classes in regular expressions
    "no-empty-character-class": 2,

    // disallow assigning to the exception in a catch block
    "no-ex-assign": 2,

    // disallow double-negation boolean casts in a boolean context
    "no-extra-boolean-cast": 2,

    // disallow unnecessary parentheses (off by default)
    "no-extra-parens": 2,

    // disallow unnecessary semicolons
    "no-extra-semi": 2,

    // disallow overwriting functions written as function declarations
    "no-func-assign": 2,

    // disallow function or variable declarations in nested blocks
    "no-inner-declarations": 2,

    // disallow invalid regular expression strings in the RegExp constructor
    "no-invalid-regexp": 2,

    // disallow irregular whitespace outside of strings and comments
    "no-irregular-whitespace": 2,

    // disallow negation of the left operand of an in expression
    "no-negated-in-lhs": 2,

    // disallow the use of object properties of the global object (Math and JSON) as functions
    "no-obj-calls": 2,

    // disallow multiple spaces in a regular expression literal
    "no-regex-spaces": 2,

    // disallow sparse arrays
    "no-sparse-arrays": 2,

    // disallow unreachable statements after a return, throw, continue, or break statement
    "no-unreachable": 2,

    // disallow comparisons with the value NaN
    "use-isnan": 2,

    // Ensure JSDoc comments are valid (off by default)
    "valid-jsdoc": [
      2,
      {
        "prefer": {
          "returns": "return"
        },
        "requireReturn": false,
        "requireParamDescription": false,
        "requireReturnDescription": false
      }
    ],

    // Ensure that the results of typeof are compared against a valid string
    "valid-typeof": 2,

    // Avoid code that looks like two expressions but is actually one (off by default)
    "no-unexpected-multiline": 2,

    /**
     * Best Practices
     * These are rules designed to prevent you from making mistakes.
     * They either prescribe a better way of doing something or help you avoid footguns.
     */

    // enforces getter/setter pairs in objects (off by default)
    "accessor-pairs": 0,

    // treat var statements as if they were block scoped (off by default)
    "block-scoped-var": 2,

    // specify the maximum cyclomatic complexity allowed in a program (off by default)
    "complexity": 0,

    // require return statements to either always or never specify values
    "consistent-return": 2,

    // specify curly brace conventions for all control statements
    "curly": [2, "all"],

    // require default case in switch statements (off by default)
    "default-case": 2,

    // encourages use of dot notation whenever possible
    "dot-notation": 2,

    // enforces consistent newlines before or after dots (off by default)
    "dot-location": [2, "property"],

    // require the use of === and !==
    "eqeqeq": 2,

    // make sure for-in loops have an if statement (off by default)
    "guard-for-in": 2,

    // disallow the use of alert, confirm, and prompt
    "no-alert": 2,

    // disallow use of arguments.caller or arguments.callee
    "no-caller": 2,

    // disallow division operators explicitly at beginning of regular expression (off by default)
    "no-div-regex": 2,

    // disallow else after a return in an if (off by default)
    "no-else-return": 2,

    // disallow use of labels for anything other then loops and switches
    "no-empty-label": 2,

    // disallow comparisons to null without a type-checking operator (off by default)
    "no-eq-null": 2,

    // disallow use of eval()
    "no-eval": 2,

    // disallow adding to native types
    "no-extend-native": 2,

    // disallow unnecessary function binding
    "no-extra-bind": 2,

    // disallow fallthrough of case statements
    "no-fallthrough": 2,

    // disallow the use of leading or trailing decimal points in numeric literals (off by default)
    "no-floating-decimal": 2,

    // disallow use of eval()-like methods
    "no-implied-eval": 2,

    // disallow usage of __iterator__ property
    "no-iterator": 2,

    // disallow use of labeled statements
    "no-labels": 2,

    // disallow unnecessary nested blocks
    "no-lone-blocks": 2,

    // disallow creation of functions within loops
    "no-loop-func": 2,

    // disallow use of multiple spaces
    "no-multi-spaces": 2,

    // disallow use of multiline strings
    "no-multi-str": 2,

    // disallow reassignments of native objects
    "no-native-reassign": 2,

    // disallow use of new operator when not part of the assignment or comparison
    "no-new": 2,

    // disallow use of new operator for Function object
    "no-new-func": 2,

    // disallows creating new instances of String, Number and Boolean
    "no-new-wrappers": 2,

    // disallow use of octal literals
    "no-octal": 2,

    // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251";
    "no-octal-escape": 2,

    // disallow reassignment of function parameters (off by default)
    "no-param-reassign": 2,

    // disallow use of process.env (off by default)
    "no-process-env": 0,

    // disallow usage of __proto__ property
    "no-proto": 2,

    // disallow declaring the same variable more then once
    "no-redeclare": 2,

    // disallow use of assignment in return statement
    "no-return-assign": 2,

    // disallow use of javascript: urls.
    "no-script-url": 2,

    // disallow comparisons where both sides are exactly the same (off by default)
    "no-self-compare": 2,

    // disallow use of comma operator
    "no-sequences": 2,

    // restrict what can be thrown as an exception (off by default)
    "no-throw-literal": 2,

    // disallow usage of expressions in statement position
    "no-unused-expressions": 2,

    // disallow usage of configurable warning terms in comments, e.g. TODO or FIXME (off by default)
    "no-warning-comments": 1,

    // disallow use of the with statement
    "no-with": 2,

    // require use of the second argument for parseInt() (off by default)
    "radix": 2,

    // requires to declare all vars on top of their containing scope (off by default)
    "vars-on-top": 0,

    // require immediate function invocation to be wrapped in parentheses (off by default)
    "wrap-iife": 2,

    // require or disallow Yoda conditions
    "yoda": [2, "never"],

    /**
     * Strict Mode
     * These rules relate to using strict mode.
     */

    // controls location of Use Strict Directives
    "strict": [2, "global"],

    /**
     * Variables
     * These rules have to do with variable declarations.
     */

    // disallow the catch clause parameter name being the same as a variable in the outer scope (off by default in the node environment)
    "no-catch-shadow": 0,

    // disallow deletion of variables
    "no-delete-var": 2,

    // disallow labels that share a name with a variable
    "no-label-var": 2,

    // disallow declaration of variables already declared in the outer scope
    "no-shadow": 2,

    // disallow shadowing of names such as arguments
    "no-shadow-restricted-names": 2,

    // disallow use of undeclared variables unless mentioned in a /*global */ block
    "no-undef": 2,

    // disallow use of undefined when initializing variables
    "no-undef-init": 2,

    // disallow use of undefined variable (off by default)
    "no-undefined": 0,

    // disallow declaration of variables that are not used in the code
    "no-unused-vars": [
      2,
      {
        // checks all variables for usage, including those in the global scope
        "vars": "all",
        // do not check arguments
        "args": "none"
      }
    ],

    // disallow use of variables before they are defined
    "no-use-before-define": [2, "nofunc"],

    /**
     * Node.js
     * These rules are specific to JavaScript running on Node.js.
     */

    // enforces error handling in callbacks (off by default) (on by default in the node environment)
    "handle-callback-err": [2, "^(.+_)?err(or)?$"],

    // disallow mixing regular variable and require declarations (off by default) (on by default in the node environment)
    "no-mixed-requires": [2, true],

    // disallow use of new operator with the require function (off by default) (on by default in the node environment)
    "no-new-require": 2,

    // disallow string concatenation with __dirname and __filename (off by default) (on by default in the node environment)
    "no-path-concat": 2,

    // disallow process.exit() (on by default in the node environment)
    "no-process-exit": 2,

    // restrict usage of specified node modules (off by default)
    "no-restricted-modules": [1, "chai", "should", "should-http", "should-promised", "should-sinon", "sinon", "sinon-chai"],

    // disallow use of synchronous methods (off by default)
    "no-sync": 1,

    /**
     * Stylistic Issues
     * These rules are purely matters of style and are quite subjective.
     */

    // enforce spacing inside array brackets (off by default)
    "arrays-bracket-spacing": [2, "never"],

    // this option sets a specific tab width for your code (off by default)
    "indent": [2, 2, { "indentSwitchCase": true }],

    // enforce one true brace style (off by default)
    "brace-style": [2, "stroustrup"],

    // require camel case names
    "camelcase": 0,

    // enforce spacing before and after comma
    "comma-spacing": [
      2,
      {
        "before": false,
        "after": true
      }
    ],

    // enforce one true comma style (off by default)
    "comma-style": [2, "last"],

    // require or disallow padding inside computed properties (off by default)
    "computed-property-spacing": [2, "never"],

    // enforces consistent naming when capturing the current execution context (off by default)
    "consistent-this": [1, "self"],

    // enforce newline at the end of file, with no multiple empty lines
    "eol-last": 2,

    // require function expressions to have a name (off by default)
    "func-names": 0,

    // enforces use of function declarations or expressions (off by default)
    "func-style": [2, "declaration"],

    // enforces spacing between keys and values in object literal properties
    "key-spacing": [
      2,
      {
        "beforeColon": false,
        "afterColon": true
      }
    ],

    // enforces empty lines around comments (off by default)
    "lines-around-comment": 0,

    // disallow mixed "LF" and "CRLF" as linebreaks (off by default)
    "linebreak-style": [2, "unix"],

    // specify the maximum depth callbacks can be nested (off by default)
    "max-nested-callbacks": [1, 4],

    // require a capital letter for constructors
    "new-cap": [
      2,
      {
        // When true, rule checks if all new operators are called only with uppercase-started functions.
        "newIsCap": true,
        // When true, rule checks if all uppercase-started functions are called only with new operator.
        "capIsNew": true,
        // Array of lowercase function names that are permitted to be used with the new operator.
        // "newIsCapExceptions": [],
        // Array of uppercase-starting function names that are permitted to be used without the new operator.
        "capIsNewExceptions": ["Array", "Boolean", "Number", "String", "Symbol"]
      }
    ],

    // disallow the omission of parentheses when invoking a constructor with no arguments
    "new-parens": 2,

    // allow/disallow an empty newline after var statement (off by default)
    "newline-after-var": 0,

    // disallow use of the Array constructor
    "no-array-constructor": 2,

    // disallow use of the continue statement (off by default)
    "no-continue": 0,

    // disallow comments inline after code (off by default)
    "no-inline-comments": 0,

    // disallow if as the only statement in an else block (off by default)
    "no-lonely-if": 2,

    // disallow mixed spaces and tabs for indentation
    "no-mixed-spaces-and-tabs": 2,

    // disallow multiple empty lines (off by default)
    "no-multiple-empty-lines": [2, { "max": 3 }],

    // disallow nested ternary expressions (off by default)
    "no-nested-ternary": 2,

    // disallow use of the Object constructor
    "no-new-object": 2,

    // disallow space between function identifier and application
    "no-spaced-func": 2,

    // disallow the use of ternary operators (off by default)
    "no-ternary": 0,

    // disallow trailing whitespace at the end of lines
    "no-trailing-spaces": 2,

    // disallow dangling underscores in identifiers
    "no-underscore-dangle": 0,

    // disallow the use of Boolean literals in conditional expressions (off by default)
    "no-unneeded-ternary": 2,

    // require or disallow padding inside curly braces (off by default)
    "object-curly-spacing": [2, "always"],

    // allow just one var statement per function (off by default)
    "one-var": 0,

    // require assignment operator shorthand where possible or prohibit it entirely (off by default)
    "operator-assignment": 0,

    // enforce operators to be placed before or after line breaks (off by default)
    "operator-linebreak": [2, "after"],

    // enforce padding within blocks (off by default)
    "padded-blocks": [2, "never"],

    // require quotes around object literal property names (off by default)
    "quote-props": [2, "as-needed"],

    // specify whether double or single quotes should be used
    "quotes": [2, "single", "avoid-escape"],

    // require or disallow use of semicolons instead of ASI
    "semi": [2, "always"],

    // enforce spacing before and after semicolons
    "semi-spacing": [
      2,
      {
        "before": false,
        "after": true
      }
    ],

    // sort variables within the same declaration block (off by default)
    "sort-vars": 0,

    // require a space after certain keywords (off by default)
    "space-after-keywords": [2, "always"],

    // require or disallow space before blocks (off by default)
    "space-before-blocks": [2, "always"],

    // require or disallow space before function opening parenthesis (off by default)
    "space-before-function-paren": [2, "never"],

    // require or disallow spaces inside parentheses (off by default)
    "space-in-parens": [2, "never"],

    // require spaces around operators
    "space-infix-ops": 2,

    // require a space after return, throw, and case
    "space-return-throw-case": 2,

    // Require or disallow spaces before/after unary operators (words on by default, nonwords off by default)
    "space-unary-ops": 2,

    // require or disallow a space immediately following the // or /* in a comment (off by default)
    "spaced-comment": 0,

    // require regex literals to be wrapped in parentheses (off by default)
    "wrap-regex": 1

  }
};
<commit_msg>Specify the always option in no-return-assign<commit_after>module.exports = {
  "env": {
    "node": true
  },

  "rules": {

    /**
     * Possible Errors
     * The following rules point out areas where you might have made mistakes.
     */

    // disallow or enforce trailing commas
    "comma-dangle": [1, "never"],

    // disallow assignment in conditional expressions
    "no-cond-assign": 2,

    // disallow use of console (off by default in the node environment)
    "no-console": 2,

    // disallow use of constant expressions in conditions
    "no-constant-condition": 1,

    // disallow control characters in regular expressions
    "no-control-regex": 2,

    // disallow use of debugger
    "no-debugger": 2,

    // disallow duplicate arguments in functions
    "no-dupe-args": 2,

    // disallow duplicate keys when creating object literals
    "no-dupe-keys": 2,

    // disallow a duplicate case label.
    "no-duplicate-case": 2,

    // disallow empty statements
    "no-empty": 2,

    // disallow the use of empty character classes in regular expressions
    "no-empty-character-class": 2,

    // disallow assigning to the exception in a catch block
    "no-ex-assign": 2,

    // disallow double-negation boolean casts in a boolean context
    "no-extra-boolean-cast": 2,

    // disallow unnecessary parentheses (off by default)
    "no-extra-parens": 2,

    // disallow unnecessary semicolons
    "no-extra-semi": 2,

    // disallow overwriting functions written as function declarations
    "no-func-assign": 2,

    // disallow function or variable declarations in nested blocks
    "no-inner-declarations": 2,

    // disallow invalid regular expression strings in the RegExp constructor
    "no-invalid-regexp": 2,

    // disallow irregular whitespace outside of strings and comments
    "no-irregular-whitespace": 2,

    // disallow negation of the left operand of an in expression
    "no-negated-in-lhs": 2,

    // disallow the use of object properties of the global object (Math and JSON) as functions
    "no-obj-calls": 2,

    // disallow multiple spaces in a regular expression literal
    "no-regex-spaces": 2,

    // disallow sparse arrays
    "no-sparse-arrays": 2,

    // disallow unreachable statements after a return, throw, continue, or break statement
    "no-unreachable": 2,

    // disallow comparisons with the value NaN
    "use-isnan": 2,

    // Ensure JSDoc comments are valid (off by default)
    "valid-jsdoc": [
      2,
      {
        "prefer": {
          "returns": "return"
        },
        "requireReturn": false,
        "requireParamDescription": false,
        "requireReturnDescription": false
      }
    ],

    // Ensure that the results of typeof are compared against a valid string
    "valid-typeof": 2,

    // Avoid code that looks like two expressions but is actually one (off by default)
    "no-unexpected-multiline": 2,

    /**
     * Best Practices
     * These are rules designed to prevent you from making mistakes.
     * They either prescribe a better way of doing something or help you avoid footguns.
     */

    // enforces getter/setter pairs in objects (off by default)
    "accessor-pairs": 0,

    // treat var statements as if they were block scoped (off by default)
    "block-scoped-var": 2,

    // specify the maximum cyclomatic complexity allowed in a program (off by default)
    "complexity": 0,

    // require return statements to either always or never specify values
    "consistent-return": 2,

    // specify curly brace conventions for all control statements
    "curly": [2, "all"],

    // require default case in switch statements (off by default)
    "default-case": 2,

    // encourages use of dot notation whenever possible
    "dot-notation": 2,

    // enforces consistent newlines before or after dots (off by default)
    "dot-location": [2, "property"],

    // require the use of === and !==
    "eqeqeq": 2,

    // make sure for-in loops have an if statement (off by default)
    "guard-for-in": 2,

    // disallow the use of alert, confirm, and prompt
    "no-alert": 2,

    // disallow use of arguments.caller or arguments.callee
    "no-caller": 2,

    // disallow division operators explicitly at beginning of regular expression (off by default)
    "no-div-regex": 2,

    // disallow else after a return in an if (off by default)
    "no-else-return": 2,

    // disallow use of labels for anything other then loops and switches
    "no-empty-label": 2,

    // disallow comparisons to null without a type-checking operator (off by default)
    "no-eq-null": 2,

    // disallow use of eval()
    "no-eval": 2,

    // disallow adding to native types
    "no-extend-native": 2,

    // disallow unnecessary function binding
    "no-extra-bind": 2,

    // disallow fallthrough of case statements
    "no-fallthrough": 2,

    // disallow the use of leading or trailing decimal points in numeric literals (off by default)
    "no-floating-decimal": 2,

    // disallow use of eval()-like methods
    "no-implied-eval": 2,

    // disallow usage of __iterator__ property
    "no-iterator": 2,

    // disallow use of labeled statements
    "no-labels": 2,

    // disallow unnecessary nested blocks
    "no-lone-blocks": 2,

    // disallow creation of functions within loops
    "no-loop-func": 2,

    // disallow use of multiple spaces
    "no-multi-spaces": 2,

    // disallow use of multiline strings
    "no-multi-str": 2,

    // disallow reassignments of native objects
    "no-native-reassign": 2,

    // disallow use of new operator when not part of the assignment or comparison
    "no-new": 2,

    // disallow use of new operator for Function object
    "no-new-func": 2,

    // disallows creating new instances of String, Number and Boolean
    "no-new-wrappers": 2,

    // disallow use of octal literals
    "no-octal": 2,

    // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251";
    "no-octal-escape": 2,

    // disallow reassignment of function parameters (off by default)
    "no-param-reassign": 2,

    // disallow use of process.env (off by default)
    "no-process-env": 0,

    // disallow usage of __proto__ property
    "no-proto": 2,

    // disallow declaring the same variable more then once
    "no-redeclare": 2,

    // disallow use of assignment in return statement
    "no-return-assign": [2, "always"],

    // disallow use of javascript: urls.
    "no-script-url": 2,

    // disallow comparisons where both sides are exactly the same (off by default)
    "no-self-compare": 2,

    // disallow use of comma operator
    "no-sequences": 2,

    // restrict what can be thrown as an exception (off by default)
    "no-throw-literal": 2,

    // disallow usage of expressions in statement position
    "no-unused-expressions": 2,

    // disallow usage of configurable warning terms in comments, e.g. TODO or FIXME (off by default)
    "no-warning-comments": 1,

    // disallow use of the with statement
    "no-with": 2,

    // require use of the second argument for parseInt() (off by default)
    "radix": 2,

    // requires to declare all vars on top of their containing scope (off by default)
    "vars-on-top": 0,

    // require immediate function invocation to be wrapped in parentheses (off by default)
    "wrap-iife": 2,

    // require or disallow Yoda conditions
    "yoda": [2, "never"],

    /**
     * Strict Mode
     * These rules relate to using strict mode.
     */

    // controls location of Use Strict Directives
    "strict": [2, "global"],

    /**
     * Variables
     * These rules have to do with variable declarations.
     */

    // disallow the catch clause parameter name being the same as a variable in the outer scope (off by default in the node environment)
    "no-catch-shadow": 0,

    // disallow deletion of variables
    "no-delete-var": 2,

    // disallow labels that share a name with a variable
    "no-label-var": 2,

    // disallow declaration of variables already declared in the outer scope
    "no-shadow": 2,

    // disallow shadowing of names such as arguments
    "no-shadow-restricted-names": 2,

    // disallow use of undeclared variables unless mentioned in a /*global */ block
    "no-undef": 2,

    // disallow use of undefined when initializing variables
    "no-undef-init": 2,

    // disallow use of undefined variable (off by default)
    "no-undefined": 0,

    // disallow declaration of variables that are not used in the code
    "no-unused-vars": [
      2,
      {
        // checks all variables for usage, including those in the global scope
        "vars": "all",
        // do not check arguments
        "args": "none"
      }
    ],

    // disallow use of variables before they are defined
    "no-use-before-define": [2, "nofunc"],

    /**
     * Node.js
     * These rules are specific to JavaScript running on Node.js.
     */

    // enforces error handling in callbacks (off by default) (on by default in the node environment)
    "handle-callback-err": [2, "^(.+_)?err(or)?$"],

    // disallow mixing regular variable and require declarations (off by default) (on by default in the node environment)
    "no-mixed-requires": [2, true],

    // disallow use of new operator with the require function (off by default) (on by default in the node environment)
    "no-new-require": 2,

    // disallow string concatenation with __dirname and __filename (off by default) (on by default in the node environment)
    "no-path-concat": 2,

    // disallow process.exit() (on by default in the node environment)
    "no-process-exit": 2,

    // restrict usage of specified node modules (off by default)
    "no-restricted-modules": [1, "chai", "should", "should-http", "should-promised", "should-sinon", "sinon", "sinon-chai"],

    // disallow use of synchronous methods (off by default)
    "no-sync": 1,

    /**
     * Stylistic Issues
     * These rules are purely matters of style and are quite subjective.
     */

    // enforce spacing inside array brackets (off by default)
    "arrays-bracket-spacing": [2, "never"],

    // this option sets a specific tab width for your code (off by default)
    "indent": [2, 2, { "indentSwitchCase": true }],

    // enforce one true brace style (off by default)
    "brace-style": [2, "stroustrup"],

    // require camel case names
    "camelcase": 0,

    // enforce spacing before and after comma
    "comma-spacing": [
      2,
      {
        "before": false,
        "after": true
      }
    ],

    // enforce one true comma style (off by default)
    "comma-style": [2, "last"],

    // require or disallow padding inside computed properties (off by default)
    "computed-property-spacing": [2, "never"],

    // enforces consistent naming when capturing the current execution context (off by default)
    "consistent-this": [1, "self"],

    // enforce newline at the end of file, with no multiple empty lines
    "eol-last": 2,

    // require function expressions to have a name (off by default)
    "func-names": 0,

    // enforces use of function declarations or expressions (off by default)
    "func-style": [2, "declaration"],

    // enforces spacing between keys and values in object literal properties
    "key-spacing": [
      2,
      {
        "beforeColon": false,
        "afterColon": true
      }
    ],

    // enforces empty lines around comments (off by default)
    "lines-around-comment": 0,

    // disallow mixed "LF" and "CRLF" as linebreaks (off by default)
    "linebreak-style": [2, "unix"],

    // specify the maximum depth callbacks can be nested (off by default)
    "max-nested-callbacks": [1, 4],

    // require a capital letter for constructors
    "new-cap": [
      2,
      {
        // When true, rule checks if all new operators are called only with uppercase-started functions.
        "newIsCap": true,
        // When true, rule checks if all uppercase-started functions are called only with new operator.
        "capIsNew": true,
        // Array of lowercase function names that are permitted to be used with the new operator.
        // "newIsCapExceptions": [],
        // Array of uppercase-starting function names that are permitted to be used without the new operator.
        "capIsNewExceptions": ["Array", "Boolean", "Number", "String", "Symbol"]
      }
    ],

    // disallow the omission of parentheses when invoking a constructor with no arguments
    "new-parens": 2,

    // allow/disallow an empty newline after var statement (off by default)
    "newline-after-var": 0,

    // disallow use of the Array constructor
    "no-array-constructor": 2,

    // disallow use of the continue statement (off by default)
    "no-continue": 0,

    // disallow comments inline after code (off by default)
    "no-inline-comments": 0,

    // disallow if as the only statement in an else block (off by default)
    "no-lonely-if": 2,

    // disallow mixed spaces and tabs for indentation
    "no-mixed-spaces-and-tabs": 2,

    // disallow multiple empty lines (off by default)
    "no-multiple-empty-lines": [2, { "max": 3 }],

    // disallow nested ternary expressions (off by default)
    "no-nested-ternary": 2,

    // disallow use of the Object constructor
    "no-new-object": 2,

    // disallow space between function identifier and application
    "no-spaced-func": 2,

    // disallow the use of ternary operators (off by default)
    "no-ternary": 0,

    // disallow trailing whitespace at the end of lines
    "no-trailing-spaces": 2,

    // disallow dangling underscores in identifiers
    "no-underscore-dangle": 0,

    // disallow the use of Boolean literals in conditional expressions (off by default)
    "no-unneeded-ternary": 2,

    // require or disallow padding inside curly braces (off by default)
    "object-curly-spacing": [2, "always"],

    // allow just one var statement per function (off by default)
    "one-var": 0,

    // require assignment operator shorthand where possible or prohibit it entirely (off by default)
    "operator-assignment": 0,

    // enforce operators to be placed before or after line breaks (off by default)
    "operator-linebreak": [2, "after"],

    // enforce padding within blocks (off by default)
    "padded-blocks": [2, "never"],

    // require quotes around object literal property names (off by default)
    "quote-props": [2, "as-needed"],

    // specify whether double or single quotes should be used
    "quotes": [2, "single", "avoid-escape"],

    // require or disallow use of semicolons instead of ASI
    "semi": [2, "always"],

    // enforce spacing before and after semicolons
    "semi-spacing": [
      2,
      {
        "before": false,
        "after": true
      }
    ],

    // sort variables within the same declaration block (off by default)
    "sort-vars": 0,

    // require a space after certain keywords (off by default)
    "space-after-keywords": [2, "always"],

    // require or disallow space before blocks (off by default)
    "space-before-blocks": [2, "always"],

    // require or disallow space before function opening parenthesis (off by default)
    "space-before-function-paren": [2, "never"],

    // require or disallow spaces inside parentheses (off by default)
    "space-in-parens": [2, "never"],

    // require spaces around operators
    "space-infix-ops": 2,

    // require a space after return, throw, and case
    "space-return-throw-case": 2,

    // Require or disallow spaces before/after unary operators (words on by default, nonwords off by default)
    "space-unary-ops": 2,

    // require or disallow a space immediately following the // or /* in a comment (off by default)
    "spaced-comment": 0,

    // require regex literals to be wrapped in parentheses (off by default)
    "wrap-regex": 1

  }
};
<|endoftext|>


<commit_before>'use strict';

const chokidar = require('chokidar');
const kexec = require('kexec');
const childProcess = require('child_process');

chokidar.watch('yarn.lock').on('change', () => {
    console.log('yarn.lock has been updated!');
    console.log('reinstalling dependencies');
    console.log();

    const proc = childProcess.spawn('yarn', ['--verbose', '--non-interactive']);

    proc.stdout.on('data', data => {
        console.log(data);
    });

    proc.stderr.on('data', data => {
        console.error(data);
    });

    proc.on('close', code => {
        console.log(`yarn process exited with code ${code}`);

        kexec('yarn', ['start']);
    });
});
<commit_msg>Use process.std{out,err}.write instead of console.{log,error}<commit_after>'use strict';

const chokidar = require('chokidar');
const kexec = require('kexec');
const childProcess = require('child_process');

chokidar.watch('yarn.lock').on('change', () => {
    console.log('yarn.lock has been updated!');
    console.log('reinstalling dependencies');
    console.log();

    const proc = childProcess.spawn('yarn', ['--verbose', '--non-interactive']);

    proc.stdout.on('data', data => {
        process.stdout.write(data);
    });

    proc.stderr.on('data', data => {
        process.stderr.write(data);
    });

    proc.on('close', code => {
        console.log(`yarn process exited with code ${code}`);

        kexec('yarn', ['start']);
    });
});
<|endoftext|>


<commit_before>/* globals process */
'use strict'

// other
const bigInt = require('big-integer')

// twitter api
const twitterParse = require('twitter-url-parser')
const twitterAPI = require('node-twitter-api')
const twitter = new twitterAPI({
  consumerKey: process.env.TWITTER_CONSUMER_KEY,
  consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
  callback: process.env.TWITTER_OAUTH_CALLBACK || 'http://localhost:8080/oauth'
})

// redis
const redis = require('redis')
const client = redis.createClient(process.env.REDIS_URL)

client.on('error', (error) => {
  console.log(error)
})

// request-json
const request = require('request')

// express
const express = require('express')
const app = express()
const bodyParser = require('body-parser')

app.use(bodyParser.json())

// request body:
// id
// text
// username
app.post('/', (req, res) => {
  tweetsplain(req, res, true)
})

app.post('/test', (req, res) => {
  tweetsplain(req, res, false)
})

function tweetsplain (req, res, tweetTheResult) {
  const twitterId = twitterParse(req.body.link).id
  client.hgetall('access', (error, access) => {
    if (error) {
      console.log(error)
      res.end()
    } else if (access) {
      console.log(twitterId)
      twitter.statuses(
        'show',
        {
          id: twitterId
        },
        access.token,
        access.tokenSecret,
        (error, tweet, showResponse) => {
          if (error) {
            console.log(error)
            res.end()
          } else {
            console.log(tweet.text)
            twitter.search(
              {
                q: tweet.text,
                max_id: bigInt(twitterId).minus(1).toString()
              },
              access.token,
              access.tokenSecret,
              (error, data, response) => {
                if (error) {
                  console.log(error)
                  res.end()
                } else {
                  const sourceTweet = data && data.statuses && data.statuses[0]
                    ? data.statuses[0].retweeted_status
                      ? data.statuses[0].retweeted_status
                      : data.statuses[0]
                    : undefined

                  if (sourceTweet) {
                    console.log('@' + req.body.username + ' @' + sourceTweet.user.screen_name + ' https://twitter.com/' + sourceTweet.user.screen_name + '/status/' + sourceTweet.id_str)
                    res.send('@' + req.body.username + ' @' + sourceTweet.user.screen_name + ' https://twitter.com/' + sourceTweet.user.screen_name + '/status/' + sourceTweet.id_str)
                    if (tweetTheResult) {
                      twitter.statuses(
                        'update',
                        {
                          status: '@' + req.body.username + ' @' + sourceTweet.user.screen_name + ' https://twitter.com/' + sourceTweet.user.screen_name + '/status/' + sourceTweet.id_str,
                          in_reply_to_status_id: twitterId
                        },
                        access.token,
                        access.tokenSecret,
                        (error, data, response) => {
                          if (error) {
                            console.log(error)
                          }
                        }
                      )
                    }
                  } else {
                    console.log('no matching tweet')
                    request(
                      {
                        uri: process.env.ALGOLIA_URL,
                        method: 'POST',
                        json: {
                          'params': 'query=%22' + encodeURIComponent(tweet.text) + '%22'
                        }
                      },
                      (error, response, body) => {
                        if (error) {
                          console.log(error)
                          res.end()
                        } else {
                          if (body && body.hits && body.hits[0]) {
                            console.log('@' + req.body.username + ' https://hn.algolia.com/?query=%22' + encodeURIComponent(tweet.text) + '%22&type=all ' + body.hits[0].story_url)
                            res.send('@' + req.body.username + ' https://hn.algolia.com/?query=%22' + encodeURIComponent(tweet.text) + '%22&type=all ' + body.hits[0].story_url)
                            if (tweetTheResult) {
                              twitter.statuses(
                                'update',
                                {
                                  status: '@' + req.body.username + ' https://hn.algolia.com/?query=%22' + encodeURIComponent(tweet.text) + '%22&type=all ' + body.hits[0].story_url,
                                  in_reply_to_status_id: twitterId
                                },
                                access.token,
                                access.tokenSecret,
                                (error, data, response) => {
                                  if (error) {
                                    console.log(error)
                                  }
                                }
                              )
                            }
                          } else {
                            console.log('no matching comment')
                            res.end()
                          }
                        }
                      }
                    )
                  }
                }
              }
            )
          }
        }
      )
    }
  })
}

app.get('/authenticate', (req, res) => {
  twitter.getRequestToken((error, requestToken, requestTokenSecret, results) => {
    if (error) {
      console.log('Error getting OAuth request token : ' + error)
    } else {
      client.del('request')
      client.hmset('request', 'token', requestToken, 'tokenSecret', requestTokenSecret, (error, result) => {
        if (error) {
          console.log(error)
        } else {
          res.redirect(twitter.getAuthUrl(requestToken))
        }
      })
    }
  })
})

app.get('/oauth', (req, res) => {
  client.hgetall('request', (error, request) => {
    if (error) {
      console.log(error)
    } else if (request) {
      twitter.getAccessToken(
        request.token,
        request.tokenSecret,
        req.query.oauth_verifier,
        (error, accessToken, accessTokenSecret, results) => {
          if (error) {
            console.log(error)
          } else {
            twitter.verifyCredentials(
              accessToken,
              accessTokenSecret,
              {},
              (error, data, response) => {
                if (error) {
                  console.log(error)
                } else {
                  client.del('access')
                  client.hmset('access', 'token', accessToken, 'tokenSecret', accessTokenSecret, (error, result) => {
                    if (error) {
                      console.log(error)
                    } else {
                      res.send(data['screen_name'])
                    }
                  })
                }
              })
          }
        })
    }
  })
})

app.listen(process.env.PORT || 8080, () => console.log('listening ' + (process.env.PORT || 8080)))
<commit_msg>encode parens<commit_after>/* globals process */
'use strict'

// other
const bigInt = require('big-integer')

// twitter api
const twitterParse = require('twitter-url-parser')
const twitterAPI = require('node-twitter-api')
const twitter = new twitterAPI({
  consumerKey: process.env.TWITTER_CONSUMER_KEY,
  consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
  callback: process.env.TWITTER_OAUTH_CALLBACK || 'http://localhost:8080/oauth'
})

// redis
const redis = require('redis')
const client = redis.createClient(process.env.REDIS_URL)

client.on('error', (error) => {
  console.log(error)
})

// request-json
const request = require('request')

// express
const express = require('express')
const app = express()
const bodyParser = require('body-parser')

app.use(bodyParser.json())

// request body:
// id
// text
// username
app.post('/', (req, res) => {
  tweetsplain(req, res, true)
})

app.post('/test', (req, res) => {
  tweetsplain(req, res, false)
})

function tweetsplain (req, res, tweetTheResult) {
  const twitterId = twitterParse(req.body.link).id
  client.hgetall('access', (error, access) => {
    if (error) {
      console.log(error)
      res.end()
    } else if (access) {
      console.log(twitterId)
      twitter.statuses(
        'show',
        {
          id: twitterId
        },
        access.token,
        access.tokenSecret,
        (error, tweet, showResponse) => {
          if (error) {
            console.log(error)
            res.end()
          } else {
            console.log(tweet.text)
            twitter.search(
              {
                q: tweet.text.replaceAll('(', '%28').replaceAll(')', '%29'),
                max_id: bigInt(twitterId).minus(1).toString()
              },
              access.token,
              access.tokenSecret,
              (error, data, response) => {
                if (error) {
                  console.log(error)
                  res.end()
                } else {
                  const sourceTweet = data && data.statuses && data.statuses[0]
                    ? data.statuses[0].retweeted_status
                      ? data.statuses[0].retweeted_status
                      : data.statuses[0]
                    : undefined

                  if (sourceTweet) {
                    console.log('@' + req.body.username + ' @' + sourceTweet.user.screen_name + ' https://twitter.com/' + sourceTweet.user.screen_name + '/status/' + sourceTweet.id_str)
                    res.send('@' + req.body.username + ' @' + sourceTweet.user.screen_name + ' https://twitter.com/' + sourceTweet.user.screen_name + '/status/' + sourceTweet.id_str)
                    if (tweetTheResult) {
                      twitter.statuses(
                        'update',
                        {
                          status: '@' + req.body.username + ' @' + sourceTweet.user.screen_name + ' https://twitter.com/' + sourceTweet.user.screen_name + '/status/' + sourceTweet.id_str,
                          in_reply_to_status_id: twitterId
                        },
                        access.token,
                        access.tokenSecret,
                        (error, data, response) => {
                          if (error) {
                            console.log(error)
                          }
                        }
                      )
                    }
                  } else {
                    console.log('no matching tweet')
                    request(
                      {
                        uri: process.env.ALGOLIA_URL,
                        method: 'POST',
                        json: {
                          'params': 'query=%22' + encodeURIComponent(tweet.text) + '%22'
                        }
                      },
                      (error, response, body) => {
                        if (error) {
                          console.log(error)
                          res.end()
                        } else {
                          if (body && body.hits && body.hits[0]) {
                            console.log('@' + req.body.username + ' https://hn.algolia.com/?query=%22' + encodeURIComponent(tweet.text) + '%22&type=all ' + body.hits[0].story_url)
                            res.send('@' + req.body.username + ' https://hn.algolia.com/?query=%22' + encodeURIComponent(tweet.text) + '%22&type=all ' + body.hits[0].story_url)
                            if (tweetTheResult) {
                              twitter.statuses(
                                'update',
                                {
                                  status: '@' + req.body.username + ' https://hn.algolia.com/?query=%22' + encodeURIComponent(tweet.text) + '%22&type=all ' + body.hits[0].story_url,
                                  in_reply_to_status_id: twitterId
                                },
                                access.token,
                                access.tokenSecret,
                                (error, data, response) => {
                                  if (error) {
                                    console.log(error)
                                  }
                                }
                              )
                            }
                          } else {
                            console.log('no matching comment')
                            res.end()
                          }
                        }
                      }
                    )
                  }
                }
              }
            )
          }
        }
      )
    }
  })
}

app.get('/authenticate', (req, res) => {
  twitter.getRequestToken((error, requestToken, requestTokenSecret, results) => {
    if (error) {
      console.log('Error getting OAuth request token : ' + error)
    } else {
      client.del('request')
      client.hmset('request', 'token', requestToken, 'tokenSecret', requestTokenSecret, (error, result) => {
        if (error) {
          console.log(error)
        } else {
          res.redirect(twitter.getAuthUrl(requestToken))
        }
      })
    }
  })
})

app.get('/oauth', (req, res) => {
  client.hgetall('request', (error, request) => {
    if (error) {
      console.log(error)
    } else if (request) {
      twitter.getAccessToken(
        request.token,
        request.tokenSecret,
        req.query.oauth_verifier,
        (error, accessToken, accessTokenSecret, results) => {
          if (error) {
            console.log(error)
          } else {
            twitter.verifyCredentials(
              accessToken,
              accessTokenSecret,
              {},
              (error, data, response) => {
                if (error) {
                  console.log(error)
                } else {
                  client.del('access')
                  client.hmset('access', 'token', accessToken, 'tokenSecret', accessTokenSecret, (error, result) => {
                    if (error) {
                      console.log(error)
                    } else {
                      res.send(data['screen_name'])
                    }
                  })
                }
              })
          }
        })
    }
  })
})

app.listen(process.env.PORT || 8080, () => console.log('listening ' + (process.env.PORT || 8080)))
<|endoftext|>


<commit_before>(function() {
/**
 * PLUTO
 * Native HTML Template Rendering
 *
 *
 * The MIT License (MIT)
 * Copyright (c) 2013 Roi Avinoam
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
class Template extends HTMLTemplateElement {
    render(obj) {
        var compiled = this.compile()
        return new Renderer(compiled, compiled.items).render(obj)
    }

    compile() {
        var exprs = []
        var elements = [{ el: this.content, path: [] }]
        while (elements.length > 0) {
            var { el, path } = elements.shift()

            // inner content expressions
            if (el.nodeName === '#text') {
                var expr = isExpressions(el.textContent)
                if (expr) {
                    var render = (el, v) => (el.textContent = v || '')
                    exprs.push({expr, path, render })
                }
            }

            // attributes
            [].forEach.call(el.attributes || [], function(attr) {
                var expr = isExpressions(attr.value)
                if (expr !== null) {
                    attr = attr.name
                    var evName, prop
                    if (attr.startsWith('on-')) {
                        evName = attr.slice(3)
                        var render = function(el, v) {
                            var evs = el.__plutoEvs || (el.__plutoEvs = {})
                            if (evs[evName] !== v) {
                                el.removeEventListener(evName, evs[evName])
                                el.addEventListener(evName, evs[evName] = v)
                            }
                        }
                    } else if (['style', 'class'].indexOf(attr) !== -1) {
                        var render = (el, v) => v
                            ? el.setAttribute(attr, v)
                            : el.removeAttribute(attr)
                    } else {
                        prop = snakeToCamelCase(attr)
                        var render = (el, v) => el[prop] = v
                    }

                    exprs.push({ expr, path, attr, evName, prop, render })
                }
            }, this)

            // children, enqueue.
            el.childNodes.forEach(function(el, i) {
                maybeUpgrade(el)
                var subpath = path.concat(['childNodes', i])
                if (el instanceof Template) {
                    exprs.push({ path: subpath, tpl: true })
                    return
                }

                elements.push({ el, path: subpath })
            })
        }

        // remove attributes or expressions before rendering in order to hide
        // the placeholder expressions from the constructor of custom elements.
        var clone = this.cloneNode(true)
        exprs.forEach(function(expr) {
            var el = select(clone.content, expr.path)
            if (!expr.attr) {
                el.textContent = ''
            } else {
                el.removeAttribute(expr.attr)
            }
        }, this)

        var repeat = this.getAttribute('repeat') || this.getAttribute('for')
        if (repeat) {
            clone.items = function(fn, obj) {
                var items = fn(obj)[0] || []
                obj.__plutoElse = items.length > 0
                return items
            }.bind(clone, compileExpressions([{ expr: repeat }]))
        }

        var elseIf = this.getAttribute('else-if')
        var cond = this.getAttribute('if') || elseIf
        if (cond) {
            clone.items = function(fn, obj) {
                return obj.__plutoElse = Boolean(fn(obj)[0])
            }.bind(clone, compileExpressions([{ expr: cond }]))
        }

        var else_ = this.hasAttribute('else') || elseIf
        if (else_) {
            clone.items = function(fn, obj) {
                return obj.__plutoElse ? [] : fn(obj)
            }.bind(clone, clone.items || Array)
        }

        // we opt to compile the repeat/cond expressions separately than the
        // rest of this template - because (a) the template might relay on a
        // repeated ${item} property that doesn't yet exist in the repeat
        // expression, and (b) it's must smaller/faster than the complete
        // expressions list.
        // NB: It might not be that beneficial for cond though.
        clone.exprs = Object.assign(exprs, { eval: compileExpressions(exprs) })
        return clone
    }
}

class Renderer extends DocumentFragment {
    constructor(tpl, items) {
        super()
        this.tpl = tpl
        this.elements = []
        this.paths = {}
        this.exprs = tpl.exprs
        this.items = items

        if (items) {
            this.placeholder = document.createTextNode('')
            this.appendChild(this.placeholder)
        } else {
            this.appendChild(document.importNode(this.tpl.content, true))

            // copy the list of generated elements from the template in order
            // to support removals
            this.elements = [].map.call(this.childNodes, child => child)
        }
    }

    remove() {
        while (this.elements.length > 0) {
            this.elements.pop().remove()
        }
    }

    render(obj) {
        if (!this.items) {
            return this._renderOne(obj)
        }

        var items = this.items(obj)
        var item = obj.item
        if (!Array.isArray(items) && typeof items === 'object') {
            items = Object.keys(items).map(function(k) {
                return { key: k, value: items[k] }
            })
        }

        if (typeof items === 'boolean') {
            items = Number(items) // 0 or 1
        }

        if (typeof items === 'number') {
            items = new Array(items) // range-items, repeat N times.
            items = Array.from(items).map(() => item)
        }

        // remove obsolete items
        while (this.elements.length > items.length) {
            this.elements.pop().remove()
        }

        // update existing items
        for (var i = 0; i < this.elements.length; i += 1) {
            obj.item = items[i]
            this.elements[i].render(obj)
        }

        // create new items
        while (this.elements.length < items.length) {
            var i = this.elements.length
            obj.item = items[i]
            var doc = new Renderer(this.tpl).render(obj)
            this.elements.push(doc)
            this.placeholder.before(doc)
        }

        obj.item = item // restore previous item value.
        return this
    }

    _renderOne(obj) {
        var values = this.exprs.eval(obj)
        var subtpls = []
        for (var i = 0 ; i < this.exprs.length ; i += 1) {
            var expr = this.exprs[i]
            var v = values[i]
            var el = select(this, expr.path)

            if (expr.tpl) {
                subtpls.push(el)
            } else {
                expr.render(el, v)
            }
        }

        var else_ = obj.__plutoElse
        obj.__plutoElse = false
        for (var i = 0; i < subtpls.length; i += 1) {
            var el = subtpls[i]
            if (!el.render) {
                el.render = function(obj) {
                    delete el.render
                    var subdoc = pluto(this).render(obj)
                    this.replaceWith(subdoc)
                    this.render = subdoc.render.bind(subdoc)
                    this.remove = subdoc.remove.bind(subdoc)
                }
            }

            el.render(obj)
        }
        obj.__plutoElse = else_

        return this
    }
}

// -- HELPER FUNCTIONS

function maybeUpgrade(el) {
    // don't match #text, #comment, etc.
    if (el.nodeName[0] !== '#' && el.matches('template')) {
        pluto(el) // auto-upgrade nested templates.
    }
}

// Searches for an element from root based on the property-path to the child
// example: root = <body>, path = childNodes.3.childNode.7. Resolved by walking
// the path down to the child.
// NOTE that this function is memoized on the provided root object
function select(root, path) {
    var memo = root._plutoPaths || (root._plutoPaths = {})
    var pathKey = path.join('.')
    if (memo[pathKey]) {
        return memo[pathKey]
    }

    var el = root
    for (var i = 0; el !== undefined && i < path.length; i += 1) {
        el = el[path[i]]
    }

    return memo[pathKey] = el
}

const SNAKE_RE = /-([a-z])/g
function snakeToCamelCase(s) {
    return s.replace(SNAKE_RE, g => g[1].toUpperCase())
}

// extract expressions in template-literal syntax out of a string
var EXPR_RE = /\$\{[^\}]*\}/
function isExpressions(s) {
    return EXPR_RE.test(s) ? s : null
}

// compile a list of template-literal expressions into a function that evaluates
// these expression for the provided input object
function compileExpressions(exprs) {
    var refs = []
    var code = 'this.__plutoT || (this.__plutoT = T.bind(this));\n'
    code += exprs.map(function(expr, i) {
        if (expr.expr) {
            refs = refs.concat(getIdentifiers(expr.expr))
        }

        var tagFn = ({
            'class': 'classNameT',
            'style': 'styleT'
        })[expr.attr] || 'this.__plutoT'

        return `arguments[0][${i}] = ${tagFn}\`${expr.expr}\``
    }).join(';\n')

    var keys = refs.reduce((keys, k) => (keys[k] = true, keys), {})
    var locals = `var { ${Object.keys(keys)} } = this`
    var fn = eval('(function () {\n' + locals + '\n' + code + '\n})')
    return function(obj) {
        var res = []
        try {
            fn.call(obj, res)
        } catch (e) {
            console.warn(fn)
            throw e
        }

        return res
    }

    function T(s, v) {
        if (arguments.length > 2 || typeof v === 'string') {
            return String.raw.apply(null, arguments)
        }

        if (typeof v === 'function' && this[v.name] === v) {
            if (v._plutoBound !== this) {
                v._plutoBound = v.bind(this)
            }
            return v._plutoBound
        }

        return v
    }

    function classNameT(s, v) {
        if (typeof v === 'object') {
            if (!Array.isArray(v)) {
                v = Object.keys(v).filter((k) => v[k])
            }

            return v.join(' ')
        }

        return String.raw.apply(null, arguments)
    }

    function styleT(s, v) {
        if (typeof v === 'object') {
            return Object.keys(v).map((k) => k + ':' + v[k]).join('; ')
        }

        return String.raw.apply(null, arguments)
    }
}

// generate the list of identifiers found in the code.
function getIdentifiers(expr) {
    var re = /[$A-Z_][0-9A-Z_$]*/ig
    var whitespace = ' \n\r\t'
    var disallowed = '\'\".'
    var skip = ['true', 'false', 'if', 'for', 'while', 'do', 'try', 'catch',
        'break', 'continue', 'switch', 'throw', 'this', 'instanceof', 'in',
        'function', 'delete', 'default', 'case', 'debugger', 'const', 'var',
        'with', 'typeof', 'super', 'class', 'new', 'null', 'return', 'let',
        'import', 'else', 'enum', 'extends', 'finally', '$']

    // We first match for the valid identifier, and then check the previous
    // non-whitespace character preceeding the identifier to verify that it's
    // not a string or nested element.
    var refs = {}
    var match
    while (match = re.exec(expr)) {
        if (skip.indexOf(match[0]) !== -1) {
            continue // skipped or reserved keyword
        }

        if (window[match[0]] !== undefined) {
            continue // keep global functions (Object, Array, etc.)
        }

        var lastChar = undefined
        do {
            match.index -= 1
            if (whitespace.indexOf(expr[match.index]) === -1) {
                lastChar = expr[match.index]
            }
        } while (match.index > -1 && !lastChar)

        if (disallowed.indexOf(lastChar) === -1) {
            refs[match[0]] = true
        }
    }

    return Object.keys(refs)
}

// upgrade an element
// NOTE this will be unnecessary with customElements
function pluto(el) {
    if (typeof el === 'string') {
        // support HTML-imported selections
        var doc = document._currentScript // used by pollyfills
            || document.currentScript // native.
            || document // not an import.
        el = (doc.ownerDocument || doc).querySelector(el)
    }

    return !el || el instanceof Template
        ? el
        : Object.setPrototypeOf(el, Template.prototype)
}

pluto.Template = Template
pluto.RepeatRenderer = Renderer
window.pluto = pluto
})();

(function() {

    // placed here in order to have its own scope clear of any of the pluto
    // local variables.
    pluto._eval = function(code) {
        return eval(code)
    }
})();
<commit_msg>Render function for nested templates<commit_after>(function() {
/**
 * PLUTO
 * Native HTML Template Rendering
 *
 *
 * The MIT License (MIT)
 * Copyright (c) 2013 Roi Avinoam
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
class Template extends HTMLTemplateElement {
    render(obj) {
        var compiled = this.compile()
        return new Renderer(compiled, compiled.items).render(obj)
    }

    _renderIn(obj, el) {
        if (el.__plutoRenderer) {
            el.__plutoRenderer.render(obj)
        } else {
            var doc = this.render(obj)
            el.replaceWith(doc)
            el.__plutoRenderer = doc
            el.remove = doc.remove.bind(doc)
        }
    }

    compile() {
        var exprs = []
        var elements = [{ el: this.content, path: [] }]
        while (elements.length > 0) {
            var { el, path } = elements.shift()

            // inner content expressions
            if (el.nodeName === '#text') {
                var expr = isExpressions(el.textContent)
                if (expr) {
                    var render = (el, v) => (el.textContent = v || '')
                    exprs.push({expr, path, render })
                }
            }

            // attributes
            [].forEach.call(el.attributes || [], function(attr) {
                var expr = isExpressions(attr.value)
                if (expr !== null) {
                    attr = attr.name
                    var evName, prop
                    if (attr.startsWith('on-')) {
                        evName = attr.slice(3)
                        var render = function(el, v) {
                            var evs = el.__plutoEvs || (el.__plutoEvs = {})
                            if (evs[evName] !== v) {
                                el.removeEventListener(evName, evs[evName])
                                el.addEventListener(evName, evs[evName] = v)
                            }
                        }
                    } else if (['style', 'class'].indexOf(attr) !== -1) {
                        var render = (el, v) => v
                            ? el.setAttribute(attr, v)
                            : el.removeAttribute(attr)
                    } else {
                        prop = snakeToCamelCase(attr)
                        var render = (el, v) => el[prop] = v
                    }

                    exprs.push({ expr, path, attr, evName, prop, render })
                }
            }, this)

            // children, enqueue.
            el.childNodes.forEach(function(el, i) {
                maybeUpgrade(el)
                var subpath = path.concat(['childNodes', i])
                if (el instanceof Template) {
                    var render = function(el, _, obj) {
                        pluto(el)._renderIn(obj, el)
                    }

                    exprs.push({ path: subpath, tpl: true, render })
                    return
                }

                elements.push({ el, path: subpath })
            })
        }

        // remove attributes or expressions before rendering in order to hide
        // the placeholder expressions from the constructor of custom elements.
        var clone = this.cloneNode(true)
        exprs.forEach(function(expr) {
            var el = select(clone.content, expr.path)
            if (!expr.attr) {
                el.textContent = ''
            } else {
                el.removeAttribute(expr.attr)
            }
        }, this)

        var repeat = this.getAttribute('repeat') || this.getAttribute('for')
        if (repeat) {
            clone.items = function(fn, obj) {
                var items = fn(obj)[0] || []
                obj.__plutoElse = items.length > 0
                return items
            }.bind(clone, compileExpressions([{ expr: repeat }]))
        }

        var elseIf = this.getAttribute('else-if')
        var cond = this.getAttribute('if') || elseIf
        if (cond) {
            clone.items = function(fn, obj) {
                return obj.__plutoElse = Boolean(fn(obj)[0])
            }.bind(clone, compileExpressions([{ expr: cond }]))
        }

        var else_ = this.hasAttribute('else') || elseIf
        if (else_) {
            clone.items = function(fn, obj) {
                return obj.__plutoElse ? [] : fn(obj)
            }.bind(clone, clone.items || Array)
        }

        // we opt to compile the repeat/cond expressions separately than the
        // rest of this template - because (a) the template might relay on a
        // repeated ${item} property that doesn't yet exist in the repeat
        // expression, and (b) it's must smaller/faster than the complete
        // expressions list.
        // NB: It might not be that beneficial for cond though.
        clone.exprs = Object.assign(exprs, { eval: compileExpressions(exprs) })
        return clone
    }
}

class Renderer extends DocumentFragment {
    constructor(tpl, items) {
        super()
        this.tpl = tpl
        this.elements = []
        this.paths = {}
        this.exprs = tpl.exprs
        this.items = items

        if (items) {
            this.placeholder = document.createTextNode('')
            this.appendChild(this.placeholder)
        } else {
            this.appendChild(document.importNode(this.tpl.content, true))

            // copy the list of generated elements from the template in order
            // to support removals
            this.elements = [].map.call(this.childNodes, child => child)
        }
    }

    remove() {
        while (this.elements.length > 0) {
            this.elements.pop().remove()
        }
    }

    render(obj) {
        if (!this.items) {
            return this._renderOne(obj)
        }

        var items = this.items(obj)
        var item = obj.item
        if (!Array.isArray(items) && typeof items === 'object') {
            items = Object.keys(items).map(function(k) {
                return { key: k, value: items[k] }
            })
        }

        if (typeof items === 'boolean') {
            items = Number(items) // 0 or 1
        }

        if (typeof items === 'number') {
            items = new Array(items) // range-items, repeat N times.
            items = Array.from(items).map(() => item)
        }

        // remove obsolete items
        while (this.elements.length > items.length) {
            this.elements.pop().remove()
        }

        // update existing items
        for (var i = 0; i < this.elements.length; i += 1) {
            obj.item = items[i]
            this.elements[i].render(obj)
        }

        // create new items
        while (this.elements.length < items.length) {
            var i = this.elements.length
            obj.item = items[i]
            var doc = new Renderer(this.tpl).render(obj)
            this.elements.push(doc)
            this.placeholder.before(doc)
        }

        obj.item = item // restore previous item value.
        return this
    }

    _renderOne(obj) {
        var values = this.exprs.eval(obj)
        var subtpls = []
        for (var i = 0 ; i < this.exprs.length ; i += 1) {
            var expr = this.exprs[i]
            var v = values[i]
            var el = select(this, expr.path)

            if (expr.tpl) {
                subtpls.push({ el, expr })
            } else {
                expr.render(el, v)
            }
        }

        var else_ = obj.__plutoElse
        obj.__plutoElse = false
        for (var i = 0; i < subtpls.length; i += 1) {
            var { el, expr } = subtpls[i]
            if (expr.render) {
                expr.render(el, undefined, obj)
            }
        }
        obj.__plutoElse = else_

        return this
    }
}

// -- HELPER FUNCTIONS

function maybeUpgrade(el) {
    // don't match #text, #comment, etc.
    if (el.nodeName[0] !== '#' && el.matches('template')) {
        pluto(el) // auto-upgrade nested templates.
    }
}

// Searches for an element from root based on the property-path to the child
// example: root = <body>, path = childNodes.3.childNode.7. Resolved by walking
// the path down to the child.
// NOTE that this function is memoized on the provided root object
function select(root, path) {
    var memo = root._plutoPaths || (root._plutoPaths = {})
    var pathKey = path.join('.')
    if (memo[pathKey]) {
        return memo[pathKey]
    }

    var el = root
    for (var i = 0; el !== undefined && i < path.length; i += 1) {
        el = el[path[i]]
    }

    return memo[pathKey] = el
}

const SNAKE_RE = /-([a-z])/g
function snakeToCamelCase(s) {
    return s.replace(SNAKE_RE, g => g[1].toUpperCase())
}

// extract expressions in template-literal syntax out of a string
var EXPR_RE = /\$\{[^\}]*\}/
function isExpressions(s) {
    return EXPR_RE.test(s) ? s : null
}

// compile a list of template-literal expressions into a function that evaluates
// these expression for the provided input object
function compileExpressions(exprs) {
    var refs = []
    var code = 'this.__plutoT || (this.__plutoT = T.bind(this));\n'
    code += exprs.map(function(expr, i) {
        if (expr.expr) {
            refs = refs.concat(getIdentifiers(expr.expr))
        }

        var tagFn = ({
            'class': 'classNameT',
            'style': 'styleT'
        })[expr.attr] || 'this.__plutoT'

        return `arguments[0][${i}] = ${tagFn}\`${expr.expr}\``
    }).join(';\n')

    var keys = refs.reduce((keys, k) => (keys[k] = true, keys), {})
    var locals = `var { ${Object.keys(keys)} } = this`
    var fn = eval('(function () {\n' + locals + '\n' + code + '\n})')
    return function(obj) {
        var res = []
        try {
            fn.call(obj, res)
        } catch (e) {
            console.warn(fn)
            throw e
        }

        return res
    }

    function T(s, v) {
        if (arguments.length > 2 || typeof v === 'string') {
            return String.raw.apply(null, arguments)
        }

        if (typeof v === 'function' && this[v.name] === v) {
            if (v._plutoBound !== this) {
                v._plutoBound = v.bind(this)
            }
            return v._plutoBound
        }

        return v
    }

    function classNameT(s, v) {
        if (typeof v === 'object') {
            if (!Array.isArray(v)) {
                v = Object.keys(v).filter((k) => v[k])
            }

            return v.join(' ')
        }

        return String.raw.apply(null, arguments)
    }

    function styleT(s, v) {
        if (typeof v === 'object') {
            return Object.keys(v).map((k) => k + ':' + v[k]).join('; ')
        }

        return String.raw.apply(null, arguments)
    }
}

// generate the list of identifiers found in the code.
function getIdentifiers(expr) {
    var re = /[$A-Z_][0-9A-Z_$]*/ig
    var whitespace = ' \n\r\t'
    var disallowed = '\'\".'
    var skip = ['true', 'false', 'if', 'for', 'while', 'do', 'try', 'catch',
        'break', 'continue', 'switch', 'throw', 'this', 'instanceof', 'in',
        'function', 'delete', 'default', 'case', 'debugger', 'const', 'var',
        'with', 'typeof', 'super', 'class', 'new', 'null', 'return', 'let',
        'import', 'else', 'enum', 'extends', 'finally', '$']

    // We first match for the valid identifier, and then check the previous
    // non-whitespace character preceeding the identifier to verify that it's
    // not a string or nested element.
    var refs = {}
    var match
    while (match = re.exec(expr)) {
        if (skip.indexOf(match[0]) !== -1) {
            continue // skipped or reserved keyword
        }

        if (window[match[0]] !== undefined) {
            continue // keep global functions (Object, Array, etc.)
        }

        var lastChar = undefined
        do {
            match.index -= 1
            if (whitespace.indexOf(expr[match.index]) === -1) {
                lastChar = expr[match.index]
            }
        } while (match.index > -1 && !lastChar)

        if (disallowed.indexOf(lastChar) === -1) {
            refs[match[0]] = true
        }
    }

    return Object.keys(refs)
}

// upgrade an element
// NOTE this will be unnecessary with customElements
function pluto(el) {
    if (typeof el === 'string') {
        // support HTML-imported selections
        var doc = document._currentScript // used by pollyfills
            || document.currentScript // native.
            || document // not an import.
        el = (doc.ownerDocument || doc).querySelector(el)
    }

    return !el || el instanceof Template
        ? el
        : Object.setPrototypeOf(el, Template.prototype)
}

pluto.Template = Template
pluto.RepeatRenderer = Renderer
window.pluto = pluto
})();

(function() {

    // placed here in order to have its own scope clear of any of the pluto
    // local variables.
    pluto._eval = function(code) {
        return eval(code)
    }
})();
<|endoftext|>


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

module.exports = {
  name: 'ember-c3',
  included: function(app) {
    this._super.included(app);

    app.import(app.bowerDirectory + '/d3/d3.min.js');
    app.import(app.bowerDirectory + '/c3/c3.min.css');
    app.import(app.bowerDirectory + '/c3/c3.min.js');
  }
};
<commit_msg>[BUGFIX] Allow ember-c3 to be used as a nested addon<commit_after>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-c3',
  included: function(app, parentAddon) {
    // see: https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof app.import !== 'function' && app.app) {
      this.app = app = app.app;
    }
    this._super.included(app);

    var target = parentAddon || app;

    target.import(target.bowerDirectory + '/d3/d3.min.js');
    target.import(target.bowerDirectory + '/c3/c3.min.css');
    target.import(target.bowerDirectory + '/c3/c3.min.js');
  }
};
<|endoftext|>


<commit_before>'use strict';

var Parser    = require(__dirname + '/libs/parser'),
    Circle    = require(__dirname + '/libs/elements/circle'),
    Point     = require(__dirname + '/libs/elements/point'),
    Polygon   = require(__dirname + '/libs/element/polygon'),
    text      = require(__dirname + '/libs/element/text');

module.exports = {
	Parser  : Parser,
    Circle  : Circle,
    Point   : Point,
    Polygon : Polygon,
    text    : text
};<commit_msg>fix bug<commit_after>'use strict';

var Parser    = require(__dirname + '/libs/parser'),
    Circle    = require(__dirname + '/libs/elements/circle'),
    Point     = require(__dirname + '/libs/elements/point'),
    Polygon   = require(__dirname + '/libs/element/polygon'),
    Text      = require(__dirname + '/libs/element/text');

module.exports = {
	Parser  : Parser,
    Circle  : Circle,
    Point   : Point,
    Polygon : Polygon,
    Text    : Text
};<|endoftext|>


<commit_before>var net = require('net')
var fs = require('fs')
var path = require('path')
var walker = require('folder-walker')
var level = require('level')
var hyperdrive = require('hyperdrive')
var xtend = require('xtend')
var mkdirp = require('mkdirp')
var through = require('through2')
var pump = require('pump')
var discoveryChannel = require('discovery-channel')

module.exports = Dat

function Dat (dir, opts) {
  if (!(this instanceof Dat)) return new Dat(dir, opts)
  if (!opts) opts = {}
  this.dir = dir
  var defaults = {
    createIfMissing: true
  }
  opts = xtend(opts, defaults)
  var datPath = path.join(this.dir, '.dat', 'db')
  if (opts.createIfMissing) mkdirp.sync(datPath)
  var hyperdriveOpts = {name: 'dat'}
  var drive = hyperdrive(level(datPath, opts), hyperdriveOpts)
  this.drive = drive
  this.peers = {}
  this.discovery = discoveryChannel()
}

Dat.prototype.share = function (cb) {
  var self = this
  var stream = walker(this.dir, {filter: function (filename) {
    var basename = path.basename(filename)
    if (basename[0] === '.') return false // ignore hidden files and folders
    return true
  }})
  var pack = this.drive.add()
  var adder = through.obj(function (data, enc, next) {
    var isFile = data.stat.isFile()
    if (!isFile) {
      console.log('skipping non file', data.filepath)
      return next()
    }
    console.log('reading', data.filepath)
    var entry = pack.entry({name: data.relname, mode: data.stat.mode})
    fs.createReadStream(data.filepath).pipe(entry).on('finish', next)
  })
  pump(stream, adder, function (err) {
    if (err) throw err
    pack.finalize(function () {
      var link = pack.id.toString('hex')
      self.serve(link, function (err, link, port, close) {
        if (err) throw err
        cb(null, link, port, close)
        console.log('Sharing on', port)
      })
    })
  })
}

Dat.prototype.serve = function (link, cb) {
  var self = this

  var server = net.createServer(function (socket) {
    pump(socket, self.drive.createPeerStream(), socket, function (err) {
      if (err) console.log('peer err', err)
    })
  })

  server.listen(0, function (err) {
    if (err) return cb(err)
    var port = server.address().port

    function update () {
      // discovery-channel currently only works with 20 bytes hashes
      var hash = resolveHash(link)
      self.discovery.announce(hash, port)

      var lookup = self.discovery.lookup(hash)

      lookup.on('peer', function (ip, port) {
        var peerid = ip + ':' + port
        if (self.peers[peerid]) return
        console.log('found new peer', peerid)
        self.peers[peerid] = true
        var socket = net.connect(port, ip)
        pump(socket, self.drive.createPeerStream(), socket, function (err) {
          if (err) console.log('peer err', err)
          delete self.peers[peerid]
        })
      })
    }

    update()
    var interval = setInterval(update, 1000 * 60)

    function close (cb) {
      clearInterval(interval)
      server.close()
      self.drive.db.close()
      self.discovery.close(cb)
    }

    cb(null, link, port, close)
  })
}

Dat.prototype.download = function (link, cb) {
  var self = this
  if (!cb) cb = function noop () {}

  self.serve(link, function (err, port, close) {
    if (err) throw err
    console.log('Sharing on', port)
  })

  var feed = self.drive.get(link) // the link identifies/verifies the content
  var feedStream = feed.createStream()

  feedStream.on('data', function (entry) {
    console.log('downloading', entry.value.name)
    var content = self.drive.get(entry)
    var writeStream = fs.createWriteStream(entry.value.name, {mode: entry.value.mode})
    content.createStream().pipe(writeStream)
  })
}

function resolveHash (link) {
  // TODO: handle 'pretty' or 'named' links
  return new Buffer(link, 'hex').slice(0, 20)
}
<commit_msg>call callback on download end<commit_after>var net = require('net')
var fs = require('fs')
var path = require('path')
var walker = require('folder-walker')
var level = require('level')
var hyperdrive = require('hyperdrive')
var xtend = require('xtend')
var mkdirp = require('mkdirp')
var through = require('through2')
var pump = require('pump')
var discoveryChannel = require('discovery-channel')

module.exports = Dat

function Dat (dir, opts) {
  if (!(this instanceof Dat)) return new Dat(dir, opts)
  if (!opts) opts = {}
  this.dir = dir
  var defaults = {
    createIfMissing: true
  }
  opts = xtend(opts, defaults)
  var datPath = path.join(this.dir, '.dat', 'db')
  if (opts.createIfMissing) mkdirp.sync(datPath)
  var hyperdriveOpts = {name: 'dat'}
  var drive = hyperdrive(level(datPath, opts), hyperdriveOpts)
  this.drive = drive
  this.peers = {}
  this.discovery = discoveryChannel()
}

Dat.prototype.share = function (cb) {
  var self = this
  var stream = walker(this.dir, {filter: function (filename) {
    var basename = path.basename(filename)
    if (basename[0] === '.') return false // ignore hidden files and folders
    return true
  }})
  var pack = this.drive.add()
  var adder = through.obj(function (data, enc, next) {
    var isFile = data.stat.isFile()
    if (!isFile) {
      console.log('skipping non file', data.filepath)
      return next()
    }
    console.log('reading', data.filepath)
    var entry = pack.entry({name: data.relname, mode: data.stat.mode})
    fs.createReadStream(data.filepath).pipe(entry).on('finish', next)
  })
  pump(stream, adder, function (err) {
    if (err) throw err
    pack.finalize(function () {
      var link = pack.id.toString('hex')
      self.serve(link, function (err, link, port, close) {
        if (err) throw err
        cb(null, link, port, close)
        console.log('Sharing on', port)
      })
    })
  })
}

Dat.prototype.serve = function (link, cb) {
  var self = this

  var server = net.createServer(function (socket) {
    pump(socket, self.drive.createPeerStream(), socket, function (err) {
      if (err) console.log('peer err', err)
    })
  })

  server.listen(0, function (err) {
    if (err) return cb(err)
    var port = server.address().port

    function update () {
      // discovery-channel currently only works with 20 bytes hashes
      var hash = resolveHash(link)
      self.discovery.announce(hash, port)

      var lookup = self.discovery.lookup(hash)

      lookup.on('peer', function (ip, port) {
        var peerid = ip + ':' + port
        if (self.peers[peerid]) return
        console.log('found new peer', peerid)
        self.peers[peerid] = true
        var socket = net.connect(port, ip)
        pump(socket, self.drive.createPeerStream(), socket, function (err) {
          if (err) console.log('peer err', err)
          delete self.peers[peerid]
        })
      })
    }

    update()
    var interval = setInterval(update, 1000 * 60)

    function close (cb) {
      clearInterval(interval)
      server.close()
      self.drive.db.close()
      self.discovery.close(cb)
    }

    cb(null, link, port, close)
  })
}

Dat.prototype.download = function (link, cb) {
  var self = this
  if (!cb) cb = function noop () {}

  self.serve(link, function (err, port, close) {
    if (err) throw err
    console.log('Sharing on', port)
  })

  var feed = self.drive.get(link) // the link identifies/verifies the content
  var feedStream = feed.createStream()

  feedStream.on('data', function (entry) {
    console.log('downloading', entry.value.name)
    var content = self.drive.get(entry)
    var writeStream = fs.createWriteStream(entry.value.name, {mode: entry.value.mode})
    content.createStream().pipe(writeStream)
  })

  feedStream.on('end', cb)
}

function resolveHash (link) {
  // TODO: handle 'pretty' or 'named' links
  return new Buffer(link, 'hex').slice(0, 20)
}
<|endoftext|>


<commit_before>var width = window.innerWidth || document.body.clientWidth;
var height = window.innerHeight || document.body.clientHeight;

var sidebar_width = 200;
width -= sidebar_width;

var canvas = document.getElementById('canvas');
canvas.width = width;
canvas.height = height;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';

window.show_points = true;
window.control_point = false;

// the distance between the mouse & any point
// to make the mouse modify the point
window.UI_SNAP = 5;

var ctx = canvas.getContext("2d");
var sprite, sprites = [];
function createSprite() {
  var border_color = border_input.value;
  var fill_color = fill_input.value;
  sprite = new Sprite(ctx, border_color, fill_color);
  sprites.push(sprite);
}

var dragging_pt = null;
document.body.addEventListener('mousedown', function(evt) {
  var pt = event2Point(evt);
  if (pt.x < 0)
    return;

  var close_pt = _.find(sprite.points, function(sprite_pt) {
    return distance(sprite_pt, pt) < UI_SNAP;
  });
  if (close_pt)
    dragging_pt = close_pt;
});

document.body.addEventListener('mousemove', function(evt) {
  var pt = event2Point(evt);
  if (pt.x < 0)
    return;

  if (!dragging_pt)
    return;

  dragging_pt.x = pt.x;
  dragging_pt.y = pt.y;
});

document.body.addEventListener('mouseup', function(evt) {
  var pt = event2Point(evt);
  if (pt.x < 0)
    return;

  if (dragging_pt) {
    dragging_pt = null;
  }
  else {
    if (control_point)
      sprite.addControlPoint(pt);
    else
      sprite.addPoint(pt);
  }
});

var show_pts_btn = document.getElementById('show-points');
show_pts_btn.addEventListener('click', function() {
  show_points = !show_points;
  if (show_points)
    show_pts_btn.innerHTML = 'Hide Points';
  else
    show_pts_btn.innerHTML = 'Show Points';
});

var control_pt_btn = document.getElementById('control-point');
control_pt_btn.addEventListener('click', function() {
  control_point = !control_point;
  if (control_point)
    control_pt_btn.innerHTML = 'Normal Point';
  else
    control_pt_btn.innerHTML = 'Control Point';
});

var create_btn = document.getElementById('create-shape');
create_btn.addEventListener('click', function() {
  createSprite();
});

var border_input = document.getElementById('border-color');
border_input.addEventListener('blur', function() {
  sprite.strokeStyle = border_input.value;
});

var fill_input = document.getElementById('fill-color');
fill_input.addEventListener('blur', function() {
  sprite.fillStyle = fill_input.value;
});

var close_shape_btn = document.getElementById('close-shape');
close_shape_btn.addEventListener('click', function() {
  sprite.close();
});

function distance(pt1, pt2) {
  return Math.sqrt(square(Math.abs(pt1.x - pt2.x)) + square(Math.abs(pt1.y - pt2.y)));
}

function square(x) {
  return Math.pow(x, 2);
}

// function intersects(max_pt1, min_pt1, max_pt2, min_pt2) {
//   return !(
//     max_pt1.x < min_pt2.x ||
//     max_pt1.y < min_pt2.y ||
//     min_pt1.x > max_pt2.x ||
//     min_pt1.y > max_pt2.y
//   );
// }

function event2Point(evt) {
  return {x: evt.clientX - sidebar_width, y: evt.clientY};
}

createSprite();

requestAnimationFrame(animate);
animate();

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  sprites.forEach(function(sprite) {
    sprite.draw();
    if (show_points)
      sprite.points.forEach(drawPoint);
  });
  requestAnimationFrame(animate);
}

function drawPoint(pt) {
  ctx.beginPath();
  var radius = 5;
  ctx.arc(pt.x, pt.y, radius, 0, 2 * Math.PI);
  if (pt.is_control)
    ctx.fillStyle = '#F00';
  else
    ctx.fillStyle = '#000';
  ctx.fill();
  ctx.closePath();
}
<commit_msg>Added touch event support<commit_after>var width = window.innerWidth || document.body.clientWidth;
var height = window.innerHeight || document.body.clientHeight;

var sidebar_width = 200;
width -= sidebar_width;

var canvas = document.getElementById('canvas');
canvas.width = width;
canvas.height = height;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';

window.show_points = true;
window.control_point = false;
window.state_name = null;
window.is_animating = false;
window.animate_start = null;

// the distance between the mouse & any point
// to make the mouse modify the point
window.UI_SNAP = 5;

var ctx = canvas.getContext("2d");
var sprite, sprites = [];
function createSprite() {
  var border_color = border_input.value;
  var fill_color = fill_input.value;
  sprite = new Sprite(ctx, border_color, fill_color);
  sprites.push(sprite);
}

var dragging_pt = null;
document.body.addEventListener('mousedown', onMouseDown);
document.body.addEventListener('touchstart', onMouseDown);
function onMouseDown(evt) {
  var pt = event2Point(evt);
  if (pt.x < 0)
    return;

  var close_pt = _.find(sprite.points, function(sprite_pt) {
    return distance(sprite_pt, pt) < UI_SNAP;
  });
  if (close_pt)
    dragging_pt = close_pt;
}

document.body.addEventListener('mousemove', onMouseMove);
document.body.addEventListener('touchmove', onMouseMove);
function onMouseMove(evt) {
  var pt = event2Point(evt);
  if (pt.x < 0)
    return;

  if (!dragging_pt)
    return;

  dragging_pt.x = pt.x;
  dragging_pt.y = pt.y;
}

document.body.addEventListener('mouseup', onMouseUp);
document.body.addEventListener('touchend', onMouseUp);
function onMouseUp(evt) {
  var pt = event2Point(evt);
  if (pt.x < 0)
    return;

  if (dragging_pt) {
    dragging_pt = null;
  }
  else {
    if (control_point)
      sprite.addControlPoint(pt);
    else
      sprite.addPoint(pt);
  }
}

var show_pts_btn = document.getElementById('show-points');
show_pts_btn.addEventListener('click', function() {
  show_points = !show_points;
  if (show_points)
    show_pts_btn.innerHTML = 'Hide Points';
  else
    show_pts_btn.innerHTML = 'Show Points';
});

var control_pt_btn = document.getElementById('control-point');
control_pt_btn.addEventListener('click', function() {
  control_point = !control_point;
  if (control_point)
    control_pt_btn.innerHTML = 'Normal Point';
  else
    control_pt_btn.innerHTML = 'Control Point';
});

var create_btn = document.getElementById('create-shape');
create_btn.addEventListener('click', function() {
  createSprite();
});

var border_input = document.getElementById('border-color');
border_input.addEventListener('blur', function() {
  sprite.strokeStyle = border_input.value;
});

var fill_input = document.getElementById('fill-color');
fill_input.addEventListener('blur', function() {
  sprite.fillStyle = fill_input.value;
});

var close_shape_btn = document.getElementById('close-shape');
close_shape_btn.addEventListener('click', function() {
  sprite.close();
});

function distance(pt1, pt2) {
  return Math.sqrt(square(Math.abs(pt1.x - pt2.x)) + square(Math.abs(pt1.y - pt2.y)));
}

function square(x) {
  return Math.pow(x, 2);
}

// function intersects(max_pt1, min_pt1, max_pt2, min_pt2) {
//   return !(
//     max_pt1.x < min_pt2.x ||
//     max_pt1.y < min_pt2.y ||
//     min_pt1.x > max_pt2.x ||
//     min_pt1.y > max_pt2.y
//   );
// }

function event2Point(evt) {
  return {x: evt.clientX - sidebar_width, y: evt.clientY};
}

createSprite();

requestAnimationFrame(animate);
animate();

function animate() {
  var pct = 1; // todo change this when animating
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  sprites.forEach(function(sprite) {
    sprite.draw(state_name, pct);
    if (show_points)
      sprite.points.forEach(drawPoint);
  });
  requestAnimationFrame(animate);
}

function drawPoint(pt) {
  ctx.beginPath();
  var radius = 5;
  ctx.arc(pt.x, pt.y, radius, 0, 2 * Math.PI);
  if (pt.is_control)
    ctx.fillStyle = '#F00';
  else
    ctx.fillStyle = '#000';
  ctx.fill();
  ctx.closePath();
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');

var Logger = function(namespace, debugFn) {
  this.namespace = namespace;
  this.debugger = debugFn;
};

Logger.prototype = {
  addTransactionLogger: function(transactionLogger) {
    this.transactionLogger = transactionLogger;
  },

  log: function(event, data) {
    this.debugger(this._getPrefix(event) + this._prepareData(data));
  },

  success: function(event, data) {
    this.debugger(this._getPrefix(event) + ' result=success' + this._prepareData(data));
  },

  error: function(event, errorMessage, data) {
    this.debugger(this._getPrefix(event) +' result=error errorMessage="' + errorMessage + '"' + this._prepareData(data));
  },

  sanityError: function(event, errorMessage, data) {
    this.debugger(this._getPrefix(event) +' result=error triggeredBy=sanityCheck errorMessage="' + errorMessage + '"' + this._prepareData(data));
  },

  transactionProperty: function(name, value) {
    if (!this.transactionLogger) return;
    this.transactionLogger.addCustomParameter(name, value);
  },

  _getPrefix: function(event) {
    return 'type=' + this.namespace + ' event=' + event;
  },

  _prepareData: function(data) {
    if (_.isPlainObject(data)) {
      data = _.map(data, function(value, key) {
        if (_.isString(value)) {
          value = JSON.stringify(value);
        } else {
          value = '"' + JSON.stringify(value) + '"';
        }

        return key + '=' + value;
      }).join(' ');
    }

    return data ? ' ' + data : '';
  }
};

function newrelicInDebugMode() {
  return process.env.NEW_RELIC_LICENSE_KEY
         && process.env.NEW_RELIC_CAPTURE_PARAMS_ENABLE
         && _.contains(['trace', 'debug'], process.env.NEW_RELIC_LOGGING_LEVEL);
}

module.exports = function(namespace) {
  logger = new Logger(namespace, require('debug')(namespace));
  if (newrelicInDebugMode()) logger.addTransactionLogger(require('newrelic'));
  return logger;
};

module.exports.Logger = Logger;
<commit_msg>fix module exports<commit_after>'use strict';

var _ = require('lodash');

var Logger = function(namespace, debugFn) {
  this.namespace = namespace;
  this.debugger = debugFn;
};

Logger.prototype = {
  addTransactionLogger: function(transactionLogger) {
    this.transactionLogger = transactionLogger;
  },

  log: function(event, data) {
    this.debugger(this._getPrefix(event) + this._prepareData(data));
  },

  success: function(event, data) {
    this.debugger(this._getPrefix(event) + ' result=success' + this._prepareData(data));
  },

  error: function(event, errorMessage, data) {
    this.debugger(this._getPrefix(event) +' result=error errorMessage="' + errorMessage + '"' + this._prepareData(data));
  },

  sanityError: function(event, errorMessage, data) {
    this.debugger(this._getPrefix(event) +' result=error triggeredBy=sanityCheck errorMessage="' + errorMessage + '"' + this._prepareData(data));
  },

  transactionProperty: function(name, value) {
    if (!this.transactionLogger) return;
    this.transactionLogger.addCustomParameter(name, value);
  },

  _getPrefix: function(event) {
    return 'type=' + this.namespace + ' event=' + event;
  },

  _prepareData: function(data) {
    if (_.isPlainObject(data)) {
      data = _.map(data, function(value, key) {
        if (_.isString(value)) {
          value = JSON.stringify(value);
        } else {
          value = '"' + JSON.stringify(value) + '"';
        }

        return key + '=' + value;
      }).join(' ');
    }

    return data ? ' ' + data : '';
  }
};

function newrelicInDebugMode() {
  return process.env.NEW_RELIC_LICENSE_KEY
         && process.env.NEW_RELIC_CAPTURE_PARAMS_ENABLE
         && _.contains(['trace', 'debug'], process.env.NEW_RELIC_LOGGING_LEVEL);
}

module.exports = function(namespace) {
  var logger = new Logger(namespace, require('debug')(namespace));
  if (newrelicInDebugMode()) logger.addTransactionLogger(require('newrelic'));
  return logger;
};

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