<commit_before>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const webpackMergeDll = webpackMerge.strategy({plugins: 'replace'});
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 3000;
const HMR = helpers.hasProcessFlag('hot');
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR
});

const DllBundlesPlugin = require('webpack-dll-bundles-plugin').DllBundlesPlugin;

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  return webpackMerge(commonConfig({env: ENV}), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'cheap-module-source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[file].map',

      /** The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].chunk.js',

      library: 'ac_[name]',
      libraryTarget: 'var',
    },

    module: {

      rules: [
       {
         test: /\.ts$/,
         use: [
           {
             loader: 'tslint-loader',
             options: {
               configFile: 'tslint.json'
             }
           }
         ],
         exclude: [/\.(spec|e2e)\.ts$/]
       },

        /*
         * css loader support for *.css files (styles directory only)
         * Loads external css styles into the DOM, supports HMR
         *
         */
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader'],
          include: [helpers.root('src', 'styles')]
        },

        /*
         * sass loader support for *.scss files (styles directory only)
         * Loads external sass styles into the DOM, supports HMR
         *
         */
        {
          test: /\.scss$/,
          use: ['style-loader', 'css-loader', 'sass-loader'],
          include: [helpers.root('src', 'styles')]
        },

      ]

    },

    plugins: [

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
        }
      }),

      new DllBundlesPlugin({
        bundles: {
          polyfills: [
            'core-js',
            {
              name: 'zone.js',
              path: 'zone.js/dist/zone.js'
            },
            {
              name: 'zone.js',
              path: 'zone.js/dist/long-stack-trace-zone.js'
            },
          ],
          vendor: [
            '@angular/platform-browser',
            '@angular/platform-browser-dynamic',
            '@angular/core',
            '@angular/common',
            '@angular/forms',
            '@angular/http',
            '@angular/router',
            '@angularclass/hmr',
            'rxjs',
          ]
        },
        dllDir: helpers.root('dll'),
        webpackConfig: webpackMergeDll(commonConfig({env: ENV}), {
          devtool: 'cheap-module-source-map',
          plugins: []
        })
      }),

      /**
       * Plugin: AddAssetHtmlPlugin
       * Description: Adds the given JS or CSS file to the files
       * Webpack knows about, and put it into the list of assets
       * html-webpack-plugin injects into the generated html.
       *
       * See: https://github.com/SimenB/add-asset-html-webpack-plugin
       */
      new AddAssetHtmlPlugin([
        { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('polyfills')}`) },
        { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('vendor')}`) }
      ]),

      /**
       * Plugin: NamedModulesPlugin (experimental)
       * Description: Uses file names as module name.
       *
       * See: https://github.com/webpack/webpack/commit/a04ffb928365b19feb75087c63f13cadfc08e1eb
       */
      // new NamedModulesPlugin(),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        debug: true,
        options: {

        }
      }),

    ],

    /**
     * Webpack Development Server configuration
     * Description: The webpack-dev-server is a little node.js Express server.
     * The server emits information about the compilation state to the client,
     * which reacts to those events.
     *
     * See: https://webpack.github.io/docs/webpack-dev-server.html
     */
    devServer: {
      port: METADATA.port,
      host: METADATA.host,
      historyApiFallback: true,
      watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
      }
    },

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
}
<commit_msg>changed devtool to inline-source-map<commit_after>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const webpackMergeDll = webpackMerge.strategy({plugins: 'replace'});
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 3000;
const HMR = helpers.hasProcessFlag('hot');
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR
});

const DllBundlesPlugin = require('webpack-dll-bundles-plugin').DllBundlesPlugin;

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  return webpackMerge(commonConfig({env: ENV}), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'cheap-module-source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[file].map',

      /** The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].chunk.js',

      library: 'ac_[name]',
      libraryTarget: 'var',
    },

    module: {

      rules: [
       {
         test: /\.ts$/,
         use: [
           {
             loader: 'tslint-loader',
             options: {
               configFile: 'tslint.json'
             }
           }
         ],
         exclude: [/\.(spec|e2e)\.ts$/]
       },

        /*
         * css loader support for *.css files (styles directory only)
         * Loads external css styles into the DOM, supports HMR
         *
         */
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader'],
          include: [helpers.root('src', 'styles')]
        },

        /*
         * sass loader support for *.scss files (styles directory only)
         * Loads external sass styles into the DOM, supports HMR
         *
         */
        {
          test: /\.scss$/,
          use: ['style-loader', 'css-loader', 'sass-loader'],
          include: [helpers.root('src', 'styles')]
        },

      ]

    },

    plugins: [

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
        }
      }),

      new DllBundlesPlugin({
        bundles: {
          polyfills: [
            'core-js',
            {
              name: 'zone.js',
              path: 'zone.js/dist/zone.js'
            },
            {
              name: 'zone.js',
              path: 'zone.js/dist/long-stack-trace-zone.js'
            },
          ],
          vendor: [
            '@angular/platform-browser',
            '@angular/platform-browser-dynamic',
            '@angular/core',
            '@angular/common',
            '@angular/forms',
            '@angular/http',
            '@angular/router',
            '@angularclass/hmr',
            'rxjs',
          ]
        },
        dllDir: helpers.root('dll'),
        webpackConfig: webpackMergeDll(commonConfig({env: ENV}), {
          devtool: 'inline-source-map',
          plugins: []
        })
      }),

      /**
       * Plugin: AddAssetHtmlPlugin
       * Description: Adds the given JS or CSS file to the files
       * Webpack knows about, and put it into the list of assets
       * html-webpack-plugin injects into the generated html.
       *
       * See: https://github.com/SimenB/add-asset-html-webpack-plugin
       */
      new AddAssetHtmlPlugin([
        { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('polyfills')}`) },
        { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('vendor')}`) }
      ]),

      /**
       * Plugin: NamedModulesPlugin (experimental)
       * Description: Uses file names as module name.
       *
       * See: https://github.com/webpack/webpack/commit/a04ffb928365b19feb75087c63f13cadfc08e1eb
       */
      // new NamedModulesPlugin(),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        debug: true,
        options: {

        }
      }),

    ],

    /**
     * Webpack Development Server configuration
     * Description: The webpack-dev-server is a little node.js Express server.
     * The server emits information about the compilation state to the client,
     * which reacts to those events.
     *
     * See: https://webpack.github.io/docs/webpack-dev-server.html
     */
    devServer: {
      port: METADATA.port,
      host: METADATA.host,
      historyApiFallback: true,
      watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
      }
    },

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
}
<|endoftext|>


