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

/**
 * External dependencies
 */
import {
  StoryEditor,
  InterfaceSkeleton,
} from '@googleforcreators/story-editor';

/**
 * Internal dependencies
 */
import { getMedia, saveStoryById, getFonts } from './api';
import { HeaderLayout } from './header';
import { LOCAL_STORAGE_CONTENT_KEY } from './constants';

export default {
  title: 'Playground/Stories Editor',
};

export const _default = () => {
  const content = window.localStorage.getItem(LOCAL_STORAGE_CONTENT_KEY);
  const story = content ? JSON.parse(content) : {};
  const apiCallbacks = { saveStoryById, getMedia, getFonts };

  return (
    <StoryEditor config={{ apiCallbacks }} initialEdits={{ story }}>
      <InterfaceSkeleton header={<HeaderLayout />} />
    </StoryEditor>
  );
};
<commit_msg>Fix storybook element registration error (#10986)<commit_after>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import {
  StoryEditor,
  InterfaceSkeleton,
} from '@googleforcreators/story-editor';
import { elementTypes } from '@googleforcreators/element-library';
import { registerElementType } from '@googleforcreators/elements';

/**
 * Internal dependencies
 */
import { getMedia, saveStoryById, getFonts } from './api';
import { HeaderLayout } from './header';
import { LOCAL_STORAGE_CONTENT_KEY } from './constants';

export default {
  title: 'Playground/Stories Editor',
};

export const _default = () => {
  const content = window.localStorage.getItem(LOCAL_STORAGE_CONTENT_KEY);
  const story = content ? JSON.parse(content) : {};
  const apiCallbacks = { saveStoryById, getMedia, getFonts };

  // @todo This is a temporary fix for element type registration error in storybook, not generally required.
  elementTypes.forEach(registerElementType);

  return (
    <StoryEditor config={{ apiCallbacks }} initialEdits={{ story }}>
      <InterfaceSkeleton header={<HeaderLayout />} />
    </StoryEditor>
  );
};
<|endoftext|>


<commit_before>// Karma configuration
module.exports = function(config) {
    config.set({
		// base path, that will be used to resolve files and exclude
		basePath : '',

		// list of files / patterns to load in the browser
		files : [
		  JASMINE,
		  JASMINE_ADAPTER,
		  'app/bower_components/angular/angular.js',
		  'app/bower_components/angular-mocks/angular-mocks.js',
		  'app/scripts/*.js',
		  'app/scripts/**/*.js',
		  'test/mock/**/*.js',
		  'test/spec/**/*.js'
		],

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

		// List of frameworks
		frameworks : ["jasmine"],

		// test results reporter to use
		// possible values: dots || progress || growl
		reporters : ['progress'],

		// web server port
		port : 8080,

		// 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 : LOG_INFO,

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

		// Start these browsers, currently available:
		// - Chrome
		// - ChromeCanary
		// - Firefox
		// - Opera
		// - Safari (only Mac)
		// - PhantomJS
		// - IE (only Windows)
		browsers : ['Chrome'],

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout : 20000,

		// Continuous Integration mode
		// if true, it capture browsers, run tests and exit
		singleRun : false
    });
};
<commit_msg>Align the Karma configuration to the latest version<commit_after>// Karma configuration
module.exports = function(config) {
    config.set({
		// base path, that will be used to resolve files and exclude
		basePath : '',

		// list of files / patterns to load in the browser
		files : [
		  'app/bower_components/angular/angular.js',
		  'app/bower_components/angular-mocks/angular-mocks.js',
		  'app/bower_components/angular-resource/angular-resource.js',
		  'app/scripts/*.js',
		  'app/scripts/**/*.js',
		  'test/mock/**/*.js',
		  'test/spec/**/*.js'
		],

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

		// List of frameworks
		frameworks : ["jasmine"],

		// test results reporter to use
		// possible values: dots || progress || growl
		reporters : ['progress'],

		// web server port
		port : 8080,

		// 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,

		// Start these browsers, currently available:
		// - Chrome
		// - ChromeCanary
		// - Firefox
		// - Opera
		// - Safari (only Mac)
		// - PhantomJS
		// - IE (only Windows)
		browsers : ['Chrome'],

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout : 20000,

		// Continuous Integration mode
		// if true, it capture browsers, run tests and exit
		singleRun : false
    });
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Tue Dec 08 2015 23:01:01 GMT-0800 (Pacific Standard Time)

module.exports = function (config) {
  // Check out https://saucelabs.com/platforms for expanding browser coverage
  var customLaunchers = {
    sl_chrome: {
      base: 'SauceLabs',
      browserName: 'chrome',
      platform: 'Windows 10',
      version: '46'
    },
    sl_firefox: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '30'
    }
  };

  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', 'jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'spec/helpers/marble-testing.js',
      'spec/helpers/test-helper.js',
      'spec/**/*-spec.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: {
      'spec/**/*.js': ['browserify']
    },

    // 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_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
    customLaunchers: customLaunchers,
    browsers: process.env.TRAVIS ? Object.keys(customLaunchers) : ['Chrome'],

    // 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,

    sauceLabs: {
      testName: 'RxJS 5 browser test'
    }
  });
};<commit_msg>chore(test): expand browser coverage<commit_after>// Karma configuration
// Generated on Tue Dec 08 2015 23:01:01 GMT-0800 (Pacific Standard Time)

module.exports = function (config) {
  // Check out https://saucelabs.com/platforms for expanding browser coverage
  var customLaunchers = {
    sl_chrome: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '47'
    },
    sl_chrome_beta: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: 'beta'
    },
    sl_chrome_dev: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: 'dev'
    },
    sl_firefox: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '42'
    },
    sl_firefox_beta: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: 'beta'
    },
    sl_firefox_dev: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: 'dev'
    },
    sl_safari9: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.11',
      version: '9.0'
    },
    sl_ios9: {
      base: 'SauceLabs',
      browserName: 'iphone',
      platform: 'OS X 10.10',
      version: '9.1'
    },
    sl_android5: {
      base: 'SauceLabs',
      browserName: 'android',
      platform: 'Linux',
      version: '5.1'
    }
  };

  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', 'jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'spec/helpers/marble-testing.js',
      'spec/helpers/test-helper.js',
      'spec/**/*-spec.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: {
      'spec/**/*.js': ['browserify']
    },

    // 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_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
    customLaunchers: customLaunchers,
    browsers: process.env.TRAVIS ? Object.keys(customLaunchers) : ['Chrome'],

    // 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,

    sauceLabs: {
      testName: 'RxJS 5 browser test',
      options: {
        'command-timeout': 600,
        'idle-timeout': 600,
        'max-duration': 5400
      }
    }
  });
};<|endoftext|>


<commit_before>// Dependencies
// =============================================================================
const pkg       = require('./package');
const saucelabs = require('./saucelabs.config');

// Variables
// =============================================================================
const files = {
    fixtures: './tests/fixtures/**/*',
    test    : './tests/**/*.test.js'
};

// Settings
// =============================================================================
const settings = {
    base: {
        browsers: [
            'ChromeHeadless'
        ],
        files: [
            'node_modules/@babel/polyfill/dist/polyfill.js',
            files.test,
            // Served only (Access in tests by prepending /base/ to path)
            { pattern: files.fixtures, included: false, served: true, watched: true }
        ],
        preprocessors: {
            [files.fixtures]: ['file-fixtures'],
            [files.test]    : ['eslint', 'webpack', 'sourcemap']
        },
        frameworks: ['mocha', 'chai'],
        reporters : ['mocha'],
        fileFixtures: {
            stripPrefix: 'tests/fixtures/'
        },
        webpack   : {
            mode   : 'development',
            module : {
                rules: [
                    {
                        test   : /\.js$/,
                        exclude: [/node_modules/],
                        use    : [
                            {
                                loader : 'babel-loader',
                                options: {
                                    presets: [
                                        [
                                            '@babel/env',
                                            {
                                                targets: {
                                                    browsers: ['ie >= 9']
                                                }
                                            }
                                        ]
                                    ],
                                    plugins: [
                                        'transform-custom-element-classes'
                                    ]
                                },
                            }
                        ]
                    }
                ]
            }
        },
        webpackMiddleware: {
            // https://webpack.js.org/configuration/stats/
            stats: 'minimal'
        },
        mochaReporter: {
            // https://www.npmjs.com/package/karma-mocha-reporter
            output: 'autowatch'
        },
        autoWatch                 : false,
        browserDisconnectTimeout  : 1000*2,  // default 2000
        browserDisconnectTolerance: 1,       // default 0
        browserNoActivityTimeout  : 1000*10, // default 10000
        captureTimeout            : 1000*60, // default 60000
        colors                    : true,
        concurrency               : Infinity,
        port                      : 9876,
        singleRun                 : true
    },
    coverage: {
        get reporters() {
            return [].concat(settings.base.reporters, 'coverage');
        },
        get webpack() {
            const webpackConfig = Object.assign({}, settings.base.webpack);
            const babelPluginsConfig = webpackConfig.module.rules[0].use[0].options.plugins;

            babelPluginsConfig.push(['istanbul', { exclude: 'tests/*' }]);

            return webpackConfig;
        },
        // Code coverage
        // https://www.npmjs.com/package/karma-coverage
        coverageReporter: {
            reporters: [
                { type: 'html' },
                { type: 'lcovonly' },
                { type: 'text-summary' }
            ]
        }
    },
    local: {
        get webpack() {
            const webpackConfig = Object.assign({}, settings.base.webpack);

            webpackConfig.devtool = 'inline-source-map';

            return webpackConfig;
        },
    },
    remote: {
        // Use custom hostname to prevent Safari disconnects
        // https://support.saucelabs.com/hc/en-us/articles/115010079868-Issues-with-Safari-and-Karma-Test-Runner
        hostname: 'TRAVIS' in process.env ? 'travis.dev' : 'localhost',
        get reporters() {
            return [].concat(settings.base.reporters, 'saucelabs');
        },
        sauceLabs: {
            username         : saucelabs.username || process.env.SAUCE_USERNAME,
            accessKey        : saucelabs.accessKey || process.env.SAUCE_ACCESS_KEY,
            testName         : `${pkg.name} (karma)`,
            recordScreenshots: false,
            recordVideo      : false
        }
    }
};

// Functions
// =============================================================================
function message(text, level = 'log') {
    // Credit: Thomas Brierley
    // https://stackoverflow.com/a/51506718/4903063
    const wrap = (s, w = 60) => {
        s = s.replace(new RegExp(`(?![^\\n]{1,${w}}$)([^\\n]{1,${w}})\\s`, 'g'), '$1\n');
        s = s.replace(/\n\s/g, '\n');

        return s;
    };

    // eslint-disable-next-line
    console[level]([
        '============================================================\n',
        `${wrap(text)}\n`,
        '============================================================\n'
    ].join(''));
}

