<commit_before>/**
 * Webpack Config for Javascript and CSS Bundling
 *
 * @package  generator-mh-boilerplate
 * @author   Martin Herweg <info@martinherweg.de>
 */

import webpack from 'webpack'
import { getIfUtils, removeEmpty } from 'webpack-config-utils'
import path from 'path'
import config from '../config.json'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import WriteFilePlugin from 'write-file-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import Webpack2Polyfill from 'webpack2-polyfill-plugin'<% if ( projectjsframework === 'vue' && projectstylelint) { %>
import StylelintPlugin from 'stylelint-webpack-plugin'<% } %>
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'

const {
  ifProduction,
  ifDevelopment
} = getIfUtils(process.env.NODE_ENV)

/*
 |--------------------------------------------------------------------------
 | Setting some paths for our Application
 |--------------------------------------------------------------------------
 */
const BASE_PATH = path.join(path.resolve(__dirname, '../'))
const ASSETS_ROOT = path.resolve(BASE_PATH, config.dist.base)
const JS_ROOT = path.resolve(BASE_PATH, config.src.js)
const JS_DIST = path.resolve(BASE_PATH, config.dist.js)
let outputPath = ASSETS_ROOT

if (ifDevelopment()) {
  outputPath = JS_DIST
}

/*
 |--------------------------------------------------------------------------
 | Hot Middleware Client
 |--------------------------------------------------------------------------
 */

const hotClient =
  'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true&overlay=true'

/*
 |--------------------------------------------------------------------------
 | Defining Entry Points, could be used to manually split Parts of the Application, for example
 | Admin Javascript and FrontEnd JavaScript
 |--------------------------------------------------------------------------
 */

const entryPoints = {}

Object.keys(config.src.jsEntryPoints).forEach(
  entry => (entryPoints[entry] = ifDevelopment() ? [hotClient].concat(`${JS_ROOT}/${config.src.jsEntryPoints[entry]}`) : `${JS_ROOT}/${config.src.jsEntryPoints[entry]}`)
)

function assetsPath (_path) {
  return path.posix.join('assets/', _path)
}

const chunks = []

const chunksInject = [
  {
    filename: path.resolve(`${config.dist.markup}index.html`),
    file: null,
    inject: false
  }
]

chunksInject.forEach((chunk) => {
  const plugin = new HtmlWebpackPlugin({
    filename: chunk.filename,
    inject: chunk.inject,
    minify: false,
    // necessary to consistently work with multiple chunks via CommonsChunkPlugin
    chunksSortMode: 'dependency'
  })

  chunks.push(plugin)
})

/*
 |--------------------------------------------------------------------------
 | return webpack config object
 |--------------------------------------------------------------------------
 */

export default {
  // we have to use source map for css source maps, slightly longer compile times
  // devtool: 'source-map',
  context: BASE_PATH,
  // entry is a function so that we can use environment variables
  entry: removeEmpty(entryPoints),
  output: {
    path: outputPath,
    publicPath: '',
    filename: ifProduction(
      assetsPath('js/[name].js')
    ),
    chunkFilename: assetsPath('js/[id].js')
  },
  resolve: {
    extensions: ['.js', '.json', '.vue'],
    modules: [resolve(config.src.base), resolve('node_modules')],
    alias: {
      src: resolve(config.src.base)
    }
  },
  module: {
    rules: [
      {
        test: /\.(js)$/,
        loader: 'eslint-loader',
        options: {
          formatter: require('eslint-friendly-formatter')
        },
        enforce: 'pre',
        include: resolve(config.src.base)
      },
      {
        test: /\.js$/,
        use: 'babel-loader',
        include: resolve(config.src.base)
      },<% if ( projectjsframework === 'vue') { %>
      {
        test: /\.vue$/,
        use: 'vue-loader',
        options: {
          loaders: {
            scss: ifProduction(
              ExtractTextPlugin.extract({
                use: 'css-loader!postcss-loader!sass-loader',
                fallback: 'vue-style-loader'
              }),
              'vue-style-loader!css-loader!postcss-loader!sass-loader'
            )
          }
        }
      },<% } %>

      {
        test: /\.json$/,
        use: 'json-loader'
      }
      // {
      //   test: /\.scss$/,
      //   include: resolve(config.src.css),
      //   exclude: [resolve('node_modules'), resolve('dist/')],
      //   use: ExtractTextPlugin.extract({
      //     fallback: 'style-loader',
      //     use: [
      //       {
      //         loader: 'css-loader',
      //         options: {
      //           autoprefixer: false,
      //           sourceMap: true,
      //           importLoaders: 3,
      //           url: false
      //         }
      //       },
      //       {
      //         loader: 'postcss-loader',
      //         options: {
      //           sourceMap: true
      //         }
      //       },
      //       {
      //         loader: 'sass-loader',
      //         options: {
      //           sourceMap: true
      //         }
      //       }
      //     ]
      //   })
      // }
    ]
  },
  plugins: removeEmpty([
    new Webpack2Polyfill(),
    // new CleanWebpackPlugin([config.dist.css, config.dist.js], {
    //   root: BASE_PATH,
    //   verbose: true
    // }),
    ifProduction(
      new BundleAnalyzerPlugin({
        analyzerMode: 'disabled',
        generateStatsFile: true,
        statsFilename: `${BASE_PATH}/webpack/stats.json`,
        logLevel: 'info'
      })
    ),
    ifDevelopment(new webpack.HotModuleReplacementPlugin()),
    ifDevelopment(new webpack.NamedModulesPlugin()),
    ifDevelopment(new webpack.NoEmitOnErrorsPlugin()),
    ifDevelopment(new FriendlyErrorsWebpackPlugin()),
    ifProduction(
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: '"production"'
        }
      })
    ),
    ifProduction(
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          warnings: false
        }
      })
    ),
    ifProduction(
      new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        minChunks: function (module) {
          // this assumes your vendor imports exist in the node_modules directory
          return (
            module.context && module.context.indexOf('node_modules') !== -1
          )
        }
      })
    ),
    ifProduction(
      // extract webpack runtime and module manifest to its own file in order to
      // prevent vendor hash from being updated whenever app bundle is updated
      new webpack.optimize.CommonsChunkPlugin({
        name: 'manifest',
        chunks: ['vendor']
      })
    ),
    ifProduction(
      new webpack.LoaderOptionsPlugin({
        minimize: true,
        options: {
          eslint: {
            configFile: './.eslintrc.js'
          }
        }
      })
    ),
    ifDevelopment(
      new webpack.LoaderOptionsPlugin({
        options: {
          eslint: {
            failOnError: false,
            failOnWarning: false,
            configFile: './.eslintrc-dev.js',
            formatter: require('eslint-formatter-pretty')
          }
        }
      })
    ),
    new ExtractTextPlugin({
      filename: assetsPath('css/vue-style.css')
    }),<% if ( projectjsframework === 'vue' && projectstylelint) { %>
    new StylelintPlugin({
      context: JS_ROOT,
      syntax: 'scss'
    }),<% } %>
    ...chunks,
    new WriteFilePlugin({
      log: true,
      test: /^(?!.+(?:hot-update.(js|json))).+$/
    }),
    new webpack.optimize.ModuleConcatenationPlugin()
  ])
}

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}
<commit_msg>Fix Vue-Loader Disable manifest and vendor-chunks<commit_after>/**
 * Webpack Config for Javascript and CSS Bundling
 *
 * @package  generator-mh-boilerplate
 * @author   Martin Herweg <info@martinherweg.de>
 */

import webpack from 'webpack'
import { getIfUtils, removeEmpty } from 'webpack-config-utils'
import path from 'path'
import config from '../config.json'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import WriteFilePlugin from 'write-file-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import Webpack2Polyfill from 'webpack2-polyfill-plugin'<% if ( projectjsframework === 'vue' && projectstylelint) { %>
import StylelintPlugin from 'stylelint-webpack-plugin'<% } %>
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'

const {
  ifProduction,
  ifDevelopment
} = getIfUtils(process.env.NODE_ENV)

/*
 |--------------------------------------------------------------------------
 | Setting some paths for our Application
 |--------------------------------------------------------------------------
 */
const BASE_PATH = path.join(path.resolve(__dirname, '../'))
const ASSETS_ROOT = path.resolve(BASE_PATH, config.dist.base)
const JS_ROOT = path.resolve(BASE_PATH, config.src.js)
const JS_DIST = path.resolve(BASE_PATH, config.dist.js)
let outputPath = ASSETS_ROOT

if (ifDevelopment()) {
  outputPath = JS_DIST
}

/*
 |--------------------------------------------------------------------------
 | Hot Middleware Client
 |--------------------------------------------------------------------------
 */

const hotClient =
  'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true&overlay=true'

/*
 |--------------------------------------------------------------------------
 | Defining Entry Points, could be used to manually split Parts of the Application, for example
 | Admin Javascript and FrontEnd JavaScript
 |--------------------------------------------------------------------------
 */

const entryPoints = {}

Object.keys(config.src.jsEntryPoints).forEach(
  entry => (entryPoints[entry] = ifDevelopment() ? [hotClient].concat(`${JS_ROOT}/${config.src.jsEntryPoints[entry]}`) : `${JS_ROOT}/${config.src.jsEntryPoints[entry]}`)
)

function assetsPath (_path) {
  return path.posix.join('assets/', _path)
}

const chunks = []

const chunksInject = [
  {
    filename: path.resolve(`${config.dist.markup}index.html`),
    file: null,
    inject: false
  }
]

chunksInject.forEach((chunk) => {
  const plugin = new HtmlWebpackPlugin({
    filename: chunk.filename,
    inject: chunk.inject,
    minify: false,
    // necessary to consistently work with multiple chunks via CommonsChunkPlugin
    chunksSortMode: 'dependency'
  })

  chunks.push(plugin)
})

/*
 |--------------------------------------------------------------------------
 | return webpack config object
 |--------------------------------------------------------------------------
 */

