<commit_before>var FULL_BROWSER_TEST = !!process.env.SAUCE_USERNAME; // use sauce if credentials are available

// Karma configuration
// Generated on Fri Aug 09 2013 14:14:35 GMT-0500 (CDT)

module.exports = function(config) {
  config.set({

    // Base path, that will be used to resolve files and exclude
    basePath: '',

    // Load jasmine and requirejs (require is used by the readme spec)
    frameworks: ['jasmine', 'requirejs'],

    // List of files / patterns to load in the browser
    files: [
  		// libraries
  		'bower_components/angular/angular.js',
      'bower_components/angular-inflector/dist/angular-inflector.js',
      'bower_components/angular-mocks/angular-mocks.js',

  		// our app
      'src/module.js',
      'src/module/*.js',
      'src/plugins/*.js',

  		// tests
  		{ pattern: 'test/**/*spec.js', included: false },
      { pattern: 'README.md', included: false },

      'test/requirejs-main.js',
      { pattern: 'node_modules/text/text.js', included: false }
    ],

    // Karma plugins
    plugins: [
      'karma-jasmine',
      'karma-requirejs',
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-sauce-launcher',
      'karma-osx-reporter'
    ],

    // List of files to exclude
    exclude: [

    ],

    // Test results reporter to use
    // possible values: 'dots', 'progress', 'junit'
    reporters: ['progress', 'osx', 'saucelabs'],

    // Web server port
    port: 9876,

    // cli runner port
    runnerPort: 9100,

    // Enable / disable colors in the output (reporters and logs)
    colors: true,

    // Level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Broser connection tolerances
    browserDisconnectTolerance: 2,
    browserDisconnectTimeout: 10000,
    browserNoActivityTimeout: 60000,

    // Continuous Integration mode by default
    singleRun: true,

    // Sauce config, requires username and accessKey to be loaded in ENV
    sauceLabs: {
      testName: 'Restmod Unit Tests',
      startConnect: false
    },

    // Custom sauce launchers
    customLaunchers:
    {
      sl_chrome: {
        base: 'SauceLabs',
        browserName: 'chrome',
        platform: 'Windows 7',
        version: '35'
      },
      sl_firefox: {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '30'
      },
      sl_firefox_4: {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '4'
      },
      sl_ios_safari: {
        base: 'SauceLabs',
        browserName: 'iphone',
        platform: 'OS X 10.9',
        version: '7.1'
      },
      sl_ie_9: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '9'
      },
      sl_ie_11: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 8.1',
        version: '11'
      }
    },

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: FULL_BROWSER_TEST ? ['sl_ie_9', 'sl_firefox_4', 'sl_firefox', 'sl_ie_11'] : ['Firefox']
  });
};
<commit_msg>fix(tests):more souce related tunning<commit_after>var FULL_BROWSER_TEST = !!process.env.SAUCE_USERNAME; // use sauce if credentials are available

// Karma configuration
// Generated on Fri Aug 09 2013 14:14:35 GMT-0500 (CDT)

module.exports = function(config) {
  config.set({

    // Base path, that will be used to resolve files and exclude
    basePath: '',

    // Load jasmine and requirejs (require is used by the readme spec)
    frameworks: ['jasmine', 'requirejs'],

    // List of files / patterns to load in the browser
    files: [
  		// libraries
  		'bower_components/angular/angular.js',
      'bower_components/angular-inflector/dist/angular-inflector.js',
      'bower_components/angular-mocks/angular-mocks.js',

  		// our app
      'src/module.js',
      'src/module/*.js',
      'src/plugins/*.js',

  		// tests
  		{ pattern: 'test/**/*spec.js', included: false },
      { pattern: 'README.md', included: false },

      'test/requirejs-main.js',
      { pattern: 'node_modules/text/text.js', included: false }
    ],

    // Karma plugins
    plugins: [
      'karma-jasmine',
      'karma-requirejs',
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-sauce-launcher',
      'karma-osx-reporter'
    ],

    // List of files to exclude
    exclude: [

    ],

    // Test results reporter to use
    // possible values: 'dots', 'progress', 'junit'
    reporters: ['progress', 'osx', 'saucelabs'],

    // Web server port
    port: 9876,

    // cli runner port
    runnerPort: 9100,

    // Enable / disable colors in the output (reporters and logs)
    colors: true,

    // Level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Broser connection tolerances (partially based on angularjs configuration)
    captureTimeout: 0,
    browserDisconnectTolerance: 2,
    browserDisconnectTimeout: 10000,
    browserNoActivityTimeout: 60000,

    // disable websocket for full browser tests
    transports: FULL_BROWSER_TEST ? ['xhr-polling'] : ['websocket', 'xhr-polling'],

    // Continuous Integration mode by default
    singleRun: true,

    // Sauce config, requires username and accessKey to be loaded in ENV
    sauceLabs: {
      testName: 'Restmod Unit Tests',
      startConnect: false
    },

    // Custom sauce launchers
    customLaunchers:
    {
      sl_chrome: {
        base: 'SauceLabs',
        browserName: 'chrome',
        platform: 'Windows 7',
        version: '35'
      },
      sl_firefox: {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '30'
      },
      sl_firefox_4: {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '4'
      },
      sl_ios_safari: {
        base: 'SauceLabs',
        browserName: 'iphone',
        platform: 'OS X 10.9',
        version: '7.1'
      },
      sl_ie_9: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '9'
      },
      sl_ie_11: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 8.1',
        version: '11'
      }
    },

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: FULL_BROWSER_TEST ? ['sl_ie_9', 'sl_firefox_4', 'sl_firefox', 'sl_ie_11'] : ['Firefox']
  });
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Wed Mar 09 2016 13:20:18 GMT+0000 (GMT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'node_modules/jquery/dist/jquery.js',
      'node_modules/select2/dist/js/select2.full.js',
      'node_modules/underscore/underscore.js',
      'node_modules/backbone/backbone.js',
      'node_modules/backgrid/lib/backgrid.js',
      'backgrid-select2-cell.js',
      'test/select2-cell.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'backgrid-select2-cell.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'kjhtml', 'coverage'],

    coverageReporter: {
      type: 'html',
      dir: 'test/coverage'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome', 'Firefox', 'Safari'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    browserNoActivityTimeout: 30000
  })
}
<commit_msg>Turn watch on by default<commit_after>// Karma configuration
// Generated on Wed Mar 09 2016 13:20:18 GMT+0000 (GMT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'node_modules/jquery/dist/jquery.js',
      'node_modules/select2/dist/js/select2.full.js',
      'node_modules/underscore/underscore.js',
      'node_modules/backbone/backbone.js',
      'node_modules/backgrid/lib/backgrid.js',
      'backgrid-select2-cell.js',
      'test/select2-cell.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'backgrid-select2-cell.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'kjhtml', 'coverage'],

    coverageReporter: {
      type: 'html',
      dir: 'test/coverage'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome', 'Firefox', 'Safari'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    browserNoActivityTimeout: 30000
  })
}
<|endoftext|>


<commit_before>module.exports = function (config) {
    config.set({
        frameworks: ['systemjs', 'qunit'],
        files: [
        'dist/*.test.js',
        { pattern: 'dist/**/*!(.test).js', included: false }
        ],
        plugins: ['karma-systemjs', 'karma-qunit', 'karma-chrome-launcher'],
        systemjs: {
        configFile: 'system.conf.js'
        },
        browsers: ['Chrome'],
        browserNoActivityTimeout: 15000,
        browserDisconnectTolerance: 10,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        concurrency: Infinity
    });
}<commit_msg>Update karma.conf.js to be 2 space indents instead of 4.<commit_after>module.exports = function (config) {
  config.set({
    frameworks: ['systemjs', 'qunit'],
    files: [
      'dist/*.test.js',
      { pattern: 'dist/**/*!(.test).js', included: false }
    ],
    plugins: ['karma-systemjs', 'karma-qunit', 'karma-chrome-launcher'],
    systemjs: {
    configFile: 'system.conf.js'
    },
    browsers: ['Chrome'],
    browserNoActivityTimeout: 15000,
    browserDisconnectTolerance: 10,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    concurrency: Infinity
  });
}<|endoftext|>


<commit_before>
module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['browserify', 'jasmine'],
    files: [
        'dist/libraries.js',
        'node_modules/angular-mocks/angular-mocks.js',
        'tests/setup.js',
        'tests/**/*.spec.js',
        'src/**/*.html'
    ],
    ngHtml2JsPreprocessor: {
        moduleName: 'TEMPLATES',
        stripPrefix: 'src\/',
        prependPrefix: '../monad/'
    },
    exclude: [
    ],
    preprocessors: {
        'tests/**/*.js': ['browserify'],
        'src/**/*.html': ['ng-html2js']
    },
    browserify: {
        debug: true,
        transform: ['babelify']
    },
    babelPreprocessor: {
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: true
  });
};

