<commit_before>// Copyright 2018-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only

// For reference: https://github.com/airbnb/javascript

const rules = {
  'comma-dangle': [
    'error',
    {
      arrays: 'always-multiline',
      objects: 'always-multiline',
      imports: 'always-multiline',
      exports: 'always-multiline',
      functions: 'never',
    },
  ],

  // Overrides recommended by typescript-eslint
  //   https://github.com/typescript-eslint/typescript-eslint/releases/tag/v4.0.0
  '@typescript-eslint/no-redeclare': 'error',
  '@typescript-eslint/no-shadow': 'error',
  '@typescript-eslint/no-useless-constructor': ['error'],
  'no-shadow': 'off',
  'no-useless-constructor': 'off',

  // prevents us from accidentally checking in exclusive tests (`.only`):
  'mocha/no-exclusive-tests': 'error',

  // encourage consistent use of `async` / `await` instead of `then`
  'more/no-then': 'error',

  // it helps readability to put public API at top,
  'no-use-before-define': 'off',

  // useful for unused or internal fields
  'no-underscore-dangle': 'off',

  // useful for unused parameters
  '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],

  // though we have a logger, we still remap console to log to disk
  'no-console': 'error',

  // consistently place operators at end of line except ternaries
  'operator-linebreak': [
    'error',
    'after',
    { overrides: { '?': 'ignore', ':': 'ignore' } },
  ],

  quotes: [
    'error',
    'single',
    { avoidEscape: true, allowTemplateLiterals: false },
  ],

  'no-continue': 'off',

  // Prettier overrides:
  'arrow-parens': 'off',
  'function-paren-newline': 'off',
  'max-len': [
    'error',
    {
      // Prettier generally limits line length to 80 but sometimes goes over.
      // The `max-len` plugin doesn’t let us omit `code` so we set it to a
      // high value as a buffer to let Prettier control the line length:
      code: 999,
      // We still want to limit comments as before:
      comments: 90,
      ignoreUrls: true,
    },
  ],

  'react/jsx-props-no-spreading': 'off',

  // Updated to reflect future airbnb standard
  // Allows for declaring defaultProps inside a class
  'react/static-property-placement': ['error', 'static public field'],

  // JIRA: DESKTOP-657
  'react/sort-comp': 'off',

  // We don't have control over the media we're sharing, so can't require
  // captions.
  'jsx-a11y/media-has-caption': 'off',

  // We prefer named exports
  'import/prefer-default-export': 'off',

  // Prefer functional components with default params
  'react/require-default-props': 'off',

  'jsx-a11y/label-has-associated-control': ['error', { assert: 'either' }],

  // Upgrade from a warning
  '@typescript-eslint/explicit-module-boundary-types': 'error',

  'no-restricted-syntax': [
    'error',
    {
      selector: 'TSInterfaceDeclaration',
      message:
        'Prefer `type`. Interfaces are mutable and less powerful, so we prefer `type` for simplicity.',
    },
    // Defaults
    {
      selector: 'ForInStatement',
      message:
        'for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.',
    },
    {
      selector: 'ForOfStatement',
      message:
        'iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.',
    },
    {
      selector: 'LabeledStatement',
      message:
        'Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.',
    },
    {
      selector: 'WithStatement',
      message:
        '`with` is disallowed in strict mode because it makes code impossible to predict and optimize.',
    },
  ],
  curly: 'error',
};

module.exports = {
  root: true,
  settings: {
    react: {
      version: 'detect',
    },
    'import/core-modules': ['electron'],
  },

  extends: ['airbnb-base', 'prettier'],

  plugins: ['mocha', 'more'],

  overrides: [
    {
      files: ['ts/**/*.ts', 'ts/**/*.tsx', 'app/**/*.ts'],
      parser: '@typescript-eslint/parser',
      parserOptions: {
        project: 'tsconfig.json',
        ecmaFeatures: {
          jsx: true,
        },
        ecmaVersion: 2018,
        sourceType: 'module',
      },
      plugins: ['@typescript-eslint'],
      extends: [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:react/recommended',
        'airbnb-typescript-prettier',
      ],
      rules,
    },
    {
      files: ['sticker-creator/**/*.ts', 'sticker-creator/**/*.tsx'],
      parser: '@typescript-eslint/parser',
      parserOptions: {
        project: './sticker-creator/tsconfig.json',
        ecmaFeatures: {
          jsx: true,
        },
        ecmaVersion: 2018,
        sourceType: 'module',
      },
      plugins: ['@typescript-eslint'],
      extends: [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:react/recommended',
        'airbnb-typescript-prettier',
      ],
      rules,
    },
    {
      files: ['**/*.stories.tsx', 'ts/build/**', 'ts/test-*/**'],
      rules: {
        ...rules,
        'import/no-extraneous-dependencies': 'off',
        'react/no-array-index-key': 'off',
      },
    },
  ],

  rules,
};
<commit_msg>Disable consistent-return lint rule in TypeScript<commit_after>// Copyright 2018-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only

// For reference: https://github.com/airbnb/javascript

const rules = {
  'comma-dangle': [
    'error',
    {
      arrays: 'always-multiline',
      objects: 'always-multiline',
      imports: 'always-multiline',
      exports: 'always-multiline',
      functions: 'never',
    },
  ],

  // prevents us from accidentally checking in exclusive tests (`.only`):
  'mocha/no-exclusive-tests': 'error',

  // encourage consistent use of `async` / `await` instead of `then`
  'more/no-then': 'error',

  // it helps readability to put public API at top,
  'no-use-before-define': 'off',

  // useful for unused or internal fields
  'no-underscore-dangle': 'off',

  // though we have a logger, we still remap console to log to disk
  'no-console': 'error',

  // consistently place operators at end of line except ternaries
  'operator-linebreak': [
    'error',
    'after',
    { overrides: { '?': 'ignore', ':': 'ignore' } },
  ],

  quotes: [
    'error',
    'single',
    { avoidEscape: true, allowTemplateLiterals: false },
  ],

  'no-continue': 'off',

  // Prettier overrides:
  'arrow-parens': 'off',
  'function-paren-newline': 'off',
  'max-len': [
    'error',
    {
      // Prettier generally limits line length to 80 but sometimes goes over.
      // The `max-len` plugin doesn’t let us omit `code` so we set it to a
      // high value as a buffer to let Prettier control the line length:
      code: 999,
      // We still want to limit comments as before:
      comments: 90,
      ignoreUrls: true,
    },
  ],

  'react/jsx-props-no-spreading': 'off',

  // Updated to reflect future airbnb standard
  // Allows for declaring defaultProps inside a class
  'react/static-property-placement': ['error', 'static public field'],

  // JIRA: DESKTOP-657
  'react/sort-comp': 'off',

  // We don't have control over the media we're sharing, so can't require
  // captions.
  'jsx-a11y/media-has-caption': 'off',

  // We prefer named exports
  'import/prefer-default-export': 'off',

  // Prefer functional components with default params
  'react/require-default-props': 'off',

  'jsx-a11y/label-has-associated-control': ['error', { assert: 'either' }],

  'no-restricted-syntax': [
    'error',
    {
      selector: 'TSInterfaceDeclaration',
      message:
        'Prefer `type`. Interfaces are mutable and less powerful, so we prefer `type` for simplicity.',
    },
    // Defaults
    {
      selector: 'ForInStatement',
      message:
        'for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.',
    },
    {
      selector: 'ForOfStatement',
      message:
        'iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.',
    },
    {
      selector: 'LabeledStatement',
      message:
        'Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.',
    },
    {
      selector: 'WithStatement',
      message:
        '`with` is disallowed in strict mode because it makes code impossible to predict and optimize.',
    },
  ],
  curly: 'error',
};

const typescriptRules = {
  ...rules,

  // Overrides recommended by typescript-eslint
  //   https://github.com/typescript-eslint/typescript-eslint/releases/tag/v4.0.0
  '@typescript-eslint/no-redeclare': 'error',
  '@typescript-eslint/no-shadow': 'error',
  '@typescript-eslint/no-useless-constructor': ['error'],
  'no-shadow': 'off',
  'no-useless-constructor': 'off',

  // useful for unused parameters
  '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],

  // Upgrade from a warning
  '@typescript-eslint/explicit-module-boundary-types': 'error',

  // Already enforced by TypeScript
  'consistent-return': 'off',
};

module.exports = {
  root: true,
  settings: {
    react: {
      version: 'detect',
    },
    'import/core-modules': ['electron'],
  },

  extends: ['airbnb-base', 'prettier'],

  plugins: ['mocha', 'more'],

  overrides: [
    {
      files: ['ts/**/*.ts', 'ts/**/*.tsx', 'app/**/*.ts'],
      parser: '@typescript-eslint/parser',
      parserOptions: {
        project: 'tsconfig.json',
        ecmaFeatures: {
          jsx: true,
        },
        ecmaVersion: 2018,
        sourceType: 'module',
      },
      plugins: ['@typescript-eslint'],
      extends: [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:react/recommended',
        'airbnb-typescript-prettier',
      ],
      rules: typescriptRules,
    },
    {
      files: ['sticker-creator/**/*.ts', 'sticker-creator/**/*.tsx'],
      parser: '@typescript-eslint/parser',
      parserOptions: {
        project: './sticker-creator/tsconfig.json',
        ecmaFeatures: {
          jsx: true,
        },
        ecmaVersion: 2018,
        sourceType: 'module',
      },
      plugins: ['@typescript-eslint'],
      extends: [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:react/recommended',
        'airbnb-typescript-prettier',
      ],
      rules: typescriptRules,
    },
    {
      files: ['**/*.stories.tsx', 'ts/build/**', 'ts/test-*/**'],
      rules: {
        ...typescriptRules,
        'import/no-extraneous-dependencies': 'off',
        'react/no-array-index-key': 'off',
      },
    },
  ],

  rules,
};
<|endoftext|>