export default {
  // we have to use source map for css source maps, slightly longer compile times
  // devtool: 'source-map',
  context: BASE_PATH,
  // entry is a function so that we can use environment variables
  entry: removeEmpty(entryPoints),
  output: {
    path: outputPath,
    publicPath: '',
    filename: ifProduction(
      assetsPath('js/[name].js')
    ),
    chunkFilename: assetsPath('js/[id].js')
  },
  resolve: {
    extensions: ['.js', '.json', '.vue'],
    modules: [resolve(config.src.base), resolve('node_modules')],
    alias: {
      src: resolve(config.src.base)
    }
  },
  module: {
    rules: [
      {
        test: /\.(js)$/,
        loader: 'eslint-loader',
        options: {
          formatter: require('eslint-friendly-formatter')
        },
        enforce: 'pre',
        include: resolve(config.src.base)
      },
      {
        test: /\.js$/,
        use: 'babel-loader',
        include: resolve(config.src.base)
      },<% if ( projectjsframework === 'vue') { %>
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            scss: ifProduction(
              ExtractTextPlugin.extract({
                use: 'css-loader!postcss-loader!sass-loader',
                fallback: 'vue-style-loader'
              }),
              'vue-style-loader!css-loader!postcss-loader!sass-loader'
            )
          }
        }
      },<% } %>

      {
        test: /\.json$/,
        use: 'json-loader'
      }
    ]
  },
  plugins: removeEmpty([
    new Webpack2Polyfill(),
    ifProduction(
      new BundleAnalyzerPlugin({
        analyzerMode: 'disabled',
        generateStatsFile: true,
        statsFilename: `${BASE_PATH}/webpack/stats.json`,
        logLevel: 'info'
      })
    ),
    ifDevelopment(new webpack.HotModuleReplacementPlugin()),
    ifDevelopment(new webpack.NamedModulesPlugin()),
    ifDevelopment(new webpack.NoEmitOnErrorsPlugin()),
    ifDevelopment(new FriendlyErrorsWebpackPlugin()),
    ifProduction(
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: '"production"'
        }
      })
    ),
    ifProduction(
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          warnings: false
        }
      })
    ),
    ifProduction(
      new webpack.LoaderOptionsPlugin({
        minimize: true,
        options: {
          eslint: {
            configFile: './.eslintrc.js'
          }
        }
      })
    ),
    ifDevelopment(
      new webpack.LoaderOptionsPlugin({
        options: {
          eslint: {
            failOnError: false,
            failOnWarning: false,
            configFile: './.eslintrc-dev.js',
            formatter: require('eslint-formatter-pretty')
          }
        }
      })
    ),
    new ExtractTextPlugin({
      filename: assetsPath('css/vue-style.css')
    }),<% if ( projectjsframework === 'vue' && projectstylelint) { %>
    new StylelintPlugin({
      context: JS_ROOT,
      syntax: 'scss'
    }),<% } %>
    ...chunks,
    new WriteFilePlugin({
      log: true,
      test: /^(?!.+(?:hot-update.(js|json))).+$/
    }),
    new webpack.optimize.ModuleConcatenationPlugin()
  ])
}

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}
<|endoftext|>


<commit_before>var _ = require('underscore');
var Model = require('../core/model');
var WindshaftFiltersBoundingBoxFilter = require('../windshaft/filters/bounding-box');

/**
 * Default dataview model
 */
module.exports = Model.extend({
  defaults: {
    url: '',
    data: [],
    columns: [],
    syncData: true,
    syncBoundingBox: true,
    enabled: true
  },

  url: function () {
    var params = [];
    if (this.get('boundingBox')) {
      params.push('bbox=' + this.get('boundingBox'));
    }
    return this.get('url') + '?' + params.join('&');
  },

  initialize: function (attrs, opts) {
    attrs = attrs || {};
    opts = opts || {};

    if (!opts.map) {
      throw new Error('map is required');
    }
    if (!opts.windshaftMap) {
      throw new Error('windshaftMap is required');
    }

    if (!attrs.id) {
      this.set('id', attrs.type + '-' + this.cid);
    }

    this.layer = opts.layer;
    this._map = opts.map;
    this._windshaftMap = opts.windshaftMap;

    // filter is optional, so have to guard before using it
    this.filter = opts.filter;
    if (this.filter) {
      this.filter.set('dataviewId', this.id);
    }

    this._initBinds();
  },

  _initBinds: function () {
    this.listenTo(this._windshaftMap, 'instanceCreated', this._onNewWindshaftMapInstance);

    this.listenToOnce(this, 'change:url', function () {
      this._fetch(this._onChangeBinds.bind(this));
    });

    if (this.filter) {
      this.listenTo(this.filter, 'change', this._onFilterChanged);
    }
  },

  _onFilterChanged: function (filter) {
    this._map.reload({
      sourceLayerId: this.layer.get('id')
    });
  },

  _onNewWindshaftMapInstance: function (windshaftMapInstance, sourceLayerId) {
    var url = windshaftMapInstance.getDataviewURL({
      dataviewId: this.get('id'),
      protocol: 'http'
    });

    if (url) {
      var silent = (sourceLayerId && sourceLayerId !== this.layer.get('id'));

      // TODO: Instead of setting the url here, we could invoke fetch directly
      this.set('url', url, { silent: silent });
    }
  },

  _onChangeBinds: function () {
    var BOUNDING_BOX_FILTER_WAIT = 500;
    this.listenTo(this._map, 'change:center change:zoom', _.debounce(this._onMapBoundsChanged.bind(this), BOUNDING_BOX_FILTER_WAIT));

    this.listenTo(this, 'change:url', function () {
      if (this._shouldFetchOnURLChange()) {
        this._fetch();
      }
    });
    this.listenTo(this, 'change:boundingBox', function () {
      if (this._shouldFetchOnBoundingBoxChange()) {
        this._fetch();
      }
    });

    this.listenTo(this, 'change:enabled', function (mdl, isEnabled) {
      if (isEnabled) {
        if (mdl.changedAttributes(this._previousAttrs)) {
          this._fetch();
        }
      } else {
        this._previousAttrs = {
          url: this.get('url'),
          boundingBox: this.get('boundingBox')
        };
      }
    });
  },

  _onMapBoundsChanged: function () {
    this._updateBoundingBox();
  },

  _updateBoundingBox: function () {
    var boundingBoxFilter = new WindshaftFiltersBoundingBoxFilter(this._map.getViewBounds());
    this.set('boundingBox', boundingBoxFilter.toString());
  },

  _shouldFetchOnURLChange: function () {
    return this.get('syncData') && this.get('enabled');
  },

  _shouldFetchOnBoundingBoxChange: function () {
    return this.get('enabled') && this.get('syncBoundingBox');
  },

  _fetch: function (callback) {
    var self = this;
    this.fetch({
      success: callback,
      error: function () {
        self.trigger('error');
      }
    });
  },

  fetch: function (opts) {
    this.trigger('loading', this);
    if (this.layer.getDataProvider()) {
      this._fetchFromDataProvider(opts);
    } else {
      return Model.prototype.fetch.call(this, opts);
    }
  },

  _fetchFromDataProvider: function (opts) {
    var dataProvider = this.layer.getDataProvider();

    // TODO: At the beginning, the dataProvider will not have any features
    // loaded so we will have to listen to the `featuresChanged` event, but
    // once the dataProvider has been initialized, we should implement and use
    // dataProvider.getFeatures() instead of adding yet another binding.
    dataProvider.bind('featuresChanged', function (features) {
      try {
        var data = dataProvider.generateDataForDataview(this, features);

        // TODO: this.parse() is doing some magic (like resetting this._data)
        // in some cases (category and histogram) and that's why we use it here.
        // If that wasn't the case, data could be generated by the dataProvider in
        // the format that the dataview expects.
        this.set(this.parse(data));
        this.trigger('sync');
        opts && opts.success && opts.success(this);
      } catch (error) {
        // TODO: fallback to Model.prototype.fetch.call(this, opts);?
      }
    }.bind(this));
  },

  refresh: function () {
    this._fetch();
  },

  getData: function () {
    return this.get('data');
  },

  getPreviousData: function () {
    return this.previous('data');
  },

  toJSON: function () {
    throw new Error('toJSON should be defined for each dataview');
  },

  remove: function () {
    if (this.filter) {
      this.filter.remove();
    }
    this.trigger('destroy', this);
    this.stopListening();
  }
});
<commit_msg>Revert "Removed code that is implemented yet (conflict wasn't resolved properly)"<commit_after>var _ = require('underscore');
var Model = require('../core/model');
var WindshaftFiltersBoundingBoxFilter = require('../windshaft/filters/bounding-box');

/**
 * Default dataview model
 */
module.exports = Model.extend({
  defaults: {
    url: '',
    data: [],
    columns: [],
    syncData: true,
    syncBoundingBox: true,
    enabled: true
  },

  url: function () {
    var params = [];
    if (this.get('boundingBox')) {
      params.push('bbox=' + this.get('boundingBox'));
    }
    return this.get('url') + '?' + params.join('&');
  },

  initialize: function (attrs, opts) {
    attrs = attrs || {};
    opts = opts || {};

    if (!opts.map) {
      throw new Error('map is required');
    }
    if (!opts.windshaftMap) {
      throw new Error('windshaftMap is required');
    }

    if (!attrs.id) {
      this.set('id', attrs.type + '-' + this.cid);
    }

    this.layer = opts.layer;
    this._map = opts.map;
    this._windshaftMap = opts.windshaftMap;

    // filter is optional, so have to guard before using it
    this.filter = opts.filter;
    if (this.filter) {
      this.filter.set('dataviewId', this.id);
    }

    this._initBinds();
  },

  _initBinds: function () {
    this.listenTo(this._windshaftMap, 'instanceCreated', this._onNewWindshaftMapInstance);

    this.listenToOnce(this, 'change:url', function () {
      this._fetch(this._onChangeBinds.bind(this));
    });

    if (this.filter) {
      this.listenTo(this.filter, 'change', this._onFilterChanged);
    }
  },

  _onFilterChanged: function (filter) {
    var dataProvider = this.layer.getDataProvider();
    if (dataProvider) {
      dataProvider.applyFilter(this.get('column'), filter);
    } else {
      this._map.reload({
        sourceLayerId: this.layer.get('id')
      });
    }
  },

  _onNewWindshaftMapInstance: function (windshaftMapInstance, sourceLayerId) {
    var url = windshaftMapInstance.getDataviewURL({
      dataviewId: this.get('id'),
      protocol: 'http'
    });

    if (url) {
      var silent = (sourceLayerId && sourceLayerId !== this.layer.get('id'));

      // TODO: Instead of setting the url here, we could invoke fetch directly
      this.set('url', url, { silent: silent });
    }
  },

  _onChangeBinds: function () {
    var BOUNDING_BOX_FILTER_WAIT = 500;
    this.listenTo(this._map, 'change:center change:zoom', _.debounce(this._onMapBoundsChanged.bind(this), BOUNDING_BOX_FILTER_WAIT));

    this.listenTo(this, 'change:url', function () {
      if (this._shouldFetchOnURLChange()) {
        this._fetch();
      }
    });
    this.listenTo(this, 'change:boundingBox', function () {
      if (this._shouldFetchOnBoundingBoxChange()) {
        this._fetch();
      }
    });

    this.listenTo(this, 'change:enabled', function (mdl, isEnabled) {
      if (isEnabled) {
        if (mdl.changedAttributes(this._previousAttrs)) {
          this._fetch();
        }
      } else {
        this._previousAttrs = {
          url: this.get('url'),
          boundingBox: this.get('boundingBox')
        };
      }
    });
  },

  _onMapBoundsChanged: function () {
    this._updateBoundingBox();
  },

  _updateBoundingBox: function () {
    var boundingBoxFilter = new WindshaftFiltersBoundingBoxFilter(this._map.getViewBounds());
    this.set('boundingBox', boundingBoxFilter.toString());
  },

  _shouldFetchOnURLChange: function () {
    return this.get('syncData') && this.get('enabled');
  },

  _shouldFetchOnBoundingBoxChange: function () {
    return this.get('enabled') && this.get('syncBoundingBox');
  },

  _fetch: function (callback) {
    var self = this;
    this.fetch({
      success: callback,
      error: function () {
        self.trigger('error');
      }
    });
  },

  fetch: function (opts) {
    this.trigger('loading', this);
    if (this.layer.getDataProvider()) {
      this._fetchFromDataProvider(opts);
    } else {
      return Model.prototype.fetch.call(this, opts);
    }
  },

  _fetchFromDataProvider: function (opts) {
    var dataProvider = this.layer.getDataProvider();

    // TODO: At the beginning, the dataProvider will not have any features
    // loaded so we will have to listen to the `featuresChanged` event, but
    // once the dataProvider has been initialized, we should implement and use
    // dataProvider.getFeatures() instead of adding yet another binding.
    dataProvider.bind('featuresChanged', function (features) {
      try {
        var data = dataProvider.generateDataForDataview(this, features);

        // TODO: this.parse() is doing some magic (like resetting this._data)
        // in some cases (category and histogram) and that's why we use it here.
        // If that wasn't the case, data could be generated by the dataProvider in
        // the format that the dataview expects.
        this.set(this.parse(data));
        this.trigger('sync');
        opts && opts.success && opts.success(this);
      } catch (error) {
        // TODO: fallback to Model.prototype.fetch.call(this, opts);?
      }
    }.bind(this));
  },

  refresh: function () {
    this._fetch();
  },

  getData: function () {
    return this.get('data');
  },

  getPreviousData: function () {
    return this.previous('data');
  },

  toJSON: function () {
    throw new Error('toJSON should be defined for each dataview');
  },

  remove: function () {
    if (this.filter) {
      this.filter.remove();
    }
    this.trigger('destroy', this);
    this.stopListening();
  }
});
<|endoftext|>