<commit_msg>add angular-cookies<commit_after>
module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['browserify', 'jasmine'],
    files: [
        'dist/libraries.js',
        'node_modules/angular-mocks/angular-mocks.js',
        'bower_components/angular-cookies/angular-cookies.js',
        'tests/setup.js',
        'tests/**/*.spec.js',
        'src/**/*.html'
    ],
    ngHtml2JsPreprocessor: {
        moduleName: 'TEMPLATES',
        stripPrefix: 'src\/',
        prependPrefix: '../monad/'
    },
    exclude: [
    ],
    preprocessors: {
        'tests/**/*.js': ['browserify'],
        'src/**/*.html': ['ng-html2js']
    },
    browserify: {
        debug: true,
        transform: ['babelify']
    },
    babelPreprocessor: {
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: true
  });
};

<|endoftext|>


<commit_before>var fs = require('fs');

module.exports = function init(config) {
  var customLaunchers;
  var browsers;
  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    if (!fs.existsSync('sauce.json')) {
      console.log('Create a sauce.json with your credentials based on the sauce-sample.json file.');
      process.exit(1);
    } else {
      process.env.SAUCE_ENABLED = require('./sauce.json').enabled;
      process.env.SAUCE_USERNAME = require('./sauce.json').username;
      process.env.SAUCE_ACCESS_KEY = require('./sauce.json').accessKey;
    }
  } else {
    process.env.SAUCE_ENABLED = true;
  }

  if (process.env.SAUCE_ENABLED == "true") {
    customLaunchers = {
      slChromeWin7: {
        base: 'SauceLabs',
        browserName: 'chrome',
        platform: 'Windows 7'
      },
      slFirefoxWin7: {
        base: 'SauceLabs',
        browserName: 'firefox',
        platform: 'Windows 7',
        version: '56',
      },
      slIe10Win7: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '10'
      },
      slIe9Win7: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '9'
      },
      slIe11Win10: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 10',
        version: '11'
      },
      slME25Win10: {
        base: 'SauceLabs',
        browserName: 'microsoftedge',
        platform: 'Windows 10',
        version: '13'
      },
      slSafariOsx: {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'OS X 10.9'
      },
      slIphone: {
        base: 'SauceLabs',
        browserName: 'iphone',
        platform: 'OS X 10.10',
        version: '8.2',
        deviceName: 'iPhone Simulator'
      },
      slIpad: {
        base: 'SauceLabs',
        browserName: 'iphone',
        platform: 'OS X 10.10',
        version: '8.2',
        deviceName: 'iPad Simulator'
      },
      slAndroid: {
        base: 'SauceLabs',
        browserName: 'android',
        platform: 'Linux',
        version: '5.1',
        deviceName: 'Android Emulator'
      }
    };
    browsers = Object.keys(customLaunchers);
  } else {
    customLaunchers = null;
    browsers = ["Safari"];
  }

  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: [/*'browserify',*/'mocha'],

    client: {
      mocha: {
        timeout : 7000
      }
    },

    sauceLabs: {
      testName: 'Digital Data Manager Unit Tests',
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
      recordScreenshots: false,
      startConnect: false,
      // connectOptions: {
      //   port: 5757,
      //   logfile: 'sauce_connect.log'
      // },
      // public: 'public'
    },

    // list of files / patterns to load in the browser
    files: [
      'build/dd-manager-test.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    // preprocessors: {
    //  'src/**/*.js': ['browserify'],
    //  'test/**/*.js': ['browserify']
    // },
    //
    // browserify: {
    //  debug: true,
    //  transform: ['babelify', ['polyify', { 'browsers': 'IE >= 7' }]],
    //  configure: function(bundle) {
    //    bundle.on('bundled', function(err, content) {
    //      console.log(content);
    //    });
    //  }
    // },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots'/* , 'saucelabs' */],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR ||
    // config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_ERROR,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Increase timeout in case connection in CI is slow
    captureTimeout: 120000,
    customLaunchers: customLaunchers,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultanous
    // concurrency: 1,
    // browserDisconnectTimeout: 10000,
    // browserDisconnectTolerance: 10,
    // browserNoActivityTimeout: 20000,
  });
};
<commit_msg>added samsunt<commit_after>var fs = require('fs');

module.exports = function init(config) {
  var customLaunchers;
  var browsers;
  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    if (!fs.existsSync('sauce.json')) {
      console.log('Create a sauce.json with your credentials based on the sauce-sample.json file.');
      process.exit(1);
    } else {
      process.env.SAUCE_ENABLED = require('./sauce.json').enabled;
      process.env.SAUCE_USERNAME = require('./sauce.json').username;
      process.env.SAUCE_ACCESS_KEY = require('./sauce.json').accessKey;
    }
  } else {
    process.env.SAUCE_ENABLED = true;
  }

  if (process.env.SAUCE_ENABLED == "true") {
    customLaunchers = {
      slChromeWin7: {
        base: 'SauceLabs',
        browserName: 'chrome',
        platform: 'Windows 7'
      },
      slFirefoxWin7: {
        base: 'SauceLabs',
        browserName: 'firefox',
        platform: 'Windows 7',
        version: '56',
      },
      slIe10Win7: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '10'
      },
      slIe9Win7: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '9'
      },
      slIe11Win10: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 10',
        version: '11'
      },
      slME25Win10: {
        base: 'SauceLabs',
        browserName: 'microsoftedge',
        platform: 'Windows 10',
        version: '13'
      },
      slSafariOsx: {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'OS X 10.9'
      },
      slIphone: {
        base: 'SauceLabs',
        browserName: 'iphone',
        platform: 'OS X 10.10',
        version: '8.2',
        deviceName: 'iPhone Simulator'
      },
      slIpad: {
        base: 'SauceLabs',
        browserName: 'iphone',
        platform: 'OS X 10.10',
        version: '8.2',
        deviceName: 'iPad Simulator'
      },
      slAndroid: {
        base: 'SauceLabs',
        browserName: 'android',
        platform: 'Linux',
        version: '5.1',
        deviceName: 'Android Emulator',
      },
      slSamsungAndroid: {
        base: 'SauceLabs',
        browserName: 'Browser',
        platform: 'Android',
        version: '4.4',
        deviceName: 'Samsung Galaxy S3 Emulator',
      }
    };
    browsers = Object.keys(customLaunchers);
  } else {
    customLaunchers = null;
    browsers = ["Safari"];
  }

  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: [/*'browserify',*/'mocha'],

    client: {
      mocha: {
        timeout : 7000
      }
    },

    sauceLabs: {
      testName: 'Digital Data Manager Unit Tests',
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
      recordScreenshots: false,
      startConnect: false,
      // connectOptions: {
      //   port: 5757,
      //   logfile: 'sauce_connect.log'
      // },
      // public: 'public'
    },

    // list of files / patterns to load in the browser
    files: [
      'build/dd-manager-test.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    // preprocessors: {
    //  'src/**/*.js': ['browserify'],
    //  'test/**/*.js': ['browserify']
    // },
    //
    // browserify: {
    //  debug: true,
    //  transform: ['babelify', ['polyify', { 'browsers': 'IE >= 7' }]],
    //  configure: function(bundle) {
    //    bundle.on('bundled', function(err, content) {
    //      console.log(content);
    //    });
    //  }
    // },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots'/* , 'saucelabs' */],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR ||
    // config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_ERROR,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Increase timeout in case connection in CI is slow
    captureTimeout: 120000,
    customLaunchers: customLaunchers,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultanous
    // concurrency: 1,
    // browserDisconnectTimeout: 10000,
    // browserDisconnectTolerance: 10,
    // browserNoActivityTimeout: 20000,
  });
};
<|endoftext|>


<commit_before>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['mocha'],
    files: [
      { pattern: 'https://cdn.polyfill.io/v2/polyfill.js?flags=gated&features=default,NodeList.prototype.@@iterator', watched: false, served: false, included: true },
      { pattern: 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js', watched: false, served: false, included: true },
      { pattern: 'https://cdnjs.cloudflare.com/ajax/libs/i18next/11.3.2/i18next.min.js', watched: false, served: false, included: true },
      { pattern: 'node_modules/power-assert/build/power-assert.js', watched: true, served: true, included: true },
      { pattern: 'node_modules/benchmark/benchmark.js', watched: true, served: true, included: true },
      { pattern: 'dist/*.test.js', watched: true, served: true, included: true }
    ],
    exclude: [
    ],
    espowerPreprocessor: {
      options: {
        emitActualCode: false,
        ignoreUpstreamSourceMap: true
      }
    },
    reporters: ['dots'],
    coverageIstanbulReporter: {
      reports: ['html', 'lcovonly', 'text-summary'],
      dir: 'coverage',
      combineBrowserReports: true,
      skipFilesWithNoCoverage: false,
      verbose: false,
      'report-config': {
        html: {
          subdir: 'html',
        },
      },
      instrumentation: {
        'default-excludes': false,
      },
    },
    coverageIstanbulInstrumenter: {
      esModules: true,
    },
    autoWatch: true,
    autoWatchBatchDelay: 500,
    browsers: ['Chrome'],
    singleRun: true,
  });
};
<commit_msg>Refactoring<commit_after>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['mocha'],
    files: [
      { pattern: 'https://cdn.polyfill.io/v2/polyfill.js?flags=gated&features=default,NodeList.prototype.@@iterator', watched: false, served: false, included: true },
      { pattern: 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js', watched: false, served: false, included: true },
      { pattern: 'https://cdnjs.cloudflare.com/ajax/libs/i18next/11.3.2/i18next.min.js', watched: false, served: false, included: true },
      { pattern: 'node_modules/power-assert/build/power-assert.js', watched: true, served: true, included: true },
      { pattern: 'node_modules/benchmark/benchmark.js', watched: true, served: true, included: true },
      { pattern: 'dist/*.test.js', watched: true, served: true, included: true }
    ],
    exclude: [
    ],
    espowerPreprocessor: {
      options: {
        emitActualCode: false,
        ignoreUpstreamSourceMap: true
      }
    },
    reporters: ['dots'],
    coverageIstanbulReporter: {
      reports: ['html', 'lcovonly', 'text-summary'],
      dir: 'coverage',
      combineBrowserReports: true,
      skipFilesWithNoCoverage: false,
      verbose: false,
      'report-config': {
        html: {
          subdir: 'html',
        },
      },
      instrumentation: {
        'default-excludes': false,
      },
    },
    coverageIstanbulInstrumenter: {
      esModules: true,
    },
    autoWatch: true,
    autoWatchBatchDelay: 500,
    browserDisconnectTimeout: 30000,
    browsers: ['Chrome'],
    singleRun: true,
  });
};
<|endoftext|>


