<commit_before>'use strict'

const { join } = require('path')
const { readFileSync, writeFileSync } = require('fs')
const { get } = require('https')

function getCurrentSHA (author) {
  return new Promise((resolve, reject) => {
    let isBranch = process.argv[2].indexOf('#') > -1

    get({
      host: 'api.github.com',
      path: `/repos/simulatedgreg/electron-vue/commits${isBranch ? '?sha=' + process.argv[2].split('#')[1] : ''}`,
      headers: {
        'User-Agent': author
      }
    }, res => {
      res.setEncoding('utf8')
      let rawData = ''

      res.on('data', chunk => {
        rawData += chunk
      })
      res.on('end', () => {
        try {
          let parsed = JSON.parse(rawData)
          resolve(parsed[0].sha)
        } catch (e) {
          reject(e)
        }
      })
    }).on('error', e => {
      reject(e)
    })
  })
}

function appendSHALink (sha, destDirName) {
  let readmePath = join(destDirName, '/README.md')
  let md = readFileSync(readmePath, 'utf8')
  md = md.replace(
    ' using',
    `@[${sha.substring(0, 7)}](https://github.com/SimulatedGREG/electron-vue/tree/${sha}) using`
  )
  writeFileSync(readmePath, md, 'utf8')
}

module.exports = {
  prompts: {
    name: {
      type: 'string',
      required: true,
      message: 'Application Name'
    },
    description: {
      type: 'string',
      required: false,
      message: 'Project description',
      default: 'An electron-vue project'
    },
    plugins: {
      type: 'checkbox',
      message: 'Select which Vue plugins to install',
      choices: ['axios', 'vue-electron', 'vue-router', 'vuex'],
      default: ['axios', 'vue-electron', 'vue-router', 'vuex']
    },
    eslint: {
      type: 'confirm',
      require: true,
      message: 'Use linting with ESLint?',
      default: true
    },
    eslintConfig: {
      when: 'eslint',
      type: 'list',
      message: 'Which eslint config would you like to use?',
      choices: [
        {
          name: 'Standard (https://github.com/feross/standard)',
          value: 'standard',
          short: 'Standard'
        },
        {
          name: 'AirBNB (https://github.com/airbnb/javascript)',
          value: 'airbnb',
          short: 'AirBNB'
        },
        {
          name: 'none (configure it yourself)',
          value: 'none',
          short: 'none'
        }
      ]
    },
    unit: {
      type: 'confirm',
      message: 'Setup unit testing with Karma + Mocha?',
      required: true
    },
    e2e: {
      type: 'confirm',
      message: 'Setup end-to-end testing with Spectron + Mocha?',
      require: true
    },
    builder: {
      type: 'list',
      message: 'What build tool would you like to use?',
      choices: [
        {
          name: 'electron-builder (https://github.com/electron-userland/electron-builder)',
          value: 'builder',
          short: 'builder'
        },
        {
          name: 'electron-packager (https://github.com/electron-userland/electron-packager)',
          value: 'packager',
          short: 'packager'
        }
      ]
    }
  },
  helpers: {
    isEnabled (list, check, opts) {
      if (list[check]) return opts.fn(this)
      else return opts.inverse(this)
    },
    deps (plugins) {
      let output = ''
      let dependencies = {
        'axios': '^0.16.1',
        'vue-electron': '^1.0.6',
        'vue-router': '^2.5.3',
        'vuex': '^2.3.1'
      }

      if (Object.keys(plugins).length > 0) output += ',\n'

      Object.keys(plugins).forEach((p, i) => {
        output += `    "${p}": "${dependencies[p]}"`
        if (i !== Object.keys(plugins).length - 1) output += ',\n'
      })

      return output
    },
    testing (unit, e2e, opts) {
      if (unit || e2e) {
        return opts.fn(this)
      }
    }
  },
  filters: {
    'src/renderer/routes.js': 'plugins[\'vue-router\']',
    'src/renderer/components/LandingPageView/CurrentPage.vue': 'plugins[\'vue-router\']',
    'src/renderer/router/**/*': 'plugins[\'vue-router\']',
    'src/renderer/store/**/*': 'plugins[\'vuex\']',
    'test/e2e/**/*': 'e2e',
    'test/unit/**/*': 'unit',
    '.electron-vue/build.config.js': 'builder === \'packager\'',
    'test/.eslintrc': 'e2e || unit',
    '.eslintignore': 'eslint',
    '.eslintrc.js': 'eslint',
    'appveyor.yml': 'builder === \'builder\'',
    '.travis.yml': 'builder === \'builder\''
  },
  complete (data) {
    getCurrentSHA(data.author).then(sha => {
      let path = !data.inPlace ? data.destDirName : null
      if (path !== null) appendSHALink(sha, path)
      console.log([
        '\n---',
        '',
        'All set. Welcome to your new electron-vue project!',
        '',
        'Make sure to check out the documentation for this boilerplate at',
        '\x1b[33mhttps://simulatedgreg.gitbooks.io/electron-vue/content/\x1b[0m.',
        '',
        `Next Steps:\n${!data.inPlace ? '\n  \x1b[33m$\x1b[0m cd ' + data.destDirName : ''}`,
        '  \x1b[33m$\x1b[0m yarn (or `npm install`)',
        '  \x1b[33m$\x1b[0m yarn run dev (or `npm run dev`)'
      ].join('\n'))
    }, () => {
      console.log('\x1b[33mwarning\x1b[0m Failed to append commit SHA on README.md')
    })
  }
}
<commit_msg>Update meta.js<commit_after>'use strict'

const { join } = require('path')
const { readFileSync, writeFileSync } = require('fs')
const { get } = require('https')

function getCurrentSHA (author) {
  return new Promise((resolve, reject) => {
    let isBranch = process.argv[2].indexOf('#') > -1

    get({
      host: 'api.github.com',
      path: `/repos/simulatedgreg/electron-vue/commits${isBranch ? '?sha=' + process.argv[2].split('#')[1] : ''}`,
      headers: {
        'User-Agent': author
      }
    }, res => {
      res.setEncoding('utf8')
      let rawData = ''

      res.on('data', chunk => {
        rawData += chunk
      })
      res.on('end', () => {
        try {
          let parsed = JSON.parse(rawData)
          resolve(parsed[0].sha)
        } catch (e) {
          reject(e)
        }
      })
    }).on('error', e => {
      reject(e)
    })
  })
}

function appendSHALink (sha, destDirName) {
  let readmePath = join(destDirName, '/README.md')
  let md = readFileSync(readmePath, 'utf8')
  md = md.replace(
    ' using',
    `@[${sha.substring(0, 7)}](https://github.com/SimulatedGREG/electron-vue/tree/${sha}) using`
  )
  writeFileSync(readmePath, md, 'utf8')
}

module.exports = {
  prompts: {
    name: {
      type: 'string',
      required: true,
      message: 'Application Name'
    },
    description: {
      type: 'string',
      required: false,
      message: 'Project description',
      default: 'An electron-vue project'
    },
    plugins: {
      type: 'checkbox',
      message: 'Select which Vue plugins to install',
      choices: ['axios', 'vue-electron', 'vue-router', 'vuex'],
      default: ['axios', 'vue-electron', 'vue-router', 'vuex']
    },
    eslint: {
      type: 'confirm',
      require: true,
      message: 'Use linting with ESLint?',
      default: true
    },
    eslintConfig: {
      when: 'eslint',
      type: 'list',
      message: 'Which ESLint config would you like to use?',
      choices: [
        {
          name: 'Standard (https://github.com/feross/standard)',
          value: 'standard',
          short: 'Standard'
        },
        {
          name: 'Airbnb (https://github.com/airbnb/javascript)',
          value: 'airbnb',
          short: 'Airbnb'
        },
        {
          name: 'none (configure it yourself)',
          value: 'none',
          short: 'none'
        }
      ]
    },
    unit: {
      type: 'confirm',
      message: 'Set up unit testing with Karma + Mocha?',
      required: true
    },
    e2e: {
      type: 'confirm',
      message: 'Set up end-to-end testing with Spectron + Mocha?',
      require: true
    },
    builder: {
      type: 'list',
      message: 'What build tool would you like to use?',
      choices: [
        {
          name: 'electron-builder (https://github.com/electron-userland/electron-builder)',
          value: 'builder',
          short: 'builder'
        },
        {
          name: 'electron-packager (https://github.com/electron-userland/electron-packager)',
          value: 'packager',
          short: 'packager'
        }
      ]
    }
  },
  helpers: {
    isEnabled (list, check, opts) {
      if (list[check]) return opts.fn(this)
      else return opts.inverse(this)
    },
    deps (plugins) {
      let output = ''
      let dependencies = {
        'axios': '^0.16.1',
        'vue-electron': '^1.0.6',
        'vue-router': '^2.5.3',
        'vuex': '^2.3.1'
      }

      if (Object.keys(plugins).length > 0) output += ',\n'

      Object.keys(plugins).forEach((p, i) => {
        output += `    "${p}": "${dependencies[p]}"`
        if (i !== Object.keys(plugins).length - 1) output += ',\n'
      })

      return output
    },
    testing (unit, e2e, opts) {
      if (unit || e2e) {
        return opts.fn(this)
      }
    }
  },
  filters: {
    'src/renderer/routes.js': 'plugins[\'vue-router\']',
    'src/renderer/components/LandingPageView/CurrentPage.vue': 'plugins[\'vue-router\']',
    'src/renderer/router/**/*': 'plugins[\'vue-router\']',
    'src/renderer/store/**/*': 'plugins[\'vuex\']',
    'test/e2e/**/*': 'e2e',
    'test/unit/**/*': 'unit',
    '.electron-vue/build.config.js': 'builder === \'packager\'',
    'test/.eslintrc': 'e2e || unit',
    '.eslintignore': 'eslint',
    '.eslintrc.js': 'eslint',
    'appveyor.yml': 'builder === \'builder\'',
    '.travis.yml': 'builder === \'builder\''
  },
  complete (data) {
    getCurrentSHA(data.author).then(sha => {
      let path = !data.inPlace ? data.destDirName : null
      if (path !== null) appendSHALink(sha, path)
      console.log([
        '\n---',
        '',
        'All set. Welcome to your new electron-vue project!',
        '',
        'Make sure to check out the documentation for this boilerplate at',
        '\x1b[33mhttps://simulatedgreg.gitbooks.io/electron-vue/content/\x1b[0m.',
        '',
        `Next Steps:\n${!data.inPlace ? '\n  \x1b[33m$\x1b[0m cd ' + data.destDirName : ''}`,
        '  \x1b[33m$\x1b[0m yarn (or `npm install`)',
        '  \x1b[33m$\x1b[0m yarn run dev (or `npm run dev`)'
      ].join('\n'))
    }, () => {
      console.log('\x1b[33mwarning\x1b[0m Failed to append commit SHA on README.md')
    })
  }
}
<|endoftext|>