// Export
// =============================================================================
module.exports = function(config) {
    const isRemoteCoverage = Boolean(process.argv.indexOf('--remotecoverage') > -1);
    const isRemoteTest = Boolean(process.argv.indexOf('--remotetest') > -1);
    const testConfig = Object.assign({}, settings.base);

    // Remote test
    if (isRemoteTest) {
        message('KARMA: Browser Tests');

        Object.assign(testConfig, settings.remote, {
            // SauceLabs browers
            // https://wiki.saucelabs.com/display/DOCS/Platform+Configurator#/
            customLaunchers: {
                sl_chrome: {
                    base       : 'SauceLabs',
                    browserName: 'Chrome',
                    platform   : 'Windows 10',
                    version    : '48.0'
                },
                sl_edge: {
                    base       : 'SauceLabs',
                    browserName: 'MicrosoftEdge',
                    platform   : 'Windows 10',
                    version    : '14.14393'
                },
                sl_firefox: {
                    base       : 'SauceLabs',
                    browserName: 'Firefox',
                    platform   : 'Windows 10',
                    version    : '30'
                },
                sl_ie_11: {
                    base       : 'SauceLabs',
                    browserName: 'Internet Explorer',
                    platform   : 'Windows 10',
                    version    : '11.0'
                },
                sl_ie_10: {
                    base       : 'SauceLabs',
                    browserName: 'Internet Explorer',
                    platform   : 'Windows 8',
                    version    : '10.0'
                },
                sl_ie_9: {
                    base       : 'SauceLabs',
                    browserName: 'Internet Explorer',
                    platform   : 'Windows 7',
                    version    : '9.0'
                },
                sl_safari: {
                    base       : 'SauceLabs',
                    browserName: 'Safari',
                    platform   : 'OS X 10.10',
                    version    : '8.0'
                }
            },
            get browsers() {
                return Object.keys(this.customLaunchers);
            }
        });
    }
    // Remove coverage
    else if (isRemoteCoverage) {
        message('KARMA: Code Coverage');

        Object.assign(testConfig, settings.remote, settings.coverage);
    }
    // Local
    else {
        message(`KARMA: localhost:${testConfig.port}/debug.html`);

        Object.assign(testConfig, settings.local, settings.coverage);
    }

    // Logging: LOG_DISABLE, LOG_ERROR, LOG_WARN, LOG_INFO, LOG_DEBUG
    testConfig.logLevel = config.LOG_INFO;
    config.set(testConfig);
};
<commit_msg>Use single version of IE for testing<commit_after>// Dependencies
// =============================================================================
const pkg       = require('./package');
const saucelabs = require('./saucelabs.config');

// Variables
// =============================================================================
const files = {
    fixtures: './tests/fixtures/**/*',
    test    : './tests/**/*.test.js'
};

// Settings
// =============================================================================
const settings = {
    base: {
        browsers: [
            'ChromeHeadless'
        ],
        files: [
            'node_modules/@babel/polyfill/dist/polyfill.js',
            files.test,
            // Served only (Access in tests by prepending /base/ to path)
            { pattern: files.fixtures, included: false, served: true, watched: true }
        ],
        preprocessors: {
            [files.fixtures]: ['file-fixtures'],
            [files.test]    : ['eslint', 'webpack', 'sourcemap']
        },
        frameworks: ['mocha', 'chai'],
        reporters : ['mocha'],
        fileFixtures: {
            stripPrefix: 'tests/fixtures/'
        },
        webpack   : {
            mode   : 'development',
            module : {
                rules: [
                    {
                        test   : /\.js$/,
                        exclude: [/node_modules/],
                        use    : [
                            {
                                loader : 'babel-loader',
                                options: {
                                    presets: [
                                        [
                                            '@babel/env',
                                            {
                                                targets: {
                                                    browsers: ['ie >= 9']
                                                }
                                            }
                                        ]
                                    ],
                                    plugins: [
                                        'transform-custom-element-classes'
                                    ]
                                },
                            }
                        ]
                    }
                ]
            }
        },
        webpackMiddleware: {
            // https://webpack.js.org/configuration/stats/
            stats: 'minimal'
        },
        mochaReporter: {
            // https://www.npmjs.com/package/karma-mocha-reporter
            output: 'autowatch'
        },
        autoWatch                 : false,
        browserDisconnectTimeout  : 1000*2,  // default 2000
        browserDisconnectTolerance: 1,       // default 0
        browserNoActivityTimeout  : 1000*10, // default 10000
        captureTimeout            : 1000*60, // default 60000
        colors                    : true,
        concurrency               : Infinity,
        port                      : 9876,
        singleRun                 : true
    },
    coverage: {
        get reporters() {
            return [].concat(settings.base.reporters, 'coverage');
        },
        get webpack() {
            const webpackConfig = Object.assign({}, settings.base.webpack);
            const babelPluginsConfig = webpackConfig.module.rules[0].use[0].options.plugins;

            babelPluginsConfig.push(['istanbul', { exclude: 'tests/*' }]);

            return webpackConfig;
        },
        // Code coverage
        // https://www.npmjs.com/package/karma-coverage
        coverageReporter: {
            reporters: [
                { type: 'html' },
                { type: 'lcovonly' },
                { type: 'text-summary' }
            ]
        }
    },
    local: {
        get webpack() {
            const webpackConfig = Object.assign({}, settings.base.webpack);

            webpackConfig.devtool = 'inline-source-map';

            return webpackConfig;
        },
    },
    remote: {
        // Use custom hostname to prevent Safari disconnects
        // https://support.saucelabs.com/hc/en-us/articles/115010079868-Issues-with-Safari-and-Karma-Test-Runner
        hostname: 'TRAVIS' in process.env ? 'travis.dev' : 'localhost',
        get reporters() {
            return [].concat(settings.base.reporters, 'saucelabs');
        },
        sauceLabs: {
            username         : saucelabs.username || process.env.SAUCE_USERNAME,
            accessKey        : saucelabs.accessKey || process.env.SAUCE_ACCESS_KEY,
            testName         : `${pkg.name} (karma)`,
            recordScreenshots: false,
            recordVideo      : false
        }
    }
};

// Functions
// =============================================================================
function message(text, level = 'log') {
    // Credit: Thomas Brierley
    // https://stackoverflow.com/a/51506718/4903063
    const wrap = (s, w = 60) => {
        s = s.replace(new RegExp(`(?![^\\n]{1,${w}}$)([^\\n]{1,${w}})\\s`, 'g'), '$1\n');
        s = s.replace(/\n\s/g, '\n');

        return s;
    };

    // eslint-disable-next-line
    console[level]([
        '============================================================\n',
        `${wrap(text)}\n`,
        '============================================================\n'
    ].join(''));
}

// Export
// =============================================================================
module.exports = function(config) {
    const isRemoteCoverage = Boolean(process.argv.indexOf('--remotecoverage') > -1);
    const isRemoteTest = Boolean(process.argv.indexOf('--remotetest') > -1);
    const testConfig = Object.assign({}, settings.base);

    // Remote test
    if (isRemoteTest) {
        message('KARMA: Browser Tests');

        Object.assign(testConfig, settings.remote, {
            // SauceLabs browers
            // https://wiki.saucelabs.com/display/DOCS/Platform+Configurator#/
            customLaunchers: {
                sl_chrome: {
                    base       : 'SauceLabs',
                    browserName: 'Chrome',
                    platform   : 'Windows 10',
                    version    : '48.0'
                },
                sl_edge: {
                    base       : 'SauceLabs',
                    browserName: 'MicrosoftEdge',
                    platform   : 'Windows 10',
                    version    : '14.14393'
                },
                sl_firefox: {
                    base       : 'SauceLabs',
                    browserName: 'Firefox',
                    platform   : 'Windows 10',
                    version    : '30'
                },
                sl_ie_9: {
                    base       : 'SauceLabs',
                    browserName: 'Internet Explorer',
                    platform   : 'Windows 7',
                    version    : '9.0'
                },
                sl_safari: {
                    base       : 'SauceLabs',
                    browserName: 'Safari',
                    platform   : 'OS X 10.10',
                    version    : '8.0'
                }
            },
            get browsers() {
                return Object.keys(this.customLaunchers);
            }
        });
    }
    // Remove coverage
    else if (isRemoteCoverage) {
        message('KARMA: Code Coverage');

        Object.assign(testConfig, settings.remote, settings.coverage);
    }
    // Local
    else {
        message(`KARMA: localhost:${testConfig.port}/debug.html`);

        Object.assign(testConfig, settings.local, settings.coverage);
    }

    // Logging: LOG_DISABLE, LOG_ERROR, LOG_WARN, LOG_INFO, LOG_DEBUG
    testConfig.logLevel = config.LOG_INFO;
    config.set(testConfig);
};
<|endoftext|>