<commit_before>/* eslint-disable no-console */

export default class {

    /**
     * Primer constructor.
     */
    constructor() {
        this.debug = false;

        // Stash console for later use.
        this.console = global.console;
    }

    /**
     * Get the Primer version.
     *
     * @returns {string}
     */
    get version() {
        return '0.1.4';
    }

    /**
     * Boot Primer.
     *
     * @param {bool} debug
     *
     * @returns {object}
     */
    boot(debug = false) {
        this.debug = debug;

        // Suppress console loging when debugging is disabled.
        if (! debug) {
            this.disableConsole();
        } else {
            this.enableConsole();
        }

        return this;
    }

    /**
     * Disable console logging.
     */
    disableConsole() {
        global.console = {};

        console.log
            = console.info
            = console.warm
            = console.error = () => {};
    }

    /**
     * Enable/Restore console logging.
     */
    enableConsole() {
        global.console = this.console;

        global.console.warn(`Centagon Primer ${this.version} debug mode enabled!
Please disable logging on production by calling (new Primer).boot(false);`);
    }
}
<commit_msg>version bump<commit_after>/* eslint-disable no-console */

export default class {

    /**
     * Primer constructor.
     */
    constructor() {
        this.debug = false;

        // Stash console for later use.
        this.console = global.console;
    }

    /**
     * Get the Primer version.
     *
     * @returns {string}
     */
    get version() {
        return '0.1.8';
    }

    /**
     * Boot Primer.
     *
     * @param {bool} debug
     *
     * @returns {object}
     */
    boot(debug = false) {
        this.debug = debug;

        // Suppress console loging when debugging is disabled.
        if (! debug) {
            this.disableConsole();
        } else {
            this.enableConsole();
        }

        return this;
    }

    /**
     * Disable console logging.
     */
    disableConsole() {
        global.console = {};

        console.log
            = console.info
            = console.warm
            = console.error = () => {};
    }

    /**
     * Enable/Restore console logging.
     */
    enableConsole() {
        global.console = this.console;

        global.console.warn(`Centagon Primer ${this.version} debug mode enabled!
Please disable logging on production by calling (new Primer).boot(false);`);
    }
}
<|endoftext|>