<commit_before>"use strict";

module.exports = {
  entry: "./home",
  output: {
    filename: "build.js",
    library: "home"
  },

  watch: true,

  watchOptions: {
    aggregateOptions: 100
  },

  devtool: "source-map"
};
<commit_msg>Use webpack plugins and constants for environment<commit_after>"use strict";

const webpack = require("webpack");

const DEV_ENV = "development";
const NODE_ENV = process.env.NODE_ENV || DEV_ENV;

module.exports = {
  entry: "./home",
  output: {
    filename: "build.js",
    library: "home"
  },

  watch: NODE_ENV == DEV_ENV,

  watchOptions: {
    aggregateOptions: 100
  },

  devtool: NODE_ENV == DEV_ENV ? "cheap-inline-module-source-map" : null,

  plugins: [
    new webpack.EnvironmentPlugin("NODE_ENV")
  ]
};
<|endoftext|>


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

var bowerPath = './bower_components';

module.exports = {
    devTool: 'source-map',
    entry: {
        'index1': ['./src/js/index1.js'],
        'index2': ['./src/js/index2.js']
    },
    output: {
        filename: '[name].js'
    },
    module: {
        loaders: [
            {test: /\.vue$/, loader: 'vue'}
        ]
    },
    resolve: {
        extensions: ['', '.js', '.vue', '.json', '.less'],
        alias: {
            jquery: bowerPath + '/jquery/dist/jquery.min.js',
            bootstrap: bowerPath + './bower_components/bootstrap/dist/js/bootstrap.min.js'
        }
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            bootstrap: 'bootstrap'
        })
    ]
};
<commit_msg>add uglify<commit_after>var webpack = require('webpack');

var bowerPath = './bower_components';

module.exports = {
    devTool: 'source-map',
    entry: {
        'index1': ['./src/js/index1.js'],
        'index2': ['./src/js/index2.js']
    },
    output: {
        filename: '[name].js'
    },
    module: {
        loaders: [
            {test: /\.vue$/, loader: 'vue'}
        ]
    },
    resolve: {
        extensions: ['', '.js', '.vue', '.json', '.less'],
        alias: {
            jquery: bowerPath + '/jquery/dist/jquery.min.js',
            bootstrap: bowerPath + './bower_components/bootstrap/dist/js/bootstrap.min.js'
        }
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            bootstrap: 'bootstrap'
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
    ]
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path');

var isTest = (process.argv.indexOf('--test') !== -1);

var loaders = [
  {
    test: /\.js$/,
    exclude: [
      /node_modules/
    ],
    loaders: [
      'babel-loader'
    ]
  }
];

if(isTest){
  loaders.push({
    test: /\.js$/,
    exclude: [
      /__tests__/,
      /node_modules/
    ],
    loader: 'isparta-loader'
  })
}

module.exports = {
  entry: {
    bundle: path.join(__dirname, 'example/index.js')
  },
  output: {
    filename: '[name].js',
    path: path.join(__dirname, 'example')
  },
  module: {
    loaders: loaders
  }
};
<commit_msg>added missing semi-colon in webpack.config<commit_after>'use strict';

var path = require('path');

var isTest = (process.argv.indexOf('--test') !== -1);

var loaders = [
  {
    test: /\.js$/,
    exclude: [
      /node_modules/
    ],
    loaders: [
      'babel-loader'
    ]
  }
];

if(isTest){
  loaders.push({
    test: /\.js$/,
    exclude: [
      /__tests__/,
      /node_modules/
    ],
    loader: 'isparta-loader'
  });
}

module.exports = {
  entry: {
    bundle: path.join(__dirname, 'example/index.js')
  },
  output: {
    filename: '[name].js',
    path: path.join(__dirname, 'example')
  },
  module: {
    loaders: loaders
  }
};
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');

module.exports = {
    entry: './assets/js/main.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'build'),
    },
    module: {
        rules: [
            {
                test: /\.tag?$/,
                exclude: /node_modules/,
                enforce: 'pre',
                use: 'riotjs-loader'
            },
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                use: 'babel-loader',
            },
            {
                test: /\.md?$/,
                use: [
                    'html-loader',
                    { loader: 'markdown-loader', options: { breaks: true } },
                ],
            },
            {
                test: /\.less?$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'less-loader',
                ],
            },
            {
                test: /\.(jpg|jpeg|png|svg)?$/i,
                use: 'file-loader',
                // use: {
                //     loader: 'file-loader',
                //     options: {
                //         publicPath: 'assets/images/',
                //         useRelativePath: true,
                //     },
                // },
            },
        ],
    },
    plugins: [
        new webpack.ProvidePlugin({
            riot: 'riot'
        }),
    ],
    resolve: {
        modules: [
            path.resolve(__dirname, './'),
            path.resolve(__dirname, 'assets'),
            'node_modules',
        ],
        extensions: ['.js', '.tag', '.md', '.less'],
    },
};

// const HtmlWebpackPlugin = require('html-webpack-plugin');
// const webpack = require('webpack');

/*
module.exports = {
    entry: './assets/js/main.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'build')
    },
    module: {
        rules: [
            {
                test: /\.tag?$/,
                exclude: /node_modules/,
                enforce: 'pre',
                use: 'riotjs-loader'
            },
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            },
            {
                test: /\.md?$/,
                use: [
                    'html-loader',
                    { loader: 'markdown-loader', options: { breaks: true } }
                ]
            },
            {
                test: /\.less?$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'less-loader'
                ]
            },
            {
                test: /\.(jpg|jpeg|png|svg)?$/i,
                use: 'file-loader'
            }
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
            riot: 'riot'
        }),
        new HtmlWebpackPlugin({
            template: './index.html',
            inject: false
        }),
        new webpack.HotModuleReplacementPlugin(),
    ],
    resolve: {
        modules: [
            path.resolve(__dirname, './'),
            path.resolve(__dirname, 'assets'),
            'node_modules'
        ]
    },
    devServer: {
        compress: true,
        historyApiFallback: true,
        host: '0.0.0.0',
        hot: false,
        inline: true,
        publicPath: '/build/'
    },
    resolve: {
        extensions: ['.js', '.tag', '.md', '.less']
    }
};
*/<commit_msg>Clean up webpack base config.<commit_after>const path = require('path');
const webpack = require('webpack');

module.exports = {
    entry: './assets/js/main.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'build'),
    },
    module: {
        rules: [
            {
                test: /\.tag?$/,
                exclude: /node_modules/,
                enforce: 'pre',
                use: 'riotjs-loader'
            },
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                use: 'babel-loader',
            },
            {
                test: /\.md?$/,
                use: [
                    'html-loader',
                    { loader: 'markdown-loader', options: { breaks: true } },
                ],
            },
            {
                test: /\.less?$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'less-loader',
                ],
            },
            {
                test: /\.(jpg|jpeg|png|svg)?$/i,
                use: 'file-loader',
            },
        ],
    },
    plugins: [
        new webpack.ProvidePlugin({
            riot: 'riot'
        }),
    ],
    resolve: {
        modules: [
            path.resolve(__dirname, './'),
            path.resolve(__dirname, 'assets'),
            'node_modules',
        ],
        extensions: ['.js', '.tag', '.md', '.less'],
    },
};
<|endoftext|>


<commit_before>const path = require("path");

var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");

var config = {
    entry : SRC_DIR + "/app/index.js",
    output : {
        path : DIST_DIR + "/app",
        filename : "bundle.js",
        publicPath : "/app/"
    },
    module : {
        rules : [
            {
                test : /\.js?/,
                include : SRC_DIR,
                loader : "babel-loader",
                query : {
                    presets : ["react", "es2015", "stage-2"]
                }
            }
        ]
    }
};

module.exports = config;
<commit_msg>Finally worked<commit_after>const path = require("path");

var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");

module.exports = {
    entry : SRC_DIR + "/app/index.js",
    output : {
        path : DIST_DIR + "/app",
        filename : "bundle.js",
        publicPath : "/app/"
    },
    module : {
        rules : [
            {
                test : /\.js?/,
                include : SRC_DIR,
                loader : "babel-loader",
                query : {
                    presets : ["react", "es2015", "stage-2"]
                }
            }
        ]
    },
    devServer: {
        open: true, // to open the local server in browser
        contentBase: __dirname + '/src',
    },
};
<|endoftext|>


<commit_before>var path = require('path')
var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './build'),
    publicPath: '/',
    filename: 'js/build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      },
      {
        test: /\.ejs$/,
        loader: 'ejs-compiled-loader'
      },
      {
        // Disable the hot-reloader
        test: path.resolve(__dirname, 'node_modules/webpack-dev-server/client'),
        loader: "null-loader"
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    contentBase: 'build/'
  },
  performance: {
    hints: false
  },
  devtool: '#source-map',
  plugins: [
    new HtmlWebpackPlugin({
      title: 'The Thousand Ether Homepage · Own a piece of blockchain history!',
      filename: 'index.html',
      template: 'src/templates/index.ejs',
      inject: false
    }),
    new HtmlWebpackPlugin({
      title: 'Press · The Thousand Ether Homepage',
      filename: 'press/index.html',
      template: 'src/templates/press.ejs',
      inject: false
    }),
    new HtmlWebpackPlugin({
      title: 'FAQ · The Thousand Ether Homepage',
      filename: 'faq/index.html',
      template: 'src/templates/faq.ejs',
      inject: false
    })
  ]
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    /* FIXME: Uglify is borken?
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    */
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}
<commit_msg>Delete webpack.config.js, not using it anymore<commit_after><|endoftext|>