<commit_before>module.exports = function (config) {
  config.set({
    basePath: './',
    frameworks: ['jasmine'],
    browsers: ['Chrome', 'Firefox', 'PhantomJS'],
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'dist/ng-restful-collection.js',
      'tests/**/*.js'
    ],
    captureTimeout: 60000,
    colors: true,
    logLevel: config.LOG_INFO,
    port: 9876,
    plugins: [
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-phantomjs-launcher',
      'karma-coverage'
    ],
    runnerPort: 9100,
    singleRun: true,
    autoWatch: false,
    coverageReporter: {
      type: 'lcov',
      dir: 'coverage/'
    },
    preprocessors: {
      'dist/ng-restful-collection.js': ['coverage']
    },
    reporters: ['coverage']
  });
};<commit_msg>refactor: add progress reporter back in for karma tests<commit_after>module.exports = function (config) {
  config.set({
    basePath: './',
    frameworks: ['jasmine'],
    browsers: ['Chrome', 'Firefox', 'PhantomJS'],
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'dist/ng-restful-collection.js',
      'tests/**/*.js'
    ],
    captureTimeout: 60000,
    colors: true,
    logLevel: config.LOG_INFO,
    port: 9876,
    plugins: [
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-phantomjs-launcher',
      'karma-coverage'
    ],
    runnerPort: 9100,
    singleRun: true,
    autoWatch: false,
    coverageReporter: {
      type: 'lcov',
      dir: 'coverage/'
    },
    preprocessors: {
      'dist/ng-restful-collection.js': ['coverage']
    },
    reporters: ['progress', 'coverage']
  });
};<|endoftext|>


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

    port: 9876,

    logLevel: config.LOG_INFO,

    autoWatch: true,
    singleRun: false,
    colors: true,

    plugins: [
      'karma-jasmine',
      'karma-sinon',
      'karma-spec-reporter',
      'karma-phantomjs-launcher',
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-browserify',
      'karma-sourcemap-loader'
    ],

    browsers: process.env.CI === true ? ['PhantomJS'] : [],

    frameworks: ['jasmine', 'sinon', 'browserify'],

    reporters: ['spec'],

    files: [
      'spec/helpers/**/*.coffee',
      'spec/**/*-behavior.coffee',
      'spec/**/*-spec.coffee'
    ],

    preprocessors: {
      'src/**/*.coffee': ['browserify', 'sourcemap'],
      'spec/**/*.coffee': ['browserify', 'sourcemap']
    },

    browserify: {
      extensions: ['.coffee'],
      transform: ['coffeeify'],
      watch: true,
      debug: true
    }
  });
};
<commit_msg>Revert "Conditionally set browser for karma"<commit_after>module.exports = function (config) {
  config.set({

    port: 9876,

    logLevel: config.LOG_INFO,

    autoWatch: true,
    singleRun: false,
    colors: true,

    plugins: [
      'karma-jasmine',
      'karma-sinon',
      'karma-spec-reporter',
      'karma-phantomjs-launcher',
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-browserify',
      'karma-sourcemap-loader'
    ],

    browsers: ['PhantomJS'],

    frameworks: ['jasmine', 'sinon', 'browserify'],

    reporters: ['spec'],

    files: [
      'spec/helpers/**/*.coffee',
      'spec/**/*-behavior.coffee',
      'spec/**/*-spec.coffee'
    ],

    preprocessors: {
      'src/**/*.coffee': ['browserify', 'sourcemap'],
      'spec/**/*.coffee': ['browserify', 'sourcemap']
    },

    browserify: {
      extensions: ['.coffee'],
      transform: ['coffeeify'],
      watch: true,
      debug: true
    }
  });
};
<|endoftext|>


<commit_before>module.exports = function(config) {
    config.set({
        frameworks: [ 'browserify', 'jasmine-ajax', 'jasmine' ],

        files: [
            'src/test/js/**/*.js'
        ],

        preprocessors: {
            'src/test/js/**/*.js': [ 'browserify' ]
        },

        logLevel: config.LOG_INFO,

        singleRun: true,

        autoWatch: false,

        reporters: ['dots'],

        browsers: ['Chrome'],

        plugins: [
            'karma-browserify',
            'karma-chrome-launcher',
            'karma-jasmine',
            'karma-jasmine-ajax',
            'karma-phantomjs-launcher'
        ],

        browserify: {
            configure: function(bundle) {
                bundle.on('prebundle', function() {
                    bundle.transform('babelify', {presets: ["react"]});
                });
            }
        }
    });
};<commit_msg>update karma to use phantom<commit_after>module.exports = function(config) {
    config.set({
        frameworks: [ 'browserify', 'jasmine-ajax', 'jasmine' ],

        files: [
            'src/test/js/**/*.js'
        ],

        preprocessors: {
            'src/test/js/**/*.js': [ 'browserify' ]
        },

        logLevel: config.LOG_INFO,

        singleRun: true,

        autoWatch: false,

        reporters: ['dots'],

        browsers: ['PhantomJS'],

        plugins: [
            'karma-browserify',
            'karma-chrome-launcher',
            'karma-jasmine',
            'karma-jasmine-ajax',
            'karma-phantomjs-launcher'
        ],

        browserify: {
            configure: function(bundle) {
                bundle.on('prebundle', function() {
                    bundle.transform('babelify', {presets: ["react"]});
                });
            }
        }
    });
};
<|endoftext|>


<commit_before>const packageJson = require('./package.json');
/* eslint-disable no-process-env */
let job = process.env.JOB_NUMBER || Date.now();
let browsers = [ 'ChromeHeadless' ];
let build = 'localbuild';
let branch = 'local';
let startConnect = false;
const reporters = [ 'progress', 'coverage' ];
const tags = [ `${ packageJson.name }@${ packageJson.version }` ];
const frameworks = [ 'mocha' ];
const debug = Boolean(process.env.npm_config_debug);

if (process.env.SAUCE_USERNAME) {
  browsers = [ 'SauceEdgeLatest', 'SauceInternetExplorerTen', 'SauceSafariLatest' ];
  tags.push(`${ process.env.SAUCE_USERNAME }@${ branch }`);
  reporters.push('saucelabs');
  startConnect = true;
} else if (process.env.APPVEYOR) {
  browsers = [ 'Firefox', 'ChromeHeadless', 'IE' ];
} else if (process.env.TRAVIS) {
  browsers = [ 'FirefoxHeadless', 'ChromeHeadless' ];
} else if (!process.env.KARMA_MANUAL) {
  browsers = [];
  frameworks.push('detectBrowsers');
}

if (process.env.APPVEYOR) {
  branch = process.env.APPVEYOR_REPO_BRANCH;
  build = `appveyor@${ process.env.APPVEYOR_JOB_NUMBER }`;
  job = process.env.APPVEYOR_JOB_NUMBER;
} else if (process.env.TRAVIS) {
  branch = process.env.TRAVIS_BRANCH;
  build = `travis@${ process.env.TRAVIS_JOB_NUMBER }`;
  job = process.env.TRAVIS_JOB_NUMBER;
  // Travis has its own saucelabs connect process, so ensure karma won't run it
  startConnect = false;
}
/* eslint-enable */

tags.push(build);
module.exports = function configureKarma(config) {
  config.set({
    basePath: '',
    browsers,
    singleRun: true,
    logLevel: debug ? config.LOG_DEBUG : config.LOG_INFO,
    frameworks,
    files: [ `${ packageJson.name }.test.js` ],
    reporters,
    coverageReporter: {
      type: 'lcov',
      dir: 'coverage',
    },
    customLaunchers: {
      FirefoxHeadless: {
        base: 'Firefox',
        flags: [ '-headless' ],
      },
      SauceSafariLatest: {
        base: 'SauceLabs',
        browserName: 'Safari',
        platform: 'OS X 10.11',
      },
      SauceInternetExplorerTen: {
        base: 'SauceLabs',
        browserName: 'Internet Explorer',
        version: 10,
      },
      SauceEdgeLatest: {
        base: 'SauceLabs',
        browserName: 'MicrosoftEdge',
      },
    },
    detectBrowsers: {
      enabled: true,
      usePhantomJS: false,
      postDetection(detectedBrowsers) {
        if (detectedBrowsers.length === 0) {
          /* eslint-disable no-console, no-process-exit */
          console.log('**********************************');
          console.log('**************WARNING*************');
          console.log('**********************************');
          console.log('Karma has been unable to detect a browser on your system');
          console.log('Karma will now exit(0). If you have a browser you\'d like to test');
          console.log('please run `env KARMA_MANUAL=1 karma`, and manually load up a browser');
          process.exit(0);
          /* eslint-enable */
        }
        return detectedBrowsers;
      },
    },
    sauceLabs: {
      testName: packageJson.name,
      tunnelIdentifier: job,
      startConnect,
      tags,
    },
  });
};
<commit_msg>chore: launch Chrome without sandbox in Travis<commit_after>const packageJson = require('./package.json');
/* eslint-disable no-process-env */
let job = process.env.JOB_NUMBER || Date.now();
let browsers = [ 'ChromeHeadless' ];
let build = 'localbuild';
let branch = 'local';
let startConnect = false;
const reporters = [ 'progress', 'coverage' ];
const tags = [ `${ packageJson.name }@${ packageJson.version }` ];
const frameworks = [ 'mocha' ];
const debug = Boolean(process.env.npm_config_debug);

if (process.env.SAUCE_USERNAME) {
  browsers = [ 'SauceEdgeLatest', 'SauceInternetExplorerTen', 'SauceSafariLatest' ];
  tags.push(`${ process.env.SAUCE_USERNAME }@${ branch }`);
  reporters.push('saucelabs');
  startConnect = true;
} else if (process.env.APPVEYOR) {
  browsers = [ 'Firefox', 'ChromeHeadless', 'IE' ];
} else if (process.env.TRAVIS) {
  browsers = [ 'FirefoxHeadless', 'ChromeHeadlessNoSandbox' ];
} else if (!process.env.KARMA_MANUAL) {
  browsers = [];
  frameworks.push('detectBrowsers');
}

if (process.env.APPVEYOR) {
  branch = process.env.APPVEYOR_REPO_BRANCH;
  build = `appveyor@${ process.env.APPVEYOR_JOB_NUMBER }`;
  job = process.env.APPVEYOR_JOB_NUMBER;
} else if (process.env.TRAVIS) {
  branch = process.env.TRAVIS_BRANCH;
  build = `travis@${ process.env.TRAVIS_JOB_NUMBER }`;
  job = process.env.TRAVIS_JOB_NUMBER;
  // Travis has its own saucelabs connect process, so ensure karma won't run it
  startConnect = false;
}
/* eslint-enable */

tags.push(build);
module.exports = function configureKarma(config) {
  config.set({
    basePath: '',
    browsers,
    singleRun: true,
    logLevel: debug ? config.LOG_DEBUG : config.LOG_INFO,
    frameworks,
    files: [ `${ packageJson.name }.test.js` ],
    reporters,
    coverageReporter: {
      type: 'lcov',
      dir: 'coverage',
    },
    customLaunchers: {
      ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        flags: [ '--no-sandbox' ],
      },
      FirefoxHeadless: {
        base: 'Firefox',
        flags: [ '-headless' ],
      },
      SauceSafariLatest: {
        base: 'SauceLabs',
        browserName: 'Safari',
        platform: 'OS X 10.11',
      },
      SauceInternetExplorerTen: {
        base: 'SauceLabs',
        browserName: 'Internet Explorer',
        version: 10,
      },
      SauceEdgeLatest: {
        base: 'SauceLabs',
        browserName: 'MicrosoftEdge',
      },
    },
    detectBrowsers: {
      enabled: true,
      usePhantomJS: false,
      postDetection(detectedBrowsers) {
        if (detectedBrowsers.length === 0) {
          /* eslint-disable no-console, no-process-exit */
          console.log('**********************************');
          console.log('**************WARNING*************');
          console.log('**********************************');
          console.log('Karma has been unable to detect a browser on your system');
          console.log('Karma will now exit(0). If you have a browser you\'d like to test');
          console.log('please run `env KARMA_MANUAL=1 karma`, and manually load up a browser');
          process.exit(0);
          /* eslint-enable */
        }
        return detectedBrowsers;
      },
    },
    sauceLabs: {
      testName: packageJson.name,
      tunnelIdentifier: job,
      startConnect,
      tags,
    },
  });
};
<|endoftext|>