<commit_before>// Filename: views/data/dataEdit.js
define([
	'jquery',
	'underscore',
	'backbone',
	'toastr',
	'services/user',
	'views/data/dataStreamProperties',
	'i18n!nls/strings',
	'text!templates/data/dataEdit.html'
], function($, _, Backbone, toastr, UserService, DataStreamProperties, strings, template) {

	return Backbone.View.extend({

		template: _.template(template),

		events: {
			'click #buttonCreate': 'onClickCreate'
		},

		initialize: function(options) {
			this.id = options ? options.id : null;
		},

		remove: function() {
			this.dataStreamPropertiesView.remove();
			Backbone.View.prototype.remove.call(this);
		},

		render: function() {
			this.$el.append(this.template({
				strings: strings,
				editMode: this.id
			}));

			this.dataStreamPropertiesView = new DataStreamProperties({
				dataStream: null
			});
			this.$el.find('#dataProperties').html(this.dataStreamPropertiesView.render().el);

			return this;
		},

		onClickCreate: function(e) {
			this.hideErrors();

			var name = this.$el.find('#dataStreamName').val();

			var errors = [];
			if (!name) {
				errors.push({message: strings.NeedsName});
			}
			if (this.dataStreamPropertiesView.model.length == 0) {
				errors.push({message: strings.NeedOneVariable});
			}

			if (errors.length > 0) {
				this.showErrors(this, errors);
			} else {
				// build data stream object
				var dataStream = {name: name, variables: []};
				for (var i in this.dataStreamPropertiesView.model) {
					dataStream.variables.push({
						'@id': this.dataStreamPropertiesView.model[i].variable['@id']
					});
				}
				console.debug('onClickCreate', dataStream);
				UserService.addDataStream(this, dataStream, function() {
					toastr.success(strings.DataStreamCreated);
				}, function(model, response, options) {
					if (response.status === 501) {
						toastr.error(strings.DataStreamCreationUnsupported);
					} else {
						toastr.error(strings.DataStreamCreationFailed);
					}
				});
			}
		},

		hideErrors: function() {
			this.$el.find('#error').css('display', 'none');
			this.$el.find('#errorMsg').html('');
		},

		showErrors: function(ctx, errors) {
			var msg = '
';
			for (var i=0; i < errors.length; i++) {
				msg += '
' + errors[i].message + '
';
			}
			msg += '
';
			ctx.$el.find('#error').css('display', 'block');
			ctx.$el.find('#errorMsg').html(msg);
		}

	});

});<commit_msg>Added 501 detection.<commit_after>// Filename: views/data/dataEdit.js
define([
	'jquery',
	'underscore',
	'backbone',
	'toastr',
	'services/user',
	'views/data/dataStreamProperties',
	'i18n!nls/strings',
	'text!templates/data/dataEdit.html'
], function($, _, Backbone, toastr, UserService, DataStreamProperties, strings, template) {

	return Backbone.View.extend({

		template: _.template(template),

		events: {
			'click #buttonCreate': 'onClickCreate'
		},

		initialize: function(options) {
			this.id = options ? options.id : null;
		},

		remove: function() {
			this.dataStreamPropertiesView.remove();
			Backbone.View.prototype.remove.call(this);
		},

		render: function() {
			this.$el.append(this.template({
				strings: strings,
				editMode: this.id
			}));

			this.dataStreamPropertiesView = new DataStreamProperties({
				dataStream: null
			});
			this.$el.find('#dataProperties').html(this.dataStreamPropertiesView.render().el);

			return this;
		},

		onClickCreate: function(e) {
			this.hideErrors();

			var name = this.$el.find('#dataStreamName').val();

			var errors = [];
			if (!name) {
				errors.push({message: strings.NeedsName});
			}
			if (this.dataStreamPropertiesView.model.length == 0) {
				errors.push({message: strings.NeedOneVariable});
			}

			if (errors.length > 0) {
				this.showErrors(this, errors);
			} else {
				// build data stream object
				var dataStream = {name: name, variables: []};
				for (var i in this.dataStreamPropertiesView.model) {
					dataStream.variables.push({
						'@id': this.dataStreamPropertiesView.model[i].variable['@id']
					});
				}
				console.debug('onClickCreate', dataStream);
				UserService.addDataStream(this, dataStream, function() {
					toastr.success(strings.DataStreamCreated);
				}, function(model, response, options) {
					if (response.status === 201) {
						toastr.success(strings.DataStreamCreated);
					} else if (response.status === 501) {
						toastr.error(strings.DataStreamCreationUnsupported);
					} else {
						toastr.error(strings.DataStreamCreationFailed);
					}
				});
			}
		},

		hideErrors: function() {
			this.$el.find('#error').css('display', 'none');
			this.$el.find('#errorMsg').html('');
		},

		showErrors: function(ctx, errors) {
			var msg = '
';
			for (var i=0; i < errors.length; i++) {
				msg += '
' + errors[i].message + '
';
			}
			msg += '
';
			ctx.$el.find('#error').css('display', 'block');
			ctx.$el.find('#errorMsg').html(msg);
		}

	});

});<|endoftext|>


<commit_before>import React from 'react';

import { withStyles } from '@material-ui/core/styles';
//import { MdContactPhone } from 'react-icons/md';

import Avatar from '@material-ui/core/Avatar';
import Grid from '@material-ui/core/Grid';
import IconButton from '@material-ui/core/IconButton';
import LinearProgress from '@material-ui/core/LinearProgress';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';

import AddIcon from '@material-ui/icons/Add';
import AddToPhotosIcon from '@material-ui/icons/AddToPhotos';
import BuildIcon from '@material-ui/icons/Build';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import DeleteForeverIcon from '@material-ui/icons/DeleteForever';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import HelpIcon from '@material-ui/icons/Help';
import PublishIcon from '@material-ui/icons/Publish';
import RefreshIcon from '@material-ui/icons/Refresh';

import { FaGithub as GithubIcon } from 'react-icons/fa';

import { blue } from '@material-ui/core/colors';
import { green } from '@material-ui/core/colors';

const styles = theme => ({
    root:{
        marginBottom: theme.spacing(2)
    },
    smallAvatar: {
        width: theme.spacing(3),
        height: theme.spacing(3)
    },
    table: {
        tableLayout: 'fixed',
        minWidth: 960,
        '& td': {
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
        }
    },
    hidden: {
        visibility: 'hidden'
    },
    name: {
        flexWrap: 'nowrap',
        width: 300
    },
    description: {
        width: 600
    },
    keywords: {

    },
    installed: {
        width: 120
    },
    available: {
        width: 100
    },
    license: {
        width: 150
    },
    install:{
        width: 220
    },
    green: {
        color: green[500]
    },
    blue: {
        color: blue[700]
    },
    category: {
        backgroundColor: theme.palette.background.default,
    },
    grow: {
        flexGrow: 1
    }
});

class Adapters extends React.Component {

    constructor(props) {

        super(props);

        this.state = {
            lastUpdate: 0,
            repository: {},
            installed: {},
            instances: {},
            categories: [],
            hostData: {},
            hostOs: '',
            nodeJsVersion: '',
            init: false
        };

        this.t = props.t;
    }

    componentDidMount() {
        if(this.props.ready) {
            this.getAdaptersInfo(this.props.currentHost, true);
        }
    }

    componentDidUpdate() {
        if(!this.state.init && this.props.ready) {
            this.getAdaptersInfo(this.props.currentHost, true);
        }
    }