<commit_before>module.exports = {
  env: {
    es6: true,
    node: true,
    browser: true
  },
  extends: ['eslint:recommended', 'plugin:react/recommended'],
  parser: 'babel-eslint',
  parserOptions: {
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
      jsx: true
    },
    sourceType: 'module'
  },
  plugins: [
    'react'
  ],
  rules: {
    'linebreak-style': ['error', 'unix'],
    quotes: ['error', 'single'],
    semi: ['error', 'never'],
    'no-constant-condition': [0],
    indent: ['error', 2],
    'no-unused-vars': ['warn', { 'args': 'none' }],
    'keyword-spacing': ['error', { 'before': true, 'after': true }],
    'space-before-blocks': 'error',
    'key-spacing': ['error', { 'beforeColon': false }],
    'object-curly-spacing': ['error', 'always', {
      'arraysInObjects': false,
      'objectsInObjects': false
    }]
  }
}
<commit_msg>consoleの仕様は警告に変更<commit_after>module.exports = {
  env: {
    es6: true,
    node: true,
    browser: true
  },
  extends: ['eslint:recommended', 'plugin:react/recommended'],
  parser: 'babel-eslint',
  parserOptions: {
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
      jsx: true
    },
    sourceType: 'module'
  },
  plugins: [
    'react'
  ],
  rules: {
    'linebreak-style': ['error', 'unix'],
    quotes: ['error', 'single'],
    semi: ['error', 'never'],
    'no-constant-condition': [0],
    indent: ['error', 2],
    'no-unused-vars': ['warn', { 'args': 'none' }],
    'keyword-spacing': ['error', { 'before': true, 'after': true }],
    'space-before-blocks': 'error',
    'key-spacing': ['error', { 'beforeColon': false }],
    'object-curly-spacing': ['error', 'always', {
      'arraysInObjects': false,
      'objectsInObjects': false
    }],
    'no-console': ['warn']
  }
}
<|endoftext|>


<commit_before>const semver = require('semver');

// Converts semver range `~16.6.0` to strict version `16.6.0`
const reactVersion = semver.coerce(require('./package.json').dependencies.react).version;

const defaultRules = {
  camelcase: 0,
  'comma-dangle': [2, 'never'],
  'comma-spacing': [2, { before: false, after: true }],
  'consistent-return': 0,
  curly: [2, 'multi-line'],
  'default-case': 0,
  eqeqeq: [2, 'smart'],
  'func-names': 0,
  'guard-for-in': 2,
  indent: [2, 2, { SwitchCase: 1, VariableDeclarator: { var: 2, let: 2, const: 3 } }],
  'key-spacing': [2, { beforeColon: false, afterColon: true }],
  'keyword-spacing': [2, { before: true, after: true }],
  'max-len': 0,
  'new-cap': [2, { newIsCapExceptions: ['acl.memoryBackend', 'acl'] }],
  'no-bitwise': 0,
  'no-caller': 2,
  'no-console': 2,
  'no-else-return': 0,
  'no-empty-character-class': 2,
  'no-multi-spaces': 2,
  'no-param-reassign': 0,
  'no-process-exit': 2,
  'no-shadow': 0,
  'no-spaced-func': 2,
  'no-throw-literal': 2,
  'no-trailing-spaces': 2,
  'no-undef': 2,
  'no-unneeded-ternary': 2,
  'no-unreachable': 2,
  'no-underscore-dangle': 0,
  'no-unused-expressions': 0,
  'no-unused-vars': 2,
  'no-use-before-define': [1, 'nofunc'],
  'no-var': 0,
  'object-curly-spacing': [2, 'always'],
  'one-var': [0, 'never'],
  'one-var-declaration-per-line': [2, 'always'],
  'padded-blocks': 0,
  'semi': [2, 'always'],
  'space-before-function-paren': ['error', {
    'anonymous': 'always',
    'named': 'never',
    'asyncArrow': 'always'
  }],
  'space-in-parens': [2, 'never'],
  'spaced-comment': [2, 'always'],
  strict: 0,
  'quote-props': 0,
  quotes: [1, 'single'],
  'wrap-iife': [2, 'outside'],
  'vars-on-top': 0
};

const es2018rules = {
  'no-var': 2,
  'prefer-const': 2,
  'arrow-spacing': [2, { before: true, after: true }]
};

const angularRules = {
  'angular/component-limit': 0,
  'angular/controller-as-route': 1,
  'angular/controller-as-vm': 1,
  'angular/controller-as': 1,
  'angular/deferred': 1,
  'angular/di-unused': 2,
  'angular/directive-restrict': 0,
  'angular/empty-controller': 2,
  'angular/no-controller': 0,
  'angular/no-inline-template': 0,
  'angular/no-run-logic': 0,
  'angular/no-services': 0,
  'angular/on-watch': 0,
  'angular/prefer-component': 0,
  'angular/no-cookiestore': 2,
  'angular/no-directive-replace': 0,
  'angular/no-http-callback': 2,
  'angular/angularelement': 2,
  'angular/definedundefined': 2,
  'angular/document-service': 2,
  'angular/interval-service': 2,
  'angular/json-functions': 2,
  'angular/log': 1,
  'angular/timeout-service': 2,
  'angular/typecheck-array': 2,
  'angular/typecheck-date': 2,
  'angular/typecheck-function': 2,
  'angular/typecheck-number': 2,
  'angular/typecheck-object': 2,
  'angular/typecheck-string': 2,
  'angular/window-service': 2
};

module.exports = {
  rules: defaultRules,
  env: {
    node: true,
    browser: true,
    jasmine: true,
    mocha: true,
    jquery: true
  },
  globals: {
    PhusionPassenger: true,
    by: true,
    browser: true,
    element: true,
    AppConfig: true,
    angular: true,
    inject: true,
    Promise: true,
    __TESTING__: true,
    _: false,
  },
  /*
    eventually, after the migration, these overrides will become the main rules

    it would be nice to keep the rules for client and server separate,
    because eventually, they want to become independent codebases.
  */
  overrides: [{
    env: {
      browser: true,
      jquery: true
    },
    // Overrides for Angular files
    files: [
      'modules/*/client/*.module.js',
      'modules/*/client/config/*.js',
      'modules/*/client/controllers/*.js',
      'modules/*/client/directives/*.js',
      'modules/*/client/filters/*.js',
      'modules/*/client/services/*.js',
      'modules/core/client/app/config.js',
      'modules/core/client/app/init.js',
    ],
    plugins: ['angular'],
    rules: angularRules,
    settings: {
      angular: 1,
    },
    env: {
      browser: true,
      jquery: true,
    },
    globals: {
      angular: true,
      AppConfig: true,
      L: true,
      moment: true,
      PhusionPassenger: true,
      PruneCluster: true,
      PruneClusterForLeaflet: true,
    },
  },{
    env: {
      node: true,
      jasmine: true,
      mocha: true
    },
    // overrides for server code
    // ES 2018 - specify migrated files and folders here
    files: [
      'karma.conf.js',
      'bin/db-maintenance/ensure-indexes.js',
      'modules/admin/server/**',
      'modules/admin/tests/**',
      'modules/core/server/services/file-upload.service.js',
      'modules/references/server/**',
      'modules/references/tests/server/**',
      'modules/users/tests/server/user-change-locale.server.routes.tests.js',
      'testutils/data.server.testutils.js'
    ],
    parserOptions: {
      ecmaVersion: 2018
    },
    rules: es2018rules
  }, {
    env: {
      es6: true,
      browser: true,
    },
    plugins: ['react'],
    extends: 'plugin:react/recommended',
    settings: {
      react: {
        version: reactVersion
      }
    },
    // overrides for client/react code
    files: [
      'config/client/**',
      'config/env/**',
      'config/webpack/**',
      'modules/admin/client/**',
      'modules/core/client/app/config.js',
      'modules/**/client/components/**',
      'modules/**/client/api/**',
      'modules/**/client/utils/**',
      'modules/core/client/directives/tr-boards.client.directive.js',
      'modules/core/client/services/photos.service.js',
      'modules/references/tests/client/**'
    ],
    parser: 'babel-eslint',
    parserOptions: {
      ecmaFeatures: {
        jsx: true
      },
      ecmaVersion: 2018,
      sourceType: 'module'
    },
    rules: {
      ...es2018rules,
      'react/no-access-state-in-setstate': 2
    }
  },{
    // overrides for CLI scripts and application config
    files: [
      'bin/**',
      'config/**',
      'migrations/**',
      'scripts/**',
    ],
    rules: {
      'no-console': 0,
      'no-process-exit': 0,
    }
  },{
    // overrides for CLI scripts and application config
    files: [
      'bin/**',
      'scripts/**',
    ],
    parserOptions: {
      ecmaVersion: 2018
    }
  }]
};
<commit_msg>Sort out eslint config<commit_after>const semver = require('semver');

// Converts semver range `~16.6.0` to strict version `16.6.0`
const reactVersion = semver.coerce(require('./package.json').dependencies.react).version;

const defaultRules = {
  camelcase: 0,
  'comma-dangle': [2, 'never'],
  'comma-spacing': [2, { before: false, after: true }],
  'consistent-return': 0,
  curly: [2, 'multi-line'],
  'default-case': 0,
  eqeqeq: [2, 'smart'],
  'func-names': 0,
  'guard-for-in': 2,
  indent: [2, 2, { SwitchCase: 1, VariableDeclarator: { var: 2, let: 2, const: 3 } }],
  'key-spacing': [2, { beforeColon: false, afterColon: true }],
  'keyword-spacing': [2, { before: true, after: true }],
  'max-len': 0,
  'new-cap': [2, { newIsCapExceptions: ['acl.memoryBackend', 'acl'] }],
  'no-bitwise': 0,
  'no-caller': 2,
  'no-console': 2,
  'no-else-return': 0,
  'no-empty-character-class': 2,
  'no-multi-spaces': 2,
  'no-param-reassign': 0,
  'no-process-exit': 2,
  'no-shadow': 0,
  'no-spaced-func': 2,
  'no-throw-literal': 2,
  'no-trailing-spaces': 2,
  'no-undef': 2,
  'no-unneeded-ternary': 2,
  'no-unreachable': 2,
  'no-underscore-dangle': 0,
  'no-unused-expressions': 0,
  'no-unused-vars': 2,
  'no-use-before-define': [1, 'nofunc'],
  'no-var': 0,
  'object-curly-spacing': [2, 'always'],
  'one-var': [0, 'never'],
  'one-var-declaration-per-line': [2, 'always'],
  'padded-blocks': 0,
  'semi': [2, 'always'],
  'space-before-function-paren': ['error', {
    'anonymous': 'always',
    'named': 'never',
    'asyncArrow': 'always'
  }],
  'space-in-parens': [2, 'never'],
  'spaced-comment': [2, 'always'],
  strict: 0,
  'quote-props': 0,
  quotes: [1, 'single'],
  'wrap-iife': [2, 'outside'],
  'vars-on-top': 0
};