<commit_before>module.exports = function (config) {
    config.set({
        basePath: '',
        autoWatch: true,
        frameworks: ['qunit'],
        files: [
            'static/script*.js',
            'static/test.js'
        ],

        browsers: ['PhantomJS'],
        reporters: ['progress', 'coverage'],
        preprocessors: {'*.js': ['coverage']},
        singleRun: true
    });
};<commit_msg>oprava chyb pro nastaveni codecov a travis<commit_after>module.exports = function (config) {
    config.set({
        basePath: '',
        autoWatch: true,
        frameworks: ['qunit'],
        files: [
            'static/script/*.js',
            'static/test.js'
        ],

        browsers: ['PhantomJS'],
        reporters: ['progress', 'coverage'],
        preprocessors: {'*.js': ['coverage']},
        singleRun: true
    });
};<|endoftext|>


<commit_before>function spiral(type, numberOfPoints, period) {
  var type = type || "points";
  var numberOfPoints = numberOfPoints || 1000;
  var period = period || 100;

  var margin = {top: 30, right: 30, bottom: 30, left: 30};
  var width = 750 - margin.left - margin.right;
  var height = 500 - margin.top - margin.bottom;

  var x = d3.scale.linear().range([0, width]);
  var y = d3.scale.linear().range([height, 0]);
  y.domain([-height-margin.bottom, height+margin.top]);
  x.domain([-width-margin.left, width+margin.right]);

  // For time point #t, calculate the angle to the center of the arc
  // period is the number of time points per revolution (2 PI)
  function theta(t, period) {
    return 2 * Math.PI / (period) * t;
  }

  function startAngle(t, period){
    return (theta(t-1, period) + theta(t, period))/2;
  }

  function endAngle(t, period){
    return (theta(t+1, period) + theta(t, period))/2;
  }

  function radius(spacing, angle) {
    return spacing * angle;
  }

  function cartesian(radius, angle, size, startAngle, endAngle) {
    var size = size || 1;
    var xPos = x(radius * Math.cos(angle));
    var yPos = y(radius * Math.sin(angle));
    return [xPos, yPos, size, radius, angle, startAngle, endAngle];
  }

  var svg = d3.select("body")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)

  var data = [];
  var data2 = [];
  for (var i=period; i<numberOfPoints + 1; i++) {
    var angle = theta(i, period);
    var rad = radius(8, angle);
    var size = 1 + Math.random()*1.5;
    if (i % 10 === 0) {
      size = 5.5 + Math.random()*3;
    }
    data.push(cartesian(rad, angle, size, startAngle(i, period), endAngle(i, period)))
    data2.push([i, size*period, 2])
  }

  if (type === "points") {
    svg.append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    svg.selectAll("g").selectAll("dot")
      .data(data)
        .enter().append("circle")
          .attr("r", function(d) { return d[2]; })
          .attr("cx", function(d) { return d[0]; })
          .attr("cy", function(d) { return d[1]; });
  } else if (type === "arcs") {
    svg.append("g")
      .attr("transform", "translate(" + (width * 0.5 + margin.left) + "," + (height * 0.5 + margin.top) + ")");

    svg.selectAll("g").selectAll("path")
      .data(data)
        .enter().append("path")
        .attr("d", d3.svg.arc()
        .outerRadius(function(d){return y(d[3]+10)})
        .innerRadius(function(d){return y(d[3]-10)})
        .startAngle(function(d) { return d[5] > 0 ? d[5] : 0; })
        .endAngle(function(d) { return d[6]; }))
        .attr("opacity", function(d){return d[2]/5})
  } else if (type === "paths") {

    var line = d3.svg.line()
        .interpolate("basis");

    svg.append("g")
      .attr("transform", "translate(" + (margin.left) + "," + (margin.top) + ")");

    svg.selectAll("g").selectAll("path")
        .data(quad(sample(line(data), numberOfPoints, period))) // ***** Need to figure out the proper precision to map data crrectly
      .enter().append("path")
        .style("fill", function(d) { return "black"; })
        .style("stroke", function(d) { return "black"; })
        .style("opacity", function(d) {return d.data/6})
        .attr("d", function(d) { return lineJoin(d[0], d[1], d[2], d[3], 10); });

    // Sample the SVG path string "d" uniformly with the specified precision.
    function sample(d, numberDataPoints, periodicity) {
      var path = document.createElementNS(d3.ns.prefix.svg, "path");
      path.setAttribute("d", d);

      var n = path.getTotalLength();
      var t = [0];
      var i = 1;
      var dt = Math.ceil(i/periodicity)*2;
      var lastSample = 0;
      console.log('total length', n)
      while (lastSample + dt < n) {
        dt = Math.ceil(i/periodicity)*2;
        t.push(lastSample + dt);
        console.log('dt', dt, 'lastSample + dt*i', lastSample + dt)
        lastSample = lastSample + dt;
        i++;
      }
      t.push(n);

      return t.map(function(t, index) {
        var p = path.getPointAtLength(t);
        var a = data[index] ? [p.x, p.y, data[index][2]] : [p.x, p.y, 0];
        return a;
      });
    }

    // Compute quads of adjacent points [p0, p1, p2, p3].
    function quad(points) {
      return d3.range(points.length - 1).map(function(i) {
        var a = [points[i - 1], points[i], points[i + 1], points[i + 2]];
        a.data = points[i][2];
        return a;
      });
    }

    // Compute stroke outline for segment p12.
    function lineJoin(p0, p1, p2, p3, width) {
      var u12 = perp(p1, p2),
          r = width / 2,
          a = [p1[0] + u12[0] * r, p1[1] + u12[1] * r],
          b = [p2[0] + u12[0] * r, p2[1] + u12[1] * r],
          c = [p2[0] - u12[0] * r, p2[1] - u12[1] * r],
          d = [p1[0] - u12[0] * r, p1[1] - u12[1] * r];

      if (p0) { // clip ad and dc using average of u01 and u12
        var u01 = perp(p0, p1), e = [p1[0] + u01[0] + u12[0], p1[1] + u01[1] + u12[1]];
        a = lineIntersect(p1, e, a, b);
        d = lineIntersect(p1, e, d, c);
      }

      if (p3) { // clip ab and dc using average of u12 and u23
        var u23 = perp(p2, p3), e = [p2[0] + u23[0] + u12[0], p2[1] + u23[1] + u12[1]];
        b = lineIntersect(p2, e, a, b);
        c = lineIntersect(p2, e, d, c);
      }

      return "M" + a + "L" + b + " " + c + " " + d + "Z";
    }

    // Compute intersection of two infinite lines ab and cd.
    function lineIntersect(a, b, c, d) {
      var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3;
      var y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3;
      var ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
      return [x1 + ua * x21, y1 + ua * y21];
    }

    // Compute unit vector perpendicular to p01.
    function perp(p0, p1) {
      var u01x = p0[1] - p1[1];
      var u01y = p1[0] - p0[0];
      var u01d = Math.sqrt(u01x * u01x + u01y * u01y);
      return [u01x / u01d, u01y / u01d];
    }
  } else if (type === "custom-path") {
    var pathWidth = 50;

    var customData = []
    for (var i = 0; i < numberOfPoints; i++) {
      var val = i*10 % period === 0 ? Math.random()*10 + 7 : Math.random()*5;
      customData.push([val]);
    }

    customData.forEach(function(datum, t, dataSet){
      var start = startAngle(t, period);
      var end = endAngle(t, period);

      var startInnerRadius = radius(8, start) - pathWidth*0.5;
      var startOuterRadius = radius(8, start) + pathWidth*0.5;
      var endInnerRadius = radius(8, end) - pathWidth*0.5;
      var endOuterRadius = radius(8, end) + pathWidth*0.5;

      var ctrlInnerRad = 0.01; // Use to adjust arc inner radius
      var ctrlOuterRad = 0.01; // Use to adjust arc outer radius
      var innerControlPoint = cartesian(radius(8, theta(t, period)) - pathWidth*0.5 + ctrlInnerRad, theta(t, period));
      var outerControlPoint = cartesian(radius(8, theta(t, period)) + pathWidth*0.5 + ctrlOuterRad, theta(t, period));

      var startPoint = cartesian(startInnerRadius, start); // Bottom right of arc
      var point2 = cartesian(startOuterRadius, start); // Top right of arc
      var point3 = cartesian(endOuterRadius, end); // Top left of arc
      var point4 = cartesian(endInnerRadius, end); // Bottom left of arc
      var arcPath = "M" + startPoint[0] + " " + startPoint[1] + "L" + point2[0] + " " + point2[1];
      arcPath += "Q" + outerControlPoint[0] + " " + outerControlPoint[1] + " " + point3[0] + " " + point3[1];
      arcPath += "L" + point4[0] + " " + point4[1];
      arcPath += "Q" + innerControlPoint[0] + " " + innerControlPoint[1] + " " + startPoint[0] + " " + startPoint[1] + "Z";
      datum[1] = arcPath
    });

    svg.append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    svg.selectAll("g").selectAll("path")
      .data(customData.slice(100))
      .enter().append("path")
        .style("fill", function(d) { return "black"; })
        .style("opacity", function(d) {return d[0]/10})
        .attr("d", function(d) { return d[1]});
  } else if (type === "non-spiral") {
    // --------------------vvv Standard Line Graph vvv---------------------------
    var x2 = d3.scale.linear().range([0, width]);
    var y2 = d3.scale.linear().range([height, 0]);
    x2.domain(d3.extent(data2, function(d) { return d[0]; }));
    y2.domain(d3.extent(data2, function(d) { return d[1]; }));

    var xAxis = d3.svg.axis().scale(x2)
      .orient("bottom").ticks(5);

    var yAxis = d3.svg.axis().scale(y2)
      .orient("left").ticks(5);

    var line = d3.svg.line()
      .x(function(d) { return x2(d[0]); })
      .y(function(d) { return y2(d[1]); });

    // Add the X Axis
    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate("+margin.left+"," + height + ")")
      .call(xAxis)
      .append("text")
        .attr("x", width)
        .attr("y", -3)
        .attr("dy", "-.35em")
        .style("text-anchor", "middle")
        .text("time");

    // Add the Y Axis
    svg.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate("+margin.left+",0)")
      .call(yAxis)
      .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Signal (a.u.)");

    svg.append("path")
      .datum(data2)
      .attr("class", "line")
      .attr("d", line)
      .attr("fill", "none")
      .attr("stroke-width", "1")
      .attr("stroke", "steelblue")
      .attr("transform", "translate("+margin.left+",0)")
  }
}

