<commit_before>'use strict';

// MODULES //

var debug = require( 'debug' )( 'gh-pages:build-packages:build' );
var join = require( 'path' ).join;
var copy = require( '@stdlib/utils/copy' );
var buildPkg = require( './../../package' );
var packageName = require( './package_name.js' );

// MAIN //

/**
* Builds one or more packages.
*
* @private
* @param {StringArray} pkgs - list of package paths
* @param {string} dest - destination directory
* @param {Options} opts - options
* @param {string} opts.readme - README filename
* @param {string} opts.index - index filename
* @param {string} opts.mount - base URL mount
* @param {string} opts.prepend - content to prepend to HTML body
* @param {string} opts.append - content to append to HTML body
* @param {string} opts.head - content to insert into HTML head
* @param {Object} opts.tests - tests options
* @param {string} opts.tests.pattern - glob pattern
* @param {string} opts.tests.bundle - bundle filename
* @param {string} opts.tests.folder - folder name
* @param {string} opts.tests.html - HTML filename
* @param {string} opts.tests.title - HTML title
* @param {Object} opts.benchmarks - benchmarks options
* @param {string} opts.benchmarks.pattern - benchmarks glob pattern
* @param {string} opts.benchmarks.bundle - bundle filename
* @param {string} opts.benchmarks.folder - folder name
* @param {string} opts.benchmarks.html - HTML filename
* @param {string} opts.benchmarks.title - HTML title
* @param {Callback} clbk - callback to invoke upon completion
*/
function build( pkgs, dest, opts, clbk ) {
	var count;
	var len;
	var i;

	len = pkgs.length;
	count = 0;
	i = -1;

	debug( 'Building %d packages...', len );

	// Build one package at a time to avoid filesystem limits:
	next();

	/**
	* Builds the next package.
	*
	* @private
	*/
	function next() {
		var bopts;
		var name;
		var pkg;
		var out;

		i += 1;
		pkg = pkgs[ i ];

		// TODO: read `package.json`
		name = packageName( pkg );
		debug( 'Package name: %s', name );

		out = join( dest, name );
		debug( 'Destination directory: %s', out );

		bopts = {};
		bopts.readme = opts.readme;
		bopts.index = opts.index;
		bopts.title = name;
		bopts.mount = opts.mount + name + '/';
		bopts.head = opts.head;
		bopts.prepend = opts.prepend;
		bopts.append = opts.append;

		bopts.tests = copy( opts.tests );
		bopts.tests.title = name + ' - Tests';

		bopts.benchmarks = copy( opts.benchmarks );
		bopts.benchmarks.title = name + ' - Benchmarks';

		debug( 'Build options: %s', JSON.stringify( bopts ) );

		debug( 'Building package: %s (%d of %d)', pkg, i+1, len );
		buildPkg( pkg, out, bopts, onBuild( i ) );
	} // end FUNCTION next()

	/**
	* Returns a callback to be invoked upon building a package.
	*
	* @private
	* @param {NonNegativeInteger} idx - index
	*/
	function onBuild( idx ) {
		var pkg = pkgs[ idx ];
		var k = idx + 1;
		/**
		* Callback invoked upon building a package.
		*
		* @private
		* @param {(Error|null)} error - error object
		*/
		return function onBuild( error ) {
			if ( error ) {
				debug( 'Encountered an error when building package: %s (%d of %d)', pkg, k, len );
				return done( error );
			}
			debug( 'Successfully built package: %s (%d of %d)', pkg, k, len );
			done();
		}; // end FUNCTION onBuild()
	} // end FUNCTION onBuild()

	/**
	* Callback invoked to track build progress.
	*
	* @private
	* @param {(Error|null)} error - error object
	*/
	function done( error ) {
		if ( error ) {
			return clbk( error );
		}
		count += 1;
		debug( 'Built %d of %d packages.', count, len );
		if ( count < len ) {
			return next();
		}
		// Finished...
		clbk();
	} // end FUNCTION done()
} // end FUNCTION build()

// EXPORTS //

module.exports = build;
<commit_msg>Fix require statement<commit_after>'use strict';

// MODULES //

var debug = require( 'debug' )( 'gh-pages:packages:build:build' );
var join = require( 'path' ).join;
var copy = require( '@stdlib/utils/copy' );
var buildPkg = require( './../../pkg-browser-build' );
var packageName = require( './package_name.js' );

// MAIN //

/**
* Builds one or more packages.
*
* @private
* @param {StringArray} pkgs - list of package paths
* @param {string} dest - destination directory
* @param {Options} opts - options
* @param {string} opts.readme - README filename
* @param {string} opts.index - index filename
* @param {string} opts.mount - base URL mount
* @param {string} opts.prepend - content to prepend to HTML body
* @param {string} opts.append - content to append to HTML body
* @param {string} opts.head - content to insert into HTML head
* @param {Object} opts.tests - tests options
* @param {string} opts.tests.pattern - glob pattern
* @param {string} opts.tests.bundle - bundle filename
* @param {string} opts.tests.folder - folder name
* @param {string} opts.tests.html - HTML filename
* @param {string} opts.tests.title - HTML title
* @param {Object} opts.benchmarks - benchmarks options
* @param {string} opts.benchmarks.pattern - benchmarks glob pattern
* @param {string} opts.benchmarks.bundle - bundle filename
* @param {string} opts.benchmarks.folder - folder name
* @param {string} opts.benchmarks.html - HTML filename
* @param {string} opts.benchmarks.title - HTML title
* @param {Callback} clbk - callback to invoke upon completion
*/
function build( pkgs, dest, opts, clbk ) {
	var count;
	var len;
	var i;

	len = pkgs.length;
	count = 0;
	i = -1;

	debug( 'Building %d packages...', len );

	// Build one package at a time to avoid filesystem limits:
	next();

	/**
	* Builds the next package.
	*
	* @private
	*/
	function next() {
		var bopts;
		var name;
		var pkg;
		var out;

		i += 1;
		pkg = pkgs[ i ];

		// TODO: read `package.json`
		name = packageName( pkg );
		debug( 'Package name: %s', name );

		out = join( dest, name );
		debug( 'Destination directory: %s', out );

		bopts = {};
		bopts.readme = opts.readme;
		bopts.index = opts.index;
		bopts.title = name;
		bopts.mount = opts.mount + name + '/';
		bopts.head = opts.head;
		bopts.prepend = opts.prepend;
		bopts.append = opts.append;

		bopts.tests = copy( opts.tests );
		bopts.tests.title = name + ' - Tests';

		bopts.benchmarks = copy( opts.benchmarks );
		bopts.benchmarks.title = name + ' - Benchmarks';

		debug( 'Build options: %s', JSON.stringify( bopts ) );

		debug( 'Building package: %s (%d of %d)', pkg, i+1, len );
		buildPkg( pkg, out, bopts, onBuild( i ) );
	} // end FUNCTION next()

	/**
	* Returns a callback to be invoked upon building a package.
	*
	* @private
	* @param {NonNegativeInteger} idx - index
	*/
	function onBuild( idx ) {
		var pkg = pkgs[ idx ];
		var k = idx + 1;
		/**
		* Callback invoked upon building a package.
		*
		* @private
		* @param {(Error|null)} error - error object
		*/
		return function onBuild( error ) {
			if ( error ) {
				debug( 'Encountered an error when building package: %s (%d of %d)', pkg, k, len );
				return done( error );
			}
			debug( 'Successfully built package: %s (%d of %d)', pkg, k, len );
			done();
		}; // end FUNCTION onBuild()
	} // end FUNCTION onBuild()

	/**
	* Callback invoked to track build progress.
	*
	* @private
	* @param {(Error|null)} error - error object
	*/
	function done( error ) {
		if ( error ) {
			return clbk( error );
		}
		count += 1;
		debug( 'Built %d of %d packages.', count, len );
		if ( count < len ) {
			return next();
		}
		// Finished...
		clbk();
	} // end FUNCTION done()
} // end FUNCTION build()

// EXPORTS //

module.exports = build;
<|endoftext|>


<commit_before>import _ from 'messages'
import { Button } from 'react-bootstrap-4/lib'
import Link from 'react-router/lib/Link'
import map from 'lodash/map'
import React, { Component } from 'react'

import Icon from 'icon'

export default class Menu extends Component {
  componentWillMount () {
    this.setState({collapsed: false})
  }
  render () {
    const items = [
      { to: '/home', icon: 'home', label: 'homePage' },
      { to: '/dashboard/overview', icon: 'dashboard', label: 'dashboardPage', subMenu: [
        { to: '/dashboard/overview', icon: 'dashboard-overview', label: 'overviewDashboardPage' },
        { to: '/dashboard/visualization', icon: 'dashboard-visualization', label: 'overviewVisualizationDashboardPage' },
        { to: '/dashboard/stats', icon: 'dashboard-stats', label: 'overviewStatsDashboardPage' },
        { to: '/dashboard/health', icon: 'dashboard-health', label: 'overviewHealthDashboardPage' }
      ]},
      { to: '/self/dashboard', icon: 'self-service', label: 'selfServicePage', subMenu: [
        { to: '/self/dashboard', icon: 'self-service-dashboard', label: 'selfServiceDashboardPage' },
        { to: '/self/admin', icon: 'self-service-admin', label: 'selfServiceAdminPage' }
      ]},
      { to: '/backup/overview', icon: 'backup', label: 'backupPage', subMenu: [
        { to: '/backup/overview', icon: 'backup-overview', label: 'backupOverviewPage' },
        { to: '/backup/new', icon: 'backup-new', label: 'backupNewPage' },
        { to: '/backup/remotes', icon: 'backup-remotes', label: 'backupRemotesPage' },
        { to: '/backup/restore', icon: 'backup-restore', label: 'backupRestorePage' }
      ]},
      { to: '/update', icon: 'update', label: 'updatePage' },
      { to: '/settings/servers', icon: 'settings', label: 'settingsPage', subMenu: [
        { to: '/settings/servers', icon: 'settings-servers', label: 'settingsServersPage' },
        { to: '/settings/users', icon: 'settings-users', label: 'settingsUsersPage' },
        { to: '/settings/groups', icon: 'settings-groups', label: 'settingsGroupsPage' },
        { to: '/settings/acls', icon: 'settings-acls', label: 'settingsAclsPage' },
        { to: '/settings/plugins', icon: 'settings-plugins', label: 'settingsPluginsPage' }
      ]},
      { to: '/about', icon: 'about', label: 'aboutPage' },
      { to: '/vms/new', icon: 'new', label: 'newMenu', subMenu: [
        { to: '/vms/new', icon: 'new-vm', label: 'newVmPage' },
        { to: '/srs/new', icon: 'new-sr', label: 'newSrPage' },
        { to: '/settings/servers', icon: 'settings-servers', label: 'newServerPage' },
        { to: '/import', icon: 'new-import', label: 'newImport' }
      ]}
    ]
    return

        <Button onClick={() => this.setState({collapsed: !this.state.collapsed})}>
          <Icon icon='menu-collapse' size='lg' fixedWidth />
        </Button>
        {map(items, (item, index) =>
          <MenuLinkItem key={index} item={item} collapsed={this.state.collapsed}/>
        )}

  }
}

const MenuLinkItem = (props) => {
  const { item, collapsed } = props
  const { to, icon, label, subMenu } = item

  return

    <Link activeClassName='active' className='nav-link' to={to}>
      <Icon icon={`menu-${icon}`} size='lg' fixedWidth/>
      {!collapsed &&    }
      {!collapsed && _(label)}
    </Link>
    {subMenu && <SubMenu items={subMenu}/>}

}