const es2018rules = {
  'no-var': 2,
  'prefer-const': 2,
  'arrow-spacing': [2, { before: true, after: true }]
};

module.exports = {
  rules: defaultRules,
  env: {
    browser: true,
    jasmine: true,
    jquery: true,
    mocha: true,
    node: true
  },
  globals: {
    __TESTING__: true,
    _: false,
    angular: true,
    AppConfig: true,
    browser: true,
    by: true,
    element: true,
    inject: true,
    Promise: true
  },
  /*
    eventually, after the migration, these overrides will become the main rules

    it would be nice to keep the rules for client and server separate,
    because eventually, they want to become independent codebases.
  */
  overrides: [{
    // Overrides for Angular files
    files: [
      'modules/*/client/*.module.js',
      'modules/*/client/config/*.js',
      'modules/*/client/controllers/*.js',
      'modules/*/client/directives/*.js',
      'modules/*/client/filters/*.js',
      'modules/*/client/services/*.js',
      'modules/core/client/app/config.js',
      'modules/core/client/app/init.js',
    ],
    plugins: ['angular'],
    rules: {
      'angular/component-limit': 0,
      'angular/controller-as-route': 1,
      'angular/controller-as-vm': 1,
      'angular/controller-as': 1,
      'angular/deferred': 1,
      'angular/di-unused': 2,
      'angular/directive-restrict': 0,
      'angular/empty-controller': 2,
      'angular/no-controller': 0,
      'angular/no-inline-template': 0,
      'angular/no-run-logic': 0,
      'angular/no-services': 0,
      'angular/on-watch': 0,
      'angular/prefer-component': 0,
      'angular/no-cookiestore': 2,
      'angular/no-directive-replace': 0,
      'angular/no-http-callback': 2,
      'angular/angularelement': 2,
      'angular/definedundefined': 2,
      'angular/document-service': 2,
      'angular/interval-service': 2,
      'angular/json-functions': 2,
      'angular/log': 1,
      'angular/timeout-service': 2,
      'angular/typecheck-array': 2,
      'angular/typecheck-date': 2,
      'angular/typecheck-function': 2,
      'angular/typecheck-number': 2,
      'angular/typecheck-object': 2,
      'angular/typecheck-string': 2,
      'angular/window-service': 2
    },
    settings: {
      angular: 1,
    },
    env: {
      browser: true,
      jquery: true,
    },
    globals: {
      angular: true,
      AppConfig: true,
      L: true,
      moment: true,
      PruneCluster: true,
      PruneClusterForLeaflet: true,
    },
  },{
    // overrides for server code
    // ES 2018 - specify migrated files and folders here
    files: [
      'karma.conf.js',
      'bin/db-maintenance/ensure-indexes.js',
      'modules/admin/server/**',
      'modules/admin/tests/**',
      'modules/core/server/services/file-upload.service.js',
      'modules/references/server/**',
      'modules/references/tests/server/**',
      'modules/users/tests/server/user-change-locale.server.routes.tests.js',
      'testutils/data.server.testutils.js'
    ],
    env: {
      node: true,
      jasmine: true,
      mocha: true
    },
    parserOptions: {
      ecmaVersion: 2018
    },
    rules: es2018rules,
    globals: {
      PhusionPassenger: true,
    }
  }, {
    // overrides for client/react code
    files: [
      'config/client/**',
      'config/env/**',
      'config/webpack/**',
      'modules/admin/client/**',
      'modules/core/client/app/config.js',
      'modules/**/client/components/**',
      'modules/**/client/api/**',
      'modules/**/client/utils/**',
      'modules/core/client/directives/tr-boards.client.directive.js',
      'modules/core/client/services/photos.service.js',
      'modules/references/tests/client/**'
    ],
    env: {
      es6: true,
      browser: true,
    },
    plugins: ['react'],
    extends: 'plugin:react/recommended',
    settings: {
      react: {
        version: reactVersion
      }
    },
    parser: 'babel-eslint',
    parserOptions: {
      ecmaFeatures: {
        jsx: true
      },
      ecmaVersion: 2018,
      sourceType: 'module'
    },
    rules: {
      ...es2018rules,
      'react/no-access-state-in-setstate': 2
    }
  },{
    // overrides for CLI scripts and application config
    files: [
      'bin/**',
      'config/**',
      'migrations/**',
      'scripts/**',
    ],
    env: {
      node: true,
    },
    rules: {
      'no-console': 0,
      'no-process-exit': 0,
    }
  },{
    // overrides for CLI scripts and application config
    files: [
      'bin/**',
      'scripts/**',
    ],
    env: {
      node: true,
    },
    parserOptions: {
      ecmaVersion: 2018
    }
  }]
};
<|endoftext|>


<commit_before>module.exports = {
  env: {
    es6: true,
    node: true,
    mocha: true
  },
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
    ecmaFeatures: {
      generators: false,
      objectLiteralDuplicateProperties: false
    }
  },

  rules: {
    'max-len': ['warn', 200],
    'no-plusplus': 'warn',
    'arrow-body-style': ['error', 'as-needed', {
      requireReturnForObjectLiteral: false,
    }],
    'arrow-parens': ['error', 'as-needed', {
      requireForBlockBody: true,
    }],
    'arrow-spacing': ['error', { before: true, after: true }],
    'constructor-super': 'error',
    'generator-star-spacing': ['error', { before: false, after: true }],
    'no-class-assign': 'error',
    'no-confusing-arrow': ['error', {
      allowParens: true,
    }],
    'no-const-assign': 'error',
    'no-dupe-class-members': 'error',
    'no-duplicate-imports': 'off',
    'no-new-symbol': 'error',
    'no-restricted-imports': ['off', {
      paths: [],
      patterns: []
    }],
    'no-this-before-super': 'error',
    'no-useless-computed-key': 'error',
    'no-useless-constructor': 'error',
    'no-useless-rename': ['error', {
      ignoreDestructuring: false,
      ignoreImport: false,
      ignoreExport: false,
    }],
    'no-var': 'error',
    'object-shorthand': ['error', 'always', {
      ignoreConstructors: false,
      avoidQuotes: true,
    }],
    'prefer-arrow-callback': ['error', {
      allowNamedFunctions: false,
      allowUnboundThis: true,
    }],
    'prefer-const': ['error', {
      destructuring: 'any',
      ignoreReadBeforeAssign: true,
    }],
    'prefer-destructuring': ['error', {
      VariableDeclarator: {
        array: false,
        object: true,
      },
      AssignmentExpression: {
        array: true,
        object: true,
      },
    }, {
      enforceForRenamedProperties: false,
    }],
    'prefer-numeric-literals': 'error',
    'prefer-reflect': 'off',
    'prefer-rest-params': 'error',
    'prefer-spread': 'error',
    'prefer-template': 'error',
    'require-yield': 'error',
    'rest-spread-spacing': ['error', 'never'],
    'sort-imports': ['off', {
      ignoreCase: false,
      ignoreMemberSort: false,
      memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'],
    }],
    'symbol-description': 'error',
    'template-curly-spacing': 'error',
    'yield-star-spacing': ['error', 'after']
  }
};<commit_msg>linting rules and airbnb-base<commit_after>module.exports = {
  env: {
    es6: true,
    node: true,
    mocha: true
  },
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
    ecmaFeatures: {
      generators: false,
      objectLiteralDuplicateProperties: false
    }
  },
  extends: ['airbnb-base'],
  plugins: [
    "no-only-tests"
  ],
  rules: {
    "max-len": ["warn", 200],
    "import/no-extraneous-dependencies": ["error", { "devDependencies": ["**/test/**/*.js"]}],
    "no-plusplus": "warn",
    "consistent-return": "warn",
    "no-template-curly-in-string": "warn",
    "comma-dangle": "warn",
    "import/no-unresolved": "warn",
    "no-only-tests/no-only-tests": 2
  }
};

<|endoftext|>


<commit_before>module.exports = {
    "extends": "eslint:recommended",
    "plugins": [
        "import"
    ]
};
<commit_msg>lint dirty hack<commit_after>module.exports = {
    "extends": "eslint:recommended",
    "plugins": [
        "import"
    ],
    "env": {
        "es6": true,
        "node": true,
        "browser": true
    },
    "rules": {
        "no-unused-vars": [1, { "vars": "all", "args": "none" }],
        "no-extra-semi": 1,
        "no-undef": 1,
        "no-console": 1,
        "no-unused-vars": 1
    }
};
<|endoftext|>


<commit_before>module.exports = {
  // http://eslint.org/docs/user-guide/configuring

  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaVersion": 2016,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true,
      "impliedStrict": true,
    }
  },

  "env": {
    "shared-node-browser": true,
  },

  "plugins": [
    "babel", // Adapts rules to better handle ES2016+ code
    "react", // React-specific linting rules
  ],

  "settings": {
  },

  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
  ],

  // http://eslint.org/docs/rules/
  "rules": {

    // Possible errors
    "comma-dangle": ["error", "only-multiline"],
    "eqeqeq": ["error", "smart"],

    // Best practices
    "no-alert": "error",
    "no-unused-vars": "warn",
    "no-console": "warn",

    // ES2015
    "no-var": "error",
    "arrow-parens": "error",
    "radix": ["error", "as-needed"],

    // Style
    "indent": ["error", 2],
    "semi": ["error", "always"],
    "curly": ["error", "multi-line"],
    "brace-style": ["error", "stroustrup"],

    // Overrides from airbnb
    "quotes": "off",
    "max-len": "off",
    "no-underscore-dangle": "off",
    "no-unneeded-ternary": "off",

    // FIXME: Add
    // "space-infix-ops"
    // "object-shorthand"

    // FIXME: These should be made errors:
    "no-param-reassign": "warn",

    // FIXME: Consider enforcing these:
    "object-curly-spacing": "off",
    "object-shorthand": "off",
  }
};
<commit_msg>eslint: es6 env<commit_after>module.exports = {
  // http://eslint.org/docs/user-guide/configuring

  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaVersion": 2016,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true,
      "impliedStrict": true,
    }
  },

  "env": {
    "shared-node-browser": true,
    "es6": true, // Necessary for ES global symbols like Set, Symbol
  },

  "plugins": [
    "babel", // Adapts rules to better handle ES2016+ code
    "react", // React-specific linting rules
  ],

  "settings": {
  },

  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
  ],

  // http://eslint.org/docs/rules/
  "rules": {

    // Possible errors
    "comma-dangle": ["error", "only-multiline"],
    "eqeqeq": ["error", "smart"],

    // Best practices
    "no-alert": "error",
    "no-unused-vars": "warn",
    "no-console": "warn",

    // ES2015
    "no-var": "error",
    "arrow-parens": "error",
    "radix": ["error", "as-needed"],

    // Style
    "indent": ["error", 2],
    "semi": ["error", "always"],
    "curly": ["error", "multi-line"],
    "brace-style": ["error", "stroustrup"],

    // Overrides from airbnb
    "quotes": "off",
    "max-len": "off",
    "no-underscore-dangle": "off",
    "no-unneeded-ternary": "off",

    // FIXME: Add
    // "space-infix-ops"
    // "object-shorthand"

    // FIXME: These should be made errors:
    "no-param-reassign": "warn",

    // FIXME: Consider enforcing these:
    "object-curly-spacing": "off",
    "object-shorthand": "off",
  }
};
<|endoftext|>