spiral('points');
spiral('custom-path');
spiral('paths');
spiral('arcs');
spiral('non-spiral');<commit_msg>Clean up code<commit_after>function spiral(type, numberOfPoints, period) {
  var type = type || "points";
  var numberOfPoints = numberOfPoints || 1000;
  var period = period || 100;

  var margin = {top: 30, right: 30, bottom: 30, left: 30};
  var width = 750 - margin.left - margin.right;
  var height = 500 - margin.top - margin.bottom;

  var x = d3.scale.linear().range([0, width]);
  var y = d3.scale.linear().range([height, 0]);
  y.domain([-height-margin.bottom, height+margin.top]);
  x.domain([-width-margin.left, width+margin.right]);

  // For time point #t, calculate the angle to the center of the arc
  // period is the number of time points per revolution (2 PI)
  function theta(t, period) {
    return 2 * Math.PI / (period) * t;
  }

  function startAngle(t, period){
    return (theta(t-1, period) + theta(t, period))/2;
  }

  function endAngle(t, period){
    return (theta(t+1, period) + theta(t, period))/2;
  }

  function radius(spacing, angle) {
    return spacing * angle;
  }

  function cartesian(radius, angle, size, startAngle, endAngle) {
    var size = size || 1;
    var xPos = x(radius * Math.cos(angle));
    var yPos = y(radius * Math.sin(angle));
    return [xPos, yPos, size, radius, angle, startAngle, endAngle];
  }

  var svg = d3.select("body")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)

  var data = [];
  var data2 = [];
  var customData = [];
  for (var i=period; i<numberOfPoints + 1; i++) {
    var angle = theta(i, period);
    var rad = radius(8, angle);
    var size = 1 + Math.random()*1.5;
    if (i % 10 === 0) {
      size = 5.5 + Math.random()*3;
    }
    data.push(cartesian(rad, angle, size, startAngle(i, period), endAngle(i, period)));
    data2.push([i, size*period, 2]);
    customData.push([size]);
  }

  if (type === "points") {
    svg.append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    svg.selectAll("g").selectAll("dot")
      .data(data)
        .enter().append("circle")
          .attr("r", function(d) { return d[2]; })
          .attr("cx", function(d) { return d[0]; })
          .attr("cy", function(d) { return d[1]; });
  } else if (type === "arcs") {
    svg.append("g")
      .attr("transform", "translate(" + (width * 0.5 + margin.left) + "," + (height * 0.5 + margin.top) + ")");

    svg.selectAll("g").selectAll("path")
      .data(data)
        .enter().append("path")
        .attr("d", d3.svg.arc()
        .outerRadius(function(d){return y(d[3]+10)})
        .innerRadius(function(d){return y(d[3]-10)})
        .startAngle(function(d) { return d[5] > 0 ? d[5] : 0; })
        .endAngle(function(d) { return d[6]; }))
        .attr("opacity", function(d){return d[2]/5})
  } else if (type === "paths") {

    var line = d3.svg.line()
        .interpolate("basis");

    svg.append("g")
      .attr("transform", "translate(" + (margin.left) + "," + (margin.top) + ")");

    svg.selectAll("g").selectAll("path")
        .data(quad(sample(line(data), numberOfPoints, period))) // ***** Need to figure out the proper precision to map data crrectly
      .enter().append("path")
        .style("fill", function(d) { return "black"; })
        .style("stroke", function(d) { return "black"; })
        .style("opacity", function(d) {return d.data/6})
        .attr("d", function(d) { return lineJoin(d[0], d[1], d[2], d[3], 10); });

    // Sample the SVG path string "d" uniformly with the specified precision.
    function sample(d, numberDataPoints, periodicity) {
      var path = document.createElementNS(d3.ns.prefix.svg, "path");
      path.setAttribute("d", d);

      var n = path.getTotalLength();
      var t = [0];
      var i = 1;
      var dt = Math.ceil(i/periodicity)*2;
      var lastSample = 0;
      while (lastSample + dt < n) {
        dt = Math.ceil(i/periodicity)*2;
        t.push(lastSample + dt);
        lastSample = lastSample + dt;
        i++;
      }
      t.push(n);

      return t.map(function(t, index) {
        var p = path.getPointAtLength(t);
        var a = data[index] ? [p.x, p.y, data[index][2]] : [p.x, p.y, 0];
        return a;
      });
    }

    // Compute quads of adjacent points [p0, p1, p2, p3].
    function quad(points) {
      return d3.range(points.length - 1).map(function(i) {
        var a = [points[i - 1], points[i], points[i + 1], points[i + 2]];
        a.data = points[i][2];
        return a;
      });
    }

    // Compute stroke outline for segment p12.
    function lineJoin(p0, p1, p2, p3, width) {
      var u12 = perp(p1, p2),
          r = width / 2,
          a = [p1[0] + u12[0] * r, p1[1] + u12[1] * r],
          b = [p2[0] + u12[0] * r, p2[1] + u12[1] * r],
          c = [p2[0] - u12[0] * r, p2[1] - u12[1] * r],
          d = [p1[0] - u12[0] * r, p1[1] - u12[1] * r];

      if (p0) { // clip ad and dc using average of u01 and u12
        var u01 = perp(p0, p1), e = [p1[0] + u01[0] + u12[0], p1[1] + u01[1] + u12[1]];
        a = lineIntersect(p1, e, a, b);
        d = lineIntersect(p1, e, d, c);
      }

      if (p3) { // clip ab and dc using average of u12 and u23
        var u23 = perp(p2, p3), e = [p2[0] + u23[0] + u12[0], p2[1] + u23[1] + u12[1]];
        b = lineIntersect(p2, e, a, b);
        c = lineIntersect(p2, e, d, c);
      }

      return "M" + a + "L" + b + " " + c + " " + d + "Z";
    }

    // Compute intersection of two infinite lines ab and cd.
    function lineIntersect(a, b, c, d) {
      var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3;
      var y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3;
      var ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
      return [x1 + ua * x21, y1 + ua * y21];
    }

    // Compute unit vector perpendicular to p01.
    function perp(p0, p1) {
      var u01x = p0[1] - p1[1];
      var u01y = p1[0] - p0[0];
      var u01d = Math.sqrt(u01x * u01x + u01y * u01y);
      return [u01x / u01d, u01y / u01d];
    }
  } else if (type === "custom-path") {
    var pathWidth = 50;

    customData.forEach(function(datum, t, dataSet){
      var start = startAngle(t, period);
      var end = endAngle(t, period);

      var startInnerRadius = radius(8, start) - pathWidth*0.5;
      var startOuterRadius = radius(8, start) + pathWidth*0.5;
      var endInnerRadius = radius(8, end) - pathWidth*0.5;
      var endOuterRadius = radius(8, end) + pathWidth*0.5;

      var ctrlInnerRad = 0.01; // Use to adjust arc inner radius
      var ctrlOuterRad = 0.01; // Use to adjust arc outer radius
      var innerControlPoint = cartesian(radius(8, theta(t, period)) - pathWidth*0.5 + ctrlInnerRad, theta(t, period));
      var outerControlPoint = cartesian(radius(8, theta(t, period)) + pathWidth*0.5 + ctrlOuterRad, theta(t, period));

      var startPoint = cartesian(startInnerRadius, start); // Bottom right of arc
      var point2 = cartesian(startOuterRadius, start); // Top right of arc
      var point3 = cartesian(endOuterRadius, end); // Top left of arc
      var point4 = cartesian(endInnerRadius, end); // Bottom left of arc
      var arcPath = "M" + startPoint[0] + " " + startPoint[1] + "L" + point2[0] + " " + point2[1];
      arcPath += "Q" + outerControlPoint[0] + " " + outerControlPoint[1] + " " + point3[0] + " " + point3[1];
      arcPath += "L" + point4[0] + " " + point4[1];
      arcPath += "Q" + innerControlPoint[0] + " " + innerControlPoint[1] + " " + startPoint[0] + " " + startPoint[1] + "Z";
      datum[1] = arcPath
    });

    svg.append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    svg.selectAll("g").selectAll("path")
      .data(customData.slice(100))
      .enter().append("path")
        .style("fill", function(d) { return "black"; })
        .style("opacity", function(d) {return d[0]/9})
        .attr("d", function(d) { return d[1]});
  } else if (type === "non-spiral") {
    // --------------------vvv Standard Line Graph vvv---------------------------
    var x2 = d3.scale.linear().range([0, width]);
    var y2 = d3.scale.linear().range([height, 0]);
    x2.domain(d3.extent(data2, function(d) { return d[0]; }));
    y2.domain(d3.extent(data2, function(d) { return d[1]; }));

    var xAxis = d3.svg.axis().scale(x2)
      .orient("bottom").ticks(5);

    var yAxis = d3.svg.axis().scale(y2)
      .orient("left").ticks(5);

    var line = d3.svg.line()
      .x(function(d) { return x2(d[0]); })
      .y(function(d) { return y2(d[1]); });

    // Add the X Axis
    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate("+margin.left+"," + height + ")")
      .call(xAxis)
      .append("text")
        .attr("x", width)
        .attr("y", -3)
        .attr("dy", "-.35em")
        .style("text-anchor", "middle")
        .text("time");

    // Add the Y Axis
    svg.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate("+margin.left+",0)")
      .call(yAxis)
      .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Signal (a.u.)");

    svg.append("path")
      .datum(data2)
      .attr("class", "line")
      .attr("d", line)
      .attr("fill", "none")
      .attr("stroke-width", "1")
      .attr("stroke", "steelblue")
      .attr("transform", "translate("+margin.left+",0)")
  }
}

spiral('points');
spiral('custom-path');
//spiral('paths');
//spiral('arcs');
spiral('non-spiral');<|endoftext|>