const SubMenu = (props) => {
  return

    {map(props.items, (item, index) => (

        <Link activeClassName='active' className='nav-link' to={item.to}>
          <Icon icon={`menu-${item.icon}`} size='lg' fixedWidth/>
          {_(item.label)}
        </Link>

    ))}

}
<commit_msg>menu: move remote in settings<commit_after>import _ from 'messages'
import { Button } from 'react-bootstrap-4/lib'
import Link from 'react-router/lib/Link'
import map from 'lodash/map'
import React, { Component } from 'react'

import Icon from 'icon'

export default class Menu extends Component {
  componentWillMount () {
    this.setState({collapsed: false})
  }
  render () {
    const items = [
      { to: '/home', icon: 'home', label: 'homePage' },
      { to: '/dashboard/overview', icon: 'dashboard', label: 'dashboardPage', subMenu: [
        { to: '/dashboard/overview', icon: 'dashboard-overview', label: 'overviewDashboardPage' },
        { to: '/dashboard/visualization', icon: 'dashboard-visualization', label: 'overviewVisualizationDashboardPage' },
        { to: '/dashboard/stats', icon: 'dashboard-stats', label: 'overviewStatsDashboardPage' },
        { to: '/dashboard/health', icon: 'dashboard-health', label: 'overviewHealthDashboardPage' }
      ]},
      { to: '/self/dashboard', icon: 'self-service', label: 'selfServicePage', subMenu: [
        { to: '/self/dashboard', icon: 'self-service-dashboard', label: 'selfServiceDashboardPage' },
        { to: '/self/admin', icon: 'self-service-admin', label: 'selfServiceAdminPage' }
      ]},
      { to: '/backup/overview', icon: 'backup', label: 'backupPage', subMenu: [
        { to: '/backup/overview', icon: 'backup-overview', label: 'backupOverviewPage' },
        { to: '/backup/new', icon: 'backup-new', label: 'backupNewPage' },
        { to: '/backup/restore', icon: 'backup-restore', label: 'backupRestorePage' }
      ]},
      { to: '/update', icon: 'update', label: 'updatePage' },
      { to: '/settings/servers', icon: 'settings', label: 'settingsPage', subMenu: [
        { to: '/settings/servers', icon: 'settings-servers', label: 'settingsServersPage' },
        { to: '/settings/users', icon: 'settings-users', label: 'settingsUsersPage' },
        { to: '/settings/groups', icon: 'settings-groups', label: 'settingsGroupsPage' },
        { to: '/settings/acls', icon: 'settings-acls', label: 'settingsAclsPage' },
        { to: '/settings/remotes', icon: 'backup-remotes', label: 'backupRemotesPage' },
        { to: '/settings/plugins', icon: 'settings-plugins', label: 'settingsPluginsPage' }
      ]},
      { to: '/about', icon: 'about', label: 'aboutPage' },
      { to: '/vms/new', icon: 'new', label: 'newMenu', subMenu: [
        { to: '/vms/new', icon: 'new-vm', label: 'newVmPage' },
        { to: '/srs/new', icon: 'new-sr', label: 'newSrPage' },
        { to: '/settings/servers', icon: 'settings-servers', label: 'newServerPage' },
        { to: '/import', icon: 'new-import', label: 'newImport' }
      ]}
    ]
    return

        <Button onClick={() => this.setState({collapsed: !this.state.collapsed})}>
          <Icon icon='menu-collapse' size='lg' fixedWidth />
        </Button>
        {map(items, (item, index) =>
          <MenuLinkItem key={index} item={item} collapsed={this.state.collapsed}/>
        )}

  }
}

const MenuLinkItem = (props) => {
  const { item, collapsed } = props
  const { to, icon, label, subMenu } = item

  return

    <Link activeClassName='active' className='nav-link' to={to}>
      <Icon icon={`menu-${icon}`} size='lg' fixedWidth/>
      {!collapsed &&    }
      {!collapsed && _(label)}
    </Link>
    {subMenu && <SubMenu items={subMenu}/>}

}

const SubMenu = (props) => {
  return

    {map(props.items, (item, index) => (

        <Link activeClassName='active' className='nav-link' to={item.to}>
          <Icon icon={`menu-${item.icon}`} size='lg' fixedWidth/>
          {_(item.label)}
        </Link>

    ))}

}
<|endoftext|>


<commit_before>import AuthenticatedRoute from 'ghost-admin/routes/authenticated';
import CurrentUserSettings from 'ghost-admin/mixins/current-user-settings';

export default AuthenticatedRoute.extend(CurrentUserSettings, {
    beforeModel() {
        this._super(...arguments);
        return this.get('session.user')
            .then(this.transitionAuthor())
            .then(this.transitionEditor());
    },
});<commit_msg>Fixed tests<commit_after>import AuthenticatedRoute from 'ghost-admin/routes/authenticated';
import CurrentUserSettings from 'ghost-admin/mixins/current-user-settings';

export default AuthenticatedRoute.extend(CurrentUserSettings, {
    beforeModel() {
        this._super(...arguments);
        return this.get('session.user')
            .then(this.transitionAuthor())
            .then(this.transitionEditor());
    }
});<|endoftext|>


<commit_before>'use strict';

var ensureString   = require('es5-ext/object/validate-stringifiable-value')
  , escape         = require('es5-ext/reg-exp/escape')
  , startsWith     = require('es5-ext/string/#/starts-with')
  , deferred       = require('deferred')
  , findRequires   = require('find-requires')
  , debug          = require('debug-ext')('rename-module:module')
  , readdir        = require('fs2/readdir')
  , stat           = require('fs2/stat')
  , readFile       = require('fs2/read-file')
  , writeFile      = require('fs2/write-file')
  , unlink         = require('fs2/unlink')
  , path           = require('path')
  , relative       = require('path2/posix/relative')
  , resolveModule  = require('cjs-module/resolve')
  , resolveRoot    = require('cjs-module/resolve-package-root')
  , isPathExternal = require('cjs-module/utils/is-path-external')
  , isModule       = require('./lib/is-module')
  , normalize      = require('./lib/normalize-local-path')

  , push = Array.prototype.push, stringify = JSON.stringify
  , basename = path.basename, extname = path.extname, sep = path.sep, dirname = path.dirname
  , resolve = path.resolve
  , findRequiresOpts = { raw: true };

var readdirOpts = { depth: Infinity, type: { file: true }, stream: true,
	dirFilter: function (path) { return (basename(path) !== 'node_modules'); },
	ignoreRules: 'git', pattern: new RegExp(escape(sep) + '(?:[^.]+|.+\\.js)$') };

module.exports = function (from, to) {
	from = resolve(ensureString(from));
	to = resolve(ensureString(to));

	// Validate arguments and resolve initial data
	return deferred(stat(from), resolveRoot(dirname(from)), stat(to).then(function () {
		throw new Error("Target path " + stringify(to) + " is not empty");
	}, function (err) {
		if (err.code === 'ENOENT') return null;
		throw err;
	}))(function (data) {
		var fileStats = data[0], root = data[1], dirReader, filePromises, modulesToUpdate
		  , fromExt = extname(from)
		  , rootPrefixLength = root.length + 1, trimmedPathStatus;

		if (!fileStats.isFile()) throw new Error("Input module " + stringify(from) + " is not a file");
		if (!root) {
			throw new Error("Unable to resolve package root (renamed module is expected to be placed " +
				"in scope of some package");
		}
		if (!startsWith.call(to, root + sep)) {
			throw new Error("Cannot reliably move module out of current package");
		}

		// Find all JS modules in a package
		debug('%s -> %s', from.slice(rootPrefixLength), to.slice(rootPrefixLength));
		debug('gather local modules at %s', root);
		dirReader = readdir(root, readdirOpts);
		filePromises = [];
		modulesToUpdate = [];
		dirReader.on('change', function (event) {
			push.apply(filePromises, event.added.map(function (path) {
				var filename = resolve(root, path);
				if (filename === from) return;
				return isModule(filename)(function (is) {
					if (!is) return;

					// Find if JS module contains a require to renamed module
					return readFile(filename)(function (code) {
						var dir = dirname(filename), expectedPathFull = relative(dir, from)
						  , expectedPathTrimmed;
						if (expectedPathFull[0] !== '.') expectedPathFull = './' + expectedPathFull;
						expectedPathTrimmed = expectedPathFull.slice(0, -extname(expectedPathFull).length);
						code = String(code);
						return deferred.map(findRequires(code, findRequiresOpts), function (data) {
							var modulePath;
							// Ignore requires to external packages
							if (isPathExternal(data.value)) return;

							modulePath = normalize(data.value, dir);

							// Check full path match, e.g. ./foo/bar.js (for ./foo/bar.js file)
							if (expectedPathFull === modulePath) return data;
							// Check trimmed path match, e.g. ./foo/bar (for ./foo/bar.js file)
							if (expectedPathTrimmed !== modulePath) return;
							// Validate whether trimmed path matches
							// If input module is .js file, then it surely will be matched (.js has priority)
							if (fromExt === '.js') return data;
							// Otherwise check whether some other module is not matched over moved one
							// e.g. if there's foo.json and foo.js, requiring './foo' will match foo.js
							// This check can be done once, therefore we keep once resolved value
							if (!trimmedPathStatus) trimmedPathStatus = resolveModule(dir, data.value);
							return trimmedPathStatus(function (requiredFilename) {
								if (from === requiredFilename) return data;
							});
						})(function (result) {
							result = result.filter(Boolean);
							if (!result.length) return;
							// Matching path(s) found, add module to rewrite queue
							modulesToUpdate.push({ filename: filename, dirname: dir,
								code: code, requires: result });
						});
					});
				});
			}));
		});
		return dirReader(function () {
			// Wait until all local modules are parsed
			return deferred.map(filePromises).aside(function () {
				debug('found %s dependents', modulesToUpdate.length);
			});
		})(function () {
			if (!modulesToUpdate.length) return;

			// Update affected requires in modules that require renamed module
			return deferred.map(modulesToUpdate, function (data) {
				var nuPath = relative(data.dirname, to)
				  , nuPathExt = extname(nuPath)
				  , diff = 0
				  , code = data.code;
				if (nuPath[0] !== '.') nuPath = './' + nuPath;
				data.requires.forEach(function (reqData) {
					var nuRaw = stringify((nuPathExt && !extname(reqData.value))
						? nuPath.slice(0, -nuPathExt.length) : nuPath).slice(1, -1);
					code = code.slice(0, reqData.point + diff) + nuRaw +
						code.slice(reqData.point + diff + reqData.raw.length - 2);
					diff += nuRaw.length - (reqData.raw.length - 2);
				});
				debug('rewrite %s', data.filename.slice(rootPrefixLength));
				return writeFile(data.filename, code);
			});
		})(function () {
			// Rename module, and update require paths within it
			return readFile(from)(function (code) {
				var dirFrom = dirname(from), ext = extname(from), dirTo = dirname(to);
				code = String(code);
				// If not JS module, no requires to parse
				if (ext && (ext !== '.js')) return code;
				// If module was renamed in same folder, then local paths will not change
				// (corner case would be requiring self module, but we assume nobody does that)
				if (dirFrom === dirTo) return code;
				return isModule(from)(function (is) {
					var relPath;
					// Not JS module, so no requires to parse
					if (!is) return code;
					relPath = normalize(relative(dirTo, dirFrom)) + '/';
					return deferred.map(findRequires(code, findRequiresOpts).filter(function (data) {
						// Ignore external package requires
						return !isPathExternal(data.value);
					}), function (data) {
						var oldPath = normalize(data.value)
						  , nuPath = normalize(dirTo + '/' + relPath + oldPath, dirTo);
						if (nuPath === oldPath) return;
						data.nuPath = nuPath;
						return data;
					})(function (requires) {
						var diff = 0;
						requires.filter(Boolean).forEach(function (reqData) {
							var nuPath = reqData.nuPath
							  , nuPathExt = extname(nuPath);
							var nuRaw = stringify((nuPathExt && !extname(reqData.value))
								? nuPath.slice(0, -nuPathExt.length) : nuPath).slice(1, -1);
							code = code.slice(0, reqData.point + diff) + nuRaw +
								code.slice(reqData.point + diff + reqData.raw.length - 2);
							diff += nuRaw.length - (reqData.raw.length - 2);
						});
						return code;
					});
				});
			});
		})(function (nuCode) {
			debug('rewrite %s to %s', from.slice(rootPrefixLength), to.slice(rootPrefixLength));
			return deferred(writeFile(to, nuCode, { mode: fileStats.mode, intermediate: true }),
				unlink(from));
		});
	});
};
<commit_msg>Documentation<commit_after>'use strict';