<commit_before>/* global __dirname */

const path = require('path')

module.exports = {
  entry: './src/index.js',
  devtool: 'source-map',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index.js',
    libraryTarget: 'umd',
    library: 'ScrollSync'
  },
  module: {
    loaders: [
      {
        include: [
          path.resolve(__dirname, 'src')
        ],
        test: /\.js$/,
        loader: 'babel-loader'
      }
    ]
  },
  resolve: {
    // Can require('file') instead of require('file.js') etc.
    extensions: ['', '.js', '.json']
  },
  externals: {
    react: 'react',
    'react-dom': 'react-dom'
  }
}
<commit_msg>Use path.join<commit_after>/* global __dirname */

const path = require('path')

module.exports = {
  entry: './src/index.js',
  devtool: 'source-map',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'index.js',
    libraryTarget: 'umd',
    library: 'ScrollSync'
  },
  module: {
    loaders: [
      {
        include: [
          path.resolve(__dirname, 'src')
        ],
        test: /\.js$/,
        loader: 'babel-loader'
      }
    ]
  },
  resolve: {
    // Can require('file') instead of require('file.js') etc.
    extensions: ['', '.js', '.json']
  },
  externals: {
    react: 'react',
    'react-dom': 'react-dom'
  }
}
<|endoftext|>


<commit_before>const webpack = require('webpack');
const path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const version = require('project-version');

module.exports = {
  entry: {
    main: './src/index.ts',
    collisions: './src/collisions/index.ts',
  },
  output: {
    filename: 'bundle.[contenthash].js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: [
          'vue-loader',
        ],
      },
      {
        test: /\.tsx?$/,
        use: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.s[ac]ss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader',
        ],
      },
      {
        test: /\.toml$/,
        use: [
          'raw-loader',
        ],
      },
      {
        test: /\.svg$/,
        use: [
          'svg-url-loader',
        ],
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js', '.vue'],
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
  plugins: [
    new webpack.DefinePlugin({
      __VERSION__: JSON.stringify(version)
    }),
    new CleanWebpackPlugin(),
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({
      title: "Gallifreyo · Gallifreyan Translator",
      template: './src/template.ejs',
      filename: 'index.html',
      chunks: ['main'],
    }),
    new HtmlWebpackPlugin({
      title: "Gallifreyo · Collisions Test",
      template: './src/template.ejs',
      filename: 'collisions/index.html',
      chunks: ['collisions'],
    }),
  ],
};
<commit_msg>Add viewport<commit_after>const webpack = require('webpack');
const path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const version = require('project-version');

module.exports = {
  entry: {
    main: './src/index.ts',
    collisions: './src/collisions/index.ts',
  },
  output: {
    filename: 'bundle.[contenthash].js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: [
          'vue-loader',
        ],
      },
      {
        test: /\.tsx?$/,
        use: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.s[ac]ss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader',
        ],
      },
      {
        test: /\.toml$/,
        use: [
          'raw-loader',
        ],
      },
      {
        test: /\.svg$/,
        use: [
          'svg-url-loader',
        ],
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js', '.vue'],
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
  plugins: [
    new webpack.DefinePlugin({
      __VERSION__: JSON.stringify(version)
    }),
    new CleanWebpackPlugin(),
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({
      title: "Gallifreyo · Gallifreyan Translator",
      template: './src/template.ejs',
      filename: 'index.html',
      chunks: ['main'],
      meta: { viewport: "width=device-width, initial-scale=1" },
    }),
    new HtmlWebpackPlugin({
      title: "Gallifreyo · Collisions Test",
      template: './src/template.ejs',
      filename: 'collisions/index.html',
      chunks: ['collisions'],
      meta: { viewport: "width=device-width, initial-scale=1" },
    }),
  ],
};
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');

var pluginArray = [];

var sourceMapType = 'source-map';

if (process.env.NODE_ENV !== 'development') {

/*
    console.log('Development environment detected, enabling Bundle Analyzer');

    var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

    pluginArray.push(new BundleAnalyzerPlugin({
        // Can be `server`, `static` or `disabled`.
        // In `server` mode analyzer will start HTTP server to show bundle report.
        // In `static` mode single HTML file with bundle report will be generated.
        // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
        analyzerMode: 'static',
        // Host that will be used in `server` mode to start HTTP server.
        analyzerHost: '127.0.0.1',
        // Port that will be used in `server` mode to start HTTP server.
        analyzerPort: 8888,
        // Path to bundle report file that will be generated in `static` mode.
        // Relative to bundles output directory.
        reportFilename: 'bundle_report.html',
        // Module sizes to show in report by default.
        // Should be one of `stat`, `parsed` or `gzip`.
        // See "Definitions" section for more information.
        defaultSizes: 'parsed',
        // Automatically open report in default browser
        openAnalyzer: true,
        // If `true`, Webpack Stats JSON file will be generated in bundles output directory
        generateStatsFile: false,
        // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
        // Relative to bundles output directory.
        statsFilename: 'stats.json',
        // Options for `stats.toJson()` method.
        // For example you can exclude sources of your modules from stats file with `source: false` option.
        // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
        statsOptions: null,
        // Log level. Can be 'info', 'warn', 'error' or 'silent'.
        logLevel: 'info'
    }));
*/

}

var jq = new webpack.ProvidePlugin({
    $: "jquery",
    jQuery: "jquery",
    "window.jQuery": "jquery'",
    "window.$": "jquery"
});

pluginArray.push(jq);

// Strip all locales except the ones defined in lib/language.js
// (“en” is built into Moment and can’t be removed, 'dk' is not defined in moment)
 var momentLocales = new MomentLocalesPlugin({
            localesToKeep: ['bg', 'cs', 'de', 'el', 'es', 'fi', 'fr', 'he', 'hr', 'it', 'ko', 'nb', 'nl', 'pl', 'pt', 'ro', 'ru', 'sk', 'sv', 'zh_cn', 'zh_tw'],
        }) ;
pluginArray.push(momentLocales);

module.exports = {
    context: path.resolve(__dirname, '.'),
    entry: {
        app: './bundle/bundle.source.js'
    },
    output: {
        path: path.resolve(__dirname, './tmp'),
        publicPath: '/',
        filename: 'js/bundle.js',
        sourceMapFilename: "js/bundle.js.map",
    },
    devtool: sourceMapType,
    plugins: pluginArray,
    module: {
        rules: [{
                test: /\.(jpe?g|png|gif)$/i,
                loader: "file-loader",
                query: {
                    name: '[name].[ext]',
                    outputPath: 'images/'
                        //the images will be emmited to public/assets/images/ folder
                        //the images will be put in the DOM <style> tag as eg. background: url(assets/images/image.png);
                },
                exclude: /node_modules/
        },
            {
                test: /\.css$/,
                loaders: ["style-loader", "css-loader"],
                exclude: /node_modules/
            }, {
                test: require.resolve('jquery'),
                use: [{
                    loader: 'expose-loader',
                    options: '$'
                }]
            }
        ]
    }
};<commit_msg>reformat indent =2<commit_after>const path = require('path');
const webpack = require('webpack');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');

var pluginArray = [];

var sourceMapType = 'source-map';

if (process.env.NODE_ENV !== 'development') {

  /*
   console.log('Development environment detected, enabling Bundle Analyzer');

   var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

   pluginArray.push(new BundleAnalyzerPlugin({
   // Can be `server`, `static` or `disabled`.
   // In `server` mode analyzer will start HTTP server to show bundle report.
   // In `static` mode single HTML file with bundle report will be generated.
   // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting
   // `generateStatsFile` to `true`.
   analyzerMode: 'static',
   // Host that will be used in `server` mode to start HTTP server.
   analyzerHost: '127.0.0.1',
   // Port that will be used in `server` mode to start HTTP server.
   analyzerPort: 8888,
   // Path to bundle report file that will be generated in `static` mode.
   // Relative to bundles output directory.
   reportFilename: 'bundle_report.html',
   // Module sizes to show in report by default.
   // Should be one of `stat`, `parsed` or `gzip`.
   // See "Definitions" section for more information.
   defaultSizes: 'parsed',
   // Automatically open report in default browser
   openAnalyzer: true,
   // If `true`, Webpack Stats JSON file will be generated in bundles output directory
   generateStatsFile: false,
   // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
   // Relative to bundles output directory.
   statsFilename: 'stats.json',
   // Options for `stats.toJson()` method.
   // For example you can exclude sources of your modules from stats file with `source: false` option.
   // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
   statsOptions: null,
   // Log level. Can be 'info', 'warn', 'error' or 'silent'.
   logLevel: 'info'
   }));
   */
}

var jq = new webpack.ProvidePlugin({
  $: "jquery",
  jQuery: "jquery",
  "window.jQuery": "jquery'",
  "window.$": "jquery"
});

pluginArray.push(jq);

// Strip all locales except the ones defined in lib/language.js
// (“en” is built into Moment and can’t be removed, 'dk' is not defined in moment)
var momentLocales = new MomentLocalesPlugin({
  localesToKeep: ['bg', 'cs', 'de', 'el', 'es', 'fi', 'fr', 'he', 'hr', 'it', 'ko', 'nb', 'nl', 'pl', 'pt', 'ro', 'ru',
    'sk', 'sv', 'zh_cn', 'zh_tw'],
});
pluginArray.push(momentLocales);