<commit_before>(function () {
"use strict";

var i, j, k, pieces, currentPlayer, numberOfPlayers, dragDrop;

currentPlayer = 2;
numberOfPlayers = 1;

function $(id) {
  return document.getElementById(id);
}

function html(id, text) {
  $(id).innerHTML = text;
}

function addClass(selector, value) {
  if (typeof selector === 'string') {
    selector = $(selector);
  }
  selector.className += ' ' + value;
}

function removeClass(selector, value) {
  var regex = new RegExp(' ' + value, 'g');
  if (typeof selector === 'string') {
    selector = $(selector);
  }
  selector.className = selector.className.replace(regex, '');
}

function animate(element, klass, callback) {
  var wrapper = function () {
    if (callback) {
      callback();
    }
    removeClass(element, klass);
    element.removeEventListener('webkitTransitionEnd', wrapper, true);
  };
  element.addEventListener('webkitTransitionEnd', wrapper, true);
  addClass(element, klass);
}

function findCenter(element) {
  var x = 0, y = 0;
  if (element) {
    x = element.offsetWidth / 2;
    y = element.offsetHeight / 2;
  }
  while (element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) {
    x += element.offsetLeft - element.scrollLeft;
    y += element.offsetTop - element.scrollTop;
    element = element.offsetParent;
  }
  return { x: x, y: y };
}

function countScore(total, factor) {
  return (total % factor === 0) ? total / factor : 0;
}

function getScore() {
  return parseInt($('player' + currentPlayer + '-score').innerHTML, 10);
}

function setScore(newScore) {
  html('player' + currentPlayer + '-score', newScore);
}

function countUnique(array) {
  var i, keys;
  keys = {};
  for (i = 0; i < array.length; i += 1) {
    keys[array[i]] = 1;
  }
  return Object.keys(keys).length;
}

function bonusScore(values) {
  var i, score, straight, unique;
  if (values.length <= 1) {
    return 0;
  }
  unique = countUnique(values);
  if (values.length <= 2) {
    /* a pair */
    if (unique === 1) {
      return 2;
    }
    return 0;
  }
  if (values.length <= 3) {
    /* a pair */
    if (unique === 2) {
      return 2;
    }
    /* three of a kind */
    if (unique === 1) {
      return 6;
    }
    return 0;
  }
  score = 0;
  straight = 0;
  values.sort();
  for (i = 0; i < values.length - 1; i += 1) {
    if (values[i] + 1 === values[i + 1]) {
      straight += 1;
    }
  }
  /* a straight */
  if (straight === 3) {
    score += 4;
  }
  /* a pair */
  if (unique === 3) {
    score += 2;
  }
  /* three of a kind */
  if (unique === 2) {
    score += 6;
  }
  /* four of a kind */
  if (unique === 1) {
    score += 12;
  }
  return score;
}

function guessScore(element, guess) {
  var i, j, value, values, score, classes, matches, total;
  score = getScore();
  classes = element.className.replace(/\s+/g, ' ').split(' ');
  for (i = 0; i < classes.length; i += 1) {
    total = 0;
    values = [];
    matches = document.getElementsByClassName(classes[i]);
    for (j = 0; j < matches.length; j += 1) {
      value = parseInt(matches[j].innerHTML, 10);
      if (guess && matches[j] === element) {
        value = guess;
      }
      if (!isNaN(value)) {
        values.push(value);
        total += value;
      }
    }
    score += countScore(total, 3);
    score += countScore(total, 5);
    score += countScore(total, 7);
    score += bonusScore(values);
  }
  return score;
}

function updateScore(element) {
  setScore(guessScore(element));
}

function isPlayable(element) {
  return element && element.nodeName === 'TD' && element.innerHTML === '';
}

function toggleTurn() {
  var i;
  for (i = 0; i < 8; i += 1) {
    dragDrop.unbind("piece" + currentPlayer + i);
  }
  currentPlayer = (currentPlayer === 1) ? 2 : 1;
  for (i = 0; i < 8; i += 1) {
    dragDrop.bind("piece" + currentPlayer + i);
  }
  if (numberOfPlayers === 0 || (numberOfPlayers === 1 && currentPlayer === 2)) {
    makeMove();
  }
}

function endTurn(piece, tile) {
  if (piece && tile) {
    tile.innerHTML = piece.innerHTML;
    piece.parentNode.removeChild(piece);
    updateScore(tile);
    toggleTurn();
  }
}

dragDrop = {
  initialMouseX: null,
  initialMouseY: null,
  startX: null,
  startY: null,
  draggedObject: null,
  droppedObject: null,

  bind: function (element) {
    if (typeof element === "string") {
      element = $(element);
    }
    if (element) {
      if (currentPlayer === 1 || numberOfPlayers !== 1) {
        addClass(element, 'playing');
      }
      element.addEventListener("mousedown", dragDrop.startDragMouse, false);
      element.style.top = "0px";
      element.style.left = "0px";
    }
  },

  unbind: function (element) {
    if (typeof element === "string") {
      element = $(element);
    }
    if (element) {
      if (numberOfPlayers >= 2) {
        removeClass(element, 'playing');
      }
      element.removeEventListener("mousedown", dragDrop.startDragMouse, false);
    }
  },

  startDragMouse: function (e) {
    dragDrop.startDrag(this);
    dragDrop.initialMouseX = e.clientX;
    dragDrop.initialMouseY = e.clientY;
    document.addEventListener("mousemove", dragDrop.dragMouse, false);
    document.addEventListener("mouseup", dragDrop.releaseElement, false);
    addClass(dragDrop.draggedObject, 'dragging');
    return false;
  },

  startDrag: function (object) {
    if (dragDrop.draggedObjct) {
      dragDrop.releaseElement();
    }
    dragDrop.startX = parseInt(object.style.left, 10);
    dragDrop.startY = parseInt(object.style.top, 10);
    dragDrop.draggedObject = object;
  },

  dragMouse: function (e) {
    var dx, dy;
    dx = e.clientX - dragDrop.initialMouseX;
    dy = e.clientY - dragDrop.initialMouseY;
    dragDrop.draggedObject.style.left = dragDrop.startX + dx + "px";
    dragDrop.draggedObject.style.top = dragDrop.startY + dy + "px";
    if (dragDrop.droppedObject) {
      removeClass(dragDrop.droppedObject, 'dropping');
    }
    dragDrop.draggedObject.style.display = 'none';
    dragDrop.droppedObject = document.elementFromPoint(e.clientX, e.clientY);
    dragDrop.draggedObject.style.display = 'inline-block';
    if (isPlayable(dragDrop.droppedObject)) {
      addClass(dragDrop.droppedObject, 'dropping');
    }
    return false;
  },

  releaseElement: function (e) {
    var under = null;
    document.removeEventListener("mousemove", dragDrop.dragMouse, false);
    document.removeEventListener("mouseup", dragDrop.releaseElement, false);
    removeClass(dragDrop.draggedObject, 'dragging');
    dragDrop.draggedObject.style.display = 'none';
    under = document.elementFromPoint(e.clientX, e.clientY);
    if (isPlayable(under)) {
      endTurn(dragDrop.draggedObject, under);
    } else {
      dragDrop.draggedObject.style.display = 'inline-block';
      dragDrop.draggedObject.style.left = dragDrop.startX + "px";
      dragDrop.draggedObject.style.top = dragDrop.startY + "px";
    }
    dragDrop.draggedObject = null;
    if (dragDrop.droppedObject) {
      removeClass(dragDrop.droppedObject, 'dropping');
    }
    dragDrop.droppedObject = null;
  }
};

function fakeMove(piece, tile) {
  var pieceCenter, tileCenter;

  if (isPlayable(tile)) {
    pieceCenter = findCenter(piece);
    tileCenter = findCenter(tile);
    addClass(piece, 'playing');
    animate(piece, 'moving', function () { endTurn(piece, tile); });
    piece.style.left = parseInt(piece.style.left, 10) + (tileCenter.x - pieceCenter.x) + 'px';
    piece.style.top = parseInt(piece.style.top, 10) + (tileCenter.y - pieceCenter.y) + 'px';
  }
}

function makeMove() {
  var i, j, tiles, playables, piece, pieces, value, score, scores, best;

  tiles = document.getElementsByTagName('td');
  playables = [];
  for (i = 0; i < tiles.length; i += 1) {
    if (isPlayable(tiles[i])) {
      playables.push(tiles[i]);
    }
  }

  pieces = [];
  for (i = 0; i < 8; i += 1) {
    piece = $("piece" + currentPlayer + i);
    if (piece) {
      pieces.push(piece);
    }
  }

  best = { piece: undefined, tile: undefined, score: 0 };
  for (i = 0; i < pieces.length; i += 1) {
    value = parseInt(pieces[i].innerHTML, 10);
    for (j = 0; j < playables.length; j += 1) {
      score = guessScore(playables[j], value);
      if (score >= best.score) {
        best = { piece: pieces[i], tile: playables[j], score: score };
      }
    }
  }

  fakeMove(best.piece, best.tile);

  if (best.piece && best.tile) {
    console.log('Best move is:');
    console.log('Piece: ' + best.piece.innerHTML);
    console.log('Tile: ' + best.tile.className);
    console.log('Score: ' + best.score);
  }
}

function shuffle(array) {
  var i, j, temp;
  for (i = array.length - 1; i > 0; i -= 1) {
    j = Math.floor(Math.random() * (i + 1));
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}

pieces = [];
for (i = 0; i < 4; i += 1) {
  for (j = 1; j <= 13; j += 1) {
    pieces.push(j);
  }
}
shuffle(pieces);

for (i = 0, j = 0, k = 0; i < 16; i += 1) {
  if (i % 2 === 0) {
    html("piece1" + j, pieces[i]);
    j += 1;
  } else {
    html("piece2" + k, pieces[i]);
    k += 1;
  }
}

toggleTurn();

}());
<commit_msg>Moves the makeMove function so it's defined before it's used.<commit_after>(function () {
"use strict";

var i, j, k, pieces, currentPlayer, numberOfPlayers, dragDrop;

currentPlayer = 2;
numberOfPlayers = 1;

function $(id) {
  return document.getElementById(id);
}

function html(id, text) {
  $(id).innerHTML = text;
}

function addClass(selector, value) {
  if (typeof selector === 'string') {
    selector = $(selector);
  }
  selector.className += ' ' + value;
}

function removeClass(selector, value) {
  var regex = new RegExp(' ' + value, 'g');
  if (typeof selector === 'string') {
    selector = $(selector);
  }
  selector.className = selector.className.replace(regex, '');
}

function animate(element, klass, callback) {
  var wrapper = function () {
    if (callback) {
      callback();
    }
    removeClass(element, klass);
    element.removeEventListener('webkitTransitionEnd', wrapper, true);
  };
  element.addEventListener('webkitTransitionEnd', wrapper, true);
  addClass(element, klass);
}

function findCenter(element) {
  var x = 0, y = 0;
  if (element) {
    x = element.offsetWidth / 2;
    y = element.offsetHeight / 2;
  }
  while (element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) {
    x += element.offsetLeft - element.scrollLeft;
    y += element.offsetTop - element.scrollTop;
    element = element.offsetParent;
  }
  return { x: x, y: y };
}

function countScore(total, factor) {
  return (total % factor === 0) ? total / factor : 0;
}

function getScore() {
  return parseInt($('player' + currentPlayer + '-score').innerHTML, 10);
}

function setScore(newScore) {
  html('player' + currentPlayer + '-score', newScore);
}

function countUnique(array) {
  var i, keys;
  keys = {};
  for (i = 0; i < array.length; i += 1) {
    keys[array[i]] = 1;
  }
  return Object.keys(keys).length;
}

function bonusScore(values) {
  var i, score, straight, unique;
  if (values.length <= 1) {
    return 0;
  }
  unique = countUnique(values);
  if (values.length <= 2) {
    /* a pair */
    if (unique === 1) {
      return 2;
    }
    return 0;
  }
  if (values.length <= 3) {
    /* a pair */
    if (unique === 2) {
      return 2;
    }
    /* three of a kind */
    if (unique === 1) {
      return 6;
    }
    return 0;
  }
  score = 0;
  straight = 0;
  values.sort();
  for (i = 0; i < values.length - 1; i += 1) {
    if (values[i] + 1 === values[i + 1]) {
      straight += 1;
    }
  }
  /* a straight */
  if (straight === 3) {
    score += 4;
  }
  /* a pair */
  if (unique === 3) {
    score += 2;
  }
  /* three of a kind */
  if (unique === 2) {
    score += 6;
  }
  /* four of a kind */
  if (unique === 1) {
    score += 12;
  }
  return score;
}

function guessScore(element, guess) {
  var i, j, value, values, score, classes, matches, total;
  score = getScore();
  classes = element.className.replace(/\s+/g, ' ').split(' ');
  for (i = 0; i < classes.length; i += 1) {
    total = 0;
    values = [];
    matches = document.getElementsByClassName(classes[i]);
    for (j = 0; j < matches.length; j += 1) {
      value = parseInt(matches[j].innerHTML, 10);
      if (guess && matches[j] === element) {
        value = guess;
      }
      if (!isNaN(value)) {
        values.push(value);
        total += value;
      }
    }
    score += countScore(total, 3);
    score += countScore(total, 5);
    score += countScore(total, 7);
    score += bonusScore(values);
  }
  return score;
}

function updateScore(element) {
  setScore(guessScore(element));
}

function isPlayable(element) {
  return element && element.nodeName === 'TD' && element.innerHTML === '';
}

function makeMove() {
  var i, j, tiles, playables, piece, pieces, value, score, scores, best;

  tiles = document.getElementsByTagName('td');
  playables = [];
  for (i = 0; i < tiles.length; i += 1) {
    if (isPlayable(tiles[i])) {
      playables.push(tiles[i]);
    }
  }

  pieces = [];
  for (i = 0; i < 8; i += 1) {
    piece = $("piece" + currentPlayer + i);
    if (piece) {
      pieces.push(piece);
    }
  }

  best = { piece: undefined, tile: undefined, score: 0 };
  for (i = 0; i < pieces.length; i += 1) {
    value = parseInt(pieces[i].innerHTML, 10);
    for (j = 0; j < playables.length; j += 1) {
      score = guessScore(playables[j], value);
      if (score >= best.score) {
        best = { piece: pieces[i], tile: playables[j], score: score };
      }
    }
  }

  fakeMove(best.piece, best.tile);

  if (best.piece && best.tile) {
    console.log('Best move is:');
    console.log('Piece: ' + best.piece.innerHTML);
    console.log('Tile: ' + best.tile.className);
    console.log('Score: ' + best.score);
  }
}

function toggleTurn() {
  var i;
  for (i = 0; i < 8; i += 1) {
    dragDrop.unbind("piece" + currentPlayer + i);
  }
  currentPlayer = (currentPlayer === 1) ? 2 : 1;
  for (i = 0; i < 8; i += 1) {
    dragDrop.bind("piece" + currentPlayer + i);
  }
  if (numberOfPlayers === 0 || (numberOfPlayers === 1 && currentPlayer === 2)) {
    makeMove();
  }
}

function endTurn(piece, tile) {
  if (piece && tile) {
    tile.innerHTML = piece.innerHTML;
    piece.parentNode.removeChild(piece);
    updateScore(tile);
    toggleTurn();
  }
}

dragDrop = {
  initialMouseX: null,
  initialMouseY: null,
  startX: null,
  startY: null,
  draggedObject: null,
  droppedObject: null,

  bind: function (element) {
    if (typeof element === "string") {
      element = $(element);
    }
    if (element) {
      if (currentPlayer === 1 || numberOfPlayers !== 1) {
        addClass(element, 'playing');
      }
      element.addEventListener("mousedown", dragDrop.startDragMouse, false);
      element.style.top = "0px";
      element.style.left = "0px";
    }
  },

  unbind: function (element) {
    if (typeof element === "string") {
      element = $(element);
    }
    if (element) {
      if (numberOfPlayers >= 2) {
        removeClass(element, 'playing');
      }
      element.removeEventListener("mousedown", dragDrop.startDragMouse, false);
    }
  },

  startDragMouse: function (e) {
    dragDrop.startDrag(this);
    dragDrop.initialMouseX = e.clientX;
    dragDrop.initialMouseY = e.clientY;
    document.addEventListener("mousemove", dragDrop.dragMouse, false);
    document.addEventListener("mouseup", dragDrop.releaseElement, false);
    addClass(dragDrop.draggedObject, 'dragging');
    return false;
  },

  startDrag: function (object) {
    if (dragDrop.draggedObjct) {
      dragDrop.releaseElement();
    }
    dragDrop.startX = parseInt(object.style.left, 10);
    dragDrop.startY = parseInt(object.style.top, 10);
    dragDrop.draggedObject = object;
  },

  dragMouse: function (e) {
    var dx, dy;
    dx = e.clientX - dragDrop.initialMouseX;
    dy = e.clientY - dragDrop.initialMouseY;
    dragDrop.draggedObject.style.left = dragDrop.startX + dx + "px";
    dragDrop.draggedObject.style.top = dragDrop.startY + dy + "px";
    if (dragDrop.droppedObject) {
      removeClass(dragDrop.droppedObject, 'dropping');
    }
    dragDrop.draggedObject.style.display = 'none';
    dragDrop.droppedObject = document.elementFromPoint(e.clientX, e.clientY);
    dragDrop.draggedObject.style.display = 'inline-block';
    if (isPlayable(dragDrop.droppedObject)) {
      addClass(dragDrop.droppedObject, 'dropping');
    }
    return false;
  },

  releaseElement: function (e) {
    var under = null;
    document.removeEventListener("mousemove", dragDrop.dragMouse, false);
    document.removeEventListener("mouseup", dragDrop.releaseElement, false);
    removeClass(dragDrop.draggedObject, 'dragging');
    dragDrop.draggedObject.style.display = 'none';
    under = document.elementFromPoint(e.clientX, e.clientY);
    if (isPlayable(under)) {
      endTurn(dragDrop.draggedObject, under);
    } else {
      dragDrop.draggedObject.style.display = 'inline-block';
      dragDrop.draggedObject.style.left = dragDrop.startX + "px";
      dragDrop.draggedObject.style.top = dragDrop.startY + "px";
    }
    dragDrop.draggedObject = null;
    if (dragDrop.droppedObject) {
      removeClass(dragDrop.droppedObject, 'dropping');
    }
    dragDrop.droppedObject = null;
  }
};

function fakeMove(piece, tile) {
  var pieceCenter, tileCenter;

  if (isPlayable(tile)) {
    pieceCenter = findCenter(piece);
    tileCenter = findCenter(tile);
    addClass(piece, 'playing');
    animate(piece, 'moving', function () { endTurn(piece, tile); });
    piece.style.left = parseInt(piece.style.left, 10) + (tileCenter.x - pieceCenter.x) + 'px';
    piece.style.top = parseInt(piece.style.top, 10) + (tileCenter.y - pieceCenter.y) + 'px';
  }
}

function shuffle(array) {
  var i, j, temp;
  for (i = array.length - 1; i > 0; i -= 1) {
    j = Math.floor(Math.random() * (i + 1));
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}

pieces = [];
for (i = 0; i < 4; i += 1) {
  for (j = 1; j <= 13; j += 1) {
    pieces.push(j);
  }
}
shuffle(pieces);

for (i = 0, j = 0, k = 0; i < 16; i += 1) {
  if (i % 2 === 0) {
    html("piece1" + j, pieces[i]);
    j += 1;
  } else {
    html("piece2" + k, pieces[i]);
    k += 1;
  }
}

toggleTurn();

}());
<|endoftext|>


<commit_before>/*global Reveal, hljs */
/* handles URL query, initialize Reveal and $.sample */
(function($, undefined){
  "use strict";

  // Find slide id
  var slideId = location.search.replace('?',''),
      $targetSlide,
      $targetSlideParent;

  if(slideId && $('section#'+slideId)){
    $targetSlide = $('section#'+slideId);
    $targetSlideParent = $targetSlide.parent();
    slideId = $.inArray($targetSlide.get(0), $targetSlideParent.children());

    // vertical slide
    if($targetSlideParent.is('section')){
      location.hash = '#/' + $.inArray($targetSlideParent.get(0),
                                       $targetSlideParent.parent().children()) + '/' + slideId;
    }else{ // normal horizontal slide
      location.hash = '#/' + slideId;
    }

    location.search = ''; // clear search
  }

  // initialize Reveal
  Reveal.initialize({
    // Display controls in the bottom right corner
    controls: true,

    // Display a presentation progress bar
    progress: true,

    // If true; each slide will be pushed to the browser history
    history: true,

    // Flags if mouse wheel navigation should be enabled
    mouseWheel: true,

    // Apply a 3D roll to links on hover
    rollingLinks: true,

    // UI style
    theme: 'default', // default/neon

    // Transition style
    transition: 'default', // default/cube/page/concave/linear(2d)

    update: function(indexh, indexv){
      // update sample code so that 'height' of iframe is correct
      $('section.present').not('.stack').find('script[type="text/x-sample"]').sample('update');
    }
  });

}(jQuery));<commit_msg>highlight all
 blocks created by ``` ```<commit_after>/*global Reveal, hljs */
/* handles URL query, initialize Reveal and $.sample */
(function($, undefined){
  "use strict";

  // Find slide id
  var slideId = location.search.replace('?',''),
      $targetSlide,
      $targetSlideParent;

  if(slideId && $('section#'+slideId)){
    $targetSlide = $('section#'+slideId);
    $targetSlideParent = $targetSlide.parent();
    slideId = $.inArray($targetSlide.get(0), $targetSlideParent.children());

    // vertical slide
    if($targetSlideParent.is('section')){
      location.hash = '#/' + $.inArray($targetSlideParent.get(0),
                                       $targetSlideParent.parent().children()) + '/' + slideId;
    }else{ // normal horizontal slide
      location.hash = '#/' + slideId;
    }

    location.search = ''; // clear search
  }

  // enable highlighting for all
 elements
  $('pre>code').each(function(){
    var $this = $(this);

    // do highlighting only when not contained in sample-container
    if(!$this.parents('.sample-container').length){
      $(this).html( hljs.highlightAuto($(this).text()).value );
    }
  });

  // initialize Reveal
  Reveal.initialize({
    // Display controls in the bottom right corner
    controls: true,

    // Display a presentation progress bar
    progress: true,

    // If true; each slide will be pushed to the browser history
    history: true,

    // Flags if mouse wheel navigation should be enabled
    mouseWheel: true,

    // Apply a 3D roll to links on hover
    rollingLinks: true,

    // UI style
    theme: 'default', // default/neon

    // Transition style
    transition: 'default', // default/cube/page/concave/linear(2d)

    update: function(indexh, indexv){
      // update sample code so that 'height' of iframe is correct
      $('section.present').not('.stack').find('script[type="text/x-sample"]').sample('update');
    }
  });

}(jQuery));
<|endoftext|>


<commit_before>filterKeyWords = [
    ["like page"],
    ["sponsored"],
    ["happy birthday"]];

Set.prototype.intersection = function(setB) {
    var intersection = new Set();
    for (var elem of setB) {
        if (this.has(elem)) {
            intersection.add(elem);
        }
    }
    return intersection;
}

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
}

function getRawString(str){
    return str.replaceAll("<[^>]*>", " ").toLowerCase().replaceAll("\\s+", " ").trim();
}

function toBeFiltered(element) {
    if (!element) {return true;}
    article = getRawString(element.html());
    console.log(article);
    for (var i = 0; i < filterKeyWords.length; i++) {
        for (var j = 0; j < filterKeyWords[i].length; j++) {
            if(article.contains(filterKeyWords[i][j])) return true;
        }
    }
    return false;
}

function eliminateOnInsert(e) {
    element = $(e.target);
    id = element.attr('id');
    if(id && id.startsWith('u_jsonp')) {
        parent = element.parent();
        if(parent) {
            id = parent.attr('id');
            if(id  && id.startsWith('hyperfeed_story_id') && toBeFiltered(parent)) {
                parent.hide();
            }
        }
    }
}

(function(){
    divs=$('div');
    divs = divs.filter(function(i, div){
        id = div.getAttribute('id');
        if(id) {
            return id.startsWith('hyperfeed_story_id');
        }
        return false;
    });

    divs.each(function(i, div){
        div = $(div);
        if (toBeFiltered(div)) {
            div.hide();
        }
    });
}());

$(document).on('DOMNodeInserted', eliminateOnInsert);
<commit_msg>Remove console output for facebook<commit_after>filterKeyWords = [
    ["like page"],
    ["sponsored"],
    ["happy birthday"]];

Set.prototype.intersection = function(setB) {
    var intersection = new Set();
    for (var elem of setB) {
        if (this.has(elem)) {
            intersection.add(elem);
        }
    }
    return intersection;
}

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
}