var ensureString   = require('es5-ext/object/validate-stringifiable-value')
  , escape         = require('es5-ext/reg-exp/escape')
  , startsWith     = require('es5-ext/string/#/starts-with')
  , deferred       = require('deferred')
  , findRequires   = require('find-requires')
  , debug          = require('debug-ext')('rename-module:module')
  , readdir        = require('fs2/readdir')
  , stat           = require('fs2/stat')
  , readFile       = require('fs2/read-file')
  , writeFile      = require('fs2/write-file')
  , unlink         = require('fs2/unlink')
  , path           = require('path')
  , relative       = require('path2/posix/relative')
  , resolveModule  = require('cjs-module/resolve')
  , resolveRoot    = require('cjs-module/resolve-package-root')
  , isPathExternal = require('cjs-module/utils/is-path-external')
  , isModule       = require('./lib/is-module')
  , normalize      = require('./lib/normalize-local-path')

  , push = Array.prototype.push, stringify = JSON.stringify
  , basename = path.basename, extname = path.extname, sep = path.sep, dirname = path.dirname
  , resolve = path.resolve
  , findRequiresOpts = { raw: true };

var readdirOpts = { depth: Infinity, type: { file: true }, stream: true,
	dirFilter: function (path) { return (basename(path) !== 'node_modules'); },
	ignoreRules: 'git', pattern: new RegExp(escape(sep) + '(?:[^.]+|.+\\.js)$') };

module.exports = function (from, to) {
	from = resolve(ensureString(from));
	to = resolve(ensureString(to));

	// Validate arguments and resolve initial data
	return deferred(stat(from), resolveRoot(dirname(from)), stat(to).then(function () {
		throw new Error("Target path " + stringify(to) + " is not empty");
	}, function (err) {
		if (err.code === 'ENOENT') return null;
		throw err;
	}))(function (data) {
		var fileStats = data[0], root = data[1], dirReader, filePromises, modulesToUpdate
		  , fromExt = extname(from)
		  , rootPrefixLength = root.length + 1, trimmedPathStatus;

		if (!fileStats.isFile()) throw new Error("Input module " + stringify(from) + " is not a file");
		if (!root) {
			throw new Error("Unable to resolve package root (renamed module is expected to be placed " +
				"in scope of some package");
		}
		if (!startsWith.call(to, root + sep)) {
			throw new Error("Cannot reliably move module out of current package");
		}

		// Find all JS modules in a package
		debug('%s -> %s', from.slice(rootPrefixLength), to.slice(rootPrefixLength));
		debug('gather local modules at %s', root);
		dirReader = readdir(root, readdirOpts);
		filePromises = [];
		modulesToUpdate = [];
		dirReader.on('change', function (event) {
			push.apply(filePromises, event.added.map(function (path) {
				var filename = resolve(root, path);
				if (filename === from) return;
				return isModule(filename)(function (is) {
					if (!is) return;

					// Find if JS module contains a require to renamed module
					return readFile(filename)(function (code) {
						var dir = dirname(filename), expectedPathFull = relative(dir, from)
						  , expectedPathTrimmed;
						if (expectedPathFull[0] !== '.') expectedPathFull = './' + expectedPathFull;
						expectedPathTrimmed = expectedPathFull.slice(0, -extname(expectedPathFull).length);
						code = String(code);
						return deferred.map(findRequires(code, findRequiresOpts), function (data) {
							var modulePath;
							// Ignore requires to external packages
							if (isPathExternal(data.value)) return;

							modulePath = normalize(data.value, dir);

							// Check full path match, e.g. ./foo/bar.js (for ./foo/bar.js file)
							if (expectedPathFull === modulePath) return data;
							// Check trimmed path match, e.g. ./foo/bar (for ./foo/bar.js file)
							if (expectedPathTrimmed !== modulePath) return;
							// Validate whether trimmed path matches
							// If input module is .js file, then it surely will be matched (.js has priority)
							if (fromExt === '.js') return data;
							// Otherwise check whether some other module is not matched over moved one
							// e.g. if there's foo.json and foo.js, requiring './foo' will match foo.js
							// This check can be done once, therefore we keep once resolved value
							if (!trimmedPathStatus) trimmedPathStatus = resolveModule(dir, data.value);
							return trimmedPathStatus(function (requiredFilename) {
								if (from === requiredFilename) return data;
							});
						})(function (result) {
							result = result.filter(Boolean);
							if (!result.length) return;
							// Matching path(s) found, add module to rewrite queue
							modulesToUpdate.push({ filename: filename, dirname: dir,
								code: code, requires: result });
						});
					});
				});
			}));
		});
		return dirReader(function () {
			// Wait until all local modules are parsed
			return deferred.map(filePromises).aside(function () {
				debug('found %s dependents', modulesToUpdate.length);
			});
		})(function () {
			if (!modulesToUpdate.length) return;

			// Update affected requires in modules that require renamed module
			return deferred.map(modulesToUpdate, function (data) {
				var nuPath = relative(data.dirname, to)
				  , nuPathExt = extname(nuPath)
				  , diff = 0
				  , code = data.code;
				if (nuPath[0] !== '.') nuPath = './' + nuPath;
				data.requires.forEach(function (reqData) {
					var nuRaw = stringify((nuPathExt && !extname(reqData.value))
						? nuPath.slice(0, -nuPathExt.length) : nuPath).slice(1, -1);
					code = code.slice(0, reqData.point + diff) + nuRaw +
						code.slice(reqData.point + diff + reqData.raw.length - 2);
					diff += nuRaw.length - (reqData.raw.length - 2);
				});
				debug('rewrite %s', data.filename.slice(rootPrefixLength));
				return writeFile(data.filename, code);
			});
		})(function () {
			// Rename module, and update require paths within it
			return readFile(from)(function (code) {
				var dirFrom = dirname(from), ext = extname(from), dirTo = dirname(to);
				code = String(code);
				// If not JS module, then no requires to parse
				if (ext && (ext !== '.js')) return code;
				// If module was renamed in same folder, then local paths will not change
				// (corner case would be requiring self module, but we assume nobody does that)
				if (dirFrom === dirTo) return code;
				return isModule(from)(function (is) {
					var relPath;
					// If not JS module, then no requires to parse
					if (!is) return code;
					relPath = normalize(relative(dirTo, dirFrom)) + '/';
					return deferred.map(findRequires(code, findRequiresOpts).filter(function (data) {
						// Ignore external package requires
						return !isPathExternal(data.value);
					}), function (data) {
						var oldPath = normalize(data.value)
						  , nuPath = normalize(dirTo + '/' + relPath + oldPath, dirTo);
						if (nuPath === oldPath) return;
						data.nuPath = nuPath;
						return data;
					})(function (requires) {
						var diff = 0;
						requires.filter(Boolean).forEach(function (reqData) {
							var nuPath = reqData.nuPath
							  , nuPathExt = extname(nuPath);
							var nuRaw = stringify((nuPathExt && !extname(reqData.value))
								? nuPath.slice(0, -nuPathExt.length) : nuPath).slice(1, -1);
							code = code.slice(0, reqData.point + diff) + nuRaw +
								code.slice(reqData.point + diff + reqData.raw.length - 2);
							diff += nuRaw.length - (reqData.raw.length - 2);
						});
						return code;
					});
				});
			});
		})(function (nuCode) {
			debug('rewrite %s to %s', from.slice(rootPrefixLength), to.slice(rootPrefixLength));
			return deferred(writeFile(to, nuCode, { mode: fileStats.mode, intermediate: true }),
				unlink(from));
		});
	});
};
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import axios from 'axios';

import DogImage from './dogImage';
import DogSelect from './dogSelect';

export default class RandomizedMultiselect extends Component {
  constructor(props) {
    super(props);
    this.state = {
      breeds: [],
      selectedBreeds: [],
      imageUrl: ""
    };
    this.getDogBreeds = this.getDogBreeds.bind(this);
    this.getImageForBreed = this.getImageForBreed.bind(this);
    this.getImageForSelectedBreed = this.getImageForSelectedBreed.bind(this);
    this.updateSelectedBreeds = this.updateSelectedBreeds.bind(this);
  }
  getDogBreeds() {
    let url = "https://dog.ceo/api/breeds/list";
    axios.get(url)
    .then(function(res) {
      this.setState({
        breeds: res.data.message
      });
    }.bind(this))
    .catch(function(err) {
      console.error(err);
    }.bind(this));
  }
  getImageForBreed(breed) {
    let url = "https://dog.ceo/api/breed/" + breed + "/images/random";
    axios.get(url)
    .then(function(res) {
      this.setState({
        imageUrl: res.data.message
      });
    }.bind(this))
    .catch(function(err) {
      console.error(err);
    }.bind(this));
  }
  getFromSelectedBreeds() {
    let breeds = this.state.selectedBreeds;
    let index = Math.floor(Math.random() * breeds.length);
    return breeds[index];
  }
  getImageForSelectedBreed() {
    let breed = this.getFromSelectedBreeds();
    this.getImageForBreed(breed);
  }
  updateSelectedBreeds(breeds) {
    this.setState({
      selectedBreeds: breeds
    });
    this.getImageForBreed(breeds[breeds.length-1]);
  }
  getButtonDisabled(){
    return this.state.selectedBreeds.length === 0;
  }
  render() {
    if(this.state.breeds.length === 0) {
      this.getDogBreeds();
    }
    let isButtonDisabled = this.getButtonDisabled();
    return (

            <DogSelect data={this.state.breeds} handleChange={this.updateSelectedBreeds}/>
            Another One!

            <DogImage data={this.state.imageUrl}/>

    );
  }
}<commit_msg>button now spins if an image is loading<commit_after>import React, {Component} from 'react';
import axios from 'axios';

import DogImage from './dogImage';
import DogSelect from './dogSelect';