<commit_before>const esLintConfig = require('kolibri-tools/.eslintrc');
esLintConfig.globals = {
  "$": false,
  "_": false,
  "MathQuill": false,
  "HandlebarsIntl": false,
  "MathJax": false,
}
module.exports = esLintConfig;
<commit_msg>add Raven to eslint globals<commit_after>const esLintConfig = require('kolibri-tools/.eslintrc');
esLintConfig.globals = {
  "$": false,
  "_": false,
  "MathQuill": false,
  "HandlebarsIntl": false,
  "MathJax": false,
  "Raven": false,
}
module.exports = esLintConfig;
<|endoftext|>


<commit_before>module.exports = {
    "root": true,
    "parser": "babel-eslint",
    "parserOptions": {
        sourceType: 'module'
    },
    env: {
        browser: true
    },
    "extends": ["airbnb-base", "plugin:flowtype/recommended"],
    "plugins": [
        "import",
        "flowtype"
    ],
    rules: {
        // 缩进
        "indent": ["error", 4],
        // no-tabs
        "no-tabs": "off",
        // no-plusplus 一元操作符会自动添加分号，不同的空白会改变源代码的含义
        "no-plusplus": ["error", { "allowForLoopAfterthoughts": true }],
        // no-console
        "no-console": process.env.NODE_ENV === 'production' ? 2 : 0,
        // no-debugger, allow debugger during development
        "no-debugger": process.env.NODE_ENV === 'prroduction' ? 2 : 0,
        // import/prefer-default-export
        "import/prefer-default-export": "off",
        // import/no-extraneous-dependencies
        "import/no-extraneous-dependencies": ["error", { "devDependencies": true }],
        // import/no-unresolved
        "import/no-unresolved": [2, { commonjs: true, amd: true }],
    }
};<commit_msg>update esint config<commit_after>module.exports = {
    "root": true,
    "parser": "babel-eslint",
    "parserOptions": {
        sourceType: 'module'
    },
    env: {
        browser: true
    },
    "extends": ["airbnb-base", "plugin:flowtype/recommended"],
    "plugins": [
        "import",
        "flowtype"
    ],
    rules: {
        // 缩进
        "indent": ["error", 4],
        // no-tabs
        "no-tabs": "off",
        // no-plusplus 一元操作符会自动添加分号，不同的空白会改变源代码的含义
        "no-plusplus": ["error", { "allowForLoopAfterthoughts": true }],
        // no-console
        "no-console": process.env.NODE_ENV === 'production' ? 2 : 0,
        // no-debugger, allow debugger during development
        "no-debugger": process.env.NODE_ENV === 'prroduction' ? 2 : 0,
        // no-unused-vars
        "no-unused-vars": "warn",
        // import/prefer-default-export
        "import/prefer-default-export": "off",
        // import/no-extraneous-dependencies
        "import/no-extraneous-dependencies": ["error", { "devDependencies": true }],
        // import/no-unresolved
        "import/no-unresolved": [2, { commonjs: true, amd: true }],
    }
};
<|endoftext|>


<commit_before><commit_msg>add Foundation as global and readonly since it is included into FE bundle like jQuery.<commit_after><|endoftext|>


<commit_before>module.exports = {
    "env": {
        "browser": true,
        "es6": true
    },
    "globals": {
      'require': false,
      "process": false,
      "__dirname": false
    },
    "extends": "eslint:recommended",
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaFeatures": {
            "experimentalObjectRestSpread": true,
            "jsx": true
        },
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
        "indent": [
            "error",
            2
        ],
        "linebreak-style": [
            "error",
            "unix"
        ],
        "no-console": "warn",
        "quotes": [
            "error",
            "double"
        ],
        "semi": [
            "error",
            "never"
        ]
    }
};
<commit_msg>Avoids vars used in JSX being marked unused<commit_after>module.exports = {
    "env": {
        "browser": true,
        "es6": true
    },
    "globals": {
      'require': false,
      "module": false,
      "process": false,
      "__dirname": false
    },
    "extends": "eslint:recommended",
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaFeatures": {
            "experimentalObjectRestSpread": true,
            "jsx": true
        },
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
        "indent": [
            "error",
            2
        ],
        "linebreak-style": [
            "error",
            "unix"
        ],
        "no-console": "warn",
        "quotes": [
            "error",
            "double"
        ],
        "react/jsx-uses-vars": [2],
        "semi": [
            "error",
            "never"
        ]
    }
};
<|endoftext|>


<commit_before>module.exports = {
  "env": {
    "browser": true,
    "node": true,
    "es6": true
  },
  "extends": ["eslint:recommended", "plugin:react/recommended"],
  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true
    },
    "sourceType": "module"
  },
  "plugins": [
    "class-property",
    "react"
  ],
  "rules": {
    "comma-dangle": [
      "error",
      "never"
    ],
    "indent": [
      "error",
      2,
      { "SwitchCase": 1 }
    ],
    "linebreak-style": [
      "error",
      "unix"
    ],
    "quotes": [
      "error",
      "double"
    ],
    "semi": [
      "error",
      "always"
    ],
    "no-console": [
      0
    ],
    "no-var": [
      "error"
    ]
  }
};
<commit_msg>added new rules<commit_after>module.exports = {
  "env": {
    "browser": true,
    "node": true,
    "es6": true
  },
  "extends": ["eslint:recommended", "plugin:react/recommended"],
  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true
    },
    "sourceType": "module"
  },
  "plugins": [
    "class-property",
    "react"
  ],
  "rules": {
    "no-trailing-spaces": [
      "error"
    ],
    "no-multiple-empty-lines": [
      "error",
      { "max": 2, "maxEOF": 1 }
    ],
    "eol-last": [
      "error",
      "always"
    ],
    "comma-dangle": [
      "error",
      "never"
    ],
    "indent": [
      "error",
      2,
      { "SwitchCase": 1 }
    ],
    "linebreak-style": [
      "error",
      "unix"
    ],
    "quotes": [
      "error",
      "double"
    ],
    "semi": [
      "error",
      "always"
    ],
    "no-console": [
      0
    ],
    "no-var": [
      "error"
    ]
  }
};
<|endoftext|>


<commit_before>module.exports = {
  root: true,
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
  },
  plugins: ['ember', 'prettier'],
  extends: [
    'eslint:recommended',
    'plugin:ember/recommended',
    'plugin:prettier/recommended',
    'prettier',
  ],
  env: {
    browser: true,
    node: false,
  },
  rules: {},
  overrides: [
    // node files
    {
      files: [
        '.eslintrc.js',
        '.template-lintrc.js',
        'ember-cli-build.js',
        'index.js',
        'testem.js',
        'blueprints/*/index.js',
        'config/**/*.js',
        'tests/dummy/config/**/*.js',
      ],
      excludedFiles: [
        'addon/**',
        'addon-test-support/**',
        'app/**',
        'tests/dummy/app/**',
      ],
      parserOptions: {
        sourceType: 'script',
        ecmaVersion: 2015,
      },
      env: {
        browser: false,
        node: true,
      },
      plugins: ['node'],
      extends: 'plugin:node/recommended',
    },
    {
      // typescript files
      files: ['**/*.ts'],
      parser: '@typescript-eslint/parser',
      plugins: ['@typescript-eslint'],
      rules: {
        'no-unused-vars': 'off',
        '@typescript-eslint/no-unused-vars': 'error',
      },
    },
    {
      // mixins
      files: ['addon/mixins/*.[jt]s', 'tests/unit/mixins/*.js'],
      rules: {
        'ember/no-new-mixins': 'off',
      },
    },
  ],
};
<commit_msg>Remove redundant `prettier` from `.eslintrc.js` extends.<commit_after>module.exports = {
  root: true,
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
  },
  plugins: ['ember', 'prettier'],
  extends: [
    'eslint:recommended',
    'plugin:ember/recommended',
    'plugin:prettier/recommended',
  ],
  env: {
    browser: true,
    node: false,
  },
  rules: {},
  overrides: [
    // node files
    {
      files: [
        '.eslintrc.js',
        '.template-lintrc.js',
        'ember-cli-build.js',
        'index.js',
        'testem.js',
        'blueprints/*/index.js',
        'config/**/*.js',
        'tests/dummy/config/**/*.js',
      ],
      excludedFiles: [
        'addon/**',
        'addon-test-support/**',
        'app/**',
        'tests/dummy/app/**',
      ],
      parserOptions: {
        sourceType: 'script',
        ecmaVersion: 2015,
      },
      env: {
        browser: false,
        node: true,
      },
      plugins: ['node'],
      extends: 'plugin:node/recommended',
    },
    {
      // typescript files
      files: ['**/*.ts'],
      parser: '@typescript-eslint/parser',
      plugins: ['@typescript-eslint'],
      rules: {
        'no-unused-vars': 'off',
        '@typescript-eslint/no-unused-vars': 'error',
      },
    },
    {
      // mixins
      files: ['addon/mixins/*.[jt]s', 'tests/unit/mixins/*.js'],
      rules: {
        'ember/no-new-mixins': 'off',
      },
    },
  ],
};
<|endoftext|>