function getRawString(str){
    return str.replaceAll("<[^>]*>", " ").toLowerCase().replaceAll("\\s+", " ").trim();
}

function toBeFiltered(element) {
    if (!element) {return true;}
    article = getRawString(element.html());
    for (var i = 0; i < filterKeyWords.length; i++) {
        for (var j = 0; j < filterKeyWords[i].length; j++) {
            if(article.contains(filterKeyWords[i][j])) return true;
        }
    }
    return false;
}

function eliminateOnInsert(e) {
    element = $(e.target);
    id = element.attr('id');
    if(id && id.startsWith('u_jsonp')) {
        parent = element.parent();
        if(parent) {
            id = parent.attr('id');
            if(id  && id.startsWith('hyperfeed_story_id') && toBeFiltered(parent)) {
                parent.hide();
            }
        }
    }
}

(function(){
    divs=$('div');
    divs = divs.filter(function(i, div){
        id = div.getAttribute('id');
        if(id) {
            return id.startsWith('hyperfeed_story_id');
        }
        return false;
    });

    divs.each(function(i, div){
        div = $(div);
        if (toBeFiltered(div)) {
            div.hide();
        }
    });
}());

$(document).on('DOMNodeInserted', eliminateOnInsert);
<|endoftext|>


<commit_before>
/*
 Timer
 Score
 Lives
 Main Menu
 Game Mode
 ball bounce 45 to normal
 multiple balls
 barrier code
 hud - Jesse's grinning visage

  Lorin
  Tim
  Jesse
  and a big fuck you to the intern Ben

excess shit
high score
sarcasm generated
*/
var settings = {
    arena : [500, 500]
}

var go = {
    balls : [],
    ball : {
        radius : 10,
        vector : [5.0,6.0],
        location : [100,100]
    },
    //
    walls : [[0, 0, settings.arena[0], 0], // top horizontal
             [0, 0, 0, settings.arena[1]], // left vertical
             [0, settings.arena[1], settings.arena[0], settings.arena[1]], // bottom horizontal
             [settings.arena[0], 0, settings.arena[0], settings.arena[1]]]
}

function mainloop() {
    var canvas=document.getElementById("maincanvas");
    var ctx=canvas.getContext('2d');

    updateball(go.ball);

    for (var i = 0; i < go.walls.length; i++) {
        intersect(go.walls[i], go.ball);
    }

    drawarena();
    drawball();
}

function drawarena() {
    var canvas=document.getElementById("maincanvas");
    var ctx=canvas.getContext('2d');
    ctx.clearRect(0,0,500,500);
    ctx.lineWidth = 5;
    ctx.strokeRect(0,0,500,500);
}

function drawball() {
    var canvas=document.getElementById("maincanvas");
    var ctx=canvas.getContext('2d');
    ctx.beginPath();
    ctx.arc(go.ball.location[0],
            go.ball.location[1],
            go.ball.radius,
            0,
            2 * Math.PI,
            false);
    ctx.fillStyle = 'green';
    ctx.fill();
    ctx.lineWidth = 2;
    ctx.strokeStyle = '#000000';
    ctx.stroke();
}

function updateball(ball) {

    ball.location[0] = ball.vector[0] + ball.location[0];
    ball.location[1] = ball.vector[1] + ball.location[1];

    for (var i = 0; i < go.walls.length; i++) {
        if (intersect(go.walls[i], go.ball)) {
            bounce(go.walls[i], go.ball);
        }
    }
/*
    if(ball.l cation[0] < 0) {
        ball.location[0] = 0;
        ball.vector[0] = -1 * ball.vector[0];
    } else if (ball.location[0] > 500) {
        ball.location[0] = 500;
        ball.vector[0] = -1 * ball.vector[0];
    }

    if(ball.location[1] < 0) {
        ball.location[1] = 0;
        ball.vector[1] = -1 * ball.vector[1];
    } else if (ball.location[1] > 500) {
        ball.location[1] = 500;
        ball.vector[1] = -1 * ball.vector[1];
    }
*/
}