export default class RandomizedMultiselect extends Component {
  constructor(props) {
    super(props);
    this.state = {
      breeds: [],
      selectedBreeds: [],
      imageUrl: "",
      loadingSelectedItemData: false
    };
    this.getDogBreeds = this.getDogBreeds.bind(this);
    this.getImageForBreed = this.getImageForBreed.bind(this);
    this.getImageForSelectedBreed = this.getImageForSelectedBreed.bind(this);
    this.updateSelectedBreeds = this.updateSelectedBreeds.bind(this);
  }
  getDogBreeds() {
    let url = "https://dog.ceo/api/breeds/list";
    axios.get(url)
    .then(function(res) {
      this.setState({
        breeds: res.data.message
      });
    }.bind(this))
    .catch(function(err) {
      console.error(err);
    }.bind(this));
  }
  getImageForBreed(breed) {
    let url = "https://dog.ceo/api/breed/" + breed + "/images/random";
    this.setState({ loadingSelectedItemData: true });

    axios.get(url)
    .then(function(res) {
      this.setState({
        imageUrl: res.data.message,
        loadingSelectedItemData: false
      });
    }.bind(this))
    .catch(function(err) {
      console.error(err);
    }.bind(this));
  }
  getFromSelectedBreeds() {
    let breeds = this.state.selectedBreeds;
    let index = Math.floor(Math.random() * breeds.length);
    return breeds[index];
  }
  getImageForSelectedBreed() {
    let breed = this.getFromSelectedBreeds();
    this.getImageForBreed(breed);
  }
  updateSelectedBreeds(breeds) {
    this.setState({
      selectedBreeds: breeds
    });
    this.getImageForBreed(breeds[breeds.length-1]);
  }
  getButtonClass(){
    let extraClass = (this.state.loadingSelectedItemData) ? 'is-loading' : '';
    return 'button is-primary is-fullwidth ' + extraClass;
  }
  getButtonDisabled(){
    return this.state.selectedBreeds.length === 0;
  }
  render() {
    if(this.state.breeds.length === 0) {
      this.getDogBreeds();
    }
    let buttonClass = this.getButtonClass();
    let isButtonDisabled = this.getButtonDisabled();
    return (

            <DogSelect data={this.state.breeds} handleChange={this.updateSelectedBreeds}/>
            Go

            <DogImage data={this.state.imageUrl}/>

    );
  }
}<|endoftext|>


<commit_before>exports.newlogonProcessorAcceptor = function() {
    return new logonProcessorAcceptor();
};

var path = require('path');
var fs = require('fs');
var sys = require('sys');

//static vars
var SOHCHAR = String.fromCharCode(1);

function logonProcessorAcceptor(){

    var self = this;

    //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||INCOMING
    this.incoming = function(ctx, event){

        if(event.type !== 'data'){
            ctx.sendNext(event);
            return;
        }

        //====================================Step 3: Convert to map====================================
        var raw = event.data;
        var fix = convertToMap(raw);

        //====================================Step 4: Create Data Store==========================
        var msgType = fix['35'];

        if(ctx.state.session['isLoggedIn'] === false && msgType !== 'A'){
            var error = '[ERROR] First message must be logon:'+JSON.stringify(fix);
            sys.log(error);
            ctx.stream.end();
            ctx.sendNext({data:error, type:'error'});
            return;
        }
        else if(ctx.state.session['isLoggedIn'] === false && msgType === 'A'){
            var fixVersion = fix['8'];
            var senderCompID = fix['56'];
            var targetCompID = fix['49'];

            var incomingSeqNum = 1;
            var outgoingSeqNum = 1;

            var heartbeatInMilliSeconds = fix[108] || '30';

            ctx.state.session['fixVersion'] = fixVersion;
            ctx.state.session['senderCompID'] = senderCompID;
            ctx.state.session['targetCompID'] = targetCompID;
            ctx.state.session['incomingSeqNum'] = incomingSeqNum;
            ctx.state.session['outgoingSeqNum'] = outgoingSeqNum;
            ctx.state.session['heartbeatDuration'] = parseInt(heartbeatInMilliSeconds,10) * 1000;
            ctx.state.session['timeOfLastIncoming'] = new Date().getTime();

            var fileName = './traffic/' + fixVersion + '-' + senderCompID + '-' + targetCompID + '.log';
            sys.log('Attempting to read file '+fileName);

            ctx.state.fileStream = fs.createWriteStream(fileName, {'flags':'a'});
            fs.readFile(fileName, encoding='ascii', function(err,data){
                if(err){
                    //console.log('debug: file doesnt exist, but must due to createWriteStream call');
                    //console.log('debug actual error:'+err);
                }
                else{
                    var transactions = data.split('\n');
                    for(var i=0; i<transactions.length; i++){
                        var tmap = convertToMap(transactions[i]);

                        if(tmap[49] === senderCompID){ //If msg senderCompID matches our senderCompID, then it is outgoing msg
                            outgoingSeqNum = parseInt(tmap[34],10) +1;
                            ctx.sendPrev({data:tmap, type:'resync'});
                        }
                        if(tmap[49] === targetCompID){ //incoming msg
                            incomingSeqNum = parseInt(tmap[34],10) +1;
                            ctx.sendNext({data:tmap, type:'resync'});
                        }
                    }

                    ctx.state.session.incomingSeqNum = incomingSeqNum;
                    ctx.state.session.outgoingSeqNum = outgoingSeqNum;

                }

                ctx.state.session['isLoggedIn'] = true;

                ctx.state.fileStream.write(raw + '\n');
                ctx.sendNext({data:fix, type:'data'});
            });
        }
        else{ // if isLoggedIn === true and mstType === anything
            ctx.state.session.timeOfLastIncoming = new Date().getTime();
            ctx.state.fileStream.write(raw + '\n');
            ctx.sendNext({data:fix, type:'data'});
        }
    }

    //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||OUTGOING
    this.outgoing = function(ctx, event){

        if(event.type !== 'data'){
            ctx.sendNext(event);
            return;
        }

        var fix = event.data;

        var outmsg = convertToFIX(fix,ctx.state.session.fixVersion,
            getUTCTimeStamp(new Date()),
            ctx.state.session.senderCompID,
            ctx.state.session.targetCompID,
            ctx.state.session.outgoingSeqNum);

        ctx.state.session.outgoingSeqNum ++;

        ctx.state.session.timeOfLastOutgoing = new Date().getTime();
        ctx.state.fileStream.write(outmsg+'\n');
        ctx.sendNext({data:outmsg, type:'data'});
    }
}

function convertToMap(msg) {
    var fix = {};
    var keyvals = msg.split(SOHCHAR);
    for (var kv in Object.keys(keyvals)) {
        var kvpair = keyvals[kv].split('=');
        fix[kvpair[0]] = kvpair[1];
    }
    return fix;

}

function convertToFIX(msgraw, fixVersion, timeStamp, senderCompID, targetCompID, outgoingSeqNum){
    //sys.log('c2F:'+JSON.stringify(msgraw));
    //defensive copy
    var msg = {};
    for (var tag in msgraw) {
        if (msgraw.hasOwnProperty(tag)) msg[tag] = msgraw[tag];
    }

    delete msg['9']; //bodylength
    delete msg['10']; //checksum

    var timestamp = new Date();
    var headermsgarr = [];
    var bodymsgarr = [];
    var trailermsgarr = [];

    msg['8'] = fixVersion; //fixversion
    msg['52'] = timeStamp; //timestamp
    msg['49'] = senderCompID; //sendercompid
    msg['56'] = targetCompID; //targetcompid
    msg['34'] = outgoingSeqNum; //seqnum

    headermsgarr.push('52=' + msg['52'] , SOHCHAR);
    headermsgarr.push('49=' + msg['49'] , SOHCHAR);
    headermsgarr.push('56=' + msg['56'] , SOHCHAR);
    headermsgarr.push('34=' + msg['34'] , SOHCHAR);

    for (var tag in msg) {
        if (msg.hasOwnProperty(tag)
            && tag !== 8
            && tag !== 9
            && tag !== 10
            && tag !== 52
            && tag !== 49
            && tag !== 56
            && tag !== 34
            ) bodymsgarr.push(tag, '=' , msg[tag] , SOHCHAR);
    }

    var headermsg = headermsgarr.join('');
    var trailermsg = trailermsgarr.join('');
    var bodymsg = bodymsgarr.join('');

    var outmsgarr = [];
    outmsgarr.push('8=' , msg['8'] , SOHCHAR);
    outmsgarr.push('9=' , (headermsg.length + bodymsg.length + trailermsg.length) , SOHCHAR);
    outmsgarr.push(headermsg);
    outmsgarr.push(bodymsg);
    outmsgarr.push(trailermsg);

    var outmsg = outmsgarr.join('');

    outmsg += '10=' + checksum(outmsg) + SOHCHAR;

    return outmsg;

}

function checksum(str) {
    var chksm = 0;
    for (var i = 0; i < str.length; i++) {
        chksm += str.charCodeAt(i);
    }

    chksm = chksm % 256;

    var checksumstr = '';
    if (chksm < 10) {
        checksumstr = '00' + (chksm + '');
    }
    else if (chksm >= 10 && chksm < 100) {
        checksumstr = '0' + (chksm + '');
    }
    else {
        checksumstr = '' + (chksm + '');
    }

    return checksumstr;
}

function getUTCTimeStamp(datetime) {
    var timestamp = datetime || new Date();

    var year = timestamp.getUTCFullYear();
    var month = timestamp.getUTCMonth();
    var day = timestamp.getUTCDate();
    var hours = timestamp.getUTCHours();
    var minutes = timestamp.getUTCMinutes();
    var seconds = timestamp.getUTCSeconds();
    var millis = timestamp.getUTCMilliseconds();

    if (month < 10) { month = '0' + month;}

    if (day < 10) { day = '0' + day;}

    if (hours < 10) { hours = '0' + hours;}

    if (minutes < 10) { minutes = '0' + minutes;}

    if (seconds < 10) { seconds = '0' + seconds;}

    if (millis < 10) {
        millis = '00' + millis;
    } else if (millis < 100) {
        millis = '0' + millis;
    }

    var ts = [year, month, day, '-' , hours, ':' , minutes, ':' , seconds, '.' , millis].join('');

    return ts;
}
<commit_msg>cleans up some more logon logic<commit_after>exports.newlogonProcessorAcceptor = function() {
    return new logonProcessorAcceptor();
};

var path = require('path');
var fs = require('fs');
var sys = require('sys');

//static vars
var SOHCHAR = String.fromCharCode(1);