<commit_before>module.exports = function (config) {
  var path = require('path')
  var nodeForgePath = path.resolve(__dirname, 'node_modules/peer-id/deps/forge.bundle.js')

  config.set({
    basePath: '',
    frameworks: ['mocha'],

    files: [
      nodeForgePath,
      'tests/test-core/browser.js'
    ],

    preprocessors: {
      'tests/test-core/*': ['webpack']
    },

    webpack: {
      resolve: {
        extensions: ['', '.js', '.json']
      },
      externals: {
        fs: '{}',
        'node-forge': 'forge'
      },
      node: {
        Buffer: true
      },
      module: {
        loaders: [
          { test: /\.json$/, loader: 'json' }
        ]
      }
    },

    webpackMiddleware: {
      noInfo: true,
      stats: {
        colors: true
      }
    },
    reporters: ['spec'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    browsers: process.env.TRAVIS ? ['Firefox'] : ['Chrome'],
    singleRun: true
  })
}
<commit_msg>restore captureTimeout in karma<commit_after>module.exports = function (config) {
  var path = require('path')
  var nodeForgePath = path.resolve(__dirname, 'node_modules/peer-id/deps/forge.bundle.js')

  config.set({
    basePath: '',
    frameworks: ['mocha'],

    files: [
      nodeForgePath,
      'tests/test-core/browser.js'
    ],

    preprocessors: {
      'tests/test-core/*': ['webpack']
    },

    webpack: {
      resolve: {
        extensions: ['', '.js', '.json']
      },
      externals: {
        fs: '{}',
        'node-forge': 'forge'
      },
      node: {
        Buffer: true
      },
      module: {
        loaders: [
          { test: /\.json$/, loader: 'json' }
        ]
      }
    },

    webpackMiddleware: {
      noInfo: true,
      stats: {
        colors: true
      }
    },
    reporters: ['spec'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    browsers: process.env.TRAVIS ? ['Firefox'] : ['Chrome'],
    captureTimeout: 60000,
    singleRun: true
  })
}
<|endoftext|>


<commit_before>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function (config) {
    config.set({
        // base path, that will be used to resolve files and exclude
        basePath: 'static/',

        // testing framework to use (jasmine/mocha/qunit/...)
        frameworks: ['mocha'],

        // list of files / patterns to load in the browser
        files: [
            'lib/chai/chai.js',
            'lib/seajs/sea.js',
            'lib/seajs-text/seajs-text.js',
            'js/config.js',
            {
                pattern: 'lib/jquery/jquery.js',
                included: false
            },
            {
                pattern: 'plugin/**/*.js',
                included: false
            },
            'plugin/**/*.spec.js'
        ],

        // web server port
        port: 8080,

        proxies: {
            '/lib': '/base/lib',
            '/plugin': '/base/plugin'
        },

        // 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: true,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false
    });
};
<commit_msg>修改mocha reporter形式<commit_after>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function (config) {
    config.set({
        // base path, that will be used to resolve files and exclude
        basePath: 'static/',

        // testing framework to use (jasmine/mocha/qunit/...)
        frameworks: ['mocha'],

        client: {
            mocha: {
                reporter: 'html',
                ui: 'bdd'
            }
        },

        // list of files / patterns to load in the browser
        files: [
            'lib/chai/chai.js',
            'lib/seajs/sea.js',
            'lib/seajs-text/seajs-text.js',
            'js/config.js',
            {
                pattern: 'lib/jquery/jquery.js',
                included: false
            },
            {
                pattern: 'plugin/**/*.js',
                included: false
            },
            'plugin/**/*.spec.js'
        ],

        // web server port
        port: 8080,

        proxies: {
            '/lib': '/base/lib',
            '/plugin': '/base/plugin'
        },

        // 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: true,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false
    });
};
<|endoftext|>


<commit_before>// Copyright 2022, University of Colorado Boulder

/**
 * Do not allow basic assertions in typescript files where typescript typesc make that redundant. This rule applies in
 * cases like:
 *
 * assert && assert( typeof x === 'number', 'should be a number' );
 * assert && assert( x instanceof Node, 'why is this thing not a Node );
 *
 * In typescript, x should just have the correct type to begin with, instead of relying on runtime assertions.
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */

module.exports = function( context ) {

  const getBadTextTester = require( './getBadTextTester' );

  // see getBadTextTester for schema.
  const forbiddenTextObject = [
    {
      id: 'asserting values are instanceof or typeof in typescript is redundant',
      regex: /assert && assert\((( \w+ instanceof \w+ )|( typeof \w+ === '\w+' ))\)/
    }
  ];

  return {
    Program: getBadTextTester( 'bad-typescript-text', forbiddenTextObject, context )
  };
};

module.exports.schema = [
  // JSON Schema for rule options goes here
];<commit_msg>Generalize no-simple-type-checking-assertions regex, see https://github.com/phetsims/chipper/issues/1344<commit_after>// Copyright 2022, University of Colorado Boulder

/**
 * Do not allow basic assertions in typescript files where typescript typesc make that redundant. This rule applies in
 * cases like:
 *
 * assert && assert( typeof x === 'number', 'should be a number' );
 * assert && assert( x instanceof Node, 'why is this thing not a Node );
 *
 * In typescript, x should just have the correct type to begin with, instead of relying on runtime assertions.
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */

module.exports = function( context ) {

  const getBadTextTester = require( './getBadTextTester' );

  // see getBadTextTester for schema.
  const forbiddenTextObject = [
    {
      id: 'asserting values are instanceof or typeof in typescript is redundant',
      regex: /assert && assert\((( \w+ instanceof \w+)|( typeof \w+ === '\w+'))( \)|,)/
    }
  ];

  return {
    Program: getBadTextTester( 'bad-typescript-text', forbiddenTextObject, context )
  };
};

module.exports.schema = [
  // JSON Schema for rule options goes here
];<|endoftext|>


<commit_before>/*
	Width management tool for responsive designs

	Author
		Aurélien Delogu (dev@dreamysource.fr)

	Some readings
		http://www.alistapart.com/articles/fontresizing/
		http://tripleodeon.com/2011/12/first-understand-your-screen/

	Notes
		Thanks to Lawrence Carvalho (carvalho@uk.yahoo-inc.com) for his useful TextResizeDetector script :)
*/

;(function(context,name,definition){
	if(typeof module!='undefined' && module.exports){
		module.exports=definition();
	}
	else if(typeof define=='function' && define.amd){
		define(definition);
	}
	else{
		context[name]=definition();
	}
}(this,'W',function(){

	// Prepare
	var win=window,
		doc=document,
		html=doc.documentElement,
		a,b,
		textElement,
		textHeight,
		listeners=[],
		trigger=false,
		unit,
		refreshUnit=function(){
			a=doc.createElement('div');
			a.style.width='1em';
			html.appendChild(a);
			unit=a.offsetWidth;
			console.log(unit);
			unit=unit?unit:16; // 16px as fallback
			html.removeChild(a);
		};
	refreshUnit();

	// Catch window resize event
	if(win.addEventListener){
		win.addEventListener('resize',function(){
			trigger=true;
		},false);
	}
	else{
		win.attachEvent('onresize',function(){
			trigger=true;
		});
	}

	// Initialize the text element to catch text resizes
	textElement=doc.createElement('b');
	textElement.style.position='absolute';
	textElement.style.top='-99em';
	textElement.innerHTML='W';
	html.appendChild(textElement);
	textHeight=textElement.offsetHeight;

	// Verify resizes every 250ms
	setInterval(function(){
		// Verify text element state
		a=textElement.offsetHeight;
		if(a!=textHeight){
			trigger=true;
		}
		textHeight=a;
		// Text has been resized
		if(trigger && html.clientWidth){
			refreshUnit();
			for(var i=0,j=listeners.length;i<j;++i){
				listeners[i]();
			}
			trigger=false;
		}
	},250);

	// Define W object
	return {
		px2em: function(px){
			return px/unit;
		},
		getViewportWidth: function(){
			// Viewport width
			a=navigator.userAgent.match(/iPhone|iPod|iPad/i)?win.outerWidth:screen.width;
			// Window width
			if(!(b=win.innerWidth)){
				b=html.clientWidth;
			}
			// Guess the correct width
			return (b-a)*100/b<5?b:a;
		},
		getViewportHeight: function(){
			// Viewport height
			a=navigator.userAgent.match(/iPhone|iPod|iPad/i)?win.outerHeight:screen.height;
			// Window height
			if(!(b=win.innerHeight)){
				b=html.clientHeight;
			}
			// Guess the correct height
			return (b-a)*100/b<5?b:a;
		},
		addListener: function(func){
			listeners.push(func);
			return func;
		}
	};

}));<commit_msg>Remove console.log()<commit_after>/*
	Width management tool for responsive designs

	Author
		Aurélien Delogu (dev@dreamysource.fr)

	Some readings
		http://www.alistapart.com/articles/fontresizing/
		http://tripleodeon.com/2011/12/first-understand-your-screen/

	Notes
		Thanks to Lawrence Carvalho (carvalho@uk.yahoo-inc.com) for his useful TextResizeDetector script :)
*/

;(function(context,name,definition){
	if(typeof module!='undefined' && module.exports){
		module.exports=definition();
	}
	else if(typeof define=='function' && define.amd){
		define(definition);
	}
	else{
		context[name]=definition();
	}
}(this,'W',function(){

	// Prepare
	var win=window,
		doc=document,
		html=doc.documentElement,
		a,b,
		textElement,
		textHeight,
		listeners=[],
		trigger=false,
		unit,
		refreshUnit=function(){
			a=doc.createElement('div');
			a.style.width='1em';
			html.appendChild(a);
			unit=a.offsetWidth;
			unit=unit?unit:16;
			html.removeChild(a);
		};
	refreshUnit();

	// Catch window resize event
	if(win.addEventListener){
		win.addEventListener('resize',function(){
			trigger=true;
		},false);
	}
	else{
		win.attachEvent('onresize',function(){
			trigger=true;
		});
	}

	// Initialize the text element to catch text resizes
	textElement=doc.createElement('b');
	textElement.style.position='absolute';
	textElement.style.top='-99em';
	textElement.innerHTML='W';
	html.appendChild(textElement);
	textHeight=textElement.offsetHeight;

	// Verify resizes every 250ms
	setInterval(function(){
		// Verify text element state
		a=textElement.offsetHeight;
		if(a!=textHeight){
			trigger=true;
		}
		textHeight=a;
		// Text has been resized
		if(trigger && html.clientWidth){
			refreshUnit();
			for(var i=0,j=listeners.length;i<j;++i){
				listeners[i]();
			}
			trigger=false;
		}
	},250);

	// Define W object
	return {
		px2em: function(px){
			return px/unit;
		},
		getViewportWidth: function(){
			// Viewport width
			a=navigator.userAgent.match(/iPhone|iPod|iPad/i)?win.outerWidth:screen.width;
			// Window width
			if(!(b=win.innerWidth)){
				b=html.clientWidth;
			}
			// Guess the correct width
			return (b-a)*100/b<5?b:a;
		},
		getViewportHeight: function(){
			// Viewport height
			a=navigator.userAgent.match(/iPhone|iPod|iPad/i)?win.outerHeight:screen.height;
			// Window height
			if(!(b=win.innerHeight)){
				b=html.clientHeight;
			}
			// Guess the correct height
			return (b-a)*100/b<5?b:a;
		},
		addListener: function(func){
			listeners.push(func);
			return func;
		}
	};

}));<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const path = require('path');

// Parse args
const args = {};
const raw = process.argv.slice(2);
for (var i = 0; i < raw.length; i++) {
    if (raw[i].substr(0, 2) === '--' && raw[i].indexOf('=') !== -1) {
        raw[i] = raw[i].split('=');
        args[raw[i][0].replace('--', '')] = raw[i].slice(1).join('=');
        continue;
    }
    if (raw[i].substr(0, 2) === '--') {
        args[raw[i].replace('--', '')] = raw[++i];
        continue;
    }
    if (raw[i].substr(0, 1) === '-') {
        args[raw[i].replace('-', '')] = raw[++i];
        continue;
    }
    args[raw[i]] = raw[++i];
}

// If there is no function - exit;
var name = args.f || args.function;
if (typeof(name) === 'undefined') {
    console.log('Invalid function name. It should be accessible from invocation place');
    process.exit(1);
}
const basename = path.basename(name);

// Function path recognition
try {
    if (name.substr(-3) !== '.js') name += '.js';
    name = path.resolve(name);
} catch (e) {
    console.log('Cannot resolve given function ' + name);
    process.exit(1);
}

const resolve = function(file) {
    try {
        if (file.substr(-5) !== '.json') file += '.json';
        file = path.resolve(file);
        file = require.resolve(file);
        file = require(file);
        if (typeof(file) === 'string') file = JSON.parse(file);
        return file;
    } catch (e) {}
    return undefined;
};

// Resolve event object
var event = args.e || args.event;
if (typeof(event) !== 'undefined') event = resolve(event);
if (!event) event = {};

// if input argument Context exists - use it
var context = args.c || args.context;
if (typeof(context) !== 'undefined') context = resolve(context);
if (!context) {
    const hash = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
    context = {
        awsRequestId    : [
            hash.substr(0, 8), hash.substr(9, 4), hash.substr(12, 4), hash.substr(16, 4), hash.substr(20, 12)
        ].join('-'),
        logGroupName    : '/aws/lambda/' + basename,
        logStreamName   : (new Date()).toISOString().substr(0, 10).replace(/-/g, '/') + '/[$LATEST]' + hash,
        functionName    : basename,
        memoryLimitInMB : '128',
        functionVersion : '$LATEST',
        invokedFunctionArn : 'arn:aws:lambda:aws-region:1234567890123:function:' + basename
    };
    context.invokeId = context.awsRequestId;
}
context.succeed = function(output)
{
    if (Object.prototype.toString.call(output) === '[object Object]') output = JSON.stringify(output, null, 4);
    console.log('OUTPUT');
    console.log('-'.repeat(32));
    console.log(output);
    process.exit();
};
context.fail = function(error)
{
    if (Object.prototype.toString.call(error) === '[object Object]') error = JSON.stringify(error, null, 4);
    console.log('ERROR');
    console.log('-'.repeat(32));
    console.log(error);
};
context.done = function(error, message)
{
    if (error) this.fail(error);
    this.succeed(message);
};

const timeout = args.t || args.timeout || 30;
setTimeout(function() {
    console.log('Lambda function ' + basename + ' was timed out after ' + timeout + ' seconds');
    process.exit(1);
}, timeout*1000);
require(name).handler(event, context);
<commit_msg>Revert ES6 changes. Const -> var<commit_after>#!/usr/bin/env node
'use strict';

var path = require('path');

// Parse args
var args = {};
var raw = process.argv.slice(2);
for (var i = 0; i < raw.length; i++) {
    if (raw[i].substr(0, 2) === '--' && raw[i].indexOf('=') !== -1) {
        raw[i] = raw[i].split('=');
        args[raw[i][0].replace('--', '')] = raw[i].slice(1).join('=');
        continue;
    }
    if (raw[i].substr(0, 2) === '--') {
        args[raw[i].replace('--', '')] = raw[++i];
        continue;
    }
    if (raw[i].substr(0, 1) === '-') {
        args[raw[i].replace('-', '')] = raw[++i];
        continue;
    }
    args[raw[i]] = raw[++i];
}

// If there is no function - exit;
var name = args.f || args.function;
if (typeof(name) === 'undefined') {
    console.log('Invalid function name. It should be accessible from invocation place');
    process.exit(1);
}
var basename = path.basename(name);

// Function path recognition
try {
    if (name.substr(-3) !== '.js') name += '.js';
    name = path.resolve(name);
} catch (e) {
    console.log('Cannot resolve given function ' + name);
    process.exit(1);
}

var resolve = function(file) {
    try {
        if (file.substr(-5) !== '.json') file += '.json';
        file = path.resolve(file);
        file = require.resolve(file);
        file = require(file);
        if (typeof(file) === 'string') file = JSON.parse(file);
        return file;
    } catch (e) {}
    return undefined;
};

// Resolve event object
var event = args.e || args.event;
if (typeof(event) !== 'undefined') event = resolve(event);
if (!event) event = {};

// if input argument Context exists - use it
var context = args.c || args.context;
if (typeof(context) !== 'undefined') context = resolve(context);
if (!context) {
    var hash = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
    context = {
        awsRequestId    : [
            hash.substr(0, 8), hash.substr(9, 4), hash.substr(12, 4), hash.substr(16, 4), hash.substr(20, 12)
        ].join('-'),
        logGroupName    : '/aws/lambda/' + basename,
        logStreamName   : (new Date()).toISOString().substr(0, 10).replace(/-/g, '/') + '/[$LATEST]' + hash,
        functionName    : basename,
        memoryLimitInMB : '128',
        functionVersion : '$LATEST',
        invokedFunctionArn : 'arn:aws:lambda:aws-region:1234567890123:function:' + basename
    };
    context.invokeId = context.awsRequestId;
}
context.succeed = function(output)
{
    if (Object.prototype.toString.call(output) === '[object Object]') output = JSON.stringify(output, null, 4);
    console.log('OUTPUT');
    console.log('-'.repeat(32));
    console.log(output);
    process.exit();
};
context.fail = function(error)
{
    if (Object.prototype.toString.call(error) === '[object Object]') error = JSON.stringify(error, null, 4);
    console.log('ERROR');
    console.log('-'.repeat(32));
    console.log(error);
};
context.done = function(error, message)
{
    if (error) this.fail(error);
    this.succeed(message);
};

var timeout = args.t || args.timeout || 30;
setTimeout(function() {
    console.log('Lambda function ' + basename + ' was timed out after ' + timeout + ' seconds');
    process.exit(1);
}, timeout*1000);
require(name).handler(event, context);
<|endoftext|>


<commit_before>var path = require('path'),
    argv = require('yargs').argv,
    _ = require('lodash'),
    webpack = require('webpack');

var playgroundPath = __dirname,
    rootPath = path.join(playgroundPath, '..'),
    modulesPath = path.join(rootPath, 'node_modules'),
    cwd = process.cwd();

var resolvePath = function(userPath) {
  return path.resolve(cwd, userPath);
};

var config = {},
    userConfig;

try {
  userConfig = require(
    resolvePath(argv.configPath || 'component-playground.config'));
} catch (e) {
  if (e instanceof Error && e.code === 'MODULE_NOT_FOUND') {
    userConfig = {};
  } else {
    throw e;
  }
}

config.server = _.extend({
  port: 8989,
  hostname: 'localhost'
}, userConfig.server);

config.webpack = {
  context: playgroundPath,
  entry: [
    'webpack-dev-server/client?http://localhost:' + config.server.port,
    'webpack/hot/dev-server',
    './entry'
  ],
  resolve: {
    alias: {
      components: resolvePath(argv.componentsPath || 'components'),
      fixtures: resolvePath(argv.fixturesPath || 'fixtures')
    },
    extensions: ['', '.js', '.jsx']
  },
  resolveLoader: {
    root: modulesPath
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loaders: ['react-hot-loader', 'babel-loader']
    }, {
      test: /\.css$/,
      loader: 'style-loader!css-loader'
    }, {
      test: /\.less$/,
      loader: 'style-loader!css-loader!less-loader'
    }]
  },
  output: {
    libraryTarget: 'umd',
    library: 'cosmosRouter',
    path: path.join(playgroundPath, 'public', 'build'),
    filename: 'bundle.js',
    publicPath: '/build/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ]
};

if (userConfig.webpack) {
  config.webpack = userConfig.webpack(config.webpack);
}

module.exports = config;
<commit_msg>Set hostname for HMR<commit_after>var path = require('path'),
    argv = require('yargs').argv,
    _ = require('lodash'),
    webpack = require('webpack');

var playgroundPath = __dirname,
    rootPath = path.join(playgroundPath, '..'),
    modulesPath = path.join(rootPath, 'node_modules'),
    cwd = process.cwd();

var resolvePath = function(userPath) {
  return path.resolve(cwd, userPath);
};

var config = {},
    userConfig;

try {
  userConfig = require(
    resolvePath(argv.configPath || 'component-playground.config'));
} catch (e) {
  if (e instanceof Error && e.code === 'MODULE_NOT_FOUND') {
    userConfig = {};
  } else {
    throw e;
  }
}

config.server = _.extend({
  port: 8989,
  hostname: 'localhost'
}, userConfig.server);

config.webpack = {
  context: playgroundPath,
  entry: [
    'webpack-dev-server/client?http://' + config.server.hostname + ':' +
                                          config.server.port,
    'webpack/hot/dev-server',
    './entry'
  ],
  resolve: {
    alias: {
      components: resolvePath(argv.componentsPath || 'components'),
      fixtures: resolvePath(argv.fixturesPath || 'fixtures')
    },
    extensions: ['', '.js', '.jsx']
  },
  resolveLoader: {
    root: modulesPath
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loaders: ['react-hot-loader', 'babel-loader']
    }, {
      test: /\.css$/,
      loader: 'style-loader!css-loader'
    }, {
      test: /\.less$/,
      loader: 'style-loader!css-loader!less-loader'
    }]
  },
  output: {
    libraryTarget: 'umd',
    library: 'cosmosRouter',
    path: path.join(playgroundPath, 'public', 'build'),
    filename: 'bundle.js',
    publicPath: '/build/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ]
};