function intersect(wall, ball) {
    // if the wall array has more than 4 elements, someone's doing it wrong
    if ((ball.location[0] < wall[0]) ||
        (ball.location[0] > wall[1]) ||
        (ball.location[1] < wall[2]) ||
        (ball.location[1] > wall[3])) {
        bounce(wall,ball);
    }
}

/**
 *
 */
function bounce(wall, ball) {
    // [a2-a1,b2-b1]
    var wallvect = [wall[0] - wall[2],
                    wall[1] - wall[3]];
    // a dot b = ||a|| * b|| * cos theta == (a dot b) / (||a|| * ||b||) = cos theta, then remove arccos
    var theta = Math.acos (dotprod(wallvect, ball.vector) / (vecmag(wallvect) * vecmag(ball.vector)) );

}

/**
 * calculate dot product
 */
function dotprod(v1, v2) {
    return (v1[0] * v2[0]) + (v1[1] * v2[1]);
}

/**
 * calculate 2D vector magnitude
 */
function vecmag(v) {
    return Math.sqrt(v[0]*v[0] + v[1]*v[1]);
}
<commit_msg>removed comments reenabling naive collision detection<commit_after>
/*
 Timer
 Score
 Lives
 Main Menu
 Game Mode
 ball bounce 45 to normal
 multiple balls
 barrier code
 hud - Jesse's grinning visage

  Lorin
  Tim
  Jesse
  and a big fuck you to the intern Ben

excess shit
high score
sarcasm generated
*/
var settings = {
    arena : [500, 500]
}

var go = {
    balls : [],
    ball : {
        radius : 10,
        vector : [5.0,6.0],
        location : [100,100]
    },
    //
    walls : [[0, 0, settings.arena[0], 0], // top horizontal
             [0, 0, 0, settings.arena[1]], // left vertical
             [0, settings.arena[1], settings.arena[0], settings.arena[1]], // bottom horizontal
             [settings.arena[0], 0, settings.arena[0], settings.arena[1]]]
}

function mainloop() {
    var canvas=document.getElementById("maincanvas");
    var ctx=canvas.getContext('2d');

    updateball(go.ball);

    for (var i = 0; i < go.walls.length; i++) {
        intersect(go.walls[i], go.ball);
    }

    drawarena();
    drawball();
}

function drawarena() {
    var canvas=document.getElementById("maincanvas");
    var ctx=canvas.getContext('2d');
    ctx.clearRect(0,0,500,500);
    ctx.lineWidth = 5;
    ctx.strokeRect(0,0,500,500);
}

function drawball() {
    var canvas=document.getElementById("maincanvas");
    var ctx=canvas.getContext('2d');
    ctx.beginPath();
    ctx.arc(go.ball.location[0],
            go.ball.location[1],
            go.ball.radius,
            0,
            2 * Math.PI,
            false);
    ctx.fillStyle = 'green';
    ctx.fill();
    ctx.lineWidth = 2;
    ctx.strokeStyle = '#000000';
    ctx.stroke();
}

function updateball(ball) {

    ball.location[0] = ball.vector[0] + ball.location[0];
    ball.location[1] = ball.vector[1] + ball.location[1];

    for (var i = 0; i < go.walls.length; i++) {
        if (intersect(go.walls[i], go.ball)) {
            bounce(go.walls[i], go.ball);
        }
    }

    if(ball.location[0] < 0) {
        ball.location[0] = 0;
        ball.vector[0] = -1 * ball.vector[0];
    } else if (ball.location[0] > 500) {
        ball.location[0] = 500;
        ball.vector[0] = -1 * ball.vector[0];
    }

    if(ball.location[1] < 0) {
        ball.location[1] = 0;
        ball.vector[1] = -1 * ball.vector[1];
    } else if (ball.location[1] > 500) {
        ball.location[1] = 500;
        ball.vector[1] = -1 * ball.vector[1];
    }

}

function intersect(wall, ball) {
    // if the wall array has more than 4 elements, someone's doing it wrong
    if ((ball.location[0] < wall[0]) ||
        (ball.location[0] > wall[1]) ||
        (ball.location[1] < wall[2]) ||
        (ball.location[1] > wall[3])) {
        bounce(wall,ball);
    }
}

/**
 *
 */
function bounce(wall, ball) {
    // [a2-a1,b2-b1]
    var wallvect = [wall[0] - wall[2],
                    wall[1] - wall[3]];
    // a dot b = ||a|| * b|| * cos theta == (a dot b) / (||a|| * ||b||) = cos theta, then remove arccos
    var theta = Math.acos (dotprod(wallvect, ball.vector) / (vecmag(wallvect) * vecmag(ball.vector)) );

}

/**
 * calculate dot product
 */
function dotprod(v1, v2) {
    return (v1[0] * v2[0]) + (v1[1] * v2[1]);
}

/**
 * calculate 2D vector magnitude
 */
function vecmag(v) {
    return Math.sqrt(v[0]*v[0] + v[1]*v[1]);
}
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var debug = require('debug')('wpcom:batch');

/**
 * Create a `Batch` instance
 *
 * @param {WPCOM} wpcom
 * @api public
 */

function Batch(wpcom) {
  if (!(this instanceof Batch)) {
    return new Batch(wpcom);
  }

  this.wpcom = wpcom;

  this.urls = [];
}

/**
 * Add url to batch requests
 *
 * @param {String} url
 * @api public
 */

Batch.prototype.add = function (url) {
  this.urls.push(url);
  return this;
};

/**
 * Run the batch request
 *
 * @param {Object} [query]
 * @param {Function} fn
 * @api public
 */

Batch.prototype.run = function (query, fn) {
  // add urls to query object
  if ('function' === typeof query) {
    fn = query;
    query = {};
  }
  query.urls = this.urls;

  return this.wpcom.req.get('/batch', query, fn);
};

/**
 * Expose `Batch` module
 */

module.exports = Batch;<commit_msg>batch: pass `urls[]` in the query<commit_after>
/**
 * Module dependencies.
 */

var debug = require('debug')('wpcom:batch');

/**
 * Create a `Batch` instance
 *
 * @param {WPCOM} wpcom
 * @api public
 */

function Batch(wpcom) {
  if (!(this instanceof Batch)) {
    return new Batch(wpcom);
  }

  this.wpcom = wpcom;

  this.urls = [];
}

/**
 * Add url to batch requests
 *
 * @param {String} url
 * @api public
 */

Batch.prototype.add = function (url) {
  this.urls.push(url);
  return this;
};

/**
 * Run the batch request
 *
 * @param {Object} [query]
 * @param {Function} fn
 * @api public
 */

Batch.prototype.run = function (query, fn) {
  // add urls to query object
  if ('function' === typeof query) {
    fn = query;
    query = {};
  }
  query['urls[]'] = this.urls;

  return this.wpcom.req.get('/batch', query, fn);
};

/**
 * Expose `Batch` module
 */

module.exports = Batch;
<|endoftext|>


<commit_before>/*eslint-env node */

module.exports = function (grunt) {
  grunt.initConfig({
    "bolt-init": {
      "theme": {
        config_dir: "config/bolt"
      }
    },

    "bolt-build": {
      "theme": {
        config_js: "config/bolt/prod.js",
        output_dir: "scratch",
        main: "tinymce.themes.mobile.Theme",
        filename: "theme",

        generate_inline: true,
        minimise_module_names: true,

        files: {
          src: ["src/main/js/Theme.js"]
        }
      }
    },

    copy: {
      "theme": {
        files: [
          {
            src: "scratch/inline/theme.raw.js",
            dest: "dist/inline/theme.js"
          }
        ]
      },

      "standalone": {
        files: [
          {
            expand: true,
            flatten: true,
            src: ['src/main/css/**'],
            dest: 'deploy-local/css',
            filter: 'isFile'
          },
          {
            expand: true,
            flatten: true,
            src: ['src/main/icons/**'],
            dest: 'deploy-local/icons',
            filter: 'isFile'
          },
          {
            src: "../../../js/tinymce/tinymce.min.js",
            dest: "deploy-local/js/tinymce.min.js"
          },
          {
            src: "../../../js/tinymce/plugins/lists/plugin.min.js",
            dest: "deploy-local/js/plugins/lists/plugin.min.js"
          },
          {
            src: "scratch/inline/theme.js",
            dest: "deploy-local/js/mobile_theme.js"
          },
          {
            src: "index.html",
            dest: "deploy-local/index.html"
          }

        ]
      }
    },

    eslint: {
      options: {
        config: "../../../.eslintrc"
      },

      src: [
        "src"
      ]
    },

    uglify: {
      options: {
        beautify: {
          ascii_only: true,
          screw_ie8: false
        },

        compress: {
          screw_ie8: false
        }
      },

      "standalone": {
        files: [
          {
            src: "deploy-local/js/mobile_theme.js",
            dest: "deploy-local/js/mobile_theme.min.js"
          }
        ]
      },

      "theme": {
        files: [
          {
            src: "scratch/inline/theme.js",
            dest: "dist/inline/theme.min.js"
          }
        ]
      }
    },
    less: {
      development: {
        options: {
          plugins : [ new (require('less-plugin-autoprefix'))({browsers : [ "last 2 versions" ]}) ],
          compress: true,
          yuicompress: true,
          optimization: 2
        },
        files: {
          "src/main/css/mobile.css": "src/main/css/app/mobile-less.less" // destination file and source file
        }
      }
    },
    watch: {
      styles: {
        files: ['src/main/css/**/*.less'], // which files to watch
        tasks: ['less'],
        options: {
          nospawn: true
        }
      }
    }
  });

  grunt.task.loadTasks("../../../node_modules/@ephox/bolt/tasks");
  grunt.task.loadTasks("../../../node_modules/grunt-contrib-copy/tasks");
  grunt.task.loadTasks("../../../node_modules/grunt-contrib-uglify/tasks");
  grunt.task.loadTasks("../../../node_modules/grunt-eslint/tasks");
  grunt.task.loadTasks("../../../node_modules/grunt-contrib-less/tasks");
  grunt.task.loadTasks("../../../node_modules/grunt-contrib-watch/tasks");

  grunt.registerTask("default", ["bolt-init", "bolt-build", "copy", "eslint", "uglify:theme"]);
  grunt.registerTask("standalone", [ "bolt-build", "copy:standalone", "uglify:standalone"]);
};
<commit_msg>TM-34: add grunt watch option to run less task on start<commit_after>/*eslint-env node */