    async getAdaptersInfo(update, updateRepo) {
        if (!this.props.currentHost) {
            return;
        }

        if (update) {
            // Do not update too often
            if (new Date().getTime() - this.state.lastUpdate > 1000) {

                const currentHost = this.props.currentHost;

                try {
                    const hostData = await this.props.socket.getHostInfo(currentHost);
                    const nodeJsVersion = hostData['Node.js'].replace('v', '');
                    const hostOs = hostData.os;

                    const repository = await this.props.socket.getRepository(currentHost, {repo: this.props.systemConfig.common.activeRepo, update: updateRepo});
                    const installed = await this.props.socket.getInstalled(currentHost);
                    const instances = await this.props.socket.getAdapterInstances();
                    const categories = {};
                    const categoriesSorted = [];

                    Object.keys(installed).forEach(value => {

                        const adapter = installed[value];

                        if (!adapter.controller && value !== 'hosts') {
                            if (!repository[value]) {
                                repository[value] = adapter;
                            }
                        }
                    });

                    Object.keys(repository).forEach(value => {

                        const adapter = repository[value];

                        if (!adapter.controller) {

                            const type = adapter.type;
                            const installedInGroup = installed[value];

                            if (!categories[type]) {
                                categories[type] = {
                                    name: type,
                                    translation: this.t(type + '_group'),
                                    expanded: false,
                                    count: 1,
                                    installed: installedInGroup ? 1 : 0
                                };
                            } else {
                                categories[type].count++;
                                if (installedInGroup) {
                                    categories[type].installed++;
                                }
                            }
                        }
                    });

                    Object.keys(instances).forEach(value => {

                        const instance = instances[value];
                        const name = instance.common.name;
                        const enabled = instance.common.enabled;

                        if (installed[name]) {
                            if (installed[name].count) {
                                installed[name].count++;
                            } else {
                                installed[name].count = 1;
                            }

                            if (enabled) {
                                if (installed[name].enabled) {
                                    installed[name].enabled++;
                                } else {
                                    installed[name].enabled = 1;
                                }
                            }
                        }
                    });

                    Object.keys(categories).forEach(value => {
                        categoriesSorted.push(categories[value]);
                    });

                    categoriesSorted.sort((a, b) => {

                        const result = b.installed - a.installed;

                        return result !== 0 ? result : a.translation  b.translation ? 1 : 0;
                    });

                    this.setState({
                        lastUpdate: Date.now(),
                        hostData,
                        hostOs,
                        nodeJsVersion,
                        repository,
                        installed,
                        instances,
                        categories: categoriesSorted,
                        init: true
                    });
                } catch(error) {
                    console.error(error);
                }
            }
        }
    }

    toggleCategory(category) {

        const categories = this.state.categories;
        categories[category].expanded = !categories[category].expanded;

        this.setState({
            categories
        });
    }

    getRows() {
        const rows = [];
        const { classes } = this.props;

        Object.keys(this.state.categories).forEach(value => {

            const category = this.state.categories[value];
            const categoryName = category.name;

            rows.push(
                <TableRow
                    key={ categoryName }
                    className={ classes.category }
                >
                    <TableCell>
                        <Grid container spacing={ 1 } alignItems="center" className={ classes.name }>
                            <Grid item>
                                <IconButton
                                    size="small"
                                    onClick={ () => this.toggleCategory(value) }
                                >
                                    { category.expanded ? <ExpandMoreIcon /> : <ChevronRightIcon />}
                                </IconButton>
                            </Grid>
                            <Grid item>
                                { category.translation }
                            </Grid>
                        </Grid>
                    </TableCell>
                    <TableCell>
                        <Typography component="span" variant="body2" className={ classes.green }>
                            { category.installed }
                        </Typography>
                        { ` ${this.t('of')} ` }
                        <Typography component="span" variant="body2" className={ classes.blue }>
                            { category.count }
                        </Typography>
                        { ` ${this.t('Adapters from this Group installed')}` }
                    </TableCell>
                    <TableCell />
                    <TableCell />
                    <TableCell />
                    <TableCell />
                    <TableCell />
                </TableRow>
            );

            if (category.expanded) {

                Object.keys(this.state.repository).forEach(value => {

                    const adapter = this.state.repository[value];

                    if (!adapter.controller && adapter.type === categoryName) {

                        const installed = this.state.installed[value];

                        const title = (adapter.title.toString() || '').replace('ioBroker Visualisation - ', '');
                        const desc = adapter.desc ? adapter.desc[this.props.lang] || adapter.desc['en'] : '';
                        const image = installed ? installed.localIcon : adapter.extIcon;

                        if (title instanceof Object || !desc) {
                            console.log(adapter);
                        }

                        rows.push(
                            <TableRow
                                key={ value }
                                hover
                            >
                                <TableCell>
                                    <Grid container spacing={ 1 } alignItems="center" className={ classes.name }>
                                        <Grid item>
                                            <Avatar
                                                variant="square"
                                                alt={ title.toString() }
                                                src={ image }
                                                className={ classes.smallAvatar }
                                            />
                                        </Grid>
                                        <Grid item>
                                            { title.toString() }
                                        </Grid>
                                    </Grid>
                                </TableCell>
                                <TableCell>
                                    { desc }
                                </TableCell>
                                <TableCell>
                                    { adapter.keywords && adapter.keywords.join(' ') }
                                </TableCell>
                                <TableCell>
                                    { installed && `${installed.version} (${installed.count}${installed.count !== installed.enabled ? '~' : ''})` }
                                </TableCell>
                                <TableCell>
                                    { adapter.version }
                                </TableCell>
                                <TableCell>
                                    { adapter.license }
                                </TableCell>
                                <TableCell>
                                    <IconButton size="small">
                                        <AddIcon />
                                    </IconButton>
                                    <IconButton size="small">
                                        <HelpIcon />
                                    </IconButton>
                                    { this.props.expertMode &&
                                        <IconButton
                                            size="small"
                                            className={ !installed ? classes.hidden : '' }
                                            onClick={ () => this.props.executeCommand('upload ' + value)}
                                        >
                                            <PublishIcon />
                                        </IconButton>
                                    }
                                    <IconButton size="small" className={ !installed ? classes.hidden : '' }>
                                        <DeleteForeverIcon />
                                    </IconButton>
                                    { this.props.expertMode &&
                                        <IconButton size="small" className={ !installed ? classes.hidden : '' }>
                                            <AddToPhotosIcon />
                                        </IconButton>
                                    }
                                    { this.props.expertMode &&
                                        <IconButton size="small" className={ !installed ? classes.hidden : '' }>
                                            <BuildIcon />
                                        </IconButton>
                                    }
                                </TableCell>
                            </TableRow>
                        );
                    }
                });
            }
        });

        return rows;
    }

    render() {

        if (!this.state.init) {
            return <LinearProgress />
        }

        const { classes } = this.props;

        return (
            <Paper className={ classes.root }>
                <Grid
                    container
                    direction="column"
                    className={ classes.flexContainer }
                >
                    <Grid
                        item
                        container
                        alignItems="center"
                    >
                        <IconButton>
                            <RefreshIcon />
                        </IconButton>
                        <IconButton>
                            <GithubIcon />
                        </IconButton>

                        <TextField label={ this.t('Filter') } />

                    </Grid>
                    <TableContainer className={ classes.container }>

                            <TableHead>
                                <TableRow>
                                    <TableCell className={ classes.name }>
                                        <Typography>{ this.t('Name') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.description }>
                                        <Typography>{ this.t('Description') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.keywords }>
                                        <Typography>{ this.t('Keywords') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.installed }>
                                        <Typography>{ this.t('Installed') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.available }>
                                        <Typography>{ this.t('Available') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.license }>
                                        <Typography>{ this.t('License') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.install }>
                                        <Typography>{ this.t('Install') }</Typography>
                                    </TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                { this.getRows() }
                            </TableBody>

                    </TableContainer>
                </Grid>
            </Paper>
        );
    }
}

export default withStyles(styles)(Adapters);<commit_msg>Added #547<commit_after>import React from 'react';

import { withStyles } from '@material-ui/core/styles';
//import { MdContactPhone } from 'react-icons/md';

import Avatar from '@material-ui/core/Avatar';
import Grid from '@material-ui/core/Grid';
import IconButton from '@material-ui/core/IconButton';
import LinearProgress from '@material-ui/core/LinearProgress';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';

import AddIcon from '@material-ui/icons/Add';
import AddToPhotosIcon from '@material-ui/icons/AddToPhotos';
import BuildIcon from '@material-ui/icons/Build';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import DeleteForeverIcon from '@material-ui/icons/DeleteForever';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import HelpIcon from '@material-ui/icons/Help';
import PublishIcon from '@material-ui/icons/Publish';
import RefreshIcon from '@material-ui/icons/Refresh';

import { FaGithub as GithubIcon } from 'react-icons/fa';

import { blue } from '@material-ui/core/colors';
import { green } from '@material-ui/core/colors';

const styles = theme => ({
    root:{
        marginBottom: theme.spacing(2)
    },
    smallAvatar: {
        width: theme.spacing(3),
        height: theme.spacing(3)
    },
    table: {
        tableLayout: 'fixed',
        minWidth: 960,
        '& td': {
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
        }
    },
    hidden: {
        visibility: 'hidden'
    },
    name: {
        flexWrap: 'nowrap',
        width: 300
    },
    description: {
        width: 600
    },
    keywords: {

    },
    installed: {
        width: 120
    },
    available: {
        width: 100
    },
    license: {
        width: 150
    },
    install:{
        width: 220
    },
    green: {
        color: green[500]
    },
    blue: {
        color: blue[700]
    },
    category: {
        backgroundColor: theme.palette.background.default,
    },
    grow: {
        flexGrow: 1
    }
});