function logonProcessorAcceptor(){

    var self = this;

    //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||INCOMING
    this.incoming = function(ctx, event){

        if(event.type !== 'data'){
            ctx.sendNext(event);
            return;
        }

        //====================================Step 3: Convert to map====================================
        var raw = event.data;
        var fix = convertToMap(raw);

        //====================================Step 4: Create Data Store==========================
        var msgType = fix['35'];

        if(ctx.state.session['isLoggedIn'] === false && msgType !== 'A'){
            var error = '[ERROR] First message must be logon:'+JSON.stringify(fix);
            sys.log(error);
            ctx.stream.end();
            ctx.sendNext({data:error, type:'error'});
            return;
        }
        else if(ctx.state.session['isLoggedIn'] === false && msgType === 'A'){
            var fixVersion = fix['8'];
            var senderCompID = fix['56'];
            var targetCompID = fix['49'];

            var incomingSeqNum = 1;
            var outgoingSeqNum = 1;

            var heartbeatInMilliSeconds = fix[108] || '30';

            ctx.state.session['fixVersion'] = fixVersion;
            ctx.state.session['senderCompID'] = senderCompID;
            ctx.state.session['targetCompID'] = targetCompID;
            ctx.state.session['incomingSeqNum'] = incomingSeqNum;
            ctx.state.session['outgoingSeqNum'] = outgoingSeqNum;
            ctx.state.session['heartbeatDuration'] = parseInt(heartbeatInMilliSeconds,10) * 1000;
            ctx.state.session['timeOfLastIncoming'] = new Date().getTime();

            var fileName = './traffic/' + fixVersion + '-' + senderCompID + '-' + targetCompID + '.log';
            sys.log('Attempting to read file '+fileName);

            ctx.state.fileStream = fs.createWriteStream(fileName, {'flags':'a'});
            fs.readFile(fileName, encoding='ascii', function(err,data){
                if(err){
                    //console.log('debug: file doesnt exist, but must due to createWriteStream call');
                    //console.log('debug actual error:'+err);
                }
                else{
                    var transactions = data.split('\n');
                    for(var i=0; i<transactions.length; i++){
                        var tmap = convertToMap(transactions[i]);

                        if(tmap[49] === senderCompID){ //If msg senderCompID matches our senderCompID, then it is outgoing msg
                            outgoingSeqNum = parseInt(tmap[34],10) +1;
                            ctx.sendPrev({data:tmap, type:'resync'});
                        }
                        if(tmap[49] === targetCompID){ //incoming msg
                            incomingSeqNum = parseInt(tmap[34],10) +1;
                            ctx.sendNext({data:tmap, type:'resync'});
                        }
                    }

                    ctx.state.session.incomingSeqNum = incomingSeqNum;
                    ctx.state.session.outgoingSeqNum = outgoingSeqNum;

                }

                ctx.state.session['isLoggedIn'] = true;

                ctx.state.fileStream.write(raw + '\n');
                ctx.sendNext({data:fix, type:'data'});
            });
        }
        else{ // if isLoggedIn === true and mstType === anything
            ctx.state.session.timeOfLastIncoming = new Date().getTime();
            ctx.state.fileStream.write(raw + '\n');
            ctx.sendNext({data:fix, type:'data'});
        }
    }

    //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||OUTGOING
    this.outgoing = function(ctx, event){

        if(event.type !== 'data'){
            ctx.sendNext(event);
            return;
        }

        var fix = event.data;

        var outmsg = convertToFIX(fix,ctx.state.session.fixVersion,
            getUTCTimeStamp(new Date()),
            ctx.state.session.senderCompID,
            ctx.state.session.targetCompID,
            ctx.state.session.outgoingSeqNum);

        ctx.state.session.outgoingSeqNum ++;

        ctx.state.session.timeOfLastOutgoing = new Date().getTime();
        ctx.state.fileStream.write(outmsg+'\n');
        ctx.sendNext({data:outmsg, type:'data'});
    }
}

function convertToMap(msg) {
    var fix = {};
    var keyvals = msg.split(SOHCHAR);
    for (var kv in Object.keys(keyvals)) {
        var kvpair = keyvals[kv].split('=');
        fix[kvpair[0]] = kvpair[1];
    }
    return fix;

}

function convertToFIX(msgraw, fixVersion, timeStamp, senderCompID, targetCompID, outgoingSeqNum){
    //sys.log('c2F:'+JSON.stringify(msgraw));
    //defensive copy
    var msg = {};
    for (var tag in msgraw) {
        if (msgraw.hasOwnProperty(tag)) msg[tag] = msgraw[tag];
    }

    delete msg['9']; //bodylength
    delete msg['10']; //checksum

    var timestamp = new Date();
    var headermsgarr = [];
    var bodymsgarr = [];
    var trailermsgarr = [];

    msg['8'] = fixVersion; //fixversion
    msg['52'] = timeStamp; //timestamp
    msg['49'] = senderCompID; //sendercompid
    msg['56'] = targetCompID; //targetcompid
    msg['34'] = outgoingSeqNum; //seqnum

    headermsgarr.push('52=' + msg['52'] , SOHCHAR);
    headermsgarr.push('49=' + msg['49'] , SOHCHAR);
    headermsgarr.push('56=' + msg['56'] , SOHCHAR);
    headermsgarr.push('34=' + msg['34'] , SOHCHAR);

    for (var tag in msg) {
        if (msg.hasOwnProperty(tag)
            && tag !== 8
            && tag !== 9
            && tag !== 10
            && tag !== 52
            && tag !== 49
            && tag !== 56
            && tag !== 34
            ) bodymsgarr.push(tag, '=' , msg[tag] , SOHCHAR);
    }

    var headermsg = headermsgarr.join('');
    var trailermsg = trailermsgarr.join('');
    var bodymsg = bodymsgarr.join('');

    var outmsgarr = [];
    outmsgarr.push('8=' , msg['8'] , SOHCHAR);
    outmsgarr.push('9=' , (headermsg.length + bodymsg.length + trailermsg.length) , SOHCHAR);
    outmsgarr.push(headermsg);
    outmsgarr.push(bodymsg);
    outmsgarr.push(trailermsg);

    var outmsg = outmsgarr.join('');

    outmsg += '10=' + checksum(outmsg) + SOHCHAR;

    return outmsg;

}

function checksum(str) {
    var chksm = 0;
    for (var i = 0; i < str.length; i++) {
        chksm += str.charCodeAt(i);
    }

    chksm = chksm % 256;

    var checksumstr = '';
    if (chksm < 10) {
        checksumstr = '00' + (chksm + '');
    }
    else if (chksm >= 10 && chksm < 100) {
        checksumstr = '0' + (chksm + '');
    }
    else {
        checksumstr = '' + (chksm + '');
    }

    return checksumstr;
}

function getUTCTimeStamp(datetime) {
    var timestamp = datetime || new Date();

    var year = timestamp.getUTCFullYear();
    var month = timestamp.getUTCMonth();
    var day = timestamp.getUTCDate();
    var hours = timestamp.getUTCHours();
    var minutes = timestamp.getUTCMinutes();
    var seconds = timestamp.getUTCSeconds();
    var millis = timestamp.getUTCMilliseconds();

    if (month < 10) { month = '0' + month;}

    if (day < 10) { day = '0' + day;}

    if (hours < 10) { hours = '0' + hours;}

    if (minutes < 10) { minutes = '0' + minutes;}

    if (seconds < 10) { seconds = '0' + seconds;}

    if (millis < 10) {
        millis = '00' + millis;
    } else if (millis < 100) {
        millis = '0' + millis;
    }

    var ts = [year, month, day, '-' , hours, ':' , minutes, ':' , seconds, '.' , millis].join('');

    return ts;
}
<|endoftext|>


<commit_before>(function () {
  const darkSwitch = document.getElementById('darkSwitch');

  const turnOnDarkMode = (save) => {
    document.body.setAttribute('data-theme', 'dark');
    darkSwitch.classList.add('darkModeOn');
    darkSwitch.setAttribute('title', 'Turn off dark mode');
    if (save) localStorage.setItem('darkSwitch', 'on');
  };

  const turnOffDarkMode = (save) => {
    document.body.removeAttribute('data-theme');
    darkSwitch.classList.remove('darkModeOn');
    darkSwitch.setAttribute('title', 'Turn on dark mode');
    if (save) localStorage.setItem('darkSwitch', 'off');
  };

  const init = () => {
    // 1. check app setting
    if (
      localStorage.getItem('darkSwitch') !== null &&
      localStorage.getItem('darkSwitch') === 'on'
    ) {
      turnOnDarkMode(false);
    }
    // 2. check system setting
    else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
      turnOnDarkMode(false);
    } else {
      turnOffDarkMode(false);
    }
    document.body.style.visibility = 'visible';
    document.body.style.opacity = 1;
  };

  const toggle = () =>
    darkSwitch.classList.contains('darkModeOn')
      ? turnOffDarkMode(true)
      : turnOnDarkMode(true);

  window.addEventListener('load', function () {
    if (darkSwitch) {
      init();
      darkSwitch.addEventListener('click', function () {
        toggle();
      });
    }
  });
})();
<commit_msg>Dark mode bug fix for when system setting is dark<commit_after>(function () {
  const darkSwitch = document.getElementById('darkSwitch');

  const turnOnDarkMode = (save) => {
    document.body.setAttribute('data-theme', 'dark');
    darkSwitch.classList.add('darkModeOn');
    darkSwitch.setAttribute('title', 'Turn off dark mode');
    if (save) localStorage.setItem('darkSwitch', 'on');
  };

  const turnOffDarkMode = (save) => {
    document.body.removeAttribute('data-theme');
    darkSwitch.classList.remove('darkModeOn');
    darkSwitch.setAttribute('title', 'Turn on dark mode');
    if (save) localStorage.setItem('darkSwitch', 'off');
  };

  const init = () => {
    // 1. check app setting
    if (localStorage.getItem('darkSwitch') !== null) {
      if (localStorage.getItem('darkSwitch') === 'on') {
        turnOnDarkMode(false);
      } else {
        turnOffDarkMode(false);
      }
    }
    // 2. check system setting
    else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
      turnOnDarkMode(false);
    } else {
      turnOffDarkMode(false);
    }
    document.body.style.visibility = 'visible';
    document.body.style.opacity = 1;
  };

  const toggle = () =>
    darkSwitch.classList.contains('darkModeOn')
      ? turnOffDarkMode(true)
      : turnOnDarkMode(true);

  window.addEventListener('load', function () {
    if (darkSwitch) {
      init();
      darkSwitch.addEventListener('click', function () {
        toggle();
      });
    }
  });
})();
<|endoftext|>


<commit_before>$(document).ready(function() {
    $("#filterBuilderButton").click(function() {
        var boxName = "#filterBox" + $("#filterBuilderSelect").val();
        $(boxName).slideDown();
        return false;
    });
    $(".filterBuilderRemove").click(function() {
        var boxName = "#" + $(this).parents(".filterBox").attr('id');
        $(boxName).slideUp();
        $(boxName).children("input:text").each(function() {
            $(this).val("");
        });
        $(boxName).children("input:checkbox").each(function() {
            this.checked = false;
        });
        $(boxName).children("select").each(function() {
            this.selectedIndex = -1;
        });

        var selectId = $(this).parents(".filterBox").attr('id');
        var attr = selectId.replace("filterBox", "");
        $("#filterBuilderSelect-" + attr)[0].disabled = "";

        return false;
    });
});

/**
 * Called, when filterBuilderSelect input changed - will make input div appear
 * to the user. Also disable this option in the Add filter menu
 *
 * @param {string} val name of selected filter value
 */
var onFilterChange = function(val) {
  if (val) {
    var boxName = "#filterBox" + val;
    $(boxName).slideDown();
    $(boxName)[0].style.display="block";

    $("#filterBuilderSelect-" + val)[0].disabled = "disabled";
  }
};
<commit_msg>Fix the filterBuilderRemove and update var keyword to let or const<commit_after>$(document).ready(function() {
    $("#filterBuilderButton").click(function() {
        const boxName = "#filterBox" + $("#filterBuilderSelect").val();
        $(boxName).slideDown();
        return false;
    });
    $(".filterBuilderRemove").click(function() {
        const boxName = "#" + $(this).parents(".filterBox").attr('id');
        $(boxName).slideUp();
        $(boxName).find("input:text").each(function() {
            $(this).val("");
        });
        $(boxName).find("input:checkbox").each(function() {
            this.checked = false;
        });
        $(boxName).find("select").each(function() {
            this.selectedIndex = -1;
        });

        let selectId = $(this).parents(".filterBox").attr('id');
        const attr = selectId.replace("filterBox", "");
        $("#filterBuilderSelect-" + attr)[0].disabled = "";

        return false;
    });
});

/**
 * Called, when filterBuilderSelect input changed - will make input div appear
 * to the user. Also disable this option in the Add filter menu
 *
 * @param {string} val name of selected filter value
 */
const onFilterChange = function(val) {
  if (val) {
    const boxName = "#filterBox" + val;
    $(boxName).slideDown();
    $(boxName)[0].style.display="block";

    $("#filterBuilderSelect-" + val)[0].disabled = "disabled";
  }
};
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var _ = require('lodash');
var util = require('util');