module.exports = function (grunt) {
  grunt.initConfig({
    "bolt-init": {
      "theme": {
        config_dir: "config/bolt"
      }
    },

    "bolt-build": {
      "theme": {
        config_js: "config/bolt/prod.js",
        output_dir: "scratch",
        main: "tinymce.themes.mobile.Theme",
        filename: "theme",

        generate_inline: true,
        minimise_module_names: true,

        files: {
          src: ["src/main/js/Theme.js"]
        }
      }
    },

    copy: {
      "theme": {
        files: [
          {
            src: "scratch/inline/theme.raw.js",
            dest: "dist/inline/theme.js"
          }
        ]
      },

      "standalone": {
        files: [
          {
            expand: true,
            flatten: true,
            src: ['src/main/css/**'],
            dest: 'deploy-local/css',
            filter: 'isFile'
          },
          {
            expand: true,
            flatten: true,
            src: ['src/main/icons/**'],
            dest: 'deploy-local/icons',
            filter: 'isFile'
          },
          {
            src: "../../../js/tinymce/tinymce.min.js",
            dest: "deploy-local/js/tinymce.min.js"
          },
          {
            src: "../../../js/tinymce/plugins/lists/plugin.min.js",
            dest: "deploy-local/js/plugins/lists/plugin.min.js"
          },
          {
            src: "scratch/inline/theme.js",
            dest: "deploy-local/js/mobile_theme.js"
          },
          {
            src: "index.html",
            dest: "deploy-local/index.html"
          }

        ]
      }
    },

    eslint: {
      options: {
        config: "../../../.eslintrc"
      },

      src: [
        "src"
      ]
    },

    uglify: {
      options: {
        beautify: {
          ascii_only: true,
          screw_ie8: false
        },

        compress: {
          screw_ie8: false
        }
      },

      "standalone": {
        files: [
          {
            src: "deploy-local/js/mobile_theme.js",
            dest: "deploy-local/js/mobile_theme.min.js"
          }
        ]
      },

      "theme": {
        files: [
          {
            src: "scratch/inline/theme.js",
            dest: "dist/inline/theme.min.js"
          }
        ]
      }
    },
    less: {
      development: {
        options: {
          plugins : [ new (require('less-plugin-autoprefix'))({browsers : [ "last 2 versions" ]}) ],
          compress: true,
          yuicompress: true,
          optimization: 2
        },
        files: {
          "src/main/css/mobile.css": "src/main/css/app/mobile-less.less" // destination file and source file
        }
      }
    },
    watch: {
      styles: {
        files: ['src/main/css/**/*.less'], // which files to watch
        tasks: ['less'],
        options: {
          nospawn: true,
          atBegin: true
        }
      }
    }
  });

  grunt.task.loadTasks("../../../node_modules/@ephox/bolt/tasks");
  grunt.task.loadTasks("../../../node_modules/grunt-contrib-copy/tasks");
  grunt.task.loadTasks("../../../node_modules/grunt-contrib-uglify/tasks");
  grunt.task.loadTasks("../../../node_modules/grunt-eslint/tasks");
  grunt.task.loadTasks("../../../node_modules/grunt-contrib-less/tasks");
  grunt.task.loadTasks("../../../node_modules/grunt-contrib-watch/tasks");

  grunt.registerTask("default", ["bolt-init", "bolt-build", "copy", "eslint", "uglify:theme"]);
  grunt.registerTask("standalone", [ "bolt-build", "copy:standalone", "uglify:standalone"]);
};
<|endoftext|>


<commit_before>/**
 * scheda.js
 * http://ravenjohn.github.io/scheda.js
 */

(function (root) {
    "use strict";

    /* jslint browser: true, regexp: true */

    var scheda = {},
        history = [],
        save = true,
        canvas_id,
        canvas,
        c,
        w,
        h,
        conf = {
            bgColor : "#D9FBCE",
            headerBgColor : "#6BBB62",
            miniGridColor : "#DFE0D2",
            hMainGridColor : "#BBDFBC",
            vMainGridColor : "#BBDFBC",
            timeColumnWidth : 50,
            time : {
                color : "#FFFFFF",
                bgColor : "#6BBB62",
                style : "normal",
                font : "Arial",
                size : 13
            },
            day : {
                color : "#FFFFFF",
                style : "normal",
                font : "Arial",
                size : 13
            },
            sched : {
                color : "#FFFFFF",
                style : "normal",
                font : "Arial",
                size : 13
            }
        },

        cvrt = function (e, f) {
            e.length < 3 && (e += "00");
            e = parseInt(e, 10);
            (e < 700 || (f && e == 700)) && (e += 1200);
            e += "";
            return ((parseInt(e.substring(0, e.length - 2), 10) - 7) * 4) + (parseInt(e.substring(e.length - 2), 10) / 15);
        },

        tC = function (w, c, t) {
            return (w - c.measureText(t).width) / 2;
        },

        gTop = function (x, ma, h, w, c) {
            var my = Math.floor(ma / 4) * h + h;
            switch (ma % 4) {
            case 0:
                c.lineTo(x, my);
                c.lineTo(x + w, my);
                break;
            case 1:
                c.lineTo(x, my);
                c.lineTo(x + (w / 2), my + (h / 2));
                c.lineTo(x + w, my);
                break;
            case 2:
                c.lineTo(x, my);
                c.lineTo(x + w, my + h);
                break;
            case 3:
                c.lineTo(x, my + h);
                c.lineTo(x + (w / 2), my + (h / 2));
                c.lineTo(x + w, my + h);
                break;
            }
        },

        gBottom = function (x, ma, h, w, c) {
            var my = Math.floor(ma / 4) * h + h;
            switch (ma % 4) {
            case 0:
                c.lineTo(x + w, my);
                c.lineTo(x, my);
                break;
            case 1:
                c.lineTo(x + w, my);
                c.lineTo(x + (w / 2), my + (h / 2));
                c.lineTo(x, my);
                break;
            case 2:
                c.lineTo(x + w, my + h);
                c.lineTo(x, my);
                break;
            case 3:
                c.lineTo(x + w, my + h);
                c.lineTo(x + (w / 2), my + (h / 2));
                c.lineTo(x, my + h);
                break;
            }
        },

        uuid = function (separator) {
            var S4 = function () {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            };
            return [S4() + S4(), S4(), S4(), S4(), S4() + S4() + S4()].join(separator || "-");
        };

    scheda.drawSchedule = function (day, time, courseCode, sectionName, room, color) {
        var y,
            sp,
            id,
            randomColor = function () {
                var rn = function () {
                    return parseInt(Math.random() * 255, 10);
                };
                return "rgb(" + rn() + ", " + rn() + ", " + rn() + ")";
            },
            draw = function (xx) {
                var x = (xx * w) + conf.timeColumnWidth;
                c.beginPath();
                gTop(x, time[0], h, w, c);
                gBottom(x, time[1] + time[0], h, w, c);
                c.strokeStyle = c.fillStyle = color;
                c.fill();
                c.lineWidth = 0.5;
                c.fillStyle = conf.sched.color;
                c.font = conf.sched.style + " " + conf.sched.size + "px " + conf.sched.font;
                if (room === "") {
                    c.fillText(courseCode, tC(w, c, courseCode) + x, y + (sp / 2) - 2);
                }
                else {
                    c.fillText(courseCode, tC(w, c, courseCode) + x, y + (sp / 2) - 2);
                    c.fillText(room, tC(w, c, room) + x, y + (sp / 2) + 10);
                }
                c.stroke();
            };

        save && history.push({id : (id = uuid()), args : arguments});
        time = time.replace(/:/g, "").split("-");
        time[1] = cvrt(time[1], 1) - (time[0] = cvrt(time[0]));
        y = (time[0] / 4) * h + h;
        sp = (time[1] / 4) * h;
        room = room || "";
        courseCode = courseCode + "\n" + (sectionName || "");
        day = day.toUpperCase();
        !color && (color = randomColor());
        if (~day.indexOf("M")) {
            draw(0);
        }
        if (~day.indexOf("TH")) {
            draw(3);
            day = day.replace("TH", "");
        }
        if (~day.indexOf("T")) {
            draw(1);
        }
        if (~day.indexOf("W")) {
            draw(2);
        }
        if (~day.indexOf("F")) {
            draw(4);
        }
        if (~day.indexOf("S")) {
            draw(5);
        }

        return id;
    };

    scheda.setConfig = function (config) {
        var i,
            j;
        for (i in config) {
            if(config.hasOwnProperty(i) && conf[i]){
                if(typeof config[i] === "object"){
                    for (j in config[i]) {
                        conf[i][j] = config[i][j];
                    }
                }
                else {
                    conf[i] = config[i];
                }
            }
        }
        scheda.repaint();
    };

    scheda.getConfig = function (p) {
        switch ((p = p.split(".")).length) {
        case 1: return conf[p[0]];
        case 2: return conf[p[0]][p[1]];
        }
    };

    scheda.repaint = function () {
        var i;
        scheda.init();
        save = false;
        for (i in history) {
            i > -1 && scheda.drawSchedule.apply(undefined, history[i].args);
        }
        save = true;
    };

    scheda.remove = function (id) {
        var i;
        for (i in history) {
            (i > -1 && id === history[i].id) && history.splice(i, 1);
        }
        scheda.repaint();
    };

    scheda.getHistory = function () {
        return history;
    };

    scheda.init = function (id, config) {
        var days = ["Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur"],
            i,
            j;

        id = id || canvas_id;

        if (!(canvas = document.getElementById(id))) {
            throw new Error("Unable to find canvas with id [" + id + "]");
        }

        canvas.width === 300 && (canvas.width = 811);
        canvas.height === 150 && (canvas.height = 391);
        c = canvas.getContext("2d");
        h = canvas.height / 13;
        w = (canvas.width - conf.timeColumnWidth) / 6;
        config && scheda.setConfig(config);
        canvas_id = id;

        // draw canvas background
        c.fillStyle = conf.bgColor;
        c.fillRect(0, 0, canvas.width, h * 13);

        // draw table header bg
        c.fillStyle = conf.headerBgColor;
        c.fillRect(0, 0, canvas.width, h);

        // draw mini grid
        c.beginPath();
        c.strokeStyle = conf.miniGridColor;
        for (i = 0, j = (h / 4) + h; i < 48; i += 1, j += (h / 4)) {
            c.moveTo(0, j);
            c.lineTo(canvas.width, j);
        }
        c.stroke();

        // draw time bg
        c.fillStyle = conf.time.bgColor;
        c.fillRect(0, h, conf.timeColumnWidth, canvas.height);

        // draw horizontal main grid
        c.beginPath();
        c.strokeStyle = conf.hMainGridColor;
        for (i = 0, j = h; i < 13; i += 1, j += h) {
            c.moveTo(0, j);
            c.lineTo(canvas.width, j);
        }
        c.stroke();

        // draw vertical main grid
        c.beginPath();
        c.strokeStyle = conf.vMainGridColor;
        c.moveTo(conf.timeColumnWidth, 0);
        c.lineTo(conf.timeColumnWidth, canvas.height);
        for (i = 0; i < 7; i += 1) {
            c.moveTo(i * w + conf.timeColumnWidth, 0);
            c.lineTo(i * w + conf.timeColumnWidth, canvas.height);
        }
        c.stroke();

        // draw time labels
        c.beginPath();
        c.fillStyle = conf.time.color;
        c.font = conf.time.style + " " + conf.time.size + "px " + conf.time.font;
        for (i = 7; i < 19; i += 1) {
            if (i === 12) {
                j = i + "-1";
            } else if (i > 12) {
                j = (i - 12) + "-" + (i - 11);
            } else {
                j = i + "-" + (i + 1);
            }
            c.fillText(j, tC(conf.timeColumnWidth, c, j), ((h / 2) + (conf.time.size / 2)) + ((i - 7) * h) + h);
        }

        // draw day labels
        c.fillStyle = conf.day.color;
        c.font = conf.day.style + " " + conf.day.size + "px " + conf.day.font;
        c.fillText("Time", tC(conf.timeColumnWidth, c, "Time"), ((h / 2) + (conf.day.size / 2)));
        for (i in days) {
            i > -1 && c.fillText(days[i] + "day", conf.timeColumnWidth + tC(w, c, days[i] + "day") + (i * w), ((h / 2) + (conf.day.size / 2)));
        }

    };

    scheda.downloadSchedule = function (e) {
        var a = document.createElement("a");
        if ((a.download = prompt("Please input desired file name:") + ".png") != "null.png") {
            a.type = "image/png";
            a.href = canvas.toDataURL().replace(/^data:image\/[^;]/, "data:application/octet-stream");
            a.onclick = function () {
                this.parentNode.removeChild(this);
            };
            document.getElementsByTagName("body")[0].appendChild(a);
            a.click();
        }
        e && e.preventDefault();
    };

    // expose scheda fn
    root.scheda = scheda;
}(this));
<commit_msg>Fixed empty file name bug<commit_after>/**
 * scheda.js
 * http://ravenjohn.github.io/scheda.js
 */