<commit_before>var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var root = require('./root-helper');
var CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = webpackMerge(commonConfig, {
  devtool: 'cheap-source-map',
  output: {
    path: root.root('dist'),
    publicPath: '/',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js'
  },

  plugins: [
    new ExtractTextPlugin('[name].css'),
    new CopyWebpackPlugin([
      { from: './assets/**/*', context: 'demo', to: './' },
    ])
  ],

  devServer: {
    historyApiFallback: true,
    stats: 'minimal'
  }
});<commit_msg>add cesium script loader<commit_after>var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var root = require('./root-helper');
var CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = webpackMerge(commonConfig, {
  devtool: 'cheap-source-map',
  output: {
    path: root.root('dist'),
    publicPath: '/',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js'
  },

  module: {
    rules: [
      {
        test: /Cesium\.js$/,
        loader: 'script-loader'
      }
    ]
  },

  plugins: [
    new ExtractTextPlugin('[name].css'),
    new CopyWebpackPlugin([
       { from: './assets/**/*', context: 'demo', to: './' },
    ])
  ],

  devServer: {
    historyApiFallback: true,
    stats: 'minimal'
  }
});<|endoftext|>


<commit_before>'use strict'

var shimmer = require('shimmer')
var debug = require('debug')('opbeat')

var SERVER_FNS = ['insert', 'update', 'remove', 'cursor', 'auth']
var CURSOR_FNS_FIRST = ['kill', 'next'] // TODO: what is kill used for - do we need to wrap it?