/**
 *
 * @param  {[type]} scope [description]
 * @return {[type]}       [description]
 */
module.exports = function dataForPackageJSON(scope) {

  var sailsPkg = scope.sailsPackageJSON || {};

  // To determine the sails dep. to inject in the newly created package.json,
  // use `sails.prerelease` specified in the package.json of Sails itself.
  // If a `prerelease` version no. is not specified, just use `version`
  var sailsVersionDependency = (sailsPkg.sails && sailsPkg.sails.prerelease) || ('~' + sailsPkg.version);

  // List default dependencies used for apps with a frontend
  var dependenciesFrontAndBackend = {
    'ejs': getDependencyVersion(sailsPkg, 'ejs'),
    'grunt': getDependencyVersion(sailsPkg, 'grunt'),
    'grunt-contrib-clean': getDependencyVersion(sailsPkg, 'grunt-contrib-clean'),
    'grunt-contrib-coffee': getDependencyVersion(sailsPkg, 'grunt-contrib-coffee'),
    'grunt-contrib-concat': getDependencyVersion(sailsPkg, 'grunt-contrib-concat'),
    'grunt-contrib-copy': getDependencyVersion(sailsPkg, 'grunt-contrib-copy'),
    'grunt-contrib-cssmin': getDependencyVersion(sailsPkg, 'grunt-contrib-cssmin'),
    'grunt-contrib-jst': getDependencyVersion(sailsPkg, 'grunt-contrib-jst'),
    'grunt-contrib-less': getDependencyVersion(sailsPkg, 'grunt-contrib-less'),
    'grunt-contrib-uglify': getDependencyVersion(sailsPkg, 'grunt-contrib-uglify'),
    'grunt-contrib-watch': getDependencyVersion(sailsPkg, 'grunt-contrib-watch'),
    'grunt-sails-linker': getDependencyVersion(sailsPkg, 'grunt-sails-linker'),
    'grunt-sync': getDependencyVersion(sailsPkg, 'grunt-sync'),
    'include-all': getDependencyVersion(sailsPkg, 'include-all'),
    'rc': getDependencyVersion(sailsPkg, 'rc'),
    'sails': sailsVersionDependency,
    'sails-disk': getDependencyVersion(sailsPkg, 'sails-disk')
  };

  // List default dependencies used for back-end only apps (--no-frontend)
  var dependenciesBackendOnly = {
    'include-all': getDependencyVersion(sailsPkg, 'include-all'),
    'rc': getDependencyVersion(sailsPkg, 'rc'),
    'sails': sailsVersionDependency,
    'sails-disk': getDependencyVersion(sailsPkg, 'sails-disk')
  };

  // Creating default package.json file content
  var defaultPackageJSONContent = {
    name: scope.appName,
    private: true,
    version: '0.0.0',
    description: 'a Sails application',
    keywords: [],
    dependencies: (scope['frontend'] === false) ? dependenciesBackendOnly : dependenciesFrontAndBackend,
    scripts: {
      debug: 'node debug app.js',
      start: 'node app.js'
    },
    main: 'app.js',
    repository: {
      type: 'git',
      url: util.format('git://github.com/%s/%s.git', scope.github.username, scope.appName)
    },
    author: scope.author || '',
    license: ''
  };

  //
  // Check for `packageJson` configuration
  //

  if (scope.packageJson && _.isObject(scope.packageJson)) {
    //
    // Adding new dependencies to package.json
    //
    _.merge(defaultPackageJSONContent, (scope.packageJson || {}));

    //
    // Remove dependencies that has false as version
    // If somebody don't need dependency it could be removed using passing to scope:
    //
    // ```
    // packageJson: {
    //    dependencies: {
    //      ejs: false
    //    }
    // }
    // ```
    //
    if (scope.packageJson.dependencies) {
      defaultPackageJSONContent.dependencies = _.omit(defaultPackageJSONContent.dependencies, function(value) {
        return value === false;
      });
    }
  }

  return _.defaults(scope.appPackageJSON || {}, defaultPackageJSONContent);
};

/**
 * getDependencyVersion
 *
 * @param  {Object} packageJSON
 * @param  {String} module
 * @return {String}
 * @api private
 */

function getDependencyVersion(packageJSON, module) {
  return (
    packageJSON.dependencies && packageJSON.dependencies[module] ||
    packageJSON.devDependencies && packageJSON.devDependencies[module] ||
    packageJSON.optionalDependencies && packageJSON.optionalDependencies[module]
  );
}
<commit_msg>Allow description to be passed in as scope value<commit_after>/**
 * Module dependencies
 */

var _ = require('lodash');
var util = require('util');

/**
 *
 * @param  {[type]} scope [description]
 * @return {[type]}       [description]
 */
module.exports = function dataForPackageJSON(scope) {

  var sailsPkg = scope.sailsPackageJSON || {};

  // To determine the sails dep. to inject in the newly created package.json,
  // use `sails.prerelease` specified in the package.json of Sails itself.
  // If a `prerelease` version no. is not specified, just use `version`
  var sailsVersionDependency = (sailsPkg.sails && sailsPkg.sails.prerelease) || ('~' + sailsPkg.version);

  // List default dependencies used for apps with a frontend
  var dependenciesFrontAndBackend = {
    'ejs': getDependencyVersion(sailsPkg, 'ejs'),
    'grunt': getDependencyVersion(sailsPkg, 'grunt'),
    'grunt-contrib-clean': getDependencyVersion(sailsPkg, 'grunt-contrib-clean'),
    'grunt-contrib-coffee': getDependencyVersion(sailsPkg, 'grunt-contrib-coffee'),
    'grunt-contrib-concat': getDependencyVersion(sailsPkg, 'grunt-contrib-concat'),
    'grunt-contrib-copy': getDependencyVersion(sailsPkg, 'grunt-contrib-copy'),
    'grunt-contrib-cssmin': getDependencyVersion(sailsPkg, 'grunt-contrib-cssmin'),
    'grunt-contrib-jst': getDependencyVersion(sailsPkg, 'grunt-contrib-jst'),
    'grunt-contrib-less': getDependencyVersion(sailsPkg, 'grunt-contrib-less'),
    'grunt-contrib-uglify': getDependencyVersion(sailsPkg, 'grunt-contrib-uglify'),
    'grunt-contrib-watch': getDependencyVersion(sailsPkg, 'grunt-contrib-watch'),
    'grunt-sails-linker': getDependencyVersion(sailsPkg, 'grunt-sails-linker'),
    'grunt-sync': getDependencyVersion(sailsPkg, 'grunt-sync'),
    'include-all': getDependencyVersion(sailsPkg, 'include-all'),
    'rc': getDependencyVersion(sailsPkg, 'rc'),
    'sails': sailsVersionDependency,
    'sails-disk': getDependencyVersion(sailsPkg, 'sails-disk')
  };

  // List default dependencies used for back-end only apps (--no-frontend)
  var dependenciesBackendOnly = {
    'include-all': getDependencyVersion(sailsPkg, 'include-all'),
    'rc': getDependencyVersion(sailsPkg, 'rc'),
    'sails': sailsVersionDependency,
    'sails-disk': getDependencyVersion(sailsPkg, 'sails-disk')
  };

  // Creating default package.json file content
  var defaultPackageJSONContent = {
    name: scope.appName,
    private: true,
    version: '0.0.0',
    description: scope.description || 'a Sails application',
    keywords: [],
    dependencies: (scope['frontend'] === false) ? dependenciesBackendOnly : dependenciesFrontAndBackend,
    scripts: {
      debug: 'node debug app.js',
      start: 'node app.js'
    },
    main: 'app.js',
    repository: {
      type: 'git',
      url: util.format('git://github.com/%s/%s.git', scope.github.username, scope.appName)
    },
    author: scope.author || '',
    license: ''
  };

  //
  // Check for `packageJson` configuration
  //

  if (scope.packageJson && _.isObject(scope.packageJson)) {
    //
    // Adding new dependencies to package.json
    //
    _.merge(defaultPackageJSONContent, (scope.packageJson || {}));

    //
    // Remove dependencies that has false as version
    // If somebody don't need dependency it could be removed using passing to scope:
    //
    // ```
    // packageJson: {
    //    dependencies: {
    //      ejs: false
    //    }
    // }
    // ```
    //
    if (scope.packageJson.dependencies) {
      defaultPackageJSONContent.dependencies = _.omit(defaultPackageJSONContent.dependencies, function(value) {
        return value === false;
      });
    }
  }

  return _.defaults(scope.appPackageJSON || {}, defaultPackageJSONContent);
};

/**
 * getDependencyVersion
 *
 * @param  {Object} packageJSON
 * @param  {String} module
 * @return {String}
 * @api private
 */

function getDependencyVersion(packageJSON, module) {
  return (
    packageJSON.dependencies && packageJSON.dependencies[module] ||
    packageJSON.devDependencies && packageJSON.devDependencies[module] ||
    packageJSON.optionalDependencies && packageJSON.optionalDependencies[module]
  );
}
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var _ = require('lodash');
var util = require('util');

/**
 *
 * @param  {[type]} scope [description]
 * @return {[type]}       [description]
 */
module.exports = function dataForPackageJSON(scope) {

  var sailsPkg = scope.sailsPackageJSON || {};

  // To determine the sails dep. to inject in the newly created package.json,
  // use `sails.prerelease` specified in the package.json of Sails itself.
  // If a `prerelease` version no. is not specified, just use `version`
  var sailsVersionDependency = (sailsPkg.sails && sailsPkg.sails.prerelease) || ('~' + sailsPkg.version);

  // Creating default package.json file content
	var defaultPackageJSONContent = {
		name: scope.appName,
		private: true,
		version: '0.0.0',
		description: 'a Sails application',
		keywords: [],
		dependencies: {
			'ejs': getDependencyVersion(sailsPkg, 'ejs'),
			'grunt': getDependencyVersion(sailsPkg, 'grunt'),
			'grunt-contrib-clean': getDependencyVersion(sailsPkg, 'grunt-contrib-clean'),
			'grunt-contrib-coffee': getDependencyVersion(sailsPkg, 'grunt-contrib-coffee'),
			'grunt-contrib-concat': getDependencyVersion(sailsPkg, 'grunt-contrib-concat'),
			'grunt-contrib-copy': getDependencyVersion(sailsPkg, 'grunt-contrib-copy'),
			'grunt-contrib-cssmin': getDependencyVersion(sailsPkg, 'grunt-contrib-cssmin'),
			'grunt-contrib-jst': getDependencyVersion(sailsPkg, 'grunt-contrib-jst'),
			'grunt-contrib-less': getDependencyVersion(sailsPkg, 'grunt-contrib-less'),
			'grunt-contrib-uglify': getDependencyVersion(sailsPkg, 'grunt-contrib-uglify'),
			'grunt-contrib-watch': getDependencyVersion(sailsPkg, 'grunt-contrib-watch'),
			'grunt-sails-linker': getDependencyVersion(sailsPkg, 'grunt-sails-linker'),
			'grunt-sync': getDependencyVersion(sailsPkg, 'grunt-sync'),
			'include-all': getDependencyVersion(sailsPkg, 'include-all'),
			'rc': getDependencyVersion(sailsPkg, 'rc'),
			'sails': sailsVersionDependency,
			'sails-disk': getDependencyVersion(sailsPkg, 'sails-disk')
		},
		scripts: {
			debug: 'node debug app.js',
			start: 'node app.js'
		},
		main: 'app.js',
		repository: {
			type: 'git',
			url: util.format('git://github.com/%s/%s.git', scope.github.username, scope.appName)
		},
		author: scope.author || '',
		license: ''
	};

  //
  // Check for `packageJson` configuration
  //

  if (scope.packageJson && _.isObject(scope.packageJson)) {
    //
    // Adding new dependencies to package.json
    //
    _.merge(defaultPackageJSONContent, (scope.packageJson || {}));

    //
    // Remove dependencies that has false as version
    // If somebody don't need dependency it could be removed using passing to scope:
    //
    // ```
    // packageJson: {
    // 		dependencies: {
    // 			ejs: false
    // 		}
    // }
    // ```
    //
    if (scope.packageJson.dependencies) {
      _.omit(defaultPackageJSONContent.dependencies, function(value) {
        return value === false;
      });
    }
  }

  return _.defaults(scope.appPackageJSON || {}, defaultPackageJSONContent);
};