(function (root) {
    "use strict";

    /* jslint browser: true, regexp: true */

    var scheda = {},
        history = [],
        save = true,
        canvas_id,
        canvas,
        c,
        w,
        h,
        conf = {
            bgColor : "#D9FBCE",
            headerBgColor : "#6BBB62",
            miniGridColor : "#DFE0D2",
            hMainGridColor : "#BBDFBC",
            vMainGridColor : "#BBDFBC",
            timeColumnWidth : 50,
            time : {
                color : "#FFFFFF",
                bgColor : "#6BBB62",
                style : "normal",
                font : "Arial",
                size : 13
            },
            day : {
                color : "#FFFFFF",
                style : "normal",
                font : "Arial",
                size : 13
            },
            sched : {
                color : "#FFFFFF",
                style : "normal",
                font : "Arial",
                size : 13
            }
        },

        cvrt = function (e, f) {
            e.length < 3 && (e += "00");
            e = parseInt(e, 10);
            (e < 700 || (f && e == 700)) && (e += 1200);
            e += "";
            return ((parseInt(e.substring(0, e.length - 2), 10) - 7) * 4) + (parseInt(e.substring(e.length - 2), 10) / 15);
        },

        tC = function (w, c, t) {
            return (w - c.measureText(t).width) / 2;
        },

        gTop = function (x, ma, h, w, c) {
            var my = Math.floor(ma / 4) * h + h;
            switch (ma % 4) {
            case 0:
                c.lineTo(x, my);
                c.lineTo(x + w, my);
                break;
            case 1:
                c.lineTo(x, my);
                c.lineTo(x + (w / 2), my + (h / 2));
                c.lineTo(x + w, my);
                break;
            case 2:
                c.lineTo(x, my);
                c.lineTo(x + w, my + h);
                break;
            case 3:
                c.lineTo(x, my + h);
                c.lineTo(x + (w / 2), my + (h / 2));
                c.lineTo(x + w, my + h);
                break;
            }
        },

        gBottom = function (x, ma, h, w, c) {
            var my = Math.floor(ma / 4) * h + h;
            switch (ma % 4) {
            case 0:
                c.lineTo(x + w, my);
                c.lineTo(x, my);
                break;
            case 1:
                c.lineTo(x + w, my);
                c.lineTo(x + (w / 2), my + (h / 2));
                c.lineTo(x, my);
                break;
            case 2:
                c.lineTo(x + w, my + h);
                c.lineTo(x, my);
                break;
            case 3:
                c.lineTo(x + w, my + h);
                c.lineTo(x + (w / 2), my + (h / 2));
                c.lineTo(x, my + h);
                break;
            }
        },

        uuid = function (separator) {
            var S4 = function () {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            };
            return [S4() + S4(), S4(), S4(), S4(), S4() + S4() + S4()].join(separator || "-");
        };

    scheda.drawSchedule = function (day, time, courseCode, sectionName, room, color) {
        var y,
            sp,
            id,
            randomColor = function () {
                var rn = function () {
                    return parseInt(Math.random() * 255, 10);
                };
                return "rgb(" + rn() + ", " + rn() + ", " + rn() + ")";
            },
            draw = function (xx) {
                var x = (xx * w) + conf.timeColumnWidth;
                c.beginPath();
                gTop(x, time[0], h, w, c);
                gBottom(x, time[1] + time[0], h, w, c);
                c.strokeStyle = c.fillStyle = color;
                c.fill();
                c.lineWidth = 0.5;
                c.fillStyle = conf.sched.color;
                c.font = conf.sched.style + " " + conf.sched.size + "px " + conf.sched.font;
                if (room === "") {
                    c.fillText(courseCode, tC(w, c, courseCode) + x, y + (sp / 2) - 2);
                }
                else {
                    c.fillText(courseCode, tC(w, c, courseCode) + x, y + (sp / 2) - 2);
                    c.fillText(room, tC(w, c, room) + x, y + (sp / 2) + 10);
                }
                c.stroke();
            };

        save && history.push({id : (id = uuid()), args : arguments});
        time = time.replace(/:/g, "").split("-");
        time[1] = cvrt(time[1], 1) - (time[0] = cvrt(time[0]));
        y = (time[0] / 4) * h + h;
        sp = (time[1] / 4) * h;
        room = room || "";
        courseCode = courseCode + "\n" + (sectionName || "");
        day = day.toUpperCase();
        !color && (color = randomColor());
        if (~day.indexOf("M")) {
            draw(0);
        }
        if (~day.indexOf("TH")) {
            draw(3);
            day = day.replace("TH", "");
        }
        if (~day.indexOf("T")) {
            draw(1);
        }
        if (~day.indexOf("W")) {
            draw(2);
        }
        if (~day.indexOf("F")) {
            draw(4);
        }
        if (~day.indexOf("S")) {
            draw(5);
        }

        return id;
    };

    scheda.setConfig = function (config) {
        var i,
            j;
        for (i in config) {
            if(config.hasOwnProperty(i) && conf[i]){
                if(typeof config[i] === "object"){
                    for (j in config[i]) {
                        conf[i][j] = config[i][j];
                    }
                }
                else {
                    conf[i] = config[i];
                }
            }
        }
        scheda.repaint();
    };

    scheda.getConfig = function (p) {
        switch ((p = p.split(".")).length) {
        case 1: return conf[p[0]];
        case 2: return conf[p[0]][p[1]];
        }
    };

    scheda.repaint = function () {
        var i;
        scheda.init();
        save = false;
        for (i in history) {
            i > -1 && scheda.drawSchedule.apply(undefined, history[i].args);
        }
        save = true;
    };

    scheda.remove = function (id) {
        var i;
        for (i in history) {
            (i > -1 && id === history[i].id) && history.splice(i, 1);
        }
        scheda.repaint();
    };

    scheda.getHistory = function () {
        return history;
    };

    scheda.init = function (id, config) {
        var days = ["Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur"],
            i,
            j;

        id = id || canvas_id;

        if (!(canvas = document.getElementById(id))) {
            throw new Error("Unable to find canvas with id [" + id + "]");
        }

        canvas.width === 300 && (canvas.width = 811);
        canvas.height === 150 && (canvas.height = 391);
        c = canvas.getContext("2d");
        h = canvas.height / 13;
        w = (canvas.width - conf.timeColumnWidth) / 6;
        config && scheda.setConfig(config);
        canvas_id = id;

        // draw canvas background
        c.fillStyle = conf.bgColor;
        c.fillRect(0, 0, canvas.width, h * 13);

        // draw table header bg
        c.fillStyle = conf.headerBgColor;
        c.fillRect(0, 0, canvas.width, h);

        // draw mini grid
        c.beginPath();
        c.strokeStyle = conf.miniGridColor;
        for (i = 0, j = (h / 4) + h; i < 48; i += 1, j += (h / 4)) {
            c.moveTo(0, j);
            c.lineTo(canvas.width, j);
        }
        c.stroke();

        // draw time bg
        c.fillStyle = conf.time.bgColor;
        c.fillRect(0, h, conf.timeColumnWidth, canvas.height);

        // draw horizontal main grid
        c.beginPath();
        c.strokeStyle = conf.hMainGridColor;
        for (i = 0, j = h; i < 13; i += 1, j += h) {
            c.moveTo(0, j);
            c.lineTo(canvas.width, j);
        }
        c.stroke();

        // draw vertical main grid
        c.beginPath();
        c.strokeStyle = conf.vMainGridColor;
        c.moveTo(conf.timeColumnWidth, 0);
        c.lineTo(conf.timeColumnWidth, canvas.height);
        for (i = 0; i < 7; i += 1) {
            c.moveTo(i * w + conf.timeColumnWidth, 0);
            c.lineTo(i * w + conf.timeColumnWidth, canvas.height);
        }
        c.stroke();

        // draw time labels
        c.beginPath();
        c.fillStyle = conf.time.color;
        c.font = conf.time.style + " " + conf.time.size + "px " + conf.time.font;
        for (i = 7; i < 19; i += 1) {
            if (i === 12) {
                j = i + "-1";
            } else if (i > 12) {
                j = (i - 12) + "-" + (i - 11);
            } else {
                j = i + "-" + (i + 1);
            }
            c.fillText(j, tC(conf.timeColumnWidth, c, j), ((h / 2) + (conf.time.size / 2)) + ((i - 7) * h) + h);
        }

        // draw day labels
        c.fillStyle = conf.day.color;
        c.font = conf.day.style + " " + conf.day.size + "px " + conf.day.font;
        c.fillText("Time", tC(conf.timeColumnWidth, c, "Time"), ((h / 2) + (conf.day.size / 2)));
        for (i in days) {
            i > -1 && c.fillText(days[i] + "day", conf.timeColumnWidth + tC(w, c, days[i] + "day") + (i * w), ((h / 2) + (conf.day.size / 2)));
        }

    };

    scheda.downloadSchedule = function (e) {
        var a = document.createElement("a");
        if ((a.download = prompt("Please input desired file name:") + ".png") != ".png") {
            console.log(a.download);
            a.type = "image/png";
            a.href = canvas.toDataURL().replace(/^data:image\/[^;]/, "data:application/octet-stream");
            a.onclick = function () {
                this.parentNode.removeChild(this);
            };
            document.getElementsByTagName("body")[0].appendChild(a);
            a.click();
        }
        e && e.preventDefault();
    };

    // expose scheda fn
    root.scheda = scheda;
}(this));
<|endoftext|>