module.exports = {
  context: path.resolve(__dirname, '.'),
  entry: {
    app: './bundle/bundle.source.js'
  },
  output: {
    path: path.resolve(__dirname, './tmp'),
    publicPath: '/',
    filename: 'js/bundle.js',
    sourceMapFilename: "js/bundle.js.map",
  },
  devtool: sourceMapType,
  plugins: pluginArray,
  module: {
    rules: [{
      test: /\.(jpe?g|png|gif)$/i,
      loader: "file-loader",
      query: {
        name: '[name].[ext]',
        outputPath: 'images/'
        //the images will be emmited to public/assets/images/ folder
        //the images will be put in the DOM <style> tag as eg. background: url(assets/images/image.png);
      },
      exclude: /node_modules/
    },
      {
        test: /\.css$/,
        loaders: ["style-loader", "css-loader"],
        exclude: /node_modules/
      }, {
        test: require.resolve('jquery'),
        use: [{
          loader: 'expose-loader',
          options: '$'
        }]
      }
    ]
  }
};<|endoftext|>


<commit_before>/* Copyright (c) 2006 MetaCarta, Inc., published under the BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the full
 * text of the license. */

// @require: OpenLayers/Layer/HTTPRequest.js
// @require: OpenLayers/Util.js

/**
 * @class
 */
OpenLayers.Layer.Grid = Class.create();
OpenLayers.Layer.Grid.prototype =
  Object.extend( new OpenLayers.Layer.HTTPRequest(), {

    /** @type OpenLayers.Size */
    tileSize: null,

    /** this is an array of rows, each row is an array of tiles
     *
     * @type Array(Array) */
    grid: null,

    /** @type Integer */
    buffer: 2,

    /**
     * @constructor
     *
     * @param {String} name
     * @param {String} url
     * @param {Object} params
     * @param {Object} options Hashtable of extra options to tag onto the layer
    */
    initialize: function(name, url, params, options) {
        OpenLayers.Layer.HTTPRequest.prototype.initialize.apply(this,
                                                                arguments);
        this.grid = new Array();
    },

    /** on destroy, clear the grid.
     *
     */
    destroy: function() {
        this.clearGrid();
        this.grid = null;
        this.alpha = null;
        this.tileSize = null;
        OpenLayers.Layer.HTTPRequest.prototype.destroy.apply(this, arguments);
    },

    /**
     * @param {Object} obj
     *
     * @returns An exact clone of this OpenLayers.Layer.Grid
     * @type OpenLayers.Layer.Grid
     */
    clone: function (obj) {

        if (obj == null) {
            obj = new OpenLayers.Layer.Grid(this.name,
                                            this.url,
                                            this.params,
                                            this.options);
        }

        //get all additions from superclasses
        obj = OpenLayers.Layer.HTTPRequest.prototype.clone.apply(this, [obj]);

        // copy/set any non-init, non-simple values here
        if (this.tileSize != null) {
            obj.tileSize = this.tileSize.clone();
        }

        // we do not want to copy reference to grid. that should stay at null
        obj.grid = null;

        return obj;
    },

    /** When the layer is added to a map, then we can ask the map for
     *   its default tile size
     *
     * @param {OpenLayers.Map} map
     */
    setMap: function(map) {
        OpenLayers.Layer.HTTPRequest.prototype.setMap.apply(this, arguments);
        if (this.tileSize == null) {
            this.tileSize = this.map.getTileSize();
        }
    },

    /**
     * @deprecated User should just set the 'tileSize' via options
     *
     * @param {OpenLayers.Size} size
     */
    setTileSize: function (size) {
        if (size) {
            this.tileSize = size.clone();
        }
    },

    /**
     * @param {String} tileID
     *
     * @returns The OpenLayers.Tile with the corresponding ID from the grid.
     *           if no tile is found, returns null
     * @type OpenLayers.Tile
     */
    getTile: function(tileID) {
        var foundTile = null;
        if (this.grid) {

            for(var iRow = 0; iRow < this.grid.length; iRow++) {
                var row = this.grid[iRow];
                for(var iCol = 0; iCol < row.length; iCol++) {
                    var tile = row[iCol];
                    if (tile.id == tileID) {
                        foundTile = tile;
                    }
                }
            }
        }
        return foundTile;
    },

    /** This function is called whenever the map is moved. All the moving
     * of actual 'tiles' is done by the map, but moveTo's role is to accept
     * a bounds and make sure the data that that bounds requires is pre-loaded.
     *
     * @param {OpenLayers.Bounds} bounds
     * @param {Boolean} zoomChanged
     * @param {Boolean} dragging
     */
    moveTo:function(bounds, zoomChanged, dragging) {
        if (bounds == null) {
            bounds = this.map.getExtent();
        }
        if (bounds != null) {
            if (!this.getVisibility()) {
                if (zoomChanged) {
                    // HACK HACK HACK -- should be this.hideGrid() basically
                }
            } else if (!this.grid.length || zoomChanged
                      || !this.getGridBounds().containsBounds(bounds, true)) {
                this._initTiles();
            } else {
                while (true) {
                    var topLeft = this.map.getViewPortPxFromLayerPx( this.grid[0][0].position );
                    if (topLeft.x > -this.tileSize.w * (this.buffer - 1)) {
                        this.shiftColumn(true);
                    } else if (topLeft.x < -this.tileSize.w * this.buffer) {
                        this.shiftColumn(false);
                    } else if (topLeft.y > -this.tileSize.w * (this.buffer - 1)) {
                        this.shiftRow(true);
                    } else if (topLeft.y < -this.tileSize.h * this.buffer) {
                        this.shiftRow(false);
                    } else {
                        break;
                    }
                }
            }
        }
    },

    /**
     * @returns A Bounds object representing the bounds of all the currently
     *           loaded tiles (including those partially or not at all seen
     *           onscreen)
     * @type OpenLayers.Bounds
     */
    getGridBounds:function() {

        var bottom = this.grid.length - 1;
        var bottomLeftTile = this.grid[bottom][0];

        var right = this.grid[0].length - 1;
        var topRightTile = this.grid[0][right];

        return new OpenLayers.Bounds(bottomLeftTile.bounds.left,
                                     bottomLeftTile.bounds.bottom,
                                     topRightTile.bounds.right,
                                     topRightTile.bounds.top);
    },

    /**
     *
     */
    _initTiles:function() {
        var viewSize = this.map.getSize();
        var bounds = this.map.getExtent();
        var extent = this.map.getMaxExtent();
        var resolution = this.map.getResolution();
        var tilelon = resolution * this.tileSize.w;
        var tilelat = resolution * this.tileSize.h;

        var offsetlon = bounds.left - extent.left;
        var tilecol = Math.floor(offsetlon/tilelon) - this.buffer;
        var tilecolremain = offsetlon/tilelon - tilecol;
        var tileoffsetx = -tilecolremain * this.tileSize.w;
        var tileoffsetlon = extent.left + tilecol * tilelon;

        var offsetlat = bounds.top - (extent.bottom + tilelat);
        var tilerow = Math.ceil(offsetlat/tilelat) + this.buffer;
        var tilerowremain = tilerow - offsetlat/tilelat;
        var tileoffsety = -tilerowremain * this.tileSize.h;
        var tileoffsetlat = extent.bottom + tilerow * tilelat;

        tileoffsetx = Math.round(tileoffsetx); // heaven help us
        tileoffsety = Math.round(tileoffsety);

        this.origin = new OpenLayers.Pixel(tileoffsetx, tileoffsety);

        var startX = tileoffsetx;
        var startLon = tileoffsetlon;

        var newGrid = (this.grid.length == 0);
        var rowidx = 0;

        do {
            var row;

            row = this.grid[rowidx++];
            if (!row) {
                row = new Array();
                this.grid.push(row);
            }

            tileoffsetlon = startLon;
            tileoffsetx = startX;

            var colidx = 0;

            do {
                var tileBounds = new OpenLayers.Bounds(tileoffsetlon,
                                                      tileoffsetlat,
                                                      tileoffsetlon + tilelon,
                                                      tileoffsetlat + tilelat);

                var x = tileoffsetx;
                x -= parseInt(this.map.layerContainerDiv.style.left);

                var y = tileoffsety;
                y -= parseInt(this.map.layerContainerDiv.style.top);

                var px = new OpenLayers.Pixel(x, y);
                var tile;

                tile = row[colidx++];
                if (!tile) {
                    tile = this.addTile(tileBounds, px);
                    tile.draw();
                    row.push(tile);
                } else {
                    tile.moveTo(tileBounds, px);
                }

                tileoffsetlon += tilelon;
                tileoffsetx += this.tileSize.w;
            } while (tileoffsetlon <= bounds.right + tilelon * this.buffer)

            tileoffsetlat -= tilelat;
            tileoffsety += this.tileSize.h;
        } while(tileoffsetlat >= bounds.bottom - tilelat * this.buffer)

    },

    /**
     * addTile gives subclasses of Grid the opportunity to create an
     * OpenLayer.Tile of their choosing. The implementer should initialize
     * the new tile and take whatever steps necessary to display it.
     *
     * @param {OpenLayers.Bounds} bounds
     *
     * @returns The added OpenLayers.Tile
     * @type OpenLayers.Tile
     */
    addTile:function(bounds, position) {
        // Should be implemented by subclasses
    },

  /********************************************************/
  /*                                                      */
  /*                 Baselayer Functions                  */
  /*                                                      */
  /********************************************************/

    /**
     * @returns Degrees per Pixel
     * @type float
     */
    getResolution: function() {
        var maxRes = this.map.getMaxResolution();
        var zoom = this.map.getZoom();

        return maxRes / Math.pow(2, zoom);
    },

    /** Calculates based on resolution, center, and mapsize
     *
     * @returns A Bounds object which represents the lon/lat bounds of the
     *          current viewPort.
     * @type OpenLayers.Bounds
     */
    getExtent: function () {
        var extent = null;

        var center = this.map.getCenter();
        if (center != null) {

            var res = this.getResolution();
            var size = this.map.getSize();
            var w_deg = size.w * res;
            var h_deg = size.h * res;

            extent = new OpenLayers.Bounds(center.lon - w_deg / 2,
                                           center.lat - h_deg / 2,
                                           center.lon + w_deg / 2,
                                           center.lat + h_deg / 2);

        }

        return extent;
    },

    /**
     * @param {OpenLayers.Bounds} bounds
     *
     * @return {int}
     */
    getZoomForExtent: function (bounds) {

        var maxRes = this.map.getMaxResolution();
        var viewSize = this.map.getSize();

        var width = bounds.getWidth();
        var height = bounds.getHeight();

        var degPerPixel = (width > height) ? width / viewSize.w
                                           : height / viewSize.h;

        var zoom = Math.floor( (Math.log(maxRes/degPerPixel)) / Math.log(2) );

        var maxZoomLevel = this.map.getMaxZoomLevel();
        var minZoomLevel = this.map.getMinZoomLevel();

        //make sure zoom is within bounds
        zoom = Math.min( Math.max(zoom, minZoomLevel),
                         maxZoomLevel );

        return zoom;
    },

    /** go through and remove all tiles from the grid, calling
     *    destroy() on each of them to kill circular references
     *
     * @private
     */
    clearGrid:function() {
        if (this.grid) {
            while(this.grid.length > 0) {
                var row = this.grid[0];
                while(row.length > 0) {
                    var tile = row[0];
                    tile.destroy();
                    row.remove(tile);
                }
                this.grid.remove(row);
            }
        }
    },

    /**
     * @private
     *
     * @param {Boolean} prepend if true, prepend to beginning.
     *                          if false, then append to end
     */
    shiftRow:function(prepend) {
        var modelRowIndex = (prepend) ? 0 : (this.grid.length - 1);
        var modelRow = this.grid[modelRowIndex];

        var resolution = this.map.getResolution();
        var deltaY = (prepend) ? -this.tileSize.h : this.tileSize.h;
        var deltaLat = resolution * -deltaY;

        var row = (prepend) ? this.grid.pop() : this.grid.shift();

        for (var i=0; i < modelRow.length; i++) {
            var modelTile = modelRow[i];
            var bounds = modelTile.bounds.clone();
            var position = modelTile.position.clone();
            bounds.bottom = bounds.bottom + deltaLat;
            bounds.top = bounds.top + deltaLat;
            position.y = position.y + deltaY;
            row[i].moveTo(bounds, position);
        }

        if (prepend) {
            this.grid.unshift(row);
        } else {
            this.grid.push(row);
        }
    },

    /**
     * @private
     *
     * @param {Boolean} prepend if true, prepend to beginning.
     *                          if false, then append to end
     */
    shiftColumn: function(prepend) {
        var deltaX = (prepend) ? -this.tileSize.w : this.tileSize.w;
        var resolution = this.map.getResolution();
        var deltaLon = resolution * deltaX;

        for (var i=0; i<this.grid.length; i++) {
            var row = this.grid[i];
            var modelTileIndex = (prepend) ? 0 : (row.length - 1);
            var modelTile = row[modelTileIndex];

            var bounds = modelTile.bounds.clone();
            var position = modelTile.position.clone();
            bounds.left = bounds.left + deltaLon;
            bounds.right = bounds.right + deltaLon;
            position.x = position.x + deltaX;

            var tile = prepend ? this.grid[i].pop() : this.grid[i].shift()
            tile.moveTo(bounds, position);
            if (prepend) {
                this.grid[i].unshift(tile);
            } else {
                this.grid[i].push(tile);
            }
        }
    },

    /** @final @type String */
    CLASS_NAME: "OpenLayers.Layer.Grid"
});
<commit_msg>clean up clearGrid()<commit_after>/* Copyright (c) 2006 MetaCarta, Inc., published under the BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the full
 * text of the license. */