<commit_before>module.exports = {
  env: {
    node: true,
  },
  extends: [
    'airbnb-base',
    'plugin:@typescript-eslint/recommended',
    'prettier',
    'prettier/@typescript-eslint',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: './tsconfig.json',
  },
  plugins: ['import', 'promise', '@typescript-eslint'],
  rules: {
    '@typescript-eslint/camelcase': 'off', // disabled until ??
    '@typescript-eslint/no-var-requires': 'off', // disable until all files converted to typescript
    '@typescript-eslint/no-use-before-define': 'off', // disable until all files converted to typescript
    'require-await': 'error',
    'no-use-before-define': 0,
    'no-restricted-syntax': 0,
    'no-await-in-loop': 0,
    'prefer-destructuring': 'off',
    'prefer-template': 'off',
    'promise/always-return': 'error',
    'promise/no-return-wrap': 'error',
    'promise/param-names': 'error',
    'promise/catch-or-return': 'error',
    'promise/no-native': 'off',
    'promise/no-nesting': 'warn',
    'promise/no-promise-in-callback': 'warn',
    'promise/no-callback-in-promise': 'warn',
    'promise/avoid-new': 'warn',
  },
  settings: {
    'import/resolver': {
      node: {
        paths: ['lib'],
        extensions: ['.js', '.ts'],
      },
    },
  },
};
<commit_msg>chore(lint): speed up linting (#3683)<commit_after>module.exports = {
  env: {
    node: true,
  },
  extends: [
    'airbnb-base',
    'plugin:@typescript-eslint/recommended',
    'prettier',
    'prettier/@typescript-eslint',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    // project: './tsconfig.json',
  },
  plugins: ['import', 'promise', '@typescript-eslint'],
  rules: {
    '@typescript-eslint/camelcase': 'off', // disabled until ??
    '@typescript-eslint/no-var-requires': 'off', // disable until all files converted to typescript
    '@typescript-eslint/no-use-before-define': 'off', // disable until all files converted to typescript
    'require-await': 'error',
    'no-use-before-define': 0,
    'no-restricted-syntax': 0,
    'no-await-in-loop': 0,
    'prefer-destructuring': 'off',
    'prefer-template': 'off',
    'promise/always-return': 'error',
    'promise/no-return-wrap': 'error',
    'promise/param-names': 'error',
    'promise/catch-or-return': 'error',
    'promise/no-native': 'off',
    'promise/no-nesting': 'warn',
    'promise/no-promise-in-callback': 'warn',
    'promise/no-callback-in-promise': 'warn',
    'promise/avoid-new': 'warn',
  },
  settings: {
    'import/resolver': {
      node: {
        paths: ['lib'],
        extensions: ['.js', '.ts'],
      },
    },
  },
};
<|endoftext|>


<commit_before>const connect = serverUrl => {
  return new Promise((resolve, reject) => {
    var socket = new WebSocket(serverUrl);
    socket.onopen = e => {
      return resolve(socket);
    };
  });
};

const disconnect = socket => {
  socket.close();
};

module.exports = {
  connect: connect,
  disconnect: disconnect
}
<commit_msg>return the rejection onerror<commit_after>const connect = serverUrl => {
  return new Promise((resolve, reject) => {
    var socket = new WebSocket(serverUrl);
    socket.onopen = e => {
      console.log('Connected.');
      return resolve(socket);
    };
    socket.onerror = e => {
      return reject(e);
    }
  }); // don't need a catch clause here because of the onerror above
};

module.exports = {
  connect: connect
}
<|endoftext|>


<commit_before>// these should not end in slashes !
var engineURL = 'http://localhost:8000';
var bbURL = 'http://my.rochester.edu';

// temporary storage for what we've already got
var contentURL = null;
var coursesURL = null;
var authenticated = false;
var courses = new Array(0);
var newCourses = new Array(0);
var loginForm = null;

// $(document).ready(init);

function init() {
	getContentURL(function(data) {
		response = JSON.parse(data);
		contentURL = response["contentURL"];
	});
	isAuthenticated(start);
	// refresh in 30 seconds
	setTimeout(init, 30*1000);
	// update courses 10 seconds from now, after they're probably gotten (2 minutes is safer, 4 is safest, but I don't want
	// to put it off too long)
	setTimeout(updateCourses, 10*1000);
}

function updateCourses() {
	console.log('Starting to update courses.');
	// go through newCourses
	for (newIndex in newCourses) {
		oldIndex = findSubMember(courses, 'shortname', newCourses[newIndex]['shortname']);
		if (oldIndex >= 0) {
			console.log("Updating course " + newCourses[newIndex]['shortname']);
			// exists, update it
			courses[oldIndex]['name'] = newCourses[newIndex]['name'];

			// run through sections
			newSections = newCourses[newIndex]['sections'];

			for (newSectionIndex in newSections) {
				oldSectionIndex = findSubMember(courses[oldIndex]['sections'], 'name', newSections[newSectionIndex]['name']);
				if (oldSectionIndex >= 0) {
					console.log("  Updating section " + newSections[newSectionIndex]['name']);
					courses[oldIndex]['sections'][oldSectionIndex]['url'] = newSections[newSectionIndex]['url'];

					// run through subsections
					newSubsections = newSections[newSectionIndex]['subsections'];

					for (newSubsectionIndex in newSubsections) {
						oldSubsectionIndex = findSubMember(courses[oldIndex]['sections'][oldSectionIndex]['subsections'], 'details', newSubsections[newSubsectionIndex]['details']);

						if (oldSubsectionIndex >= 0) {
							console.log("    Updating subsection " + newSubsections[newSubsectionIndex]['name']);
							courses[oldIndex]['sections'][oldSectionIndex]['subsections'][oldSubsectionIndex]['author'] = newSubsections[newSubsectionIndex]['author'];
							courses[oldIndex]['sections'][oldSectionIndex]['subsections'][oldSubsectionIndex]['date'] = newSubsections[newSubsectionIndex]['date'];
							courses[oldIndex]['sections'][oldSectionIndex]['subsections'][oldSubsectionIndex]['name'] = newSubsections[newSubsectionIndex]['name'];
						}
					}
				} else {
					// section doesn't exist, grab it, then splice to insert it
					courses[oldIndex]['sections'].splice(newIndex, 0, newSections[newSectionIndex]);
				}
			}
		} else {
			// course doesn't exist, grab it, then use splice to insert it
			courses.splice(newIndex, 0, newCourses[newIndex]);
		}
	}
	console.log("Done updating courses.");
}
function findSubMember(arr, member, value) {
	for (i in arr) {
		if (arr[i][member] == value) {
			return i;
		}
	}
	return -1;
}

/**
 * Whole bunch of async
 **/

function start(data) {
	response = JSON.parse(data);
	authenticated = response["authenticated"];
	loginForm = response["loginForm"];
	getCourses();
}

/*

function getContentURL(success) {
	$.get(bbURL + '/', function(data) {
		$.post(engineURL + '/getContentURL/', {'html': data}, success);
	});
}

function getNavURL(success) {
	$.get(bbURL + '/', function(data) {
		$.post(engineURL + '/getNavURL/', {'html': data}, success);
	});
}

function getCoursesURL(success) {
	getNavURL(function(data) {
		response = JSON.parse(data)
		$.get(bbURL + response['navURL'], function(data) {
			$.post(engineURL + '/getCoursesURL/', {'html': data}, function(data) {
				response = JSON.parse(data)
				console.log(response['coursesURL'])
				$.get(bbURL + response['coursesURL'], function(data) {
					$.post(engineURL + '/getContentURL/', {'html': data}, success)
				});
			});
		});
	});
}

function isAuthenticated(success) {
    getContentURL(function(data) {
		response = JSON.parse(data);
		$.get(bbURL + response['contentURL'], function(data) {
			$.post(engineURL + '/isAuthenticated/', {'html': data}, success);
		});
	});
}

function getCourses() {
	if (authenticated) {
		$.get(bbURL + contentURL, function(data) {
			$.post(engineURL + '/getCourses/', {'html': data}, function(data) {
				response = JSON.parse(data);
				newCourses = response['courses'];
				if (newCourses.length > 0) {
					for (i in newCourses) {
						course = newCourses[i];
						getCourseSections(course);
					}
				}
			});
		});
	} else {
		console.log('User not authenticated.');
	}
}

function getCourseSections(course) {
	$.get(bbURL + course['url'], function(data) {
		$.post(engineURL + '/getCourseSections/', {'html': data, 'url': course['url']}, function(data) {
			response = JSON.parse(data);
			course['sections'] = response['sections'];
			for (i in course['sections']) {
				section = course['sections'][i];
				getCourseSubsections(section);
			}
		});
	});
}

function getCourseSubsections(section) {
	$.get(bbURL + section['url'], function(data) {
		$.post(engineURL + '/getCourseSubsections/', {'html': data}, function(data) {
			response = JSON.parse(data);
			section['subsections'] = response['subsections'];
		});
	});
}

*/

/**
 * Quick Functions for getting data
 **/

// get recent announcements
function getRecentAnnouncements(limit) {
	if (limit == null) {
		limit = 10;
	}

	announcements = []
	for (course in courses) {
		// announcements are always the first section, and they are guaranteed to exist by parsley
		theseAnnce = newCourses[course]['sections'][0]['subsections']
		announcements = announcements.concat(theseAnnce)
	}
	// ======= REMOVE BAD ELEMENTS FROM HERE ========
	for (i in announcements) {
		if (announcements[i]['author'] == null) {
			announcements.splice(i, 1);
		}
	}

	announcements.sort(function(a, b) {
		console.log('===')
		console.log(a)
		console.log(b)
		// b - a so that they are sorted with the most recent (highest) first
		if (b == null) {
			return a;
		}
		return announceSorted(b) - announceSorted(a);
	});

	// cut off everything after limit
	announcements.splice(limit)

	return announcements
}
function announceSorted(item) {
	ms = 0;
	console.log(item)
	if (item['date'] == null) {
		return 0;
	}
	if (item['date'].length > 0) {
		ms = Date.parse(item['date']);
	}
	return ms;
}<commit_msg>Removed obsolete background.js.<commit_after><|endoftext|>