module.exports = function (mongodb, agent) {
  if (mongodb.Server) {
    debug('shimming mongodb-core.Server.prototype.command')
    shimmer.wrap(mongodb.Server.prototype, 'command', wrapCommand)
    debug('shimming mongodb-core.Server.prototype functions:', SERVER_FNS)
    shimmer.massWrap(mongodb.Server.prototype, SERVER_FNS, wrapQuery)
  }

  if (mongodb.Cursor) {
    debug('shimming mongodb-core.Cursor.prototype functions:', CURSOR_FNS_FIRST)
    shimmer.massWrap(mongodb.Cursor.prototype, CURSOR_FNS_FIRST, wrapCursor)
  }

  return mongodb

  function wrapCommand (orig) {
    return function wrappedFunction (ns, cmd) {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Server.prototype.command %o', { uuid: uuid, ns: ns })

      if (trace && arguments.length > 0) {
        var index = arguments.length - 1
        var cb = arguments[index]
        if (typeof cb === 'function') {
          var type
          if (cmd.findAndModify) type = 'findAndModify'
          else if (cmd.createIndexes) type = 'createIndexes'
          else if (cmd.ismaster) type = 'ismaster'
          else if (cmd.count) type = 'count'
          else type = 'command'

          arguments[index] = wrappedCallback
          trace.start(ns + '.' + type, 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Server.prototype.command callback %o', { uuid: uuid })
        trace.end()
        return cb.apply(null, arguments)
      }
    }
  }

  function wrapQuery (orig, name) {
    return function wrappedFunction (ns) {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Server.prototype.%s %o', name, { uuid: uuid, ns: ns })

      if (trace && arguments.length > 0) {
        var index = arguments.length - 1
        var cb = arguments[index]
        if (typeof cb === 'function') {
          arguments[index] = wrappedCallback
          trace.start(ns + '.' + name, 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Server.prototype.%s callback %o', name, { uuid: uuid })
        trace.end()
        return cb.apply(null, arguments)
      }
    }
  }

  function wrapCursor (orig, name) {
    return function wrappedFunction () {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Cursor.prototype.%s %o', name, { uuid: uuid })

      if (trace && arguments.length > 0) {
        var cb = arguments[0]
        if (typeof cb === 'function') {
          arguments[0] = wrappedCallback
          trace.start(this.ns + '.' + (name === 'next' && this.cmd.find ? 'find' : name), 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Cursor.prototype.%s callback %o', name, { uuid: uuid })
        trace.end()
        return cb.apply(null, arguments)
      }
    }
  }
}
<commit_msg>mongodb: improve cursor instrumentation<commit_after>'use strict'

var shimmer = require('shimmer')
var debug = require('debug')('opbeat')

var SERVER_FNS = ['insert', 'update', 'remove', 'auth']
var CURSOR_FNS_FIRST = ['_find', '_getmore']

module.exports = function (mongodb, agent) {
  if (mongodb.Server) {
    debug('shimming mongodb-core.Server.prototype.command')
    shimmer.wrap(mongodb.Server.prototype, 'command', wrapCommand)
    debug('shimming mongodb-core.Server.prototype functions:', SERVER_FNS)
    shimmer.massWrap(mongodb.Server.prototype, SERVER_FNS, wrapQuery)
  }

  if (mongodb.Cursor) {
    debug('shimming mongodb-core.Cursor.prototype functions:', CURSOR_FNS_FIRST)
    shimmer.massWrap(mongodb.Cursor.prototype, CURSOR_FNS_FIRST, wrapCursor)
  }

  return mongodb

  function wrapCommand (orig) {
    return function wrappedFunction (ns, cmd) {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Server.prototype.command %o', { uuid: uuid, ns: ns })

      if (trace && arguments.length > 0) {
        var index = arguments.length - 1
        var cb = arguments[index]
        if (typeof cb === 'function') {
          var type
          if (cmd.findAndModify) type = 'findAndModify'
          else if (cmd.createIndexes) type = 'createIndexes'
          else if (cmd.ismaster) type = 'ismaster'
          else if (cmd.count) type = 'count'
          else type = 'command'

          arguments[index] = wrappedCallback
          trace.start(ns + '.' + type, 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Server.prototype.command callback %o', { uuid: uuid })
        trace.end()
        return cb.apply(null, arguments)
      }
    }
  }

  function wrapQuery (orig, name) {
    return function wrappedFunction (ns) {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Server.prototype.%s %o', name, { uuid: uuid, ns: ns })

      if (trace && arguments.length > 0) {
        var index = arguments.length - 1
        var cb = arguments[index]
        if (typeof cb === 'function') {
          arguments[index] = wrappedCallback
          trace.start(ns + '.' + name, 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Server.prototype.%s callback %o', name, { uuid: uuid })
        trace.end()
        return cb.apply(null, arguments)
      }
    }
  }

  function wrapCursor (orig, name) {
    return function wrappedFunction () {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Cursor.prototype.%s %o', name, { uuid: uuid })

      if (trace && arguments.length > 0) {
        var cb = arguments[0]
        if (typeof cb === 'function') {
          arguments[0] = wrappedCallback
          trace.start(this.ns + '.' + (this.cmd.find ? 'find' : name), 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Cursor.prototype.%s callback %o', name, { uuid: uuid })
        trace.end()
        return cb.apply(null, arguments)
      }
    }
  }
}
<|endoftext|>


<commit_before>// We start with an example of for... of loops.

// This quite similar to the array helper methods we looked at when starting the course.

// The for...of statement creates a loop iterating over iterable objects (including Array, Map,
// Set, String, TypedArray, arguments object and so on), invoking a custom iteration hook with statements
// to be executed for the value of each distinct property.

(function(){

	const colors = ['red', 'green', 'blue'];

	for (let color of colors) {
		console.log(color);
	}

	const numbers = [1,2,3,4];

	let total = 0;
	for (let number of numbers) {
		total += number;
		console.log(total);
	}

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

})();

// Generators let us run some code, return a value and then return to the function and continue executing code.

// From MDN:

// Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.

// Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead.
// When the iterator's next() method is called, the generator function's body is executed until the first yield expression,
// which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function.
// The next() method returns an object with a value property containing the yielded value and a done property which indicates
// whether the generator has yielded its last value as a boolean. Calling the next() method with an argument will resume
// the generator function execution, replacing the yield statement where execution was paused with the argument from next().

(function() {

	function* shopping() {

		// stuff on the sidewalk

		// walking down the sidewalk

		// go int othe store with cash

		const stuffFromStore = yield 'cash';

		// walking to laundry place

		const cleanClothes = yield 'laundry';

		// walking back home

		return [stuffFromStore, cleanClothes];
	}

	// Stuff happening in the store

	const gen = shopping(); // Invoking our generator function with parens doesn't actually do anything.

	console.log(gen); // shopping generator object

	console.log(gen.next()); // leaving our house

	// walk into the store
	// walk up and down the aisles
	// purchase our stuff

	console.log(gen.next('groceries')); // leaving the store with groceries

	console.log(gen.next('clean clothes')); // leave the laundry place with clean clothes

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

 })();

// Another example with a colors generator function.

(function(){

	function* colors() {
		yield 'red';
		yield 'blue';
		yield 'green';
	}

		// const gen = colors();
		// console.log(gen.next());
		// console.log(gen.next());
		// console.log(gen.next());

	//  ---------------------------------------------------------------------------------------------------------------------------------------
	//  ---------------------------------------------------------------------------------------------------------------------------------------
	//  ------------------------------- Stephen's "big reveal": generators work perfectly with for...of loops.  -------------------------------
	//  ---------------------------------------------------------------------------------------------------------------------------------------
	//  ---------------------------------------------------------------------------------------------------------------------------------------

	// Below is the example.

	// Our loop iterates through our generator and pushes each result into our myColors array.

	const myColors = [];

	for (let color of colors()) {
		myColors.push(color);
	}
	console.log(myColors); // ["red", "blue", "green"]

	// Generators can be used to iterate over any data structure we want, which is one of their biggest uses.

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

})();

// Below is another example, showing where generator functions can be useful.

// We are first creating an object that represents a software engineering team.

// We then create another object representing a testing team, which will be separate from the engineering team.

// We then combine generator functions.

(function(){

	const testingTeam = {
		lead: 'Amanada',
		tester: 'Bill'
	};

	const engineeringTeam = {

		testingTeam,
		size: 3,
		department: 'Engineering',
		lead: 'Jill',
		manager: 'Alex',
		engineer: 'Dave'

	};

	// What we might use a generator for is to create a function that only iterates through our employee keys on the above object,
	// not the size or department.

	function* TeamIterator(team) {
		yield team.lead;
		yield team.manager;
		yield team.engineer;
		const testTeamGenerator = TestTeamIterator(team.testingTeam);

		// The yield* keyword can be thought of as a trap door that lets our for..of loop fall into our TestTeamIterator generator
		// and lets it also iterate over our other yield statements in the TeamTeamIterator generator.

		// This is called Generator Delegation.

		yield* testTeamGenerator;
	}

	function* TestTeamIterator(team) {
		yield team.lead;
		yield team.tester;
	}

	const myTeam = [];

	for (let member of TeamIterator(engineeringTeam)) {
		myTeam.push(member);
	}
	console.log(myTeam);

	console.log("-----------------------------------------------------------------");

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

})();

// Next, we take the above code and refactor it to make it more concise.

// We use symbol iterators to do this.

// The way it helps is that it allows us to merge our Iterator generators into our two team objects.

// Symbol iterator is a special object in ES6 that teaches objects how to deal with for...of loop.

(function(){

	const testingTeam = {
		lead: 'Amanada',
		tester: 'Bill',

		// Our for...of loop discovers the key called [Symbol.iterator] and if it exists,
		// it will use the generator function it is pointing at for iteration.

		// In ES6 we can use key interpolation by using square brackets around the key name.
		// This does not create an array, but allows us to have a dynamically generated key.

		[Symbol.iterator]: function* () {

			// We use 'this' here to refer to the testingteam object.

			yield this.lead;
			yield this.tester;
		}
	};

	const engineeringTeam = {

		testingTeam,
		size: 3,
		department: 'Engineering',
		lead: 'Jill',
		manager: 'Alex',
		engineer: 'Dave',
		[Symbol.iterator]: function* () {

			yield this.lead;
			yield this.manager;
			yield this.engineer;

			// We use yield* here to make sure that when iterating through our engineeringTeam object,
			// we also drop down into our testingTeam object and also walk through that too.

			yield* testingTeam;
		}

	};

	const myTeam = [];

	// We no longer need to use a separately defined generator function.

	// We can just pass our engineeringTeam object and our for...of loop will find the [Symbol.iterator] object
	// which will use the generator to iterate through the object and also the testingTeam object to produce
	// the same result as before.

	for (let member of engineeringTeam) {
		myTeam.push(member);
	}

	console.log(myTeam);

	console.log("-----------------------------------------------------------------");

})();
	<commit_msg>Adjustment to spacing<commit_after>// We start with an example of for... of loops.

// This quite similar to the array helper methods we looked at when starting the course.

// The for...of statement creates a loop iterating over iterable objects (including Array, Map,
// Set, String, TypedArray, arguments object and so on), invoking a custom iteration hook with statements
// to be executed for the value of each distinct property.

(function(){

	const colors = ['red', 'green', 'blue'];

	for (let color of colors) {
		console.log(color);
	}

	const numbers = [1,2,3,4];

	let total = 0;
	for (let number of numbers) {
		total += number;
		console.log(total);
	}

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

})();

// Generators let us run some code, return a value and then return to the function and continue executing code.

// From MDN:

// Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.

// Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead.
// When the iterator's next() method is called, the generator function's body is executed until the first yield expression,
// which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function.
// The next() method returns an object with a value property containing the yielded value and a done property which indicates
// whether the generator has yielded its last value as a boolean. Calling the next() method with an argument will resume
// the generator function execution, replacing the yield statement where execution was paused with the argument from next().

(function() {

	function* shopping() {

		// stuff on the sidewalk

		// walking down the sidewalk

		// go int othe store with cash

		const stuffFromStore = yield 'cash';

		// walking to laundry place

		const cleanClothes = yield 'laundry';

		// walking back home

		return [stuffFromStore, cleanClothes];
	}

	// Stuff happening in the store

	const gen = shopping(); // Invoking our generator function with parens doesn't actually do anything.

	console.log(gen); // shopping generator object

	console.log(gen.next()); // leaving our house

	// walk into the store
	// walk up and down the aisles
	// purchase our stuff

	console.log(gen.next('groceries')); // leaving the store with groceries

	console.log(gen.next('clean clothes')); // leave the laundry place with clean clothes

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

 })();

// Another example with a colors generator function.

(function(){

	function* colors() {
		yield 'red';
		yield 'blue';
		yield 'green';
	}

		// const gen = colors();
		// console.log(gen.next());
		// console.log(gen.next());
		// console.log(gen.next());

	//  ---------------------------------------------------------------------------------------------------------------------------------------
	//  ---------------------------------------------------------------------------------------------------------------------------------------
	//  ------------------------------- Stephen's "big reveal": generators work perfectly with for...of loops.  -------------------------------
	//  ---------------------------------------------------------------------------------------------------------------------------------------
	//  ---------------------------------------------------------------------------------------------------------------------------------------

	// Below is the example.

	// Our loop iterates through our generator and pushes each result into our myColors array.

	const myColors = [];

	for (let color of colors()) {
		myColors.push(color);
	}
	console.log(myColors); // ["red", "blue", "green"]

	// Generators can be used to iterate over any data structure we want, which is one of their biggest uses.

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

})();

// Below is another example, showing where generator functions can be useful.

// We are first creating an object that represents a software engineering team.

// We then create another object representing a testing team, which will be separate from the engineering team.

// We then combine generator functions.

(function(){

	const testingTeam = {
		lead: 'Amanada',
		tester: 'Bill'
	};

	const engineeringTeam = {

		testingTeam,
		size: 3,
		department: 'Engineering',
		lead: 'Jill',
		manager: 'Alex',
		engineer: 'Dave'

	};

	// What we might use a generator for is to create a function that only iterates through our employee keys on the above object,
	// not the size or department.

	function* TeamIterator(team) {
		yield team.lead;
		yield team.manager;
		yield team.engineer;
		const testTeamGenerator = TestTeamIterator(team.testingTeam);

		// The yield* keyword can be thought of as a trap door that lets our for..of loop fall into our TestTeamIterator generator
		// and lets it also iterate over our other yield statements in the TeamTeamIterator generator.

		// This is called Generator Delegation.

		yield* testTeamGenerator;
	}

	function* TestTeamIterator(team) {
		yield team.lead;
		yield team.tester;
	}

	const myTeam = [];

	for (let member of TeamIterator(engineeringTeam)) {
		myTeam.push(member);
	}
	console.log(myTeam);

	console.log("-----------------------------------------------------------------");

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

})();

// Next, we take the above code and refactor it to make it more concise.

// We use symbol iterators to do this.

// The way it helps is that it allows us to merge our Iterator generators into our two team objects.

// Symbol iterator is a special object in ES6 that teaches objects how to deal with for...of loop.

(function(){

	const testingTeam = {
		lead: 'Amanada',
		tester: 'Bill',

		// Our for...of loop discovers the key called [Symbol.iterator] and if it exists,
		// it will use the generator function it is pointing at for iteration.

		// In ES6 we can use key interpolation by using square brackets around the key name.
		// This does not create an array, but allows us to have a dynamically generated key.

		[Symbol.iterator]: function* () {

			// We use 'this' here to refer to the testingteam object.

			yield this.lead;
			yield this.tester;
		}
	};

	const engineeringTeam = {

		testingTeam,
		size: 3,
		department: 'Engineering',
		lead: 'Jill',
		manager: 'Alex',
		engineer: 'Dave',
		[Symbol.iterator]: function* () {

			yield this.lead;
			yield this.manager;
			yield this.engineer;

			// We use yield* here to make sure that when iterating through our engineeringTeam object,
			// we also drop down into our testingTeam object and also walk through that too.

			yield* testingTeam;
		}

	};

	const myTeam = [];

	// We no longer need to use a separately defined generator function.

	// We can just pass our engineeringTeam object and our for...of loop will find the [Symbol.iterator] object
	// which will use the generator to iterate through the object and also the testingTeam object to produce
	// the same result as before.

	for (let member of engineeringTeam) {
		myTeam.push(member);
	}

	console.log(myTeam);

	console.log("-----------------------------------------------------------------");

})();
	<|endoftext|>


<commit_before>// LICENSE : MIT
"use strict";
// Replace key to value mapping
// This is not for Constants.
var exports = {
    "root": "Document",
    "paragraph": "Paragraph",
    "blockquote": "BlockQuote",
    "listItem": "ListItem",
    "list": "List",
    "Bullet": "Bullet", // no need?
    "heading": "Header",
    "code": "CodeBlock",
    "HtmlBlock": "Html",
    "ReferenceDef": "ReferenceDef",
    "horizontalRule": "HorizontalRule",
    // inline block
    'text': 'Str',
    'Softbreak': 'Break',
    'Hardbreak': 'Break',
    'emphasis': 'Emphasis',
    'strong': 'Strong',
    'html': 'Html',
    'link': 'Link',
    'image': 'Image',
    'inlineCode': 'Code'
};
module.exports = exports;<commit_msg>feat(ast): implement Break node<commit_after>// LICENSE : MIT
"use strict";
// Replace key to value mapping
// This is not for Constants.
var exports = {
    "root": "Document",
    "paragraph": "Paragraph",
    "blockquote": "BlockQuote",
    "listItem": "ListItem",
    "list": "List",
    "Bullet": "Bullet", // no need?
    "heading": "Header",
    "code": "CodeBlock",
    "HtmlBlock": "Html",
    "ReferenceDef": "ReferenceDef",
    "horizontalRule": "HorizontalRule",
    // inline block
    'text': 'Str',
    'break': 'Break',
    'emphasis': 'Emphasis',
    'strong': 'Strong',
    'html': 'Html',
    'link': 'Link',
    'image': 'Image',
    'inlineCode': 'Code'
};
module.exports = exports;<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose'),
    fmt = require('fmt'),
    _ = require('lodash'),
    Supplier = require('./schema').Supplier;

// Find Supplier by id
exports.supplier = function(req, res, next, id) {
    Supplier.load(id, function(err, supplier) {
        if (err) return next(err);
        if (!supplier) return next(new Error('Failed to load Supplier: ' + id));
        req.supplier = supplier;
        next();
    });
};

//List all Supplier
exports.all = function(req, res) {
    var opts = [{
        path: 'creator',
        select: 'name'
    }];
    Supplier
        .find()
        .sort('-created')
        .populate(opts)
        .exec(function(err, suppliers) {
            if (!err) {
                console.log(suppliers);
                res.jsonp(suppliers);
            } else {
                return res.send(err);
            }
        });
};

//Show Supplier
exports.show = function(req, res) {
    res.jsonp(req.supplier);
};

//Update Supplier
exports.update = function(req, res) {
    var updateSupplier = req.supplier;
    updateSupplier = _.extend(updateSupplier, req.body);

    updateSupplier.save(function(err) {
        if (err) {
            return res.send('login', {
                errors: err.errors,
                updateSupplier: updateSupplier
            });
        } else {
            res.jsonp(updateSupplier);
        }
    });
};
// Create Supplier
exports.create = function(req, res) {
    var request = req.body;
    var newSupplier = new Supplier(request);
    var validFrom = request.valid_from;
    var validTo = request.valid_to;
    newSupplier.creator = req.user;
    if(validFrom){
        newSupplier.valid_from = new Date(req.body.valid_from);
    }
    if(validTo){
        newSupplier.valid_to = new Date(req.body.valid_to);
    }
    newSupplier.save(function(err) {
        if (!err) {
            res.jsonp(newSupplier);
        } else {
            return res.send(err);
        }
    });
};

<commit_msg>added status check based from valid_to field<commit_after>'use strict';

var mongoose = require('mongoose'),
    fmt = require('fmt'),
    _ = require('lodash'),
    moment = require('moment'),
    Supplier = require('./schema').Supplier;

// Find Supplier by id
exports.supplier = function(req, res, next, id) {
    Supplier.load(id, function(err, supplier) {
        if (err) return next(err);
        if (!supplier) return next(new Error('Failed to load Supplier: ' + id));
        req.supplier = supplier;
        next();
    });
};

//List all Supplier
exports.all = function(req, res) {
    var opts = [{
        path: 'creator',
        select: 'name'
    }];
    Supplier
        .find()
        .sort('-created')
        .populate(opts)
        .lean()
        .exec(function(err, suppliers) {
            if (!err) {
                suppliers = suppliers.map(function(supplier) {
                    supplier.active = moment(supplier.valid_to).isBefore();
                    supplier.active
                        ? supplier.status = 'inactive'
                        : supplier.status = 'active';
                    return supplier;
                });
                res.jsonp(suppliers);
            } else {
                return res.send(err);
            }
        });
};

//Show Supplier
exports.show = function(req, res) {
    var supplier = req.supplier.toObject();
    var isActive = moment(supplier.valid_to).isBefore();
    supplier["active"] = isActive;
    isActive
        ? supplier["status"] = 'inactive'
        : supplier["status"] = 'active';
    res.jsonp(supplier);
};

//Update Supplier
exports.update = function(req, res) {
    var updateSupplier = req.supplier;
    updateSupplier = _.extend(updateSupplier, req.body);

    updateSupplier.save(function(err) {
        if (err) {
            return res.send('login', {
                errors: err.errors,
                updateSupplier: updateSupplier
            });
        } else {
            res.jsonp(updateSupplier);
        }
    });
};
// Create Supplier
exports.create = function(req, res) {
    var request = req.body;
    var newSupplier = new Supplier(request);
    var validFrom = request.valid_from;
    var validTo = request.valid_to;
    newSupplier.creator = req.user;
    if (validFrom) {
        newSupplier.valid_from = new Date(req.body.valid_from);
    }
    if (validTo) {
        newSupplier.valid_to = new Date(req.body.valid_to);
    }
    newSupplier.save(function(err) {
        if (!err) {
            res.jsonp(newSupplier);
        } else {
            return res.send(err);
        }
    });
};

<|endoftext|>


<commit_before>validatePhone = function (num) {
  console.log('Validating \'' + num + '\' as phone number');
  num = num.replace(/[^0-9]/g, '')
  if (num.substring(0, 1) != '1') num = '1' + num;
  if (num.length == 11) return num;
  return false;
}

commanderData = function () {
  thisPhone = validatePhone($(phoneField).val());
  thisLocation = $(zipField).val();
  console.log('Phone is ' + thisPhone);
  console.log('ZIP is ' + thisLocation);

  if (thisPhone & thisLocation) geoCheck(thisLocation);
  if (!thisPhone) console.log('No phone number.');
  if (!thisLocation) console.log('No location.');
}

handleCallResponse = function (res) {
  console.log(res);
  $('div#can_thank_you').slideUp();
  if (res.status == '200') {
    console.log('Got response 200 OK');
    targetHTML = res.responseJSON.script
  } else {
    console.log('Got response ' + res.status + ' ' + res.statusText);
    targetHTML = 'There was an error with your call (' + res.status + ' ' + res.statusText + '.  Please try again.'
  }
  actionDiv = $('
').addClass('action_description').html(targetHTML).addClass('whitespacefix');
  newh2 = $('
').text('Call your senator');
  $('div#can_embed_form').append(newh2).append(actionDiv);

}

makeTheCall = function (data) {
  if (data) {
    $.ajax({
      method: 'get',
      data: data,
      url: 'https://advocacycommons.callpower.org/call/create',
      dataType: 'json',
      complete: function (res) {
        handleCallResponse(res);
      }
    });
  }
}
<commit_msg>Wait for can_embed_submitted to modify thank you page w/ script<commit_after>validatePhone = function (num) {
  console.log('Validating \'' + num + '\' as phone number');
  num = num.replace(/[^0-9]/g, '')
  if (num.substring(0, 1) != '1') num = '1' + num;
  if (num.length == 11) return num;
  return false;
}

commanderData = function () {
  thisPhone = validatePhone($(phoneField).val());
  thisLocation = $(zipField).val();
  console.log('Phone is ' + thisPhone);
  console.log('ZIP is ' + thisLocation);

  if (thisPhone & thisLocation) geoCheck(thisLocation);
  if (!thisPhone) console.log('No phone number.');
  if (!thisLocation) console.log('No location.');
}

handleCallResponse = function (res) {
  console.log(res);
  if (res.status == '200') {
    console.log('Got response 200 OK');
    targetHTML = res.responseJSON.script
  } else {
    console.log('Got response ' + res.status + ' ' + res.statusText);
    targetHTML = 'There was an error with your call (' + res.status + ' ' + res.statusText + '.  Please try again.'
  }
  actionDiv = $('
').addClass('action_description').html(targetHTML).addClass('whitespacefix');
  newh2 = $('
').text('Call your senator');
  $(document).on('can_embed_submitted',function(){
    console.log('Embed submitted.');
		$('div#can_thank_you').slideUp();
		$('div#can_embed_form').append(newh2).append(actionDiv);
  });

}

makeTheCall = function (data) {
  if (data) {
    $.ajax({
      method: 'get',
      data: data,
      url: 'https://advocacycommons.callpower.org/call/create',
      dataType: 'json',
      complete: function (res) {
        handleCallResponse(res);
      }
    });
  }
}
<|endoftext|>


<commit_before>/**
 * Status Message
 */
var Msg = function() {
    this.set = function(msg, done) {
        $('#status').show(200);
        $('#status').html(msg);
        if (done === 'fadeout') {
            setTimeout(function() {
                $('#status').hide(500);
            }, 5000);
        }
    };
};
var msg = new Msg();

/*
 * Converts bytes to human readable format
 *
 *
 */
var bytesToSize = function(bytes) {
    var sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB'];
    if (bytes === 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10);
    return Math.round((i === 0) ? (bytes / Math.pow(1024, i)) : (bytes / Math.pow(1024, i)).toFixed(1) * 10) / 10 + sizes[i];
};

/*
 * Checks if string is valid url
 *
 *
 */
var validateURL = function(textval) {
    var urlregex = new RegExp("^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
    return urlregex.test(textval.trim());
};

/**
 * Creates a JDownloader div-link
 *
 * This link opens a Downloadable Link in jDownloader
 *
 */
var jDLink = function(link) {
    var div = document.createElement('div');
    div.className = 'icon iconjd';
    div.title = 'open in jDownloader';
    div.onclick = function() {
        $.ajax({
            type: 'POST',
            url: 'http://127.0.0.1:9666/flash/add',
            data: {
                urls: link
            }
        });
    };
    return div;
};

/*
 * Loads the list of Downloaded files that are on the server
 */
var loadFiles = function() {
    $.ajax({
        url: '/files',
        type: 'get',
        cache: false,
        dataType: 'json'
    }).done(function(data){
        $('#rss_files tbody').empty();
        // Sort files by Filename
        data.sort(function(a, b) {
            a = a.filename.toLowerCase();
            b = b.filename.toLowerCase();
            return a > b ? 1 : a < b ? -1 : 0;
        });
        var tr, td = [], a, icon, del, s, i;
        for(i in data) {
            $('#rss_files tbody').append(fileRow(data[i]));
        }
    }).fail(function(){

    });
};

/**
 * Plowdown a File to the server
 *
 * @param {String} id The ul.to/id
 */
var plowdown = function(link) {
    msg.set('start downloading file to the server...');
    $.post('plowdown', {link: link}, function(success) {
        msg.set(success == true ? 'download complete!' : 'error while downloading!', 'fadeout');
        loadFiles(); // reload files-table to show newly downloaded file
    }, 'json');
};

/**
 * Download a File to your diskstation
 *
 * @param {String} url The url of the link
 */
var DownloadStation = function(uri) {
    msg.set('start downloading file to Diskstation...');
    $.ajax({
        type: "POST",
        url: 'diskstation/DownloadStation',
        data: {method: 'create', uri: uri},
        success: function(body) {
            msg.set(body);
        },
        dataType: 'json'
    });
};

Date.prototype.easy = function() {
    var now = new Date();
    var diff;
    var today_start = (new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0)).getTime();
    if(this.getTime() - today_start > 0) {
        return 'today';
    } else if(this.getTime() - (today_start - 86400000) > 0) {
        return 'yesterday';
    }
    if(this.getTime() - (today_start - 7 * 86400000) > 0) {
        return Math.floor((now.getTime() - this.getTime()) / 86400000) + ' days ago';
    }
    diff = Math.floor((now.getTime() - this.getTime()) / 86400000 / 7);
    return diff + ' week' + (diff > 1 ? 's' : '') + ' ago';
};<commit_msg>jquery error<commit_after>/**
 * Status Message
 */
var Msg = function() {
    this.set = function(msg, done) {
        $('#status').show(200);
        $('#status').html(msg);
        if (done === 'fadeout') {
            setTimeout(function() {
                $('#status').hide(500);
            }, 5000);
        }
    };
};
var msg = new Msg();

/*
 * Converts bytes to human readable format
 *
 *
 */
var bytesToSize = function(bytes) {
    var sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB'];
    if (bytes === 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10);
    return Math.round((i === 0) ? (bytes / Math.pow(1024, i)) : (bytes / Math.pow(1024, i)).toFixed(1) * 10) / 10 + sizes[i];
};

/*
 * Checks if string is valid url
 *
 *
 */
var validateURL = function(textval) {
    var urlregex = new RegExp("^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
    return urlregex.test(textval.trim());
};

/**
 * Creates a JDownloader div-link
 *
 * This link opens a Downloadable Link in jDownloader
 *
 */
var jDLink = function(link) {
    var div = document.createElement('div');
    div.className = 'icon iconjd';
    div.title = 'open in jDownloader';
    div.onclick = function() {
        $.ajax({
            type: 'POST',
            url: 'http://127.0.0.1:9666/flash/add',
            data: {
                urls: link
            }
        });
    };
    return div;
};

/*
 * Loads the list of Downloaded files that are on the server
 */
var loadFiles = function() {
    $.ajax({
        url: '/files',
        type: 'get',
        cache: false,
        dataType: 'json'
    }).done(function(data){
        $('#rss_files tbody').empty();
        // Sort files by Filename
        data.sort(function(a, b) {
            a = a.filename.toLowerCase();
            b = b.filename.toLowerCase();
            return a > b ? 1 : a < b ? -1 : 0;
        });
        var tr, td = [], a, icon, del, s, i;
        for(i in data) {
            $('#rss_files tbody').append(fileRow(data[i]));
        }
    }).fail(function(){

    });
};

/**
 * Plowdown a File to the server
 *
 * @param {String} id The ul.to/id
 */
var plowdown = function(link) {
    msg.set('start downloading file to the server...');
    $.post('plowdown', {link: link}, function(success) {
        msg.set(success == true ? 'download complete!' : 'error while downloading!', 'fadeout');
        loadFiles(); // reload files-table to show newly downloaded file
    }, 'json');
};

/**
 * Download a File to your diskstation
 *
 * @param {String} url The url of the link
 */
var DownloadStation = function(uri) {
    msg.set('start downloading file to Diskstation...');
    $.ajax({
        type: 'POST',
        url: '/diskstation/DownloadStation',
        data: {method: 'create', uri: uri},
        success: function(body) {
            msg.set(body);
        },
        dataType: 'json'
    });
};

Date.prototype.easy = function() {
    var now = new Date();
    var diff;
    var today_start = (new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0)).getTime();
    if(this.getTime() - today_start > 0) {
        return 'today';
    } else if(this.getTime() - (today_start - 86400000) > 0) {
        return 'yesterday';
    }
    if(this.getTime() - (today_start - 7 * 86400000) > 0) {
        return Math.floor((now.getTime() - this.getTime()) / 86400000) + ' days ago';
    }
    diff = Math.floor((now.getTime() - this.getTime()) / 86400000 / 7);
    return diff + ' week' + (diff > 1 ? 's' : '') + ' ago';
};<|endoftext|>


<commit_before>jQuery(document).ready(function($){

  $('input#checkout_use_billing').click(function() {
    show_billing(!this.checked);
  });

  var show_billing = function(show) {
    if(show) {
      $('#shipping .inner').show();
      $('#shipping .inner input').removeAttr('disabled', 'disabled');
    } else {
      $('#shipping .inner').hide();
      $('#shipping .inner input').attr('disabled', 'disabled');
    }
  }

  var update_state = function(region) {
    var country        = $('span#' + region + 'country :only-child').val();
    var states         = state_mapper[country];

    var state_select = $('span#' + region + 'state select');
    var state_input = $('span#' + region + 'state input');

    if(states) {
      state_select.html('');
      var states_with_blank = [["",""]].concat(states);
      $.each(states_with_blank, function(pos,id_nm) {
        var opt = $(document.createElement('option'))
                  .attr('value', id_nm[0])
                  .html(id_nm[1]);
        state_select.append(opt);
      });
      state_select.removeAttr('disabled').show();;
      state_input.hide().attr('disabled', 'disabled');

    } else {
      state_input.removeAttr('disabled').show();
      state_select.hide().attr('disabled', 'disabled');
    }

  };

  var update_state = function(region) {
    var country        = $('span#' + region + 'country :only-child').val();
    var states         = state_mapper[country];

    var state_select = $('span#' + region + 'state select');
    var state_input = $('span#' + region + 'state input');

    if(states) {
      state_select.html('');
      var states_with_blank = [["",""]].concat(states);
      $.each(states_with_blank, function(pos,id_nm) {
        var opt = $(document.createElement('option'))
                  .attr('value', id_nm[0])
                  .html(id_nm[1]);
        state_select.append(opt);
      });
      state_select.removeAttr('disabled').show();;
      state_input.hide().attr('disabled', 'disabled');

    } else {
      state_input.removeAttr('disabled').show();
      state_select.hide().attr('disabled', 'disabled');
    }

  };

  jQuery(document).ready(function(){
    $('span#bcountry select').change(function() { update_state('b'); });
    $('span#scountry select').change(function() { update_state('s'); });
  });

});
<commit_msg>Removed duplication of update_state definition.<commit_after>jQuery(document).ready(function($){

  $('input#checkout_use_billing').click(function() {
    show_billing(!this.checked);
  });

  var show_billing = function(show) {
    if(show) {
      $('#shipping .inner').show();
      $('#shipping .inner input').removeAttr('disabled', 'disabled');
    } else {
      $('#shipping .inner').hide();
      $('#shipping .inner input').attr('disabled', 'disabled');
    }
  }

  var update_state = function(region) {
    var country        = $('span#' + region + 'country :only-child').val();
    var states         = state_mapper[country];

    var state_select = $('span#' + region + 'state select');
    var state_input = $('span#' + region + 'state input');

    if(states) {
      state_select.html('');
      var states_with_blank = [["",""]].concat(states);
      $.each(states_with_blank, function(pos,id_nm) {
        var opt = $(document.createElement('option'))
                  .attr('value', id_nm[0])
                  .html(id_nm[1]);
        state_select.append(opt);
      });
      state_select.removeAttr('disabled').show();;
      state_input.hide().attr('disabled', 'disabled');

    } else {
      state_input.removeAttr('disabled').show();
      state_select.hide().attr('disabled', 'disabled');
    }

  };

  jQuery(document).ready(function(){
    $('span#bcountry select').change(function() { update_state('b'); });
    $('span#scountry select').change(function() { update_state('s'); });
  });

});
<|endoftext|>


<commit_before>
if (!CR) {
    var CR = {};
}

$(document).ready(function() {

  var c = $.cookie('c')

  if (c) {
      var bc_u = c.match(/bc_u\/~([0-9]+)/);
      if (bc_u && bc_u[1] > 0) {
          c = bc_u[1];
          var login_link = $("#login_link");
          login_link.html("Logout");
          login_link.attr('href', '/logout');
      }
      else {
          c = 0;
      }
  }

  if (c) {
      $("div.review").each(
          function() {
              var attr = $(this).attr("data-user");
              if (attr == c) {
                  $(this).find(".helpfulq").html(" ");
              }
          });
  }

  $("#show_unhelpful").click(function(ev) {
       var unhelpful_div = $(this);
       $.ajax({ url: "/api/review/get",
                success: function(data) {
                    if (data.html) {
                        unhelpful_div.parents("#reviews").append( data.html );
                        unhelpful_div.hide();
                    }
                },
                data: { "auth_token": global_auth_token,
                        "dist": $(this).attr('data-dist'),
                        "unhelpful": 1,
                        "html": 1
                      },
                dataType: "json",
                type: "GET"
      });
  });

  $("span.helpful").click(function(ev) {
       var review = $(this).parents("div.review");
       var review_id = review.attr('data-review');

       var thanks_span = review.find("span.thanks");
       var vote = $(this).text().toLowerCase();

       // $("#reviews").find("span.thanks.done").not(thanks_span).fadeOut();

       thanks_span.removeClass("error");
       thanks_span.html("Saving ...");
       thanks_span.show();

       var set_error = function (err) {
           thanks_span.html(err);
           thanks_span.addClass("error");
           thanks_span.addClass("done");
       };

       $.ajax({ url: "/api/helpful/vote",
                success: function(data) {
                    if (data.error) {
                        thanks_span.html( data.error );
                        thanks_span.addClass("error");
                        return;
                    }
                    thanks_span.addClass("done");
                    thanks_span.html(data.message);
                },
                data: { "auth_token": global_auth_token,
                          "vote": vote,
                          "review_id": review_id
                      },

                dataType: "json",
                type: "POST",
                statusCode: {
                    412: function() {
                        set_error("Login before voting");
                    }
                },
                error: function(msg) {
                    set_error("Whoops - something went wrong!
" + msg);
                }
             });
  });

  /* images/progress.gif */
});
<commit_msg>Allow adding helpful votes to unhelpful reviews again<commit_after>
if (!CR) {
    var CR = {};
}

$(document).ready(function() {

  var c = $.cookie('c')

  if (c) {
      var bc_u = c.match(/bc_u\/~([0-9]+)/);
      if (bc_u && bc_u[1] > 0) {
          c = bc_u[1];
          var login_link = $("#login_link");
          login_link.html("Logout");
          login_link.attr('href', '/logout');
      }
      else {
          c = 0;
      }
  }

  if (c) {
      $("div.review").each(
          function() {
              var attr = $(this).attr("data-user");
              if (attr == c) {
                  $(this).find(".helpfulq").html(" ");
              }
          });
  }

  $("#show_unhelpful").click(function(ev) {
       var unhelpful_div = $(this);
       $.ajax({ url: "/api/review/get",
                success: function(data) {
                    if (data.html) {
                        unhelpful_div.parents("#reviews").append( data.html );
                        unhelpful_div.hide();
                    }
                },
                data: { "auth_token": global_auth_token,
                        "dist": $(this).attr('data-dist'),
                        "unhelpful": 1,
                        "html": 1
                      },
                dataType: "json",
                type: "GET"
      });
  });

  $("span.helpful").live('click', function(ev) {
       var review = $(this).parents("div.review");
       var review_id = review.attr('data-review');

       var thanks_span = review.find("span.thanks");
       var vote = $(this).text().toLowerCase();

       // $("#reviews").find("span.thanks.done").not(thanks_span).fadeOut();

       thanks_span.removeClass("error");
       thanks_span.html("Saving ...");
       thanks_span.show();

       var set_error = function (err) {
           thanks_span.html(err);
           thanks_span.addClass("error");
           thanks_span.addClass("done");
       };

       $.ajax({ url: "/api/helpful/vote",
                success: function(data) {
                    if (data.error) {
                        thanks_span.html( data.error );
                        thanks_span.addClass("error");
                        return;
                    }
                    thanks_span.addClass("done");
                    thanks_span.html(data.message);
                },
                data: { "auth_token": global_auth_token,
                          "vote": vote,
                          "review_id": review_id
                      },

                dataType: "json",
                type: "POST",
                statusCode: {
                    412: function() {
                        set_error("Login before voting");
                    }
                },
                error: function(msg) {
                    set_error("Whoops - something went wrong!
" + msg);
                }
             });
  });

  /* images/progress.gif */
});
<|endoftext|>