// @require: OpenLayers/Layer/HTTPRequest.js
// @require: OpenLayers/Util.js

/**
 * @class
 */
OpenLayers.Layer.Grid = Class.create();
OpenLayers.Layer.Grid.prototype =
  Object.extend( new OpenLayers.Layer.HTTPRequest(), {

    /** @type OpenLayers.Size */
    tileSize: null,

    /** this is an array of rows, each row is an array of tiles
     *
     * @type Array(Array) */
    grid: null,

    /** @type Integer */
    buffer: 2,

    /**
     * @constructor
     *
     * @param {String} name
     * @param {String} url
     * @param {Object} params
     * @param {Object} options Hashtable of extra options to tag onto the layer
    */
    initialize: function(name, url, params, options) {
        OpenLayers.Layer.HTTPRequest.prototype.initialize.apply(this,
                                                                arguments);
        this.grid = new Array();
    },

    /** on destroy, clear the grid.
     *
     */
    destroy: function() {
        this.clearGrid();
        this.grid = null;
        this.alpha = null;
        this.tileSize = null;
        OpenLayers.Layer.HTTPRequest.prototype.destroy.apply(this, arguments);
    },

    /**
     * @param {Object} obj
     *
     * @returns An exact clone of this OpenLayers.Layer.Grid
     * @type OpenLayers.Layer.Grid
     */
    clone: function (obj) {

        if (obj == null) {
            obj = new OpenLayers.Layer.Grid(this.name,
                                            this.url,
                                            this.params,
                                            this.options);
        }

        //get all additions from superclasses
        obj = OpenLayers.Layer.HTTPRequest.prototype.clone.apply(this, [obj]);

        // copy/set any non-init, non-simple values here
        if (this.tileSize != null) {
            obj.tileSize = this.tileSize.clone();
        }

        // we do not want to copy reference to grid. that should stay at null
        obj.grid = null;

        return obj;
    },

    /** When the layer is added to a map, then we can ask the map for
     *   its default tile size
     *
     * @param {OpenLayers.Map} map
     */
    setMap: function(map) {
        OpenLayers.Layer.HTTPRequest.prototype.setMap.apply(this, arguments);
        if (this.tileSize == null) {
            this.tileSize = this.map.getTileSize();
        }
    },

    /**
     * @deprecated User should just set the 'tileSize' via options
     *
     * @param {OpenLayers.Size} size
     */
    setTileSize: function (size) {
        if (size) {
            this.tileSize = size.clone();
        }
    },

    /**
     * @param {String} tileID
     *
     * @returns The OpenLayers.Tile with the corresponding ID from the grid.
     *           if no tile is found, returns null
     * @type OpenLayers.Tile
     */
    getTile: function(tileID) {
        var foundTile = null;
        if (this.grid) {

            for(var iRow = 0; iRow < this.grid.length; iRow++) {
                var row = this.grid[iRow];
                for(var iCol = 0; iCol < row.length; iCol++) {
                    var tile = row[iCol];
                    if (tile.id == tileID) {
                        foundTile = tile;
                    }
                }
            }
        }
        return foundTile;
    },

    /** This function is called whenever the map is moved. All the moving
     * of actual 'tiles' is done by the map, but moveTo's role is to accept
     * a bounds and make sure the data that that bounds requires is pre-loaded.
     *
     * @param {OpenLayers.Bounds} bounds
     * @param {Boolean} zoomChanged
     * @param {Boolean} dragging
     */
    moveTo:function(bounds, zoomChanged, dragging) {
        if (bounds == null) {
            bounds = this.map.getExtent();
        }
        if (bounds != null) {
            if (!this.getVisibility()) {
                if (zoomChanged) {
                    // HACK HACK HACK -- should be this.hideGrid() basically
                }
            } else if (!this.grid.length || zoomChanged
                      || !this.getGridBounds().containsBounds(bounds, true)) {
                this._initTiles();
            } else {
                while (true) {
                    var topLeft = this.map.getViewPortPxFromLayerPx( this.grid[0][0].position );
                    if (topLeft.x > -this.tileSize.w * (this.buffer - 1)) {
                        this.shiftColumn(true);
                    } else if (topLeft.x < -this.tileSize.w * this.buffer) {
                        this.shiftColumn(false);
                    } else if (topLeft.y > -this.tileSize.w * (this.buffer - 1)) {
                        this.shiftRow(true);
                    } else if (topLeft.y < -this.tileSize.h * this.buffer) {
                        this.shiftRow(false);
                    } else {
                        break;
                    }
                }
            }
        }
    },

    /**
     * @returns A Bounds object representing the bounds of all the currently
     *           loaded tiles (including those partially or not at all seen
     *           onscreen)
     * @type OpenLayers.Bounds
     */
    getGridBounds:function() {

        var bottom = this.grid.length - 1;
        var bottomLeftTile = this.grid[bottom][0];

        var right = this.grid[0].length - 1;
        var topRightTile = this.grid[0][right];

        return new OpenLayers.Bounds(bottomLeftTile.bounds.left,
                                     bottomLeftTile.bounds.bottom,
                                     topRightTile.bounds.right,
                                     topRightTile.bounds.top);
    },

    /**
     *
     */
    _initTiles:function() {
        var viewSize = this.map.getSize();
        var bounds = this.map.getExtent();
        var extent = this.map.getMaxExtent();
        var resolution = this.map.getResolution();
        var tilelon = resolution * this.tileSize.w;
        var tilelat = resolution * this.tileSize.h;

        var offsetlon = bounds.left - extent.left;
        var tilecol = Math.floor(offsetlon/tilelon) - this.buffer;
        var tilecolremain = offsetlon/tilelon - tilecol;
        var tileoffsetx = -tilecolremain * this.tileSize.w;
        var tileoffsetlon = extent.left + tilecol * tilelon;

        var offsetlat = bounds.top - (extent.bottom + tilelat);
        var tilerow = Math.ceil(offsetlat/tilelat) + this.buffer;
        var tilerowremain = tilerow - offsetlat/tilelat;
        var tileoffsety = -tilerowremain * this.tileSize.h;
        var tileoffsetlat = extent.bottom + tilerow * tilelat;

        tileoffsetx = Math.round(tileoffsetx); // heaven help us
        tileoffsety = Math.round(tileoffsety);

        this.origin = new OpenLayers.Pixel(tileoffsetx, tileoffsety);

        var startX = tileoffsetx;
        var startLon = tileoffsetlon;

        var newGrid = (this.grid.length == 0);
        var rowidx = 0;

        do {
            var row;

            row = this.grid[rowidx++];
            if (!row) {
                row = new Array();
                this.grid.push(row);
            }

            tileoffsetlon = startLon;
            tileoffsetx = startX;

            var colidx = 0;

            do {
                var tileBounds = new OpenLayers.Bounds(tileoffsetlon,
                                                      tileoffsetlat,
                                                      tileoffsetlon + tilelon,
                                                      tileoffsetlat + tilelat);

                var x = tileoffsetx;
                x -= parseInt(this.map.layerContainerDiv.style.left);

                var y = tileoffsety;
                y -= parseInt(this.map.layerContainerDiv.style.top);

                var px = new OpenLayers.Pixel(x, y);
                var tile;

                tile = row[colidx++];
                if (!tile) {
                    tile = this.addTile(tileBounds, px);
                    tile.draw();
                    row.push(tile);
                } else {
                    tile.moveTo(tileBounds, px);
                }

                tileoffsetlon += tilelon;
                tileoffsetx += this.tileSize.w;
            } while (tileoffsetlon <= bounds.right + tilelon * this.buffer)

            tileoffsetlat -= tilelat;
            tileoffsety += this.tileSize.h;
        } while(tileoffsetlat >= bounds.bottom - tilelat * this.buffer)

    },

    /**
     * addTile gives subclasses of Grid the opportunity to create an
     * OpenLayer.Tile of their choosing. The implementer should initialize
     * the new tile and take whatever steps necessary to display it.
     *
     * @param {OpenLayers.Bounds} bounds
     *
     * @returns The added OpenLayers.Tile
     * @type OpenLayers.Tile
     */
    addTile:function(bounds, position) {
        // Should be implemented by subclasses
    },

  /********************************************************/
  /*                                                      */
  /*                 Baselayer Functions                  */
  /*                                                      */
  /********************************************************/

    /**
     * @returns Degrees per Pixel
     * @type float
     */
    getResolution: function() {
        var maxRes = this.map.getMaxResolution();
        var zoom = this.map.getZoom();

        return maxRes / Math.pow(2, zoom);
    },

    /** Calculates based on resolution, center, and mapsize
     *
     * @returns A Bounds object which represents the lon/lat bounds of the
     *          current viewPort.
     * @type OpenLayers.Bounds
     */
    getExtent: function () {
        var extent = null;

        var center = this.map.getCenter();
        if (center != null) {

            var res = this.getResolution();
            var size = this.map.getSize();
            var w_deg = size.w * res;
            var h_deg = size.h * res;

            extent = new OpenLayers.Bounds(center.lon - w_deg / 2,
                                           center.lat - h_deg / 2,
                                           center.lon + w_deg / 2,
                                           center.lat + h_deg / 2);

        }

        return extent;
    },

    /**
     * @param {OpenLayers.Bounds} bounds
     *
     * @return {int}
     */
    getZoomForExtent: function (bounds) {

        var maxRes = this.map.getMaxResolution();
        var viewSize = this.map.getSize();

        var width = bounds.getWidth();
        var height = bounds.getHeight();

        var degPerPixel = (width > height) ? width / viewSize.w
                                           : height / viewSize.h;

        var zoom = Math.floor( (Math.log(maxRes/degPerPixel)) / Math.log(2) );

        var maxZoomLevel = this.map.getMaxZoomLevel();
        var minZoomLevel = this.map.getMinZoomLevel();

        //make sure zoom is within bounds
        zoom = Math.min( Math.max(zoom, minZoomLevel),
                         maxZoomLevel );

        return zoom;
    },

    /** go through and remove all tiles from the grid, calling
     *    destroy() on each of them to kill circular references
     *
     * @private
     */
    clearGrid:function() {
        if (this.grid) {
            for(var iRow=0; iRow < this.grid.length; iRow++) {
                var row = this.grid[iRow];
                for(var iCol=0; iCol < row.length; iCol++) {
                    row[iCol].clear();
                }
            }
        }
    },

    /**
     * @private
     *
     * @param {Boolean} prepend if true, prepend to beginning.
     *                          if false, then append to end
     */
    shiftRow:function(prepend) {
        var modelRowIndex = (prepend) ? 0 : (this.grid.length - 1);
        var modelRow = this.grid[modelRowIndex];

        var resolution = this.map.getResolution();
        var deltaY = (prepend) ? -this.tileSize.h : this.tileSize.h;
        var deltaLat = resolution * -deltaY;

        var row = (prepend) ? this.grid.pop() : this.grid.shift();

        for (var i=0; i < modelRow.length; i++) {
            var modelTile = modelRow[i];
            var bounds = modelTile.bounds.clone();
            var position = modelTile.position.clone();
            bounds.bottom = bounds.bottom + deltaLat;
            bounds.top = bounds.top + deltaLat;
            position.y = position.y + deltaY;
            row[i].moveTo(bounds, position);
        }

        if (prepend) {
            this.grid.unshift(row);
        } else {
            this.grid.push(row);
        }
    },

    /**
     * @private
     *
     * @param {Boolean} prepend if true, prepend to beginning.
     *                          if false, then append to end
     */
    shiftColumn: function(prepend) {
        var deltaX = (prepend) ? -this.tileSize.w : this.tileSize.w;
        var resolution = this.map.getResolution();
        var deltaLon = resolution * deltaX;

        for (var i=0; i<this.grid.length; i++) {
            var row = this.grid[i];
            var modelTileIndex = (prepend) ? 0 : (row.length - 1);
            var modelTile = row[modelTileIndex];

            var bounds = modelTile.bounds.clone();
            var position = modelTile.position.clone();
            bounds.left = bounds.left + deltaLon;
            bounds.right = bounds.right + deltaLon;
            position.x = position.x + deltaX;

            var tile = prepend ? this.grid[i].pop() : this.grid[i].shift()
            tile.moveTo(bounds, position);
            if (prepend) {
                this.grid[i].unshift(tile);
            } else {
                this.grid[i].push(tile);
            }
        }
    },

    /** @final @type String */
    CLASS_NAME: "OpenLayers.Layer.Grid"
});
<|endoftext|>


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