class Adapters extends React.Component {

    constructor(props) {

        super(props);

        this.state = {
            lastUpdate: 0,
            repository: {},
            installed: {},
            instances: {},
            categories: [],
            hostData: {},
            hostOs: '',
            nodeJsVersion: '',
            init: false
        };

        this.t = props.t;
    }

    componentDidMount() {
        if(this.props.ready) {
            this.getAdaptersInfo(this.props.currentHost, true);
        }
    }

    componentDidUpdate() {
        if(!this.state.init && this.props.ready) {
            this.getAdaptersInfo(this.props.currentHost, true);
        }
    }

    async getAdaptersInfo(update, updateRepo) {
        if (!this.props.currentHost) {
            return;
        }

        if (update) {
            // Do not update too often
            if (new Date().getTime() - this.state.lastUpdate > 1000) {

                const currentHost = this.props.currentHost;

                try {
                    const hostData = await this.props.socket.getHostInfo(currentHost);
                    const nodeJsVersion = hostData['Node.js'].replace('v', '');
                    const hostOs = hostData.os;

                    const repository = await this.props.socket.getRepository(currentHost, {repo: this.props.systemConfig.common.activeRepo, update: updateRepo});
                    const installed = await this.props.socket.getInstalled(currentHost);
                    const instances = await this.props.socket.getAdapterInstances();
                    const categories = {};
                    const categoriesSorted = [];

                    Object.keys(installed).forEach(value => {

                        const adapter = installed[value];

                        if (!adapter.controller && value !== 'hosts') {
                            if (!repository[value]) {
                                repository[value] = adapter;
                            }
                        }
                    });

                    Object.keys(repository).forEach(value => {

                        const adapter = repository[value];

                        if (!adapter.controller) {

                            const type = adapter.type;
                            const installedInGroup = installed[value];

                            if (!categories[type]) {
                                categories[type] = {
                                    name: type,
                                    translation: this.t(type + '_group'),
                                    expanded: false,
                                    count: 1,
                                    installed: installedInGroup ? 1 : 0
                                };
                            } else {
                                categories[type].count++;
                                if (installedInGroup) {
                                    categories[type].installed++;
                                }
                            }
                        }
                    });

                    Object.keys(instances).forEach(value => {

                        const instance = instances[value];
                        const name = instance.common.name;
                        const enabled = instance.common.enabled;

                        if (installed[name]) {
                            if (installed[name].count) {
                                installed[name].count++;
                            } else {
                                installed[name].count = 1;
                            }

                            if (enabled) {
                                if (installed[name].enabled) {
                                    installed[name].enabled++;
                                } else {
                                    installed[name].enabled = 1;
                                }
                            }
                        }
                    });

                    Object.keys(categories).forEach(value => {
                        categoriesSorted.push(categories[value]);
                    });

                    categoriesSorted.sort((a, b) => {

                        const result = b.installed - a.installed;

                        return result !== 0 ? result : a.translation  b.translation ? 1 : 0;
                    });

                    this.setState({
                        lastUpdate: Date.now(),
                        hostData,
                        hostOs,
                        nodeJsVersion,
                        repository,
                        installed,
                        instances,
                        categories: categoriesSorted,
                        init: true
                    });
                } catch(error) {
                    console.error(error);
                }
            }
        }
    }

    toggleCategory(category) {

        const categories = this.state.categories;
        categories[category].expanded = !categories[category].expanded;

        this.setState({
            categories
        });
    }

    getRows() {
        const rows = [];
        const { classes } = this.props;

        Object.keys(this.state.categories).forEach(value => {

            const category = this.state.categories[value];
            const categoryName = category.name;

            rows.push(
                <TableRow
                    key={ categoryName }
                    className={ classes.category }
                >
                    <TableCell>
                        <Grid container spacing={ 1 } alignItems="center" className={ classes.name }>
                            <Grid item>
                                <IconButton
                                    size="small"
                                    onClick={ () => this.toggleCategory(value) }
                                >
                                    { category.expanded ? <ExpandMoreIcon /> : <ChevronRightIcon />}
                                </IconButton>
                            </Grid>
                            <Grid item>
                                { category.translation }
                            </Grid>
                        </Grid>
                    </TableCell>
                    <TableCell>
                        <Typography component="span" variant="body2" className={ classes.green }>
                            { category.installed }
                        </Typography>
                        { ` ${this.t('of')} ` }
                        <Typography component="span" variant="body2" className={ classes.blue }>
                            { category.count }
                        </Typography>
                        { ` ${this.t('Adapters from this Group installed')}` }
                    </TableCell>
                    <TableCell />
                    <TableCell />
                    <TableCell />
                    <TableCell />
                    <TableCell />
                </TableRow>
            );

            if (category.expanded) {

                Object.keys(this.state.repository).forEach(value => {

                    const adapter = this.state.repository[value];

                    if (!adapter.controller && adapter.type === categoryName) {

                        const installed = this.state.installed[value];

                        const title = (adapter.title.toString() || '').replace('ioBroker Visualisation - ', '');
                        const desc = adapter.desc ? adapter.desc[this.props.lang] || adapter.desc['en'] : '';
                        const image = installed ? installed.localIcon : adapter.extIcon;

                        if (title instanceof Object || !desc) {
                            console.log(adapter);
                        }

                        rows.push(
                            <TableRow
                                key={ value }
                                hover
                            >
                                <TableCell>
                                    <Grid container spacing={ 1 } alignItems="center" className={ classes.name }>
                                        <Grid item>
                                            <Avatar
                                                variant="square"
                                                alt={ title.toString() }
                                                src={ image }
                                                className={ classes.smallAvatar }
                                            />
                                        </Grid>
                                        <Grid item>
                                            { title.toString() }
                                        </Grid>
                                    </Grid>
                                </TableCell>
                                <TableCell>
                                    { desc }
                                </TableCell>
                                <TableCell>
                                    { adapter.keywords && adapter.keywords.join(' ') }
                                </TableCell>
                                <TableCell>
                                    { installed && `${installed.version} (${installed.count}${installed.count !== installed.enabled ? '~' : ''})` }
                                </TableCell>
                                <TableCell>
                                    { adapter.version }
                                </TableCell>
                                <TableCell>
                                    { adapter.license }
                                </TableCell>
                                <TableCell>
                                    <IconButton size="small">
                                        <AddIcon />
                                    </IconButton>
                                    <IconButton size="small">
                                        <HelpIcon />
                                    </IconButton>
                                    { this.props.expertMode &&
                                        <IconButton
                                            size="small"
                                            className={ !installed ? classes.hidden : '' }
                                            onClick={ () => this.props.executeCommand('upload ' + value) }
                                        >
                                            <PublishIcon />
                                        </IconButton>
                                    }
                                    <IconButton size="small" className={ !installed ? classes.hidden : '' }>
                                        <DeleteForeverIcon />
                                    </IconButton>
                                    { this.props.expertMode &&
                                        <IconButton size="small" className={ !installed ? classes.hidden : '' }>
                                            <AddToPhotosIcon />
                                        </IconButton>
                                    }
                                    { this.props.expertMode &&
                                        <IconButton
                                            size="small"
                                            className={ !installed ? classes.hidden : '' }
                                            onClick={ () => this.props.executeCommand('rebuild ' + value) }
                                        >
                                            <BuildIcon />
                                        </IconButton>
                                    }
                                </TableCell>
                            </TableRow>
                        );
                    }
                });
            }
        });

        return rows;
    }

    render() {

        if (!this.state.init) {
            return <LinearProgress />
        }

        const { classes } = this.props;

        return (
            <Paper className={ classes.root }>
                <Grid
                    container
                    direction="column"
                    className={ classes.flexContainer }
                >
                    <Grid
                        item
                        container
                        alignItems="center"
                    >
                        <IconButton>
                            <RefreshIcon />
                        </IconButton>
                        <IconButton>
                            <GithubIcon />
                        </IconButton>

                        <TextField label={ this.t('Filter') } />

                    </Grid>
                    <TableContainer className={ classes.container }>

                            <TableHead>
                                <TableRow>
                                    <TableCell className={ classes.name }>
                                        <Typography>{ this.t('Name') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.description }>
                                        <Typography>{ this.t('Description') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.keywords }>
                                        <Typography>{ this.t('Keywords') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.installed }>
                                        <Typography>{ this.t('Installed') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.available }>
                                        <Typography>{ this.t('Available') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.license }>
                                        <Typography>{ this.t('License') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.install }>
                                        <Typography>{ this.t('Install') }</Typography>
                                    </TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                { this.getRows() }
                            </TableBody>

                    </TableContainer>
                </Grid>
            </Paper>
        );
    }
}

export default withStyles(styles)(Adapters);<|endoftext|>