<commit_before>/**
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

exports.plugins = [
  // Markdown linting
  // https://github.com/remarkjs/remark-lint#rules
  require('remark-lint'),
  require('remark-frontmatter', ['yaml']),

  // 3rd Party
  // prettier-ignore
  [require('remark-lint-prohibited-strings'), [2, [
    { no: 'master' },
    { no: 'slave' },
    { no: 'tribal' },
    { no: 'tribalism' },
    { no: 'nitty(-|\s)?gritty' },
    { no: 'voodoo' },
    { no: 'off(-|\s)?the(-|\s)?reservation' },
    { no: 'natives' },
    { no: 'first(-|\s)?class' },
    { no: 'supremacy' },
    { no: 'dummy' },
    { no: 'sane' },
    { no: 'crazy' },
    { no: 'insane' },
    { no: 'cripple' },
    { no: 'sanity(-|\s)check' },
    { no: 'grandfathered' },
    { no: 's?he' },
    { no: '^h(is|er(s?))$' },
    { no: 'man-in-the-middle' },
    { no: 'mitm' },
    { no: 'redline' },
    { no: '(black|white|gray|grey)(-|\s)?(hat|list|glove|label)' },
    { no: 'rtfm' },
    { no: 'wtf' }],
    { no: 'post mortem' }
  ]],

  // Custom
  [require('./lib/linting/content-models.js'), [2]],
  [require('./lib/linting/md-name-lint'), [2]],
];
<commit_msg>💎(site) Update prohibited strings (#314)<commit_after>/**
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

exports.plugins = [
  // Markdown linting
  // https://github.com/remarkjs/remark-lint#rules
  require('remark-lint'),
  require('remark-frontmatter', ['yaml']),

  // 3rd Party
  // prettier-ignore
  [require('remark-lint-prohibited-strings'), [2, [
    { no: 'master' },
    { no: 'slave' },
    { no: 'tribal' },
    { no: 'tribal(-|\s|ism)?(division|knowledge|wisdom)'},
    { no: 'nitty(-|\s)?gritty' },
    { no: 'voodoo' },
    { no: 'off(-|\s)?the(-|\s)?reservation' },
    { no: '(-|\s)natives'},
    { no: 'first(-|\s)?class' },
    { no: 'quatum(-|\s)?supremacy'},
    { no: 'supremacy' },
    { no: 'dummy' },
    { no: 'sane' },
    { no: 'crazy' },
    { no: 'insane' },
    { no: 'cripple' },
    { no: 'sanity(-|\s)check' },
    { no: 'grandfathered' },
    { no: '(grandfather)(-|\s)?(clause|ed|ing)' },
    { no: '(mom|girlfriend|grandma|grandmother)(-|\s)?(test)' },
    { no: '(build)(-|\s)?(cop|sheriff)' },
    { no: 'open(-|\s)?the(-|\s)?kimono' },
    { no: 's?he' },
    { no: 'final(-|\s)?solution' },
    { no: '(WTF|wtf)(-|\s)?(error)?' },
    { no: 'ninja' },
    { no: 'guru' },
    { no: '^h(is|er(s?))$' },
    { no: 'man-in-the-middle' },
    { no: 'mitm' },
    { no: 'redline' },
    { no: '(black|white|gray|grey|dark|light)(-|\s)?(hat|list|glove|label)' },
    { no: 'rtfm' },
    { no: 'post(-|\s)?mortem' },
    { no: 'retarded' },
    { no: 'demented' },
    { no: 'developmentally(-|\s)?disabled' },
    { no: 'idiot' },
    { no: 'mongoloid' },
    { no: 'permanent(-|\s)?child' },
    { no: 'short(-|\s)?bus' },
    { no: 'slow(-|\s)?learner' },
    { no: 'daft' },
    { no: 'imbecil' },
    { no: 'stupid' },
    { no: 'moronic' },
    { no: '(-|\w)tard(ed)?' }
  ]],

  // Custom
  [require('./lib/linting/content-models.js'), [2]],
  [require('./lib/linting/md-name-lint'), [2]],
],
];
<|endoftext|>


<commit_before>import macro from 'vtk.js/Sources/macros';
import vtkImageData from 'vtk.js/Sources/Common/DataModel/ImageData';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';

const { vtkErrorMacro } = macro;

// see itk.js PixelTypes.js
const ITKJSPixelTypes = {
  Unknown: 0,
  Scalar: 1,
  RGB: 2,
  RGBA: 3,
  Offset: 4,
  Vector: 5,
  Point: 6,
  CovariantVector: 7,
  SymmetricSecondRankTensor: 8,
  DiffusionTensor3D: 9,
  Complex: 10,
  FixedArray: 11,
  Array: 12,
  Matrix: 13,
  VariableLengthVector: 14,
  VariableSizeMatrix: 15,
};

// itk-wasm pixel types from https://github.com/InsightSoftwareConsortium/itk-wasm/blob/master/src/core/PixelTypes.ts
const ITKWASMPixelTypes = {
  Unknown: 'Unknown',
  Scalar: 'Scalar',
  RGB: 'RGB',
  RGBA: 'RGBA',
  Offset: 'Offset',
  Vector: 'Vector',
  Point: 'Point',
  CovariantVector: 'CovariantVector',
  SymmetricSecondRankTensor: 'SymmetricSecondRankTensor',
  DiffusionTensor3D: 'DiffusionTensor3D',
  Complex: 'Complex',
  FixedArray: 'FixedArray',
  Array: 'Array',
  Matrix: 'Matrix',
  VariableLengthVector: 'VariableLengthVector',
  VariableSizeMatrix: 'VariableSizeMatrix',
};

/**
 * Converts an itk.js image to a vtk.js image.
 *
 * Requires an itk.js image as input.
 */
function convertItkToVtkImage(itkImage, options = {}) {
  const vtkImage = {
    origin: [0, 0, 0],
    spacing: [1, 1, 1],
  };

  const dimensions = [1, 1, 1];
  const direction = [1, 0, 0, 0, 1, 0, 0, 0, 1];

  // Check whether itkImage is an itk.js Image or an itk-wasm Image?
  const isITKWasm = itkImage.direction.data === undefined;
  const ITKPixelTypes = isITKWasm ? ITKWASMPixelTypes : ITKJSPixelTypes;

  for (let idx = 0; idx < itkImage.imageType.dimension; ++idx) {
    vtkImage.origin[idx] = itkImage.origin[idx];
    vtkImage.spacing[idx] = itkImage.spacing[idx];
    dimensions[idx] = itkImage.size[idx];
    for (let col = 0; col < itkImage.imageType.dimension; ++col) {
      // ITK (and VTKMath) use a row-major index axis, but the direction
      // matrix on the vtkImageData is a webGL matrix, which uses a
      // column-major data layout. Transpose the direction matrix from
      // itkImage when instantiating that vtkImageData direction matrix.
      if (isITKWasm) {
        direction[col + idx * 3] =
          itkImage.direction[idx + col * itkImage.imageType.dimension];
      } else {
        direction[col + idx * 3] =
          itkImage.direction.data[idx + col * itkImage.imageType.dimension];
      }
    }
  }

  // Create VTK Image Data
  const imageData = vtkImageData.newInstance(vtkImage);

  // Create VTK point data -- the data associated with the pixels / voxels
  const pointData = vtkDataArray.newInstance({
    name: options.scalarArrayName || 'Scalars',
    values: itkImage.data,
    numberOfComponents: itkImage.imageType.components,
  });

  imageData.setDirection(direction);
  imageData.setDimensions(...dimensions);
  // Always associate multi-component pixel types with vtk.js point data
  // scalars to facilitate multi-component volume rendering
  imageData.getPointData().setScalars(pointData);

  // Associate the point data that are 3D vectors / tensors
  // Refer to itk-js/src/PixelTypes.js for numerical values
  switch (
    isITKWasm
      ? ITKPixelTypes[itkImage.imageType.pixelType]
      : itkImage.imageType.pixelType
  ) {
    case ITKPixelTypes.Scalar:
      break;
    case ITKPixelTypes.RGB:
      break;
    case ITKPixelTypes.RGBA:
      break;
    case ITKPixelTypes.Offset:
      break;
    case ITKPixelTypes.Vector:
      if (
        itkImage.imageType.dimension === 3 &&
        itkImage.imageType.components === 3
      ) {
        imageData.getPointData().setVectors(pointData);
      }
      break;
    case ITKPixelTypes.Point:
      break;
    case ITKPixelTypes.CovariantVector:
      if (
        itkImage.imageType.dimension === 3 &&
        itkImage.imageType.components === 3
      ) {
        imageData.getPointData().setVectors(pointData);
      }
      break;
    case ITKPixelTypes.SymmetricSecondRankTensor:
      if (
        itkImage.imageType.dimension === 3 &&
        itkImage.imageType.components === 6
      ) {
        imageData.getPointData().setTensors(pointData);
      }
      break;
    case ITKPixelTypes.DiffusionTensor3D:
      if (
        itkImage.imageType.dimension === 3 &&
        itkImage.imageType.components === 6
      ) {
        imageData.getPointData().setTensors(pointData);
      }
      break;
    case ITKPixelTypes.Complex:
      break;
    case ITKPixelTypes.FixedArray:
      break;
    case ITKPixelTypes.Array:
      break;
    case ITKPixelTypes.Matrix:
      break;
    case ITKPixelTypes.VariableLengthVector:
      break;
    case ITKPixelTypes.VariableSizeMatrix:
      break;
    default:
      vtkErrorMacro(
        `Cannot handle unexpected ITK.js pixel type ${itkImage.imageType.pixelType}`
      );
      return null;
  }

  return imageData;
}

const vtkArrayTypeToItkComponentType = new Map([
  ['Uint8Array', 'uint8_t'],
  ['Int8Array', 'int8_t'],
  ['Uint16Array', 'uint16_t'],
  ['Int16Array', 'int16_t'],
  ['Uint32Array', 'uint32_t'],
  ['Int32Array', 'int32_t'],
  ['Float32Array', 'float'],
  ['Float64Array', 'double'],
]);

/**
 * Converts a vtk.js image to an itk.js image.
 *
 * Requires a vtk.js image as input.
 */