var nodeModules = {};

// This is to filter out node_modules as we don't want them
// to be made part of any bundles.
fs.readdirSync('node_modules')
  .filter(function(x) {
    return ['.bin'].indexOf(x) === -1;
  })
  .forEach(function(mod) {
    nodeModules[mod] = 'commonjs ' + mod;
  });

module.exports = {
  entry: './src/main.js',
  target: 'node',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'addons-linter.js',
    libraryTarget: 'commonjs2',
  },
  module: {
    loaders: [
      {
        exclude: /(node_modules|bower_components)/,
        test: /\.js$/,
        // babel options are in .babelrc
        loaders: ['babel'],
      },
      {
        test: /\.json$/,
        exclude: /(node_modules|bower_components|package.json)/,
        loaders: ['json-loader'],
      },
    ],
  },
  externals: nodeModules,
  plugins: [
    new webpack.BannerPlugin('require("source-map-support").install();',
                             { raw: true, entryOnly: false }),
  ],
  resolve: {
    extensions: ['', '.js', '.json'],
    modulesDirectories: [
      'node_modules',
    ],
  },
  devtool: 'sourcemap',
};
<commit_msg>exclude tests directory<commit_after>var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

var nodeModules = {};

// This is to filter out node_modules as we don't want them
// to be made part of any bundles.
fs.readdirSync('node_modules')
  .filter(function(x) {
    return ['.bin'].indexOf(x) === -1;
  })
  .forEach(function(mod) {
    nodeModules[mod] = 'commonjs ' + mod;
  });

module.exports = {
  entry: './src/main.js',
  target: 'node',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'addons-linter.js',
    libraryTarget: 'commonjs2',
  },
  module: {
    loaders: [
      {
        exclude: /(node_modules|bower_components)/,
        test: /\.js$/,
        // babel options are in .babelrc
        loaders: ['babel'],
      },
      {
        test: /\.json$/,
        exclude: /(node_modules|bower_components|tests|package.json)/,
        loaders: ['json-loader'],
      },
    ],
  },
  externals: nodeModules,
  plugins: [
    new webpack.BannerPlugin('require("source-map-support").install();',
                             { raw: true, entryOnly: false }),
  ],
  resolve: {
    extensions: ['', '.js', '.json'],
    modulesDirectories: [
      'node_modules',
    ],
  },
  devtool: 'sourcemap',
};
<|endoftext|>


<commit_before>/*
 * Nude.js - Nudity detection with Javascript and HTMLCanvas
 *
 * Author: Patrick Wied ( http://www.patrick-wied.at )
 * Version: 0.1  (2010-11-21)
 * License: MIT License
 */