<commit_before>window.onload = function() {
  // Create constants
  const section = document.querySelector('section');
  const videos = [
    { 'name' : 'crystal' },
    { 'name' : 'elf' },
    { 'name' : 'frog' },
    { 'name' : 'monster' },
    { 'name' : 'pig' },
    { 'name' : 'rabbit' }
  ];
  // Create an instance of a db object for us to store our database in
  let db;

  function init() {
    // Loop through the video titles one by one
    for(let i = 0; i < videos.length; i++) {
      // Open transaction, get object store, and get() the video by name
      let objectStore = db.transaction('videos').objectStore('videos');
      let request = objectStore.get(videos[i].name);
      request.onsuccess = function() {
        // If the result exists/is not undefined
        if(request.result) {
          // Blobs are stored in the IDB, so need to create object URLs out of these
          let mp4 = URL.createObjectURL(request.result.mp4);
          let webm = URL.createObjectURL(request.result.webm);

          displayVideo(mp4, webm, request.result.name);
        } else {
          fetchVideoFromNetwork(videos[i]);
        }
      };
    }
  }

  // Define the fetchVideoFromNetwork() function
  function fetchVideoFromNetwork(video) {
    // Fetch the MP4 and WebM version of the video using fetch() function
    let mp4Blob = fetch('videos/' + video.name + '.mp4').then(response =>
      response.blob()
    );
    let webmBlob = fetch('videos/' + video.name + '.webm').then(response =>
      response.blob()
    );;

    // Only run the next code when both promises have fulfilled
    Promise.all([mp4Blob, webmBlob]).then(function(values) {
      displayVideo(values[0], values[1], video.name);
      storeVideo(values[0], values[1], video.name);
    });
  }

  function storeVideo(mp4Blob, webmBlob, name) {
    let objectStore = db.transaction(['videos'], 'readwrite').objectStore('videos');
    let record = {
      mp4 : mp4Blob,
      webm : webmBlob,
      name : name
    }
    let request = objectStore.add(record);

    request.onsuccess = function() {
      console.log('Record addition attempt finished');
    }

    request.onerror = function() {
      console.log(request.error);
    }

  };

  // Define the displayVideo() function
  function displayVideo(mp4Blob, webmBlob, title) {
    // Create DOM elements to embed video in the page
    let article = document.createElement('article');
    let h2 = document.createElement('h2');
    h2.textContent = title;
    let video = document.createElement('video');
    video.controls = true;
    let source1 = document.createElement('source');
    source1.src = URL.createObjectURL(mp4Blob);
    source1.type = 'video/mp4';
    let source2 = document.createElement('source');
    source2.src = URL.createObjectURL(webmBlob);
    source2.type = 'video/webm';

    // Embed DOM elements into page
    section.appendChild(article);
    article.appendChild(h2);
    article.appendChild(video);
    video.appendChild(source1);
    video.appendChild(source2);
  }

  // Open our database; it is created if it doesn't already exist
  // (see onupgradeneeded below)
  let request = window.indexedDB.open('videos', 1);

  // onerror handler signifies that the database didn't open successfully
  request.onerror = function() {
    console.log('Database failed to open');
  };

  // onsuccess handler signifies that the database opened successfully
  request.onsuccess = function() {
    console.log('Database opened succesfully');

    // Store the opened database object in the db variable. This is used a lot below
    db = request.result;
    init();
  };

  // Setup the database tables if this has not already been done
  request.onupgradeneeded = function(e) {

    // Grab a reference to the opened database
    let db = e.target.result;

    // Create an objectStore to store our notes in (basically like a single table)
    // including a auto-incrementing key
    let objectStore = db.createObjectStore('videos', { keyPath: 'name' });

    // Define what data items the objectStore will contain
    objectStore.createIndex('mp4', 'mp4', { unique: false });
    objectStore.createIndex('webm', 'webm', { unique: false });

    console.log('Database setup complete');
  };
};
<commit_msg>simplifying code, trying to make the database writes work<commit_after>window.onload = function() {
  // Create constants
  const section = document.querySelector('section');
  const videos = [
    { 'name' : 'crystal' },
    { 'name' : 'elf' },
    { 'name' : 'frog' },
    { 'name' : 'monster' },
    { 'name' : 'pig' },
    { 'name' : 'rabbit' }
  ];
  // Create an instance of a db object for us to store our database in
  let db;

  function init() {
    // Loop through the video titles one by one
    for(let i = 0; i < videos.length; i++) {
      // Open transaction, get object store, and get() the video by name
      let objectStore = db.transaction('videos').objectStore('videos');
      let request = objectStore.get(videos[i].name);
      request.onsuccess = function() {
        // If the result exists/is not undefined
        if(request.result) {
          // Blobs are stored in the IDB, so need to create object URLs out of these
          let mp4 = URL.createObjectURL(request.result.mp4);
          let webm = URL.createObjectURL(request.result.webm);

          displayVideo(mp4, webm, request.result.name);
        } else {
          fetchVideoFromNetwork(videos[i]);
        }
      };
    }
  }

  // Define the fetchVideoFromNetwork() function
  function fetchVideoFromNetwork(video) {
    // Fetch the MP4 and WebM version of the video using fetch() function
    let mp4Blob = fetch('videos/' + video.name + '.mp4').then(response =>
      response.blob()
    );
    let webmBlob = fetch('videos/' + video.name + '.webm').then(response =>
      response.blob()
    );;

    // Only run the next code when both promises have fulfilled
    Promise.all([mp4Blob, webmBlob]).then(function(values) {
      displayVideo(values[0], values[1], video.name);
      storeVideo(values[0], values[1], video.name);
    });
  }

  function storeVideo(mp4Blob, webmBlob, name) {
    let objectStore = db.transaction(['videos'], 'readwrite').objectStore('videos');
    let record = {
      mp4 : mp4Blob,
      webm : webmBlob,
      name : name
    }
    let request = objectStore.add(record);

    request.onsuccess = function() {
      console.log('Record addition attempt finished');
    }

    request.onerror = function() {
      console.log(request.error);
    }

  };

  // Define the displayVideo() function
  function displayVideo(mp4Blob, webmBlob, title) {
    // Create DOM elements to embed video in the page
    let article = document.createElement('article');
    let h2 = document.createElement('h2');
    h2.textContent = title;
    let video = document.createElement('video');
    video.controls = true;
    let source1 = document.createElement('source');
    source1.src = mp4Blob;
    source1.type = 'video/mp4';
    let source2 = document.createElement('source');
    source2.src = webmBlob;
    source2.type = 'video/webm';

    // Embed DOM elements into page
    section.appendChild(article);
    article.appendChild(h2);
    article.appendChild(video);
    video.appendChild(source1);
    video.appendChild(source2);
  }

  // Open our database; it is created if it doesn't already exist
  // (see onupgradeneeded below)
  let request = window.indexedDB.open('videos', 1);

  // onerror handler signifies that the database didn't open successfully
  request.onerror = function() {
    console.log('Database failed to open');
  };

  // onsuccess handler signifies that the database opened successfully
  request.onsuccess = function() {
    console.log('Database opened succesfully');

    // Store the opened database object in the db variable. This is used a lot below
    db = request.result;
    init();
  };

  // Setup the database tables if this has not already been done
  request.onupgradeneeded = function(e) {

    // Grab a reference to the opened database
    let db = e.target.result;

    // Create an objectStore to store our notes in (basically like a single table)
    // including a auto-incrementing key
    let objectStore = db.createObjectStore('videos', { keyPath: 'name' });

    // Define what data items the objectStore will contain
    objectStore.createIndex('mp4', 'mp4', { unique: false });
    objectStore.createIndex('webm', 'webm', { unique: false });

    console.log('Database setup complete');
  };
};
<|endoftext|>


<commit_before>/*
** Module dependencies
*/
var request = require('superagent');
var _ = require('lodash');
var util = require('util');
var config = require('../config/config');
var debug = require('debug')('openfisca');
var moment = require('moment');

var prestations = {
    aspa: Number,
    acs: Number,
    cmu_c: Boolean,
    apl: Number,
    als: Number,
    alf: Number,
    af: Number,
    rsa: Number,
    asf: Number,
    cf: Number,
    ass: Number
};

function troisDerniersMois(dateDeValeur) {
    return _.map([3, 2, 1], function(nbMonths) {
        return moment(dateDeValeur || Date.now()).subtract(moment.duration(nbMonths, 'months')).format('YYYY-MM');
    });
}

function mapActivity(person, key, openfiscaObj, code) {
    var situationPro = _.find(person.situationsPro, {situation: key});
    if (situationPro) openfiscaObj.activite = code;
}

var statutMaritalMap = {
    'seul': 2,
    'mariage': 1,
    'pacs': 5,
    'relation_libre': 2
};

var ressourcesMap = {
    sali: [
        'revenusSalarie',
        'revenusNonSalarie',
        'revenusAutoEntrepreneur',
        'indJourMaternite',
        'indJourMaladie',
        'indJourMaladieProf',
        'indJourAccidentDuTravail',
        'indChomagePartiel'
    ],
    choi: [
        'allocationsChomage'
    ],
    alr: ['pensionsAlimentaires'],
    rsti: ['pensionsRetraitesRentes']
};