function convertVtkToItkImage(vtkImage, copyData = false) {
  const itkImage = {
    imageType: {
      dimension: 3,
      pixelType: ITKJSPixelTypes.Scalar,
      componentType: '',
      components: 1,
    },
    name: 'name',
    origin: vtkImage.getOrigin(),
    spacing: vtkImage.getSpacing(),
    direction: {
      data: [1, 0, 0, 0, 1, 0, 0, 0, 1],
    },
    size: vtkImage.getDimensions(),
  };

  const direction = vtkImage.getDirection();

  const dimension = itkImage.size.length;
  itkImage.imageType.dimension = dimension;
  itkImage.direction.rows = dimension;
  itkImage.direction.columns = dimension;

  // Transpose the direction matrix from column-major to row-major
  for (let idx = 0; idx < dimension; ++idx) {
    for (let idy = 0; idy < dimension; ++idy) {
      itkImage.direction.data[idx + idy * dimension] =
        direction[idy + idx * dimension];
    }
  }

  const pointData = vtkImage.getPointData();

  let vtkArray;
  if (pointData.getTensors() !== null) {
    itkImage.imageType.pixelType = ITKJSPixelTypes.DiffusionTensor3D;
    vtkArray = pointData.getTensors();
  } else if (pointData.getVectors() != null) {
    itkImage.imageType.pixelType = ITKJSPixelTypes.Vector;
    vtkArray = pointData.getVectors();
  } else {
    vtkArray = pointData.getScalars();
  }

  itkImage.imageType.componentType = vtkArrayTypeToItkComponentType.get(
    vtkArray.getDataType()
  );

  if (copyData) {
    // Copy the data array
    itkImage.data = vtkArray.getData().slice(0);
  } else {
    itkImage.data = vtkArray.getData();
  }

  return itkImage;
}

export default {
  convertItkToVtkImage,
  convertVtkToItkImage,
};
<commit_msg>fix(convertVtkToItkImage): Update for itk-wasm<commit_after>import macro from 'vtk.js/Sources/macros';
import vtkImageData from 'vtk.js/Sources/Common/DataModel/ImageData';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';

const { vtkErrorMacro } = macro;

// see itk.js PixelTypes.js
const ITKJSPixelTypes = {
  Unknown: 0,
  Scalar: 1,
  RGB: 2,
  RGBA: 3,
  Offset: 4,
  Vector: 5,
  Point: 6,
  CovariantVector: 7,
  SymmetricSecondRankTensor: 8,
  DiffusionTensor3D: 9,
  Complex: 10,
  FixedArray: 11,
  Array: 12,
  Matrix: 13,
  VariableLengthVector: 14,
  VariableSizeMatrix: 15,
};

// itk-wasm pixel types from https://github.com/InsightSoftwareConsortium/itk-wasm/blob/master/src/core/PixelTypes.ts
const ITKWASMPixelTypes = {
  Unknown: 'Unknown',
  Scalar: 'Scalar',
  RGB: 'RGB',
  RGBA: 'RGBA',
  Offset: 'Offset',
  Vector: 'Vector',
  Point: 'Point',
  CovariantVector: 'CovariantVector',
  SymmetricSecondRankTensor: 'SymmetricSecondRankTensor',
  DiffusionTensor3D: 'DiffusionTensor3D',
  Complex: 'Complex',
  FixedArray: 'FixedArray',
  Array: 'Array',
  Matrix: 'Matrix',
  VariableLengthVector: 'VariableLengthVector',
  VariableSizeMatrix: 'VariableSizeMatrix',
};

const vtkArrayTypeToItkComponentType = new Map([
  ['Uint8Array', 'uint8'],
  ['Int8Array', 'int8'],
  ['Uint16Array', 'uint16'],
  ['Int16Array', 'int16'],
  ['Uint32Array', 'uint32'],
  ['Int32Array', 'int32'],
  ['Float32Array', 'float32'],
  ['Float64Array', 'float64'],
]);

/**
 * Converts an itk-wasm Image to a vtk.js vtkImageData.
 *
 * Requires an itk-wasm Image as input.
 */
function convertItkToVtkImage(itkImage, options = {}) {
  const vtkImage = {
    origin: [0, 0, 0],
    spacing: [1, 1, 1],
  };

  const dimensions = [1, 1, 1];
  const direction = [1, 0, 0, 0, 1, 0, 0, 0, 1];

  // Check whether itkImage is an itk.js Image or an itk-wasm Image?
  const isITKWasm = itkImage.direction.data === undefined;
  const ITKPixelTypes = isITKWasm ? ITKWASMPixelTypes : ITKJSPixelTypes;

  for (let idx = 0; idx < itkImage.imageType.dimension; ++idx) {
    vtkImage.origin[idx] = itkImage.origin[idx];
    vtkImage.spacing[idx] = itkImage.spacing[idx];
    dimensions[idx] = itkImage.size[idx];
    for (let col = 0; col < itkImage.imageType.dimension; ++col) {
      // ITK (and VTKMath) use a row-major index axis, but the direction
      // matrix on the vtkImageData is a webGL matrix, which uses a
      // column-major data layout. Transpose the direction matrix from
      // itkImage when instantiating that vtkImageData direction matrix.
      if (isITKWasm) {
        direction[col + idx * 3] =
          itkImage.direction[idx + col * itkImage.imageType.dimension];
      } else {
        direction[col + idx * 3] =
          itkImage.direction.data[idx + col * itkImage.imageType.dimension];
      }
    }
  }

  // Create VTK Image Data
  const imageData = vtkImageData.newInstance(vtkImage);

  // Create VTK point data -- the data associated with the pixels / voxels
  const pointData = vtkDataArray.newInstance({
    name: options.scalarArrayName || 'Scalars',
    values: itkImage.data,
    numberOfComponents: itkImage.imageType.components,
  });

  imageData.setDirection(direction);
  imageData.setDimensions(...dimensions);
  // Always associate multi-component pixel types with vtk.js point data
  // scalars to facilitate multi-component volume rendering
  imageData.getPointData().setScalars(pointData);

  // Associate the point data that are 3D vectors / tensors
  // Refer to itk-js/src/PixelTypes.js for numerical values
  switch (
    isITKWasm
      ? ITKPixelTypes[itkImage.imageType.pixelType]
      : itkImage.imageType.pixelType
  ) {
    case ITKPixelTypes.Scalar:
      break;
    case ITKPixelTypes.RGB:
      break;
    case ITKPixelTypes.RGBA:
      break;
    case ITKPixelTypes.Offset:
      break;
    case ITKPixelTypes.Vector:
      if (
        itkImage.imageType.dimension === 3 &&
        itkImage.imageType.components === 3
      ) {
        imageData.getPointData().setVectors(pointData);
      }
      break;
    case ITKPixelTypes.Point:
      break;
    case ITKPixelTypes.CovariantVector:
      if (
        itkImage.imageType.dimension === 3 &&
        itkImage.imageType.components === 3
      ) {
        imageData.getPointData().setVectors(pointData);
      }
      break;
    case ITKPixelTypes.SymmetricSecondRankTensor:
      if (
        itkImage.imageType.dimension === 3 &&
        itkImage.imageType.components === 6
      ) {
        imageData.getPointData().setTensors(pointData);
      }
      break;
    case ITKPixelTypes.DiffusionTensor3D:
      if (
        itkImage.imageType.dimension === 3 &&
        itkImage.imageType.components === 6
      ) {
        imageData.getPointData().setTensors(pointData);
      }
      break;
    case ITKPixelTypes.Complex:
      break;
    case ITKPixelTypes.FixedArray:
      break;
    case ITKPixelTypes.Array:
      break;
    case ITKPixelTypes.Matrix:
      break;
    case ITKPixelTypes.VariableLengthVector:
      break;
    case ITKPixelTypes.VariableSizeMatrix:
      break;
    default:
      vtkErrorMacro(
        `Cannot handle unexpected ITK.js pixel type ${itkImage.imageType.pixelType}`
      );
      return null;
  }

  return imageData;
}

/**
 * Converts a vtk.js vtkImageData to an itk-wasm Image.
 *
 * Requires a vtk.js vtkImageData as input.
 *
 */
function convertVtkToItkImage(vtkImage, copyData = false) {
  const dimension = 3;
  const itkImage = {
    imageType: {
      dimension,
      pixelType: ITKWASMPixelTypes.Scalar,
      componentType: '',
      components: 1,
    },
    name: 'vtkImageData',
    origin: vtkImage.getOrigin(),
    spacing: vtkImage.getSpacing(),
    direction: new Float64Array(9),
    size: vtkImage.getDimensions(),
  };

  const direction = vtkImage.getDirection();

  // Transpose the direction matrix from column-major to row-major
  for (let idx = 0; idx < dimension; ++idx) {
    for (let idy = 0; idy < dimension; ++idy) {
      itkImage.direction[idx + idy * dimension] =
        direction[idy + idx * dimension];
    }
  }

  const pointData = vtkImage.getPointData();

  let vtkArray;
  if (pointData.getTensors() !== null) {
    itkImage.imageType.pixelType = ITKWASMPixelTypes.DiffusionTensor3D;
    vtkArray = pointData.getTensors();
  } else if (pointData.getVectors() != null) {
    itkImage.imageType.pixelType = ITKWASMPixelTypes.Vector;
    vtkArray = pointData.getVectors();
  } else {
    vtkArray = pointData.getScalars();
  }

  itkImage.imageType.componentType = vtkArrayTypeToItkComponentType.get(
    vtkArray.getDataType()
  );

  if (copyData) {
    // Copy the data array
    itkImage.data = vtkArray.getData().slice(0);
  } else {
    itkImage.data = vtkArray.getData();
  }

  return itkImage;
}

export default {
  convertItkToVtkImage,
  convertVtkToItkImage,
};
<|endoftext|>


<commit_before>import * as macro from '../../../macro';
import vtkPolyData from '../../../Common/DataModel/PolyData';

// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
// Static API
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
// vtkWarpScalar methods
// ----------------------------------------------------------------------------