(function(){
	Array.prototype.remove = function(index) {
		  var rest = this.slice(index + 1);
		  this.length = index;
		  return this.push.apply(this, rest);
	};

	var nude = (function(){
		// private var definition
		var canvas = null,
		ctx = null,
		skinRegions = [],
		skinMap = [],
		resultFn = null,
		img = null,
		domPos = null,
		// private functions
		initCanvas = function(){
			canvas = document.createElement("canvas");
			// the canvas should not be visible
			canvas.style.display = "none";
			var b = document.getElementsByTagName("body")[0];
			b.appendChild(canvas);
			ctx = canvas.getContext("2d");
		},
		loadImage = function(id){

			img = document.getElementById(id);
			canvas.width = img.width;
			canvas.height = img.height;
			img.setAttribute("style", "visibility:hidden;");
			domPos = getPosition(img);
			// reset the arrays
			skinRegions = [],
			skinMap = [];
			resultFn = null;
			// draw the image into the canvas element
			ctx.drawImage(img, 0, 0);

		},
		scanImage = function(){
			// get the image data
			var image = ctx.getImageData(0, 0, canvas.width, canvas.height),
			imageData = image.data,
			detectedRegions = [],
			mergeRegions = [],
			width = canvas.width,
			lastFrom = -1,
			lastTo = -1;

			var addMerge = function(from, to){
				lastFrom = from;
				lastTo = to;
				var len = mergeRegions.length,
				fromIndex = -1,
				toIndex = -1;

				for(var i = 0; i < len; i++){

					var region = mergeRegions[i],
					rlen = region.length;

					for(var o = 0; o < rlen; o++){

						if(region[o] == from){
							fromIndex = i;
						}

						if(region[o] == to){
							toIndex = i;
						}

					}

				}

				if(fromIndex != -1 && toIndex != -1 && fromIndex == toIndex){
					return;
				}

				if(fromIndex == -1 && toIndex == -1){

					mergeRegions.push([from, to]);

					return;
				}
				if(fromIndex != -1 && toIndex == -1){

					mergeRegions[fromIndex].push(to);
					return;
				}
				if(fromIndex == -1 && toIndex != -1){
					mergeRegions[toIndex].push(from);
					return;
				}
				if(fromIndex != -1 && toIndex != -1 && fromIndex != toIndex){
					mergeRegions[fromIndex] = mergeRegions[fromIndex].concat(mergeRegions[toIndex]);
					mergeRegions.remove(toIndex);
					return;
				}

			};

			// iterate the image from the top left to the bottom right
			var length = imageData.length,
			width = canvas.width;

			for(var i = 0, u = 1; i < length; i+=4, u++){

				var r = imageData[i],
				g = imageData[i+1],
				b = imageData[i+2],
				x = (u>width)?((u%width)-1):u,
				y = (u>width)?(Math.ceil(u/width)-1):1;

				if(classifySkin(r, g, b)){ //
					skinMap.push({"id": u, "skin": true, "region": 0, "x": x, "y": y, "checked": false});

					var region = -1,
					checkIndexes = [u-2, (u-width)-2, u-width-1, (u-width)],
					checker = false;

					for(var o = 0; o < 4; o++){
						var index = checkIndexes[o];
						if(skinMap[index] && skinMap[index].skin){
							if(skinMap[index].region!=region && region!=-1 && lastFrom!=region && lastTo!=skinMap[index].region){
								addMerge(region, skinMap[index].region);
							}
							region = skinMap[index].region;
							checker = true;
						}
					}

					if(!checker){
						skinMap[u-1].region = detectedRegions.length;
						detectedRegions.push([skinMap[u-1]]);
						continue;
					}else{

						if(region > -1){

							if(!detectedRegions[region]){
								detectedRegions[region] = [];
							}

							skinMap[u-1].region = region;
							detectedRegions[region].push(skinMap[u-1]);

						}
					}

				}else{
					skinMap.push({"id": u, "skin": false, "region": 0, "x": x, "y": y, "checked": false});
				}

			}

			merge(detectedRegions, mergeRegions);
			analyseRegions();
		},
		// function for merging detected regions
		merge = function(detectedRegions, mergeRegions){

			var length = mergeRegions.length,
			detRegions = [];

			// merging detected regions
			for(var i = 0; i < length; i++){

				var region = mergeRegions[i],
				rlen = region.length;

				if(!detRegions[i])
					detRegions[i] = [];

				for(var o = 0; o < rlen; o++){
					var index = region[o];
					detRegions[i] = detRegions[i].concat(detectedRegions[index]);
					detectedRegions[index] = [];
				}

			}

			// push the rest of the regions to the detRegions array
			// (regions without merging)
			var l = detectedRegions.length;
			while(l--){
				if(detectedRegions[l].length > 0){
					detRegions.push(detectedRegions[l]);
				}
			}

			// clean up
			clearRegions(detRegions);

		},
		// clean up function
		// only pushes regions which are bigger than a specific amount to the final result
		clearRegions = function(detectedRegions){

			var length = detectedRegions.length;

			for(var i=0; i < length; i++){
				if(detectedRegions[i].length > 30){
					skinRegions.push(detectedRegions[i]);
				}
			}

		},
		analyseRegions = function(){

			// sort the detected regions by size
			var length = skinRegions.length,
			totalPixels = canvas.width * canvas.height,
			totalSkin = 0;

			// if there are less than 3 regions
			if(length < 3){
				resultHandler(false);
				return;
			}

			// sort the skinRegions with bubble sort algorithm
			(function(){
				var sorted = false;
				while(!sorted){
					sorted = true;
					for(var i = 0; i < length-1; i++){
						if(skinRegions[i].length < skinRegions[i+1].length){
							sorted = false;
							var temp = skinRegions[i];
							skinRegions[i] = skinRegions[i+1];
							skinRegions[i+1] = temp;
						}
					}
				}
			})();

			// count total skin pixels
			while(length--){
				totalSkin += skinRegions[length].length;
			}

			// check if there are more than 15% skin pixel in the image
			if((totalSkin/totalPixels)*100 < 15){
				// if the percentage lower than 15, it's not nude!
				//console.log("it's not nude :) - total skin percent is "+((totalSkin/totalPixels)*100)+"% ");
				resultHandler(false);
				return;
			}

			// check if the largest skin region is less than 35% of the total skin count
			// AND if the second largest region is less than 30% of the total skin count
			// AND if the third largest region is less than 30% of the total skin count
			if((skinRegions[0].length/totalSkin)*100 < 35
					&& (skinRegions[1].length/totalSkin)*100 < 30
					&& (skinRegions[2].length/totalSkin)*100 < 30){
				// the image is not nude.
				//console.log("it's not nude :) - less than 35%,30%,30% skin in the biggest areas :" + ((skinRegions[0].length/totalSkin)*100) + "%, " + ((skinRegions[1].length/totalSkin)*100)+"%, "+((skinRegions[2].length/totalSkin)*100)+"%");
				resultHandler(false);
				return;

			}

			// check if the number of skin pixels in the largest region is less than 45% of the total skin count
			if((skinRegions[0].length/totalSkin)*100 < 45){
				// it's not nude
				//console.log("it's not nude :) - the biggest region contains less than 45%: "+((skinRegions[0].length/totalSkin)*100)+"%");
				resultHandler(false);
				return;
			}

			// TODO:
			// build the bounding polygon by the regions edge values:
			// Identify the leftmost, the uppermost, the rightmost, and the lowermost skin pixels of the three largest skin regions.
			// Use these points as the corner points of a bounding polygon.

			// TODO:
			// check if the total skin count is less than 30% of the total number of pixels
			// AND the number of skin pixels within the bounding polygon is less than 55% of the size of the polygon
			// if this condition is true, it's not nude.

			// TODO: include bounding polygon functionality
			// if there are more than 60 skin regions and the average intensity within the polygon is less than 0.25
			// the image is not nude
			if(skinRegions.length > 60){
				//console.log("it's not nude :) - more than 60 skin regions");
				resultHandler(false);
				return;
			}

			// otherwise it is nude
			resultHandler(true);

		},
		// the result handler will be executed when the analysing process is done
		// the result contains true (it is nude) or false (it is not nude)
		// if the user passed an result function to the scan function, the result function will be executed
		// otherwise the default resulthandling executes
		resultHandler = function(result){

			if(resultFn){
				resultFn(result);
			}
			if(result){
				// creating the "it's nudity" - message
				var message = document.createElement("div");
				message.setAttribute("style", "position:absolute;width:300px;left:"+(domPos.left+(canvas.width/2)-150)+"px;top:"+(domPos.top+(canvas.height/2))+"px;z-index:100000;cursor:pointer;padding:10px;background-color:#d9d9d9;font-family:Arial;color:#df0019;");
				message.innerHTML = "The image contains nudity.
If this image definitely does not contain nudity click on this message";
				message.onclick = function(){
					this.setAttribute("style","display:none");
					img.setAttribute("style","visibility:visible;");
				};

				var b = document.getElementsByTagName("body")[0];
				b.appendChild(message);
			}else{
				img.setAttribute("style","visibility:visible;");
			}
		},
		// colorizeRegions function is for testdevelopment only
		// the detected skinRegions will be painted in random colors (one color per region)
		colorizeRegions = function(){

			var length = skinRegions.length;
			for(var i = 0; i < length; i++){

				var region = skinRegions[i],
				regionLength = region.length,
				randR = Math.ceil(Math.random()*255),
				randG = Math.ceil(Math.random()*255),
				rangB = Math.ceil(Math.random()*255);

				for(var o = 0; o < regionLength; o++){

					var pixel = ctx.getImageData(region[o].x, region[o].y, 1,1),
					pdata = pixel.data;

					pdata[0] = randR;
					pdata[1] = randG;
					pdata[2] = rangB;

					pixel.data = pdata;

					ctx.putImageData(pixel, region[o].x, region[o].y);

				}

			}

		},
		classifySkin = function(r, g, b){
			// A Survey on Pixel-Based Skin Color Detection Techniques
			var rgbClassifier = ((r>95) && (g>40 && g <100) && (b>20) && ((Math.max(r,g,b) - Math.min(r,g,b)) > 15) && (Math.abs(r-g)>15) && (r > g) && (r > b)),
			nurgb = toNormalizedRgb(r, g, b),
			nr = nurgb[0],
			ng = nurgb[1],
			nb = nurgb[2],
			normRgbClassifier = (((nr/ng)>1.185) && (((r*b)/(Math.pow(r+g+b,2))) > 0.107) && (((r*g)/(Math.pow(r+g+b,2))) > 0.112)),
			//hsv = toHsv(r, g, b),
			//h = hsv[0]*100,
			//s = hsv[1],
			//hsvClassifier = (h < 50 && h > 0 && s > 0.23 && s < 0.68);
			hsv = toHsvTest(r, g, b),
			h = hsv[0],
			s = hsv[1],
			hsvClassifier = (h > 0 && h < 35 && s > 0.23 && s < 0.68);
			/*
			 * ycc doesnt work

			ycc = toYcc(r, g, b),
			y = ycc[0],
			cb = ycc[1],
			cr = ycc[2],
			yccClassifier = ((y > 80) && (cb > 77 && cb < 127) && (cr > 133 && cr < 173));
			*/

			return (rgbClassifier || normRgbClassifier || hsvClassifier); //
		},
		toYcc = function(r, g, b){
			r/=255,g/=255,b/=255;
			var y = 0.299*r + 0.587*g + 0.114*b,
			cr = r - y,
			cb = b - y;

			return [y, cr, cb];
		},
		toHsv = function(r, g, b){
			return [
			        // hue
			        Math.acos((0.5*((r-g)+(r-b)))/(Math.sqrt((Math.pow((r-g),2)+((r-b)*(g-b)))))),
			        // saturation
			        1-(3*((Math.min(r,g,b))/(r+g+b))),
			        // value
			        (1/3)*(r+g+b)
			        ];
		},
		toHsvTest = function(r, g, b){
			var h = 0,
			mx = Math.max(r, g, b),
			mn = Math.min(r, g, b),
			dif = mx - mn;

			if(mx == r){
				h = (g - b)/dif;
			}else if(mx == g){
				h = 2+((g - r)/dif)
			}else{
				h = 4+((r - g)/dif);
			}
			h = h*60;
			if(h < 0){
				h = h+360;
			}

			return [h, 1-(3*((Math.min(r,g,b))/(r+g+b))),(1/3)*(r+g+b)] ;

		},
		toNormalizedRgb = function(r, g, b){
			var sum = r+g+b;
			return [(r/sum), (g/sum), (b/sum)];
		},
		getPosition = function(el){
			var x = 0, y = 0;

			while(el != null){
				x += el.offsetLeft;
				y += el.offsetTop;
				el = el.offsetParent;
			}
			return { "left":x, "top":y };
		}
		// public interface
		return {
			init: function(){
				initCanvas();
			},
			load: function(id){
				loadImage(id);
			},
			scan: function(fn){
				if(arguments.length>0 && typeof(arguments[0]) == "function"){
					resultFn = fn;
				}
				scanImage();
			}
		};
	})();
	// register nude at window object
	if(!window.nude)
		window.nude = nude;
})();