function mapPatrimoine(situation, targetIndividu) {
    var patrimoine = situation.patrimoine;
    if (!patrimoine) {
        return;
    }

    targetIndividu.interets_epargne_sur_livrets = 0.01 * patrimoine.epargneSurLivret;
    targetIndividu.epargne_non_remuneree = patrimoine.epargneSansRevenus;
    targetIndividu.valeur_locative_immo_non_loue = 12 * patrimoine.valeurLocativeImmoNonLoue;
    targetIndividu.valeur_locative_terrains_non_loue = 12 * patrimoine.valeurLocativeTerrainNonLoue;

    var revenusLocatifs = 0;
    patrimoine.revenusLocatifs.forEach(function(revenuLocatif) {
        if (!revenuLocatif.debutPeriode) {
            revenusLocatifs += revenuLocatif.montant;
        }
    });
    targetIndividu.revenus_locatifs = 4 * revenusLocatifs;

    var revenusDuCapital = 0;
    patrimoine.revenusDuCapital.forEach(function(revenuDuCapital) {
        if (!revenuDuCapital.debutPeriode) {
            revenusDuCapital += revenuDuCapital.montant;
        }
    });
    targetIndividu.revenus_capital = 4 * revenusDuCapital;
}

function mapIndividus(situation) {
    return _.map(situation.individus, function(individu) {
        var target = { id: individu._id };

        var dateDeNaissance = individu.dateDeNaissance;
        if (!dateDeNaissance) {
            throw new Error('L\'individu de role "' + individu.role + '" n\'a pas de date de naissance renseignée');
        }
        target.birth = moment(dateDeNaissance).format('YYYY-MM-DD');

        var statutMarital = individu.statutMarital;
        if (statutMarital) {
            target.statmarit = statutMaritalMap[statutMarital];
        }

        target.enceinte = individu.enceinte;

        // mapActivity(individu, ACTIF_OCCUPÉ, target, 0);
        mapActivity(individu, 'demandeur_emploi', target, 1);
        mapActivity(individu, 'etudiant', target, 2);
        mapActivity(individu, 'retraite', target, 3);

        var periodes = troisDerniersMois(situation.dateDeValeur);
        var ressources = _.filter(individu.ressources, function(ressource) {
            return _.contains(periodes, ressource.periode);
        });
        var rs = {};
        ressources.forEach(function(ressource) {
            if (_.isNumber(rs[ressource.type])) {
                rs[ressource.type] += ressource.montant;
            } else {
                rs[ressource.type] = ressource.montant;
            }
        });

        _.forEach(ressourcesMap, function(ressourcesList, key) {
            var sum = 0;
            ressourcesList.forEach(function(ressource) {
                if (_.isNumber(rs[ressource])) sum += rs[ressource];
            });
            target[key] = 4 * sum;
        });

        if ('demandeur' === individu.role) {
            mapPatrimoine(situation, target);
            if ('locataire' === situation.logement.type && situation.logement.colocation) {
                target.coloc = 1;
            }
        }

        return target;
    });
}

var statusOccupationMap = {
    'proprietaireprimoaccedant': 1,
    'proprietaire': 2,
    'locatairehlm': 3,
    'locatairenonmeuble': 4,
    'locatairemeublehotel': 5,
    'gratuit': 6,
    'homeless': 0 // TODO
};

function mapLogement(logement, menage) {
    var type = logement.type;
    if (type) {
        var statusOccupationId = type;
        if (logement.primoAccedant) statusOccupationId += 'primoaccedant';
        if (logement.locationType) statusOccupationId += logement.locationType;
        menage.so = statusOccupationMap[statusOccupationId];
    }
    if (logement.loyer) {
        menage.loyer = logement.loyer;
    }
    if (logement.adresse && logement.adresse.codeInsee) {
        menage.depcom = logement.adresse.codeInsee;
    }
    if (logement.membreFamilleProprietaire) {
        menage.proprietaire_proche_famille = true;
    }
}

function mapMenages(situation) {
    var demandeur = _.find(situation.individus, {role: 'demandeur'});
    var conjoint = _.find(situation.individus, {role: 'conjoint'});
    var menage = { personne_de_reference: demandeur._id };
    if (conjoint) {
        menage.conjoint = conjoint._id;
    }
    var enfants = _.pluck(_.filter(situation.individus, {role: 'enfant'}), '_id');
    var personnesACharge = _.pluck(_.filter(situation.individus, {role: 'personneACharge'}), '_id');
    menage.enfants = enfants.concat(personnesACharge);
    mapLogement(situation.logement, menage);

    return [menage];
}

function mapFamilles(situation) {
    var parents = _.pluck(_.filter(situation.individus, function(individu) {
        return _.contains(['demandeur', 'conjoint'], individu.role);
    }), '_id');

    var enfants = _.pluck(_.filter(situation.individus, {role: 'enfant'}), '_id');
    var personnesACharge = _.pluck(_.filter(situation.individus, {role: 'personneACharge'}), '_id');
    enfants = enfants.concat(personnesACharge);

    return [{ parents: parents, enfants: enfants }];
}

function mapFoyersFiscaux(situation) {
    var declarants = _.filter(situation.individus, function(individu) {
        return _.contains(['demandeur', 'conjoint'], individu.role);
    });

    var enfants = _.pluck(_.filter(situation.individus, {role: 'enfant'}), '_id');
    var personnesACharge = _.pluck(_.filter(situation.individus, {role: 'personneACharge'}), '_id');
    enfants = enfants.concat(personnesACharge);

    return [{
        declarants: _.pluck(declarants, '_id'),
        personnes_a_charge: enfants
    }];
}

function buildRequest(situation) {
    return {
        intermediate_variables: true,
        scenarios: [{
            test_case: {
                familles: mapFamilles(situation),
                foyers_fiscaux: mapFoyersFiscaux(situation),
                individus: mapIndividus(situation),
                menages: mapMenages(situation)
            },
            date: moment(situation.dateDeValeur || Date.now()).format('YYYY-MM-DD')
        }],
        variables: _.keys(prestations)
    };
}

function calculate(situation, callback) {
    try {
        request
            .post(config.openfiscaApi + '/api/1/calculate')
            .send(buildRequest(situation))
            .end(function(err, response) {
                if (err) return callback(err);
                if (response.error) {
                    console.log('Response body: ', util.inspect(response.body, { showHidden: true, depth: null }));
                    return callback({ apiError: 'Communication error with OpenFisca' });
                }

                callback(null, response.body);
            });
    } catch(err) {
        callback(err);
    }
}

function simulate(situation, callback) {
    calculate(situation, function(err, response) {
        if (err)  return callback(err);

        var result = _.mapValues(prestations, function(type, name) {
            var value = response.value[0].familles[0][name];
            if (type === Number) return Math.round((value / 12) * 100) / 100;
            return value;
        });
        callback(null, result);
    });
}

function ping() {
    debug('PING?');
    request.get(config.openfiscaApi + '/api/1/fields').end(function(err, response) {
        if (err) return console.log('OpenFisca: Error: ' + err);
        if (response.error) return console.log('OpenFisca: Error: ' + response.status);
        debug('PONG!');
    });
}

/*
** Exports
*/
exports.mapPatrimoine = mapPatrimoine;
exports.mapIndividus = mapIndividus;
exports.mapFamilles = mapFamilles;
exports.mapMenages = mapMenages;
exports.mapLogement = mapLogement;
exports.mapFoyersFiscaux = mapFoyersFiscaux;
exports.calculate = calculate;
exports.simulate = simulate;
exports.buildRequest = buildRequest;
exports.ping = ping;
<commit_msg>Prise en charge de la ressource AAH<commit_after>/*
** Module dependencies
*/
var request = require('superagent');
var _ = require('lodash');
var util = require('util');
var config = require('../config/config');
var debug = require('debug')('openfisca');
var moment = require('moment');

var prestations = {
    aspa: Number,
    acs: Number,
    cmu_c: Boolean,
    apl: Number,
    als: Number,
    alf: Number,
    af: Number,
    rsa: Number,
    asf: Number,
    cf: Number,
    ass: Number
};

function troisDerniersMois(dateDeValeur) {
    return _.map([3, 2, 1], function(nbMonths) {
        return moment(dateDeValeur || Date.now()).subtract(moment.duration(nbMonths, 'months')).format('YYYY-MM');
    });
}

function mapActivity(person, key, openfiscaObj, code) {
    var situationPro = _.find(person.situationsPro, {situation: key});
    if (situationPro) openfiscaObj.activite = code;
}

var statutMaritalMap = {
    'seul': 2,
    'mariage': 1,
    'pacs': 5,
    'relation_libre': 2
};

var ressourcesMap = {
    sali: [
        'revenusSalarie',
        'revenusNonSalarie',
        'revenusAutoEntrepreneur',
        'indJourMaternite',
        'indJourMaladie',
        'indJourMaladieProf',
        'indJourAccidentDuTravail',
        'indChomagePartiel'
    ],
    choi: [
        'allocationsChomage'
    ],
    alr: ['pensionsAlimentaires'],
    rsti: ['pensionsRetraitesRentes'],
    aah: ['aah']
};