/**
 * getDependencyVersion
 *
 * @param  {Object} packageJSON
 * @param  {String} module
 * @return {String}
 * @api private
 */

function getDependencyVersion(packageJSON, module) {
  return (
    packageJSON.dependencies && packageJSON.dependencies[module] ||
    packageJSON.devDependencies && packageJSON.devDependencies[module] ||
    packageJSON.optionalDependencies && packageJSON.optionalDependencies[module]
  );
}
<commit_msg>change tabs to spaces<commit_after>/**
 * Module dependencies
 */

var _ = require('lodash');
var util = require('util');

/**
 *
 * @param  {[type]} scope [description]
 * @return {[type]}       [description]
 */
module.exports = function dataForPackageJSON(scope) {

  var sailsPkg = scope.sailsPackageJSON || {};

  // To determine the sails dep. to inject in the newly created package.json,
  // use `sails.prerelease` specified in the package.json of Sails itself.
  // If a `prerelease` version no. is not specified, just use `version`
  var sailsVersionDependency = (sailsPkg.sails && sailsPkg.sails.prerelease) || ('~' + sailsPkg.version);

  // Creating default package.json file content
  var defaultPackageJSONContent = {
    name: scope.appName,
    private: true,
    version: '0.0.0',
    description: 'a Sails application',
    keywords: [],
    dependencies: {
      'ejs': getDependencyVersion(sailsPkg, 'ejs'),
      'grunt': getDependencyVersion(sailsPkg, 'grunt'),
      'grunt-contrib-clean': getDependencyVersion(sailsPkg, 'grunt-contrib-clean'),
      'grunt-contrib-coffee': getDependencyVersion(sailsPkg, 'grunt-contrib-coffee'),
      'grunt-contrib-concat': getDependencyVersion(sailsPkg, 'grunt-contrib-concat'),
      'grunt-contrib-copy': getDependencyVersion(sailsPkg, 'grunt-contrib-copy'),
      'grunt-contrib-cssmin': getDependencyVersion(sailsPkg, 'grunt-contrib-cssmin'),
      'grunt-contrib-jst': getDependencyVersion(sailsPkg, 'grunt-contrib-jst'),
      'grunt-contrib-less': getDependencyVersion(sailsPkg, 'grunt-contrib-less'),
      'grunt-contrib-uglify': getDependencyVersion(sailsPkg, 'grunt-contrib-uglify'),
      'grunt-contrib-watch': getDependencyVersion(sailsPkg, 'grunt-contrib-watch'),
      'grunt-sails-linker': getDependencyVersion(sailsPkg, 'grunt-sails-linker'),
      'grunt-sync': getDependencyVersion(sailsPkg, 'grunt-sync'),
      'include-all': getDependencyVersion(sailsPkg, 'include-all'),
      'rc': getDependencyVersion(sailsPkg, 'rc'),
      'sails': sailsVersionDependency,
      'sails-disk': getDependencyVersion(sailsPkg, 'sails-disk')
    },
    scripts: {
      debug: 'node debug app.js',
      start: 'node app.js'
    },
    main: 'app.js',
    repository: {
      type: 'git',
      url: util.format('git://github.com/%s/%s.git', scope.github.username, scope.appName)
    },
    author: scope.author || '',
    license: ''
  };

  //
  // Check for `packageJson` configuration
  //

  if (scope.packageJson && _.isObject(scope.packageJson)) {
    //
    // Adding new dependencies to package.json
    //
    _.merge(defaultPackageJSONContent, (scope.packageJson || {}));

    //
    // Remove dependencies that has false as version
    // If somebody don't need dependency it could be removed using passing to scope:
    //
    // ```
    // packageJson: {
    // 		dependencies: {
    // 			ejs: false
    // 		}
    // }
    // ```
    //
    if (scope.packageJson.dependencies) {
      _.omit(defaultPackageJSONContent.dependencies, function(value) {
        return value === false;
      });
    }
  }

  return _.defaults(scope.appPackageJSON || {}, defaultPackageJSONContent);
};

/**
 * getDependencyVersion
 *
 * @param  {Object} packageJSON
 * @param  {String} module
 * @return {String}
 * @api private
 */

function getDependencyVersion(packageJSON, module) {
  return (
    packageJSON.dependencies && packageJSON.dependencies[module] ||
    packageJSON.devDependencies && packageJSON.devDependencies[module] ||
    packageJSON.optionalDependencies && packageJSON.optionalDependencies[module]
  );
}
<|endoftext|>


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