window.onload = function(){
	nude.init();
}
<commit_msg>restructured for web workers.<commit_after>/*
 * Nude.js - Nudity detection with Javascript and HTMLCanvas
 *
 * Author: Patrick Wied ( http://www.patrick-wied.at )
 * Version: 0.1  (2010-11-21)
 * License: MIT License
 */
(function(){

	var nude = (function(){
		// private var definition
		var canvas = null,
		ctx = null,
		resultFn = null,
		img = null,
		domPos = null,
		// private functions
		initCanvas = function(){
			canvas = document.createElement("canvas");
			// the canvas should not be visible
			canvas.style.display = "none";
			var b = document.getElementsByTagName("body")[0];
			b.appendChild(canvas);
			ctx = canvas.getContext("2d");
		},
		loadImage = function(id){

			img = document.getElementById(id);
			canvas.width = img.width;
			canvas.height = img.height;
			img.setAttribute("style", "visibility:hidden;");
			domPos = getPosition(img);
			resultFn = null;
			// draw the image into the canvas element
			ctx.drawImage(img, 0, 0);

		},
		// not ready for usage!! todo: debug
		loadImageFromVideo = function(video){
			canvas.width = video.width;
			canvas.height = video.height;
			ctx.drawImage(video, 0, 0, video.width, video.height);
		},
		scanImage = function(){
			// get the image data
			var image = ctx.getImageData(0, 0, canvas.width, canvas.height),
			imageData = image.data;

			var myWorker = new Worker('worker.js'),
			message = [imageData, canvas.width, canvas.height];
			myWorker.postMessage(message);
			myWorker.onmessage = function(event){
				resultHandler(event.data);
			}
		},
		// the result handler will be executed when the analysing process is done
		// the result contains true (it is nude) or false (it is not nude)
		// if the user passed an result function to the scan function, the result function will be executed
		// otherwise the default resulthandling executes
		resultHandler = function(result){

			if(resultFn){
				resultFn(result);
			}
			if(img != null){
				if(result){
					// creating the "it's nudity" - message
					var message = document.createElement("div");
					message.setAttribute("style", "position:absolute;width:300px;left:"+(domPos.left+(canvas.width/2)-150)+"px;top:"+(domPos.top+(canvas.height/2))+"px;z-index:100000;cursor:pointer;padding:10px;background-color:#d9d9d9;font-family:Arial;color:#df0019;");
					message.innerHTML = "The image contains nudity.
If this image definitely does not contain nudity click on this message";
					message.onclick = function(){
						this.setAttribute("style","display:none");
						img.setAttribute("style","visibility:visible;");
					};

					var b = document.getElementsByTagName("body")[0];
					b.appendChild(message);
				}else{
					img.setAttribute("style","visibility:visible;");
				}
			}
		},
		// colorizeRegions function is for testdevelopment only
		// the detected skinRegions will be painted in random colors (one color per region)
		colorizeRegions = function(){

			var length = skinRegions.length;
			for(var i = 0; i < length; i++){

				var region = skinRegions[i],
				regionLength = region.length,
				randR = Math.ceil(Math.random()*255),
				randG = Math.ceil(Math.random()*255),
				rangB = Math.ceil(Math.random()*255);

				for(var o = 0; o < regionLength; o++){

					var pixel = ctx.getImageData(region[o].x, region[o].y, 1,1),
					pdata = pixel.data;

					pdata[0] = randR;
					pdata[1] = randG;
					pdata[2] = rangB;

					pixel.data = pdata;

					ctx.putImageData(pixel, region[o].x, region[o].y);

				}

			}

		},
		getPosition = function(el){
			var x = 0, y = 0;

			while(el != null){
				x += el.offsetLeft;
				y += el.offsetTop;
				el = el.offsetParent;
			}
			return { "left":x, "top":y };
		}
		// public interface
		return {
			init: function(){
				initCanvas();
			},
			load: function(param){
				if(typeof(param)!="string"){
					// if it's not an image tag ID
					// it's a video element
					loadImageFromVideo(param);
				}else{
					loadImage(param);
				}
			},
			scan: function(fn){
				if(arguments.length>0 && typeof(arguments[0]) == "function"){
					resultFn = fn;
				}
				scanImage();
			}
		};
	})();
	// register nude at window object
	if(!window.nude)
		window.nude = nude;
})();

window.onload = function(){
	nude.init();
}<|endoftext|>


<commit_before>/* No ES6! */
var path = require('path'),
webpack = require('webpack'), // Da bundling modules!
NpmInstallPlugin = require('npm-install-webpack-plugin'), // Install client dependencies automatically!
merge = require('webpack-merge'), // Merge together configurations!
cssnext = require('postcss-cssnext'),
CONFIG = require('./config');

const PATHS = {
  app: CONFIG.APP_PATH,
  build: CONFIG.PUBLIC_PATH,
  img: CONFIG.IMG_PATH
};

const TARGET = process.env.npm_lifecycle_event;

const COMMON_CONFIGURATION = {
  entry: {
    app: PATHS.app
  },
  resolve: {
    extensions: ['', '.js', '.jsx'], // Resolve these extensions
  },
  output: {
    path: PATHS.build,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.css$/,
        loaders: ['style', 'css', 'postcss'],
        include: PATHS.app
      },
      {
       test: /\.jsx?$/,
       loaders: ['babel?cacheDirectory'],
       include: PATHS.app
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
            'file?hash=sha512&digest=hex&name=[hash].[ext]',
            'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ],
        include: PATHS.img
      }, {
        test: /\.worker.js$/,
        loaders: ['worker-loader', 'babel?cacheDirectory'],
        include: PATHS.app
      }
    ]
  },
  postcss: function() {
    return [ cssnext ];
  }
};

switch(TARGET) {
  // Which procedure was started?
  default:
  case 'start:dev': {
    module.exports = merge(COMMON_CONFIGURATION, {
      devServer: {
        contentBase: PATHS.build,
        historyApiFallback: true,
        hot: true,
        inline: true,
        progress: true,
        stats: 'errors-only'
      },
      plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new NpmInstallPlugin({
          save: true
        })
      ],
      devtool: 'eval-source-map'
    });
  }
  break;
  case 'start': {
    // Make later when going into production step!
    module.exports = COMMON_CONFIGURATION;
  }
}
<commit_msg>Set NODE_ENV to production.<commit_after>/* No ES6! */
var path = require('path'),
webpack = require('webpack'), // Da bundling modules!
NpmInstallPlugin = require('npm-install-webpack-plugin'), // Install client dependencies automatically!
merge = require('webpack-merge'), // Merge together configurations!
cssnext = require('postcss-cssnext'),
CONFIG = require('./config');

const PATHS = {
  app: CONFIG.APP_PATH,
  build: CONFIG.PUBLIC_PATH,
  img: CONFIG.IMG_PATH
};

const TARGET = process.env.npm_lifecycle_event;

const COMMON_CONFIGURATION = {
  entry: {
    app: PATHS.app
  },
  resolve: {
    extensions: ['', '.js', '.jsx'], // Resolve these extensions
  },
  output: {
    path: PATHS.build,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.css$/,
        loaders: ['style', 'css', 'postcss'],
        include: PATHS.app
      },
      {
       test: /\.jsx?$/,
       loaders: ['babel?cacheDirectory'],
       include: PATHS.app
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
            'file?hash=sha512&digest=hex&name=[hash].[ext]',
            'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ],
        include: PATHS.img
      }, {
        test: /\.worker.js$/,
        loaders: ['worker-loader', 'babel?cacheDirectory'],
        include: PATHS.app
      }
    ]
  },
  postcss: function() {
    return [ cssnext ];
  }
};

switch(TARGET) {
  // Which procedure was started?
  default:
  case 'start:dev': {
    module.exports = merge(COMMON_CONFIGURATION, {
      devServer: {
        contentBase: PATHS.build,
        historyApiFallback: true,
        hot: true,
        inline: true,
        progress: true,
        stats: 'errors-only'
      },
      plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new NpmInstallPlugin({
          save: true
        })
      ],
      devtool: 'eval-source-map'
    });
  }
  break;
  case 'start': {
    // Make later when going into production step!
    module.exports = merge(COMMON_CONFIGURATION, {
      plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            'NODE_ENV': JSON.stringify('production')
          }
        })
      ]
    });
  }
}
<|endoftext|>