function mapPatrimoine(situation, targetIndividu) {
    var patrimoine = situation.patrimoine;
    if (!patrimoine) {
        return;
    }

    targetIndividu.interets_epargne_sur_livrets = 0.01 * patrimoine.epargneSurLivret;
    targetIndividu.epargne_non_remuneree = patrimoine.epargneSansRevenus;
    targetIndividu.valeur_locative_immo_non_loue = 12 * patrimoine.valeurLocativeImmoNonLoue;
    targetIndividu.valeur_locative_terrains_non_loue = 12 * patrimoine.valeurLocativeTerrainNonLoue;

    var revenusLocatifs = 0;
    patrimoine.revenusLocatifs.forEach(function(revenuLocatif) {
        if (!revenuLocatif.debutPeriode) {
            revenusLocatifs += revenuLocatif.montant;
        }
    });
    targetIndividu.revenus_locatifs = 4 * revenusLocatifs;

    var revenusDuCapital = 0;
    patrimoine.revenusDuCapital.forEach(function(revenuDuCapital) {
        if (!revenuDuCapital.debutPeriode) {
            revenusDuCapital += revenuDuCapital.montant;
        }
    });
    targetIndividu.revenus_capital = 4 * revenusDuCapital;
}

function mapIndividus(situation) {
    return _.map(situation.individus, function(individu) {
        var target = { id: individu._id };

        var dateDeNaissance = individu.dateDeNaissance;
        if (!dateDeNaissance) {
            throw new Error('L\'individu de role "' + individu.role + '" n\'a pas de date de naissance renseignée');
        }
        target.birth = moment(dateDeNaissance).format('YYYY-MM-DD');

        var statutMarital = individu.statutMarital;
        if (statutMarital) {
            target.statmarit = statutMaritalMap[statutMarital];
        }

        target.enceinte = individu.enceinte;

        // mapActivity(individu, ACTIF_OCCUPÉ, target, 0);
        mapActivity(individu, 'demandeur_emploi', target, 1);
        mapActivity(individu, 'etudiant', target, 2);
        mapActivity(individu, 'retraite', target, 3);

        var periodes = troisDerniersMois(situation.dateDeValeur);
        var ressources = _.filter(individu.ressources, function(ressource) {
            return _.contains(periodes, ressource.periode);
        });
        var rs = {};
        ressources.forEach(function(ressource) {
            if (_.isNumber(rs[ressource.type])) {
                rs[ressource.type] += ressource.montant;
            } else {
                rs[ressource.type] = ressource.montant;
            }
        });

        _.forEach(ressourcesMap, function(ressourcesList, key) {
            var sum = 0;
            ressourcesList.forEach(function(ressource) {
                if (_.isNumber(rs[ressource])) sum += rs[ressource];
            });
            target[key] = 4 * sum;
        });

        if ('demandeur' === individu.role) {
            mapPatrimoine(situation, target);
            if ('locataire' === situation.logement.type && situation.logement.colocation) {
                target.coloc = 1;
            }
        }

        return target;
    });
}

var statusOccupationMap = {
    'proprietaireprimoaccedant': 1,
    'proprietaire': 2,
    'locatairehlm': 3,
    'locatairenonmeuble': 4,
    'locatairemeublehotel': 5,
    'gratuit': 6,
    'homeless': 0 // TODO
};

function mapLogement(logement, menage) {
    var type = logement.type;
    if (type) {
        var statusOccupationId = type;
        if (logement.primoAccedant) statusOccupationId += 'primoaccedant';
        if (logement.locationType) statusOccupationId += logement.locationType;
        menage.so = statusOccupationMap[statusOccupationId];
    }
    if (logement.loyer) {
        menage.loyer = logement.loyer;
    }
    if (logement.adresse && logement.adresse.codeInsee) {
        menage.depcom = logement.adresse.codeInsee;
    }
    if (logement.membreFamilleProprietaire) {
        menage.proprietaire_proche_famille = true;
    }
}

function mapMenages(situation) {
    var demandeur = _.find(situation.individus, {role: 'demandeur'});
    var conjoint = _.find(situation.individus, {role: 'conjoint'});
    var menage = { personne_de_reference: demandeur._id };
    if (conjoint) {
        menage.conjoint = conjoint._id;
    }
    var enfants = _.pluck(_.filter(situation.individus, {role: 'enfant'}), '_id');
    var personnesACharge = _.pluck(_.filter(situation.individus, {role: 'personneACharge'}), '_id');
    menage.enfants = enfants.concat(personnesACharge);
    mapLogement(situation.logement, menage);

    return [menage];
}

function mapFamilles(situation) {
    var parents = _.pluck(_.filter(situation.individus, function(individu) {
        return _.contains(['demandeur', 'conjoint'], individu.role);
    }), '_id');

    var enfants = _.pluck(_.filter(situation.individus, {role: 'enfant'}), '_id');
    var personnesACharge = _.pluck(_.filter(situation.individus, {role: 'personneACharge'}), '_id');
    enfants = enfants.concat(personnesACharge);

    return [{ parents: parents, enfants: enfants }];
}

function mapFoyersFiscaux(situation) {
    var declarants = _.filter(situation.individus, function(individu) {
        return _.contains(['demandeur', 'conjoint'], individu.role);
    });

    var enfants = _.pluck(_.filter(situation.individus, {role: 'enfant'}), '_id');
    var personnesACharge = _.pluck(_.filter(situation.individus, {role: 'personneACharge'}), '_id');
    enfants = enfants.concat(personnesACharge);

    return [{
        declarants: _.pluck(declarants, '_id'),
        personnes_a_charge: enfants
    }];
}

function buildRequest(situation) {
    return {
        intermediate_variables: true,
        scenarios: [{
            test_case: {
                familles: mapFamilles(situation),
                foyers_fiscaux: mapFoyersFiscaux(situation),
                individus: mapIndividus(situation),
                menages: mapMenages(situation)
            },
            date: moment(situation.dateDeValeur || Date.now()).format('YYYY-MM-DD')
        }],
        variables: _.keys(prestations)
    };
}

function calculate(situation, callback) {
    try {
        request
            .post(config.openfiscaApi + '/api/1/calculate')
            .send(buildRequest(situation))
            .end(function(err, response) {
                if (err) return callback(err);
                if (response.error) {
                    console.log('Response body: ', util.inspect(response.body, { showHidden: true, depth: null }));
                    return callback({ apiError: 'Communication error with OpenFisca' });
                }

                callback(null, response.body);
            });
    } catch(err) {
        callback(err);
    }
}

function simulate(situation, callback) {
    calculate(situation, function(err, response) {
        if (err)  return callback(err);

        var result = _.mapValues(prestations, function(type, name) {
            var value = response.value[0].familles[0][name];
            if (type === Number) return Math.round((value / 12) * 100) / 100;
            return value;
        });
        callback(null, result);
    });
}

function ping() {
    debug('PING?');
    request.get(config.openfiscaApi + '/api/1/fields').end(function(err, response) {
        if (err) return console.log('OpenFisca: Error: ' + err);
        if (response.error) return console.log('OpenFisca: Error: ' + response.status);
        debug('PONG!');
    });
}

/*
** Exports
*/
exports.mapPatrimoine = mapPatrimoine;
exports.mapIndividus = mapIndividus;
exports.mapFamilles = mapFamilles;
exports.mapMenages = mapMenages;
exports.mapLogement = mapLogement;
exports.mapFoyersFiscaux = mapFoyersFiscaux;
exports.calculate = calculate;
exports.simulate = simulate;
exports.buildRequest = buildRequest;
exports.ping = ping;
<|endoftext|>


<commit_before>module.exports = function(config){
  config.set({

    basePath : '',

    files : [
      'bower_components/farmbuild-core/dist/farmbuild-core.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/farmbuild-farmdata/dist/farmbuild-farmdata.js',
      'src/nutrient-calculator.js',
      'src/google-analytic/index.src.js',
      'src/animals-purchased/animalTypes.conf.src.js',
      'src/animals-purchased/index.src.js',
      'src/validations/index.src.js',
      'src/milk-sold/index.src.js',
      'src/index.js',
      'src/*.js',
      'src/**/*.js'
    ],

    autoWatch : true,

    frameworks: ['jasmine'],

    browsers : ['Chrome'],

    plugins : [
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-jasmine',
            'karma-junit-reporter'
            ],

    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }

  });
};
<commit_msg>Added animals-culled<commit_after>module.exports = function(config){
  config.set({

    basePath : '',

    files : [
      'bower_components/farmbuild-core/dist/farmbuild-core.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/farmbuild-farmdata/dist/farmbuild-farmdata.js',
      'src/nutrient-calculator.js',
      'src/google-analytic/index.src.js',
      'src/animalTypes.conf.src.js',
      'src/animals-purchased/index.src.js',
      'src/validations/index.src.js',
      'src/milk-sold/index.src.js',
      'src/index.js',
      'src/*.js',
      'src/**/*.js'
    ],

    autoWatch : true,

    frameworks: ['jasmine'],

    browsers : ['Chrome'],

    plugins : [
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-jasmine',
            'karma-junit-reporter'
            ],

    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }

  });
};
<|endoftext|>