if (userConfig.webpack) {
  config.webpack = userConfig.webpack(config.webpack);
}

module.exports = config;
<|endoftext|>


<commit_before>$(function(){
  // The 'Add story button' should show the hidden form at the bottom of the
  // backlog
  $('#new_story').hide();
  //$('#add_story').click(function() {
  //  $('#new_story').toggle();
  //  $('#story_title').focus();
  //  return false;
  //});
});

/**
 * Loads an entire column from a remote data path.  path is the path of the
 * url to call, column_id is the element id to append the data to.
 */
function loadColumn(path, column_id) {
  $.ajax({
    dataType: "json",
    url: path,
    success: function(stories) {
      $('#story_tmpl').tmpl(stories).appendTo(column_id);
    }
  });
}

// Backbone implementation

var Story = Backbone.Model.extend({
  name: 'story',

  defaults: {
    events: [],
    state: "unstarted",
    story_type: "feature"
  },

  column: function() {
    if (this.get('state') == "accepted") {
      return '#done';
    }
    else if (this.get('state') == "unstarted") {
      return "#backlog";
    }
    else {
      return "#in_progress";
    }
  },

  clear: function() {
    this.destroy();
    this.view.remove();
  },

  // State machine transitions
  start: function() {
    this.set({state: "started"});
  },

  finish: function() {
    this.set({state: "finished"});
  },

  deliver: function() {
    this.set({state: "delivered"});
  },

  accept: function() {
    this.set({state: "accepted"});
  },

  reject: function() {
    this.set({state: "rejected"});
  },

  restart: function() {
    this.set({state: "started"});
  },

  className: function() {
    return 'story ' + this.get('story_type');
  }
});