function warpScalar(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkWarpScalar');

  publicAPI.requestData = (inData, outData) => { // implement requestData
    if (!outData[0] || inData[0].getMTime() > outData[0].getMTime()) {
      const pd = vtkPolyData.newInstance();
      pd.setPolys(inData[0].getPolys());
      pd.setPoints(inData[0].getPoints());
      outData[0] = pd;
    }

  // vtkSmartPointer<vtkPointSet> input = vtkPointSet::GetData(inputVector[0]);
  // vtkPointSet *output = vtkPointSet::GetData(outputVector);

  // if (!input)
  //   {
  //   // Try converting image data.
  //   vtkImageData *inImage = vtkImageData::GetData(inputVector[0]);
  //   if (inImage)
  //     {
  //     vtkNew<vtkImageDataToPointSet> image2points;
  //     image2points->SetInputData(inImage);
  //     image2points->Update();
  //     input = image2points->GetOutput();
  //     }
  //   }

  // if (!input)
  //   {
  //   // Try converting rectilinear grid.
  //   vtkRectilinearGrid *inRect = vtkRectilinearGrid::GetData(inputVector[0]);
  //   if (inRect)
  //     {
  //     vtkNew<vtkRectilinearGridToPointSet> rect2points;
  //     rect2points->SetInputData(inRect);
  //     rect2points->Update();
  //     input = rect2points->GetOutput();
  //     }
  //   }

  // if (!input)
  //   {
  //   vtkErrorMacro(<< "Invalid or missing input");
  //   return 0;
  //   }

  // vtkPoints *inPts;
  // vtkDataArray *inNormals;
  // vtkDataArray *inScalars;
  // vtkPoints *newPts;
  // vtkPointData *pd;
  // int i;
  // vtkIdType ptId, numPts;
  // double x[3], *n, s, newX[3];

  // vtkDebugMacro(<<"Warping data with scalars");

  // // First, copy the input to the output as a starting point
  // output->CopyStructure( input );

  // inPts = input->GetPoints();
  // pd = input->GetPointData();
  // inNormals = pd->GetNormals();

  // inScalars = this->GetInputArrayToProcess(0,inputVector);
  // if ( !inPts || !inScalars )
  //   {
  //   vtkDebugMacro(<<"No data to warp");
  //   return 1;
  //   }

  // numPts = inPts->GetNumberOfPoints();

  // if ( inNormals && !this->UseNormal )
  //   {
  //   this->PointNormal = &vtkWarpScalar::DataNormal;
  //   vtkDebugMacro(<<"Using data normals");
  //   }
  // else if ( this->XYPlane )
  //   {
  //   this->PointNormal = &vtkWarpScalar::ZNormal;
  //   vtkDebugMacro(<<"Using x-y plane normal");
  //   }
  // else
  //   {
  //   this->PointNormal = &vtkWarpScalar::InstanceNormal;
  //   vtkDebugMacro(<<"Using Normal instance variable");
  //   }

  // newPts = vtkPoints::New();
  // newPts->SetNumberOfPoints(numPts);

  // // Loop over all points, adjusting locations
  // //
  // for (ptId=0; ptId < numPts; ptId++)
  //   {
  //   if ( ! (ptId % 10000) )
  //     {
  //     this->UpdateProgress ((double)ptId/numPts);
  //     if (this->GetAbortExecute())
  //       {
  //       break;
  //       }
  //     }

  //   inPts->GetPoint(ptId, x);
  //   n = (this->*(this->PointNormal))(ptId,inNormals);
  //   if ( this->XYPlane )
  //     {
  //     s = x[2];
  //     }
  //   else
  //     {
  //     s = inScalars->GetComponent(ptId,0);
  //     }
  //   for (i=0; i<3; i++)
  //     {
  //     newX[i] = x[i] + this->ScaleFactor * s * n[i];
  //     }
  //   newPts->SetPoint(ptId, newX);
  //   }

  // // Update ourselves and release memory
  // //
  // output->GetPointData()->CopyNormalsOff(); // distorted geometry
  // output->GetPointData()->PassData(input->GetPointData());
  // output->GetCellData()->CopyNormalsOff(); // distorted geometry
  // output->GetCellData()->PassData(input->GetCellData());

  // output->SetPoints(newPts);
  // newPts->Delete();

  // return 1;
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  scaleFactor: 1,
  useNormal: false,
  normal: [0, 0, 1],
  xyPlane: false,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Make this a VTK object
  macro.obj(publicAPI, model);

  // Also make it an algorithm with one input and one output
  macro.algo(publicAPI, model, 1, 1);

  // Generate macros for properties
  macro.setGet(publicAPI, model, [
    'scaleFactor',
    'useNormal',
    'xyPlane',
  ]);

  macro.setGetArray(publicAPI, model, [
    'normal',
  ], 3);

  // Object specific methods
  warpScalar(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend, 'vtkWarpScalar');

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>feat(filters): Fleshed out the vtkWarpScalar filter<commit_after>import * as macro from '../../../macro';
import vtkPolyData from '../../../Common/DataModel/PolyData';
import vtkDataArray from '../../../Common/Core/DataArray';

// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
// Static API
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
// vtkWarpScalar methods
// ----------------------------------------------------------------------------

function warpScalar(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkWarpScalar');

  let inputArrayName = null;
  let shouldAbort = false;

  /** *************************************************************
   * FIXME: Some functions needed by vtkAlgorithm instances could
   * be moved to a higher level
   * *************************************************************/
  publicAPI.setInputArrayToProcess = arrayName => {
    inputArrayName = arrayName;
  };

  publicAPI.getInputArrayToProcess = (idx, inputVector) => {
    const input = inputVector[0];
    const pointData = input.getPointData();
    return pointData.getArray(inputArrayName);
  };

  publicAPI.updateProgress = completeRatio => {
    console.log(`vtkWarpScalars is ${completeRatio} percent complete`);
  };

  publicAPI.setAbortExecute = abort => {
    shouldAbort = abort;
  };

  publicAPI.getAbortExecute = () => shouldAbort;

  publicAPI.requestData = (inData, outData) => { // implement requestData
    if (!outData[0] || inData[0].getMTime() > outData[0].getMTime()) {
      const input = inData[0];

      // if (!input)
        // {
        // Try converting image data.
        // vtkImageData *inImage = vtkImageData::GetData(inputVector[0]);
        // if (inImage)
          // {
          // vtkNew<vtkImageDataToPointSet> image2points;
          // image2points->SetInputData(inImage);
          // image2points->Update();
          // input = image2points->GetOutput();
          // }
        // }

      // if (!input)
        // {
        // Try converting rectilinear grid.
        // vtkRectilinearGrid *inRect = vtkRectilinearGrid::GetData(inputVector[0]);
        // if (inRect)
          // {
          // vtkNew<vtkRectilinearGridToPointSet> rect2points;
          // rect2points->SetInputData(inRect);
          // rect2points->Update();
          // input = rect2points->GetOutput();
          // }
        // }

      if (!input) {
        vtkErrorMacro('Invalid or missing input');
        return 1;
      }

      // First, copy the input to the output as a starting point
      // output->CopyStructure( input );

      const inPts = input.getPoints();
      const pd = input.getPointData();
      const inNormals = pd.getNormals();

      const inScalars = publicAPI.getInputArrayToProcess(0, inData);
      if (!inPts || !inScalars) {
        vtkDebugMacro('No data to warp');
        outData[0] = inData[0];
        return 1;
      }

      const numPts = inPts.getNumberOfValues();

      let pointNormal = null;

      if (inNormals && !model.getUseNormal()) {
        pointNormal = (id, normals) => normals.getTuple(id);
        vtkDebugMacro('Using data normals');
      } else if (model.getXyPlane()) {
        const normal = [0, 0, 1];
        pointNormal = (id, array) => normal;
        vtkDebugMacro('Using x-y plane normal');
      } else {
        pointNormal = (id, array) => model.getNormal();
        vtkDebugMacro('Using Normal instance variable');
      }

      // newPts = vtkPoints::New();
      // newPts->SetNumberOfPoints(numPts);
      const newPtsData = new Float32Array(numPts * 3);
      const inPoints = inPts.getData();
      let ptOffset = 0;
      let n = [0, 0, 1];
      let s = 1;

      // Loop over all points, adjusting locations
      for (let ptId = 0; ptId < numPts; ++ptId) {
        if (!(ptId % 10000)) {
          publicAPI.updateProgress(ptId / numPts);
          if (publicAPI.getAbortExecute()) {
            break;
          }
        }

        ptOffset = ptId * 3;
        n = pointNormal(ptId, inNormals);

        if (model.getXyPlane()) {
          s = inPoints[ptOffset + 2];
        } else {
          s = inScalars.getComponent(ptId, 0);
        }

        newPtsData[ptOffset] = inPoints[ptOffset] + model.getScaleFactor() * s * n[0];
        newPtsData[ptOffset + 1] = inPoints[ptOffset + 1] + model.getScaleFactor() * s * n[1];
        newPtsData[ptOffset + 2] = inPoints[ptOffset + 2] + model.getScaleFactor() * s * n[2];
      }

      const newPts = vtkDataArray.newInstance();
      newPts.setData(newPtsData);

      // Update ourselves and release memory

      // output->GetPointData()->CopyNormalsOff(); // distorted geometry
      // output->GetPointData()->PassData(input->GetPointData());
      // output->GetCellData()->CopyNormalsOff(); // distorted geometry
      // output->GetCellData()->PassData(input->GetCellData());

      const newPolyData = vtkPolyData.newInstance();
      newPolyData.setPoints(newPts);
      newPolyData.setPolys(inData[0].getPolys());
      outData[0] = newPolyData;

      // newPts->Delete();
    }

    return 1;
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  scaleFactor: 1,
  useNormal: false,
  normal: [0, 0, 1],
  xyPlane: false,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Make this a VTK object
  macro.obj(publicAPI, model);

  // Also make it an algorithm with one input and one output
  macro.algo(publicAPI, model, 1, 1);

  // Generate macros for properties
  macro.setGet(publicAPI, model, [
    'scaleFactor',
    'useNormal',
    'xyPlane',
  ]);

  macro.setGetArray(publicAPI, model, [
    'normal',
  ], 3);

  // Object specific methods
  warpScalar(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend, 'vtkWarpScalar');

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>module.exports = {
  dirs: {
    gulp: './gulp/',
    base: 'dist/',
    dist_base: './dist/',
    src: './src/',
    src1: './src/*.ts',
    src2: './src/**/*.ts',
    src3: './src/**/**/*.ts',
    testsrc: './test/**/*.ts',
    testdbpath: './dist/test/test_db/',
    dist: {
      src: './dist/src/',
      tests: './dist/**/*tests.js',
      instrument: './dist/**/*.js'
    },
    coverage: './coverage/coverage-final.json',
    lcovonly:'./coverage/lcov.info'
  },
  projectName: 'Chapp'
};<commit_msg>chore: unused var<commit_after>module.exports = {
  dirs: {
    gulp: './gulp/',
    base: 'dist/',
    dist_base: './dist/',
    src: './src/',
    src1: './src/*.ts',
    src2: './src/**/*.ts',
    src3: './src/**/**/*.ts',
    testsrc: './test/**/*.ts',
    testdbpath: './dist/test/test_db/',
    dist: {
      src: './dist/src/',
      tests: './dist/**/*tests.js',
      instrument: './dist/**/*.js'
    },
    coverage: './coverage/coverage-final.json',
    lcovonly:'./coverage/lcov.info'
  }
};
<|endoftext|>