var _self = {},
    _ID = "com.blackberry.community.nowplaying",
    exec = cordova.require("cordova/exec"),
    playbackRequested = false;

    /**
     * NowPlayingRequestPlayback
     * Set up the app for playing music and bind methods that callback to the app.
     *
     * @param input: a json object with methods that callback to the app.
     * The callback methods that must be specified are:
     * - play: Fired when the track is played.
     * - pause: Fired when the track is paused.
     * - stop: Fired when the track is stopped.
     * - next: Fired when the next track is invoked. Callback must invoke com.blackberry.community.nowplaying.play()
     *         with arguments for the next track.
     * - previous: Fired when the previous track is invoked. Callback must invoke com.blackberry.community.nowplaying.play()
     *             with arguments for the previous track.
     * - error: Fired when an internal error occurs.
     * @returns String: whether playback was requested (set up) successfully.
     */
	_self.NowPlayingRequestPlayback = function(input) {

        // TODO: verify json input.

        /* Bind callbacks */
        if (!playbackRequested) {
            var valid = _self.NowPlayingValidateCallback(input);

            if(valid){
                _self.NowPlayingBindPlayCallback(input.play);
                _self.NowPlayingBindPauseCallback(input.pause);
                _self.NowPlayingBindStopCallback(input.stop);
                _self.NowPlayingBindNextCallback(input.next);
                _self.NowPlayingBindPreviousCallback(input.previous);
                _self.NowPlayingBindErrorCallback(input.error);

                var result,
                success = function (data, response) {
                    result = data;
                    playbackRequested = true;
                },
                fail = function (data, response) {
                    console.log("Error: " + data);
                };
                exec(success, fail, _ID, "NowPlayingRequestPlayback");
                return result;
            } else {
                // passes response into error callback
                return "Playback input was not valid";
            }

        } else {
          return "Playback already requested.";
        }
	};

    _self.NowPlayingBindPlayCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindPlayCallback", null);
    };

    _self.NowPlayingBindPauseCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindPauseCallback", null);
    };

    _self.NowPlayingBindStopCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindStopCallback", null);
    };

    _self.NowPlayingBindNextCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindNextCallback", null);
    };

    _self.NowPlayingBindPreviousCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindPreviousCallback", null);
    };

    _self.NowPlayingBindErrorCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindErrorCallback", null);
    };

    /**
     * NowPlayingPlay
     * Play a specified music in the background.
     * Executes the callback method given to NowPlayingRequestPlayback.
     *
     * @param input: a json object with music details.
     * The details that must be specified are:
     * - trackURL: URL of the track to play.
     * - iconURL: URL of the icon to display on the volume overlay.
     * - metadata: a json object with metadata details to display on the volume overlay.
     *             Can include title, artist,
     * - nextEnabled: boolean used to set whether or not the Next button should be
     *                enabled on the volume overlay.
     * - previousEnabled: boolean used to set whether or not the Previous button should be
     *                    enabled on the volume overlay.
     * @returns String: whether the music played successfully.
     */
	_self.NowPlayingPlay = function (input) {

        // TODO: verify json input.
        var validInput = _self.NowPlayingValidatePlayInput(input);
        if(validInput) {
            var result,
    			success = function (data, response) {
    				result = data;
    			},
    			fail = function (data, response) {
    				console.log("Error: " + data);
    			};
    		exec(success, fail, _ID, "NowPlayingPlay", { input: input });
    		return result;
        } else {
            return "Play input was not valid";
        }

	};

    /**
     * NowPlayingPause
     * Pause the music if there is any in the background.
     * Executes the callback method given to NowPlayingRequestPlayback.
     *
     * @returns String: whether the music paused successfully.
     */
	_self.NowPlayingPause = function () {
			var result;
            success = function (data, response) {
				result = data;
			},
			fail = function (data, response) {
				console.log("Error: " + data);
			};
		exec(success, fail, _ID, "NowPlayingPause", null);
        return result;
	};

    /**
     * NowPlayingResume
     * Resume the paused music if there is any in the background.
     * Executes the callback method given to NowPlayingRequestPlayback.
     *
     * @returns String: whether the music resumed successfully.
     */
    _self.NowPlayingResume = function () {
        var result,
            success = function (data, response) {
                result = data;
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingResume", null);
        return result;
    };

    /**
     * NowPlayingStop
     * Stop the music if there is any in the background.
     * Executes the callback method given to NowPlayingRequestPlayback.
     *
     * @returns String: whether the music stopped successfully.
     */
    _self.NowPlayingStop = function () {
		var result,
			success = function (data, response) {
				result = data;
			},
			fail = function (data, response) {
				console.log("Error: " + data);
			};
        exec(success, fail, _ID, "NowPlayingStop", null);
		return result;
	};

    /**
     * NowPlayingNext
     * Play the next track according to the callback method given to
     * NowPlayingRequestPlayback.
     *
     * @returns String: whether the music was changed to next one successfully.
     */
    _self.NowPlayingNext = function () {
        var result,
            success = function (data, response) {
                result = data;
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingNext", null);
        return result;
    };

    /**
     * NowPlayingPrevious
     * Play the previous track according to the callback method given to
     * NowPlayingRequestPlayback.
     *
     * @returns String: whether the music was changed to previous one successfully.
     */
    _self.NowPlayingPrevious = function () {
        var result,
            success = function (data, response) {
                result = data;
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingPrevious", null);
        return result;
    };

    /**
     * NowPlayingError
     * Fire the error callback method given to NowPlayingRequestPlayback.
     * For debugging purposes only.
     *
     * @returns String: error information
     */
    _self.NowPlayingError = function () {
        var result,
            success = function (data, response) {
                result = data;
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingError", null);
        return result;
    };

    // Validate play input

    /* We expect the following callbacks to be present:
    play, pause, stop, next, previous, error
    */
    _self.NowPlayingValidateCallback = function(input) {
        var result = "";
        var valid = true;
        if(!('play' in input)) result = "Play callback was not provided";
        if(!('pause' in input)) result = "Pause callback was not provided";
        if(!('stop' in input)) result = "Stop callback was not provided";
        if(!('next' in input)) result = "Next callback was not provided";
        if(!('previous' in input)) result = "Previous callback was not provided";
        if(!('error' in input)) result = "Error callback was not provided";

        if(result !== "") {
            valid = false;
            // send error callback;
        }
        if(valid) {
            valid = _self.NowPlayingValidateCallbackAttributes(input);
        }
        return valid;
    };

    _self.NowPlayingValidateCallbackAttributes = function(input) {
        var result = true;
        if(!(isFunction(input.play))) result = "Play attribute was not a function";
        if(!(isFunction(input.pause))) result = "Pause attribute was not a function";
        if(!(isFunction(input.stop))) result = "Stop attribute was not a function";
        if(!(isFunction(input.next))) result = "Next attribute was not a function";
        if(!(isFunction(input.previous))) result = "Previous attribute was not a function";
        if(!(isFunction(input.error))) result = "Error attribute was not a function";

        if(typeof(result) === "boolean") && result) {
            return true;
        } else {
            // call error and return false
            return false;
        }
    };

    function isFunction(functionToCheck) {
        var getType = {};
        return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    };

    /*
     trackURL: "http://www.pch.gc.ca/DAMAssetPub/DAM-hymChs-antSgn/STAGING/audio-audio/o-canada_1359474460106_eng.MP3",
            iconURL: "img/canadian-flag-small.jpg",
            metadata: {
                Title: "O Canada",
                Artist: "Canada",
                Album: "Canada's Favorites"
            }
    */

    _self.NowPlayingValidatePlayInput = function(input) {
        var response = "";
        if(!('iconURL' in input)) response = "iconURL attribute was not provided";
        if(!('trackURL' in input)) response =  "trackURL attribute was not provided";
        if(('metadata' in input)) {
            // is this necessary or should we only check for trackURL
            if(!('Title' in input.metadata)) response = "Title field in metadata was not provided";
            if(!('Artist') in input.metadata) response = "Artist field in metadata was not provided";
            if(!('Album' in input.metadata)) response = "Album field in metadata was not provided";
        else {
            response = "metadata attribute was not provided";
        }
        var valid = true;
        if(response !=== "") {
            valid = false;
            // throw error
        }

        return valid
    }

    /**
     * NowPlayingGetState
     * Get the state of the music being played.
     * For debugging purposes only.
     *
     * @returns String: containing:
     * - the state of the MediaPlayer,
     * - whether the NowPlayingConnection is acquired,
     * - whether the NowPlayingConnection is preempted.
     */
	_self.NowPlayingGetState = function () {
		var result,
			success = function (data, response) {
				result = data;
			},
			fail = function (data, response) {
				console.log("Error: " + data);
			};
		exec(success, fail, _ID, "NowPlayingGetState", null);
		return result;
	};

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

var _self = {},
    _ID = "com.blackberry.community.nowplaying",
    exec = cordova.require("cordova/exec"),
    playbackRequested = false;

    /**
     * NowPlayingRequestPlayback
     * Set up the app for playing music and bind methods that callback to the app.
     *
     * @param input: a json object with methods that callback to the app.
     * The callback methods that must be specified are:
     * - play: Fired when the track is played.
     * - pause: Fired when the track is paused.
     * - stop: Fired when the track is stopped.
     * - next: Fired when the next track is invoked. Callback must invoke com.blackberry.community.nowplaying.play()
     *         with arguments for the next track.
     * - previous: Fired when the previous track is invoked. Callback must invoke com.blackberry.community.nowplaying.play()
     *             with arguments for the previous track.
     * - error: Fired when an internal error occurs.
     * @returns String: whether playback was requested (set up) successfully.
     */
	_self.NowPlayingRequestPlayback = function(input) {

        // TODO: verify json input.

        /* Bind callbacks */
        if (!playbackRequested) {
            var valid = _self.NowPlayingValidateCallback(input);

            if(valid){
                _self.NowPlayingBindPlayCallback(input.play);
                _self.NowPlayingBindPauseCallback(input.pause);
                _self.NowPlayingBindStopCallback(input.stop);
                _self.NowPlayingBindNextCallback(input.next);
                _self.NowPlayingBindPreviousCallback(input.previous);
                _self.NowPlayingBindErrorCallback(input.error);

                var result,
                success = function (data, response) {
                    result = data;
                    playbackRequested = true;
                },
                fail = function (data, response) {
                    console.log("Error: " + data);
                };
                exec(success, fail, _ID, "NowPlayingRequestPlayback");
                return result;
            } else {
                // passes response into error callback
                return "Playback input was not valid";
            }

        } else {
          return "Playback already requested.";
        }
	};

    _self.NowPlayingBindPlayCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindPlayCallback", null);
    };

    _self.NowPlayingBindPauseCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindPauseCallback", null);
    };

    _self.NowPlayingBindStopCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindStopCallback", null);
    };

    _self.NowPlayingBindNextCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindNextCallback", null);
    };

    _self.NowPlayingBindPreviousCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindPreviousCallback", null);
    };

    _self.NowPlayingBindErrorCallback = function (callback) {
        var success = function (data, response) {
                var json = JSON.parse(data);
                callback(json);
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingBindErrorCallback", null);
    };

    /**
     * NowPlayingPlay
     * Play a specified music in the background.
     * Executes the callback method given to NowPlayingRequestPlayback.
     *
     * @param input: a json object with music details.
     * The details that must be specified are:
     * - trackURL: URL of the track to play.
     * - iconURL: URL of the icon to display on the volume overlay.
     * - metadata: a json object with metadata details to display on the volume overlay.
     *             Can include title, artist,
     * - nextEnabled: boolean used to set whether or not the Next button should be
     *                enabled on the volume overlay.
     * - previousEnabled: boolean used to set whether or not the Previous button should be
     *                    enabled on the volume overlay.
     * @returns String: whether the music played successfully.
     */
	_self.NowPlayingPlay = function (input) {

        // TODO: verify json input.
        var validInput = _self.NowPlayingValidatePlayInput(input);
        if(validInput) {
            var result,
    			success = function (data, response) {
    				result = data;
    			},
    			fail = function (data, response) {
    				console.log("Error: " + data);
    			};
    		exec(success, fail, _ID, "NowPlayingPlay", { input: input });
    		return result;
        } else {
            return "Play input was not valid";
        }

	};

    /**
     * NowPlayingPause
     * Pause the music if there is any in the background.
     * Executes the callback method given to NowPlayingRequestPlayback.
     *
     * @returns String: whether the music paused successfully.
     */
	_self.NowPlayingPause = function () {
			var result;
            success = function (data, response) {
				result = data;
			},
			fail = function (data, response) {
				console.log("Error: " + data);
			};
		exec(success, fail, _ID, "NowPlayingPause", null);
        return result;
	};

    /**
     * NowPlayingResume
     * Resume the paused music if there is any in the background.
     * Executes the callback method given to NowPlayingRequestPlayback.
     *
     * @returns String: whether the music resumed successfully.
     */
    _self.NowPlayingResume = function () {
        var result,
            success = function (data, response) {
                result = data;
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingResume", null);
        return result;
    };

    /**
     * NowPlayingStop
     * Stop the music if there is any in the background.
     * Executes the callback method given to NowPlayingRequestPlayback.
     *
     * @returns String: whether the music stopped successfully.
     */
    _self.NowPlayingStop = function () {
		var result,
			success = function (data, response) {
				result = data;
			},
			fail = function (data, response) {
				console.log("Error: " + data);
			};
        exec(success, fail, _ID, "NowPlayingStop", null);
		return result;
	};

    /**
     * NowPlayingNext
     * Play the next track according to the callback method given to
     * NowPlayingRequestPlayback.
     *
     * @returns String: whether the music was changed to next one successfully.
     */
    _self.NowPlayingNext = function () {
        var result,
            success = function (data, response) {
                result = data;
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingNext", null);
        return result;
    };

    /**
     * NowPlayingPrevious
     * Play the previous track according to the callback method given to
     * NowPlayingRequestPlayback.
     *
     * @returns String: whether the music was changed to previous one successfully.
     */
    _self.NowPlayingPrevious = function () {
        var result,
            success = function (data, response) {
                result = data;
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingPrevious", null);
        return result;
    };

    /**
     * NowPlayingError
     * Fire the error callback method given to NowPlayingRequestPlayback.
     * For debugging purposes only.
     *
     * @returns String: error information
     */
    _self.NowPlayingError = function () {
        var result,
            success = function (data, response) {
                result = data;
            },
            fail = function (data, response) {
                console.log("Error: " + data);
            };
        exec(success, fail, _ID, "NowPlayingError", null);
        return result;
    };

    // Validate play input

    /* We expect the following callbacks to be present:
    play, pause, stop, next, previous, error
    */
    _self.NowPlayingValidateCallback = function(input) {
        var result = "";
        var valid = true;
        if(!('play' in input)) result = "Play callback was not provided";
        if(!('pause' in input)) result = "Pause callback was not provided";
        if(!('stop' in input)) result = "Stop callback was not provided";
        if(!('next' in input)) result = "Next callback was not provided";
        if(!('previous' in input)) result = "Previous callback was not provided";
        if(!('error' in input)) result = "Error callback was not provided";

        if(result !== "") {
            valid = false;
            // send error callback;
        }
        if(valid) {
            valid = _self.NowPlayingValidateCallbackAttributes(input);
        }
        return valid;
    };

    _self.NowPlayingValidateCallbackAttributes = function(input) {
        var result = true;
        if(!(isFunction(input.play))) result = "Play attribute was not a function";
        if(!(isFunction(input.pause))) result = "Pause attribute was not a function";
        if(!(isFunction(input.stop))) result = "Stop attribute was not a function";
        if(!(isFunction(input.next))) result = "Next attribute was not a function";
        if(!(isFunction(input.previous))) result = "Previous attribute was not a function";
        if(!(isFunction(input.error))) result = "Error attribute was not a function";

        if(typeof(result) === "boolean" && result === true) {
            return true;
        } else {
            // call error and return false
            return false;
        }
    };

    function isFunction(functionToCheck) {
        var getType = {};
        return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    };

    /*
     trackURL: "http://www.pch.gc.ca/DAMAssetPub/DAM-hymChs-antSgn/STAGING/audio-audio/o-canada_1359474460106_eng.MP3",
            iconURL: "img/canadian-flag-small.jpg",
            metadata: {
                Title: "O Canada",
                Artist: "Canada",
                Album: "Canada's Favorites"
            }
    */

    _self.NowPlayingValidatePlayInput = function(input) {
        var response = "";
        if(!('iconURL' in input)) response = "iconURL attribute was not provided";
        if(!('trackURL' in input)) response =  "trackURL attribute was not provided";
        if(('metadata' in input)) {
            // is this necessary or should we only check for trackURL
            if(!('Title' in input.metadata)) response = "Title field in metadata was not provided";
            if(!('Artist') in input.metadata) response = "Artist field in metadata was not provided";
            if(!('Album' in input.metadata)) response = "Album field in metadata was not provided";
        } else {
            response = "metadata attribute was not provided";
        }
        var valid = true;
        if(response !== "") {
            valid = false;
            // throw error
        }

        return valid
    };

    /**
     * NowPlayingGetState
     * Get the state of the music being played.
     * For debugging purposes only.
     *
     * @returns String: containing:
     * - the state of the MediaPlayer,
     * - whether the NowPlayingConnection is acquired,
     * - whether the NowPlayingConnection is preempted.
     */
	_self.NowPlayingGetState = function () {
		var result,
			success = function (data, response) {
				result = data;
			},
			fail = function (data, response) {
				console.log("Error: " + data);
			};
		exec(success, fail, _ID, "NowPlayingGetState", null);
		return result;
	};

module.exports = _self;
<|endoftext|>