var StoryCollection = Backbone.Collection.extend({
  model: Story,
});

var Project = Backbone.Model.extend({
  name: 'project',

  initialize: function() {
    this.stories = new StoryCollection;
    this.stories.url = this.url() + '/stories';
  },

  url: function() {
    return '/projects/' + this.id;
  },
});

var StoryView = FormView.extend({

  tagName: 'div',

  initialize: function() {
    _.bindAll(this, "render", "highlight");
    // Rerender on any change to the views story
    this.model.bind("change", this.render);
    this.model.bind("change", this.highlight);

    // Supply the model with a reference to it's own view object, so it can
    // remove itself from the page when destroy() gets called.
    this.model.view = this;
  },

  events: {
    "click img.expand": "startEdit",
    "click img.collapse": "cancelEdit",
    "click #submit": "modelSave",
    "click #cancel": "cancelEdit",
    "click .transition": "transition",
    "click input.estimate": "estimate",
    "click #destroy": "clear"
  },

  transition: function(ev) {
    // The name of the function that needs to be called on the model is the
    // value of the form button that was clicked.
    var transitionEvent = ev.target.value;
    this.model[transitionEvent]();
    this.model.save();
  },

  estimate: function(ev) {
    this.model.set({estimate: ev.target.value});
    this.model.save();
  },

  startEdit: function() {
    this.model.set({editing: true});
  },

  cancelEdit: function() {
    this.model.set({editing: false});
  },

  modelSave: function() {
    this.model.save();
    this.model.set({editing: false});
  },

  // Delete the story and remove it's view element
  clear: function() {
    this.model.clear();
  },

  // Visually highlight the story if an external change happens
  highlight: function() {
    if(!this.model.get('editing')) {
      $(this.el).effect("highlight", {}, 3000);
    }
  },

  render: function() {
    if(this.model.get('editing') === true) {
      $(this.el).empty();
      div = this.make('div');
      $(div).append(this.make("img", {class: "collapse", src: "/images/collapse.png"}));
      $(div).append(this.textField("title"));
      $(this.el).append(div);

      div = this.make('div');
      $(div).append(this.submit());
      $(div).append(this.destroy());
      $(div).append(this.cancel());
      $(this.el).append(div);

      div = this.make('div');
      $(div).append(this.label("estimate"));
      $(div).append('
');
      $(div).append(this.select("estimate", [["zero","0"],1,2,3,5,8]));
      $(this.el).append(div);

      div = this.make('div');
      $(div).append(this.label("story_type"));
      $(div).append('
');
      $(div).append(this.select("story_type", ["feature", "chore", "bug", "release"]));
      $(this.el).append(div);

      div = this.make('div');
      $(div).append(this.label("state"));
      $(div).append('
');
      $(div).append(this.select("state", ["unstarted", "started", "finished", "delivered", "accepted", "rejected"]));
      $(this.el).append(div);

      div = this.make('div');
      $(div).append(this.label("description"));
      $(div).append('
');
      $(div).append(this.textArea("description"));
      $(this.el).append(div);

    } else {
      $(this.el).html($('#story_tmpl').tmpl(this.model.toJSON()));
      //var view = this;
      //$(this.el).find('img.expand').bind("click", function() {
      //  view.model.set({editing: true});
      //  view.render();
      //});
    }
    return this;
  }
});

//var Stories = new StoryCollection();
//var Project = new Project({id: 1});

var AppView = Backbone.View.extend({

  initialize: function() {
    _.bindAll(this, 'addOne', 'addAll', 'render');

    window.Project.stories.bind('add', this.addOne);
    window.Project.stories.bind('refresh', this.addAll);
    window.Project.stories.bind('all', this.render);

    window.Project.stories.fetch();
  },

  addOne: function(story) {
    var view = new StoryView({model: story, id: story.id, className: story.className()});
    $(story.column()).append(view.render().el);
  },

  addAll: function() {
    window.Project.stories.each(this.addOne);
  }
});

$(function() {
  $('#add_story').click(function() {
    window.Project.stories.add([{
      title: "New story", events: [], editing: true
    }]);
  });
});
<commit_msg>Remove some commented javascript<commit_after>/**
 * Loads an entire column from a remote data path.  path is the path of the
 * url to call, column_id is the element id to append the data to.
 */
function loadColumn(path, column_id) {
  $.ajax({
    dataType: "json",
    url: path,
    success: function(stories) {
      $('#story_tmpl').tmpl(stories).appendTo(column_id);
    }
  });
}

// Backbone implementation

var Story = Backbone.Model.extend({
  name: 'story',

  defaults: {
    events: [],
    state: "unstarted",
    story_type: "feature"
  },

  column: function() {
    if (this.get('state') == "accepted") {
      return '#done';
    }
    else if (this.get('state') == "unstarted") {
      return "#backlog";
    }
    else {
      return "#in_progress";
    }
  },

  clear: function() {
    this.destroy();
    this.view.remove();
  },

  // State machine transitions
  start: function() {
    this.set({state: "started"});
  },

  finish: function() {
    this.set({state: "finished"});
  },

  deliver: function() {
    this.set({state: "delivered"});
  },

  accept: function() {
    this.set({state: "accepted"});
  },

  reject: function() {
    this.set({state: "rejected"});
  },

  restart: function() {
    this.set({state: "started"});
  },

  className: function() {
    return 'story ' + this.get('story_type');
  }
});

var StoryCollection = Backbone.Collection.extend({
  model: Story,
});

var Project = Backbone.Model.extend({
  name: 'project',

  initialize: function() {
    this.stories = new StoryCollection;
    this.stories.url = this.url() + '/stories';
  },

  url: function() {
    return '/projects/' + this.id;
  },
});

var StoryView = FormView.extend({

  tagName: 'div',

  initialize: function() {
    _.bindAll(this, "render", "highlight");
    // Rerender on any change to the views story
    this.model.bind("change", this.render);
    this.model.bind("change", this.highlight);

    // Supply the model with a reference to it's own view object, so it can
    // remove itself from the page when destroy() gets called.
    this.model.view = this;
  },

  events: {
    "click img.expand": "startEdit",
    "click img.collapse": "cancelEdit",
    "click #submit": "modelSave",
    "click #cancel": "cancelEdit",
    "click .transition": "transition",
    "click input.estimate": "estimate",
    "click #destroy": "clear"
  },

  transition: function(ev) {
    // The name of the function that needs to be called on the model is the
    // value of the form button that was clicked.
    var transitionEvent = ev.target.value;
    this.model[transitionEvent]();
    this.model.save();
  },

  estimate: function(ev) {
    this.model.set({estimate: ev.target.value});
    this.model.save();
  },

  startEdit: function() {
    this.model.set({editing: true});
  },

  cancelEdit: function() {
    this.model.set({editing: false});
  },

  modelSave: function() {
    this.model.save();
    this.model.set({editing: false});
  },

  // Delete the story and remove it's view element
  clear: function() {
    this.model.clear();
  },

  // Visually highlight the story if an external change happens
  highlight: function() {
    if(!this.model.get('editing')) {
      $(this.el).effect("highlight", {}, 3000);
    }
  },

  render: function() {
    if(this.model.get('editing') === true) {
      $(this.el).empty();
      div = this.make('div');
      $(div).append(this.make("img", {class: "collapse", src: "/images/collapse.png"}));
      $(div).append(this.textField("title"));
      $(this.el).append(div);

      div = this.make('div');
      $(div).append(this.submit());
      $(div).append(this.destroy());
      $(div).append(this.cancel());
      $(this.el).append(div);

      div = this.make('div');
      $(div).append(this.label("estimate"));
      $(div).append('
');
      $(div).append(this.select("estimate", [["zero","0"],1,2,3,5,8]));
      $(this.el).append(div);

      div = this.make('div');
      $(div).append(this.label("story_type"));
      $(div).append('
');
      $(div).append(this.select("story_type", ["feature", "chore", "bug", "release"]));
      $(this.el).append(div);

      div = this.make('div');
      $(div).append(this.label("state"));
      $(div).append('
');
      $(div).append(this.select("state", ["unstarted", "started", "finished", "delivered", "accepted", "rejected"]));
      $(this.el).append(div);

      div = this.make('div');
      $(div).append(this.label("description"));
      $(div).append('
');
      $(div).append(this.textArea("description"));
      $(this.el).append(div);

    } else {
      $(this.el).html($('#story_tmpl').tmpl(this.model.toJSON()));
    }
    return this;
  }
});

var AppView = Backbone.View.extend({

  initialize: function() {
    _.bindAll(this, 'addOne', 'addAll', 'render');

    window.Project.stories.bind('add', this.addOne);
    window.Project.stories.bind('refresh', this.addAll);
    window.Project.stories.bind('all', this.render);

    window.Project.stories.fetch();
  },

  addOne: function(story) {
    var view = new StoryView({model: story, id: story.id, className: story.className()});
    $(story.column()).append(view.render().el);
  },

  addAll: function() {
    window.Project.stories.each(this.addOne);
  }
});

$(function() {
  $('#add_story').click(function() {
    window.Project.stories.add([{
      title: "New story", events: [], editing: true
    }]);
  });
});
<|endoftext|>