<commit_before>/*
 config object structure
 {
 "host": <string> shows the location of the webGME server //not really used by internally run plugins = NUII,
 "project": <string> show the name of the project,
 "token": <string> authentication token for REST API //NUII,
 "selected": <string> gives the URL / path of the selected object , you can convert URL to path,
 "commit": <string> the hash / URL part of the selected commit, you can convert URL part to hash,
 "root": <string> the hash / URL of the root object, you can convert URL to hash,
 "branch": <string> the name of the selected branch
 }
 */

var main = function(CONFIG) {
    // main code
    var requirejs = require("requirejs");
    var program = require('commander');
    var path = require('path');

    var requirejsBase = __dirname + '/..';

    requirejs.config({
        nodeRequire: require,
        baseUrl: requirejsBase
    });

    program.option('-c, --config <name>', 'Configuration file');
    program.option('-p, --project <name>', 'Name of the project.', 'PetriNet');
    program.option('-b, --branch <name>', 'Name of the branch.', 'master');
    program.option('-i, --pluginPath <name>', 'Path to given plugin.', '../interpreters/RootChildDuplicator/RootChildDuplicator');
    program.option('-s, --selectedObjID <webGMEID>', 'ID to selected component.', '');
    program.parse(process.argv);

    CONFIG = CONFIG || requirejs('bin/getconfig');

    var configFilename = program.config;
    if (configFilename) {
        // TODO: check if file exists and it is json
        var resolvedFilename = path.resolve(configFilename);
        console.log('Given configuration file: ', resolvedFilename);
        var commanlineConfig = require(resolvedFilename);

        // TODO: check if commanline config valid or not
        for (var key in commanlineConfig) {
            CONFIG[key] = commanlineConfig[key];
        }
    }

    if (CONFIG.plugins && CONFIG.plugins.basePath) {

        requirejs.config({
            nodeRequire: require,
            paths: {
                'plugins': path.relative(requirejsBase, path.resolve(CONFIG.plugins.basePath))
            },
            baseUrl: requirejsBase
        });
    }

    var projectName = program.project;
    var branch = program.branch;
    var pluginName = path.relative(requirejsBase, path.resolve(program.pluginPath));
    var selectedID = program.selectedObjID;

    // TODO: logging
    console.log('Given plugin : ', pluginName);

    var config = {
        "host": CONFIG.mongoip,
        "port": CONFIG.mongoport,
        "database": CONFIG.mongodatabase,
        "project": projectName,
        "token": "",
        "selected": selectedID,
        "commit": null, //"#668b3babcdf2ddcd7ba38b51acb62d63da859d90",
        //"root": ""
        "branchName": branch
    };

    var PluginManager = requirejs('plugin/PluginManagerBase');
    // TODO: move the downloader to PluginManager

    var Plugin = requirejs(pluginName);

    // FIXME: dependency does matter!
    var WebGME = require('../webgme');

    var Core = WebGME.core,
        Storage = WebGME.serverUserStorage;
    var storage = new Storage({'host':config.host, 'port':config.port, 'database':config.database});

    var plugins = {};
    plugins[pluginName] = Plugin;

    var pluginManager = new PluginManager(storage, Core, plugins);

    pluginManager.executePlugin(pluginName, config, function (err, result) {
        console.log(result);
    });
};

if (require.main === module) {
    main();
}<commit_msg>Revert "Define the 'plugins' path for server side."<commit_after>/*
 config object structure
 {
 "host": <string> shows the location of the webGME server //not really used by internally run plugins = NUII,
 "project": <string> show the name of the project,
 "token": <string> authentication token for REST API //NUII,
 "selected": <string> gives the URL / path of the selected object , you can convert URL to path,
 "commit": <string> the hash / URL part of the selected commit, you can convert URL part to hash,
 "root": <string> the hash / URL of the root object, you can convert URL to hash,
 "branch": <string> the name of the selected branch
 }
 */

var main = function (CONFIG) {
    // main code
    var requirejs = require("requirejs");
    var program = require('commander');
    var path = require('path');

    var requirejsBase = __dirname + '/..';

    requirejs.config({
        nodeRequire: require,
        baseUrl: requirejsBase
    });

    program.option('-c, --config <name>', 'Configuration file');
    program.option('-p, --project <name>', 'Name of the project.', 'PetriNet');
    program.option('-b, --branch <name>', 'Name of the branch.', 'master');
    program.option('-i, --pluginPath <name>', 'Path to given plugin.', '../interpreters/RootChildDuplicator/RootChildDuplicator');
    program.option('-s, --selectedObjID <webGMEID>', 'ID to selected component.', '');
    program.parse(process.argv);

    CONFIG = CONFIG || requirejs('bin/getconfig');

    var configFilename = program.config;
    if (configFilename) {
        // TODO: check if file exists and it is json
        var resolvedFilename = path.resolve(configFilename);
        console.log('Given configuration file: ', resolvedFilename);
        var commanlineConfig = require(resolvedFilename);

        // TODO: check if commanline config valid or not
        for (var key in commanlineConfig) {
            CONFIG[key] = commanlineConfig[key];
        }
    }

    var projectName = program.project;
    var branch = program.branch;
    var pluginName = path.relative(requirejsBase, path.resolve(program.pluginPath));
    var selectedID = program.selectedObjID;

    // TODO: logging
    console.log('Given plugin : ', pluginName);

    var config = {
        "host": CONFIG.mongoip,
        "port": CONFIG.mongoport,
        "database": CONFIG.mongodatabase,
        "project": projectName,
        "token": "",
        "selected": selectedID,
        "commit": null, //"#668b3babcdf2ddcd7ba38b51acb62d63da859d90",
        //"root": ""
        "branchName": branch
    };

    var PluginManager = requirejs('plugin/PluginManagerBase');
    // TODO: move the downloader to PluginManager

    var Plugin = requirejs(pluginName);

    // FIXME: dependency does matter!
    var WebGME = require('../webgme');

    var Core = WebGME.core,
        Storage = WebGME.serverUserStorage;
    var storage = new Storage({'host': config.host, 'port': config.port, 'database': config.database});

    var plugins = {};
    plugins[pluginName] = Plugin;

    storage.openDatabase(function (err) {
        console.log('database is open');

        if (!err) {
            storage.openProject(config.project, function (err, project) {
                if (!err) {

                    var pluginManager = new PluginManager(project, Core, plugins);

                    pluginManager.executePlugin(pluginName, config, function (err, result) {
                        console.log(result);
                    });
                }
            });
        }
    });
};

if (require.main === module) {
    main();
}<|endoftext|>


<commit_before>var Bitly = require( 'bitly' );
var fs = require( 'fs' );
var LOG = {};

var LOGFILE = __rootdir + '/data/ofn.json';
try {
	LOG = require( LOGFILE );
} catch ( e ) {
	//
}
module.exports = {
	events: {
		url: function ( bot, url, nick, to ) {
			var bitly = new Bitly( bot.config.bitly.username, bot.config.bitly.password );
			bitly.shorten( url.href, function ( err, res ) {
				if ( err ) {
					return; // fail silently (usually duplicate URL)
				}
				if ( LOG[res.data.hash] ) {
					bot.shout( to, res.data.url + ' (ofn ×' + LOG[res.data.hash] + ')' );
					LOG[res.data.hash]++;
				} else {
					LOG[res.data.hash] = 1;
					if ( res.data.url && res.data.url.length < url.href.length ) {
						bot.shout( to, res.data.url );
					}
				}
				fs.writeFile( LOGFILE, JSON.stringify( LOG, null, 4 ) );
			} );
		}
	},
	commands: {
		shorten: {
			help: 'Shorten a URL',
			usage: [ 'url' ],
			command: function ( bot, msg ) {
				var bitly = new Bitly( bot.config.bitly.username, bot.config.bitly.password );
				bitly.shorten( msg.args.url, function ( err, res ) {
					if ( err ) {
						bot.say( msg.to, 'Unable to shorten that.' );
					}
					if ( res.data.url ) {
						bot.say( msg.to, res.data.url );
					}
				} );
			}
		}
	}
};
<commit_msg>Suppress count for ofn×1<commit_after>var Bitly = require( 'bitly' );
var fs = require( 'fs' );
var LOG = {};

var LOGFILE = __rootdir + '/data/ofn.json';
try {
	LOG = require( LOGFILE );
} catch ( e ) {
	//
}
module.exports = {
	events: {
		url: function ( bot, url, nick, to ) {
			var bitly = new Bitly( bot.config.bitly.username, bot.config.bitly.password );
			bitly.shorten( url.href, function ( err, res ) {
				if ( err ) {
					return; // fail silently (usually duplicate URL)
				}
				if ( LOG[res.data.hash] ) {
					if ( LOG[res.data.hash] ) {
						bot.shout( to, res.data.url + ' (ofn)' );
					} else {
						bot.shout( to, res.data.url + ' (ofn ×' + LOG[res.data.hash] + ')' );
					}
					LOG[res.data.hash]++;
				} else {
					LOG[res.data.hash] = 1;
					if ( res.data.url && res.data.url.length < url.href.length ) {
						bot.shout( to, res.data.url );
					}
				}
				fs.writeFile( LOGFILE, JSON.stringify( LOG, null, 4 ) );
			} );
		}
	},
	commands: {
		shorten: {
			help: 'Shorten a URL',
			usage: [ 'url' ],
			command: function ( bot, msg ) {
				var bitly = new Bitly( bot.config.bitly.username, bot.config.bitly.password );
				bitly.shorten( msg.args.url, function ( err, res ) {
					if ( err ) {
						bot.say( msg.to, 'Unable to shorten that.' );
					}
					if ( res.data.url ) {
						bot.say( msg.to, res.data.url );
					}
				} );
			}
		}
	}
};
<|endoftext|>


<commit_before>import Github from 'github-api';
import yaml from 'js-yaml';
import { parseGithubUrl } from '../utils/github';

export default {
  namespace: 'contribute',

  state: {
    visible: false,
    repo: null,
  },

  effects: {
    *validateRepo({ payload }, { put, select }) {
      // https://github.com/dvajs/dva-example-user-dashboard/
      const { user, repo } = parseGithubUrl(payload);
      if (user && repo) {
        const { auth } = yield select();
        const { accessToken } = auth;
        const github = new Github({ token: accessToken });

        // read basic information of repo
        const repos = yield github.getRepo(user, repo);
        const { data } = yield repos.getDetails();

        // parse package.json of repo
        const packageJson = yield repos.getContents('master', 'package.json', true);
        // eslint-disable-next-line
        console.log('>> packageJson', packageJson);
        yield put({
          type: 'saveRepo',
          payload: {
            ...data,
            isValidScaffold: 'start' in packageJson.data.scripts,
            isReact: 'react' in packageJson.data.dependencies,
            isAngular: 'angular' in packageJson.data.dependencies,
          },
        });
      }
    },
    *submit({ payload }, { select }) {
      const { auth } = yield select();
      const { accessToken } = auth;
      const github = new Github({ token: accessToken });
      // fork scaffold-market repo
      const scaffoldRepo = yield github.getRepo('ant-design', 'scaffold-market');
      const fork = yield scaffoldRepo.fork();
      const user = fork.data.owner.login;
      const repo = fork.data.name;

      const forkedRepo = yield github.getRepo(user, repo);

      const branchName = `scaffold-${payload.name}`;
      // create branch
      yield forkedRepo.createBranch('master', branchName);

      // update list
      yield forkedRepo.writeFile(branchName, `scaffolds/${payload.name}/index.yml`, yaml.safeDump(payload), 'submit new scaffold', {
        encode: 'utf-8',
      });

      // pr
      const pullRequestResult = yield scaffoldRepo.createPullRequest({
        title: `add scaffold ${payload.name} to antd scaffold`,
        head: `${user}:${branchName}`,
        base: 'master',
        body: yaml.safeDump(payload),
      });

      // eslint-disable-next-line
      console.log('>> pullRequestResult', pullRequestResult);

      // const master = yield forkedRepo.getBranch('master');
      // const masterSHA = master.data.commit.sha;
      // createTree
    },
  },

  reducers: {
    saveRepo(state, { payload }) {
      return { ...state, repo: payload };
    },
  },
};
<commit_msg>code indent<commit_after>import Github from 'github-api';
import yaml from 'js-yaml';
import { parseGithubUrl } from '../utils/github';

export default {
  namespace: 'contribute',

  state: {
    visible: false,
    repo: null,
  },

  effects: {
    *validateRepo({ payload }, { put, select }) {
      // https://github.com/dvajs/dva-example-user-dashboard/
      const { user, repo } = parseGithubUrl(payload);
      if (user && repo) {
        const { auth } = yield select();
        const { accessToken } = auth;
        const github = new Github({ token: accessToken });

        // read basic information of repo
        const repos = yield github.getRepo(user, repo);
        const { data } = yield repos.getDetails();

        // parse package.json of repo
        const packageJson = yield repos.getContents('master', 'package.json', true);
        // eslint-disable-next-line
        console.log('>> packageJson', packageJson);
        yield put({
          type: 'saveRepo',
          payload: {
            ...data,
            isValidScaffold: 'start' in packageJson.data.scripts,
            isReact: 'react' in packageJson.data.dependencies,
            isAngular: 'angular' in packageJson.data.dependencies,
          },
        });
      }
    },
    *submit({ payload }, { select }) {
      const { auth } = yield select();
      const { accessToken } = auth;
      const github = new Github({ token: accessToken });
      // fork scaffold-market repo
      const scaffoldRepo = yield github.getRepo('ant-design', 'scaffold-market');
      const fork = yield scaffoldRepo.fork();
      const user = fork.data.owner.login;
      const repo = fork.data.name;

      const forkedRepo = yield github.getRepo(user, repo);

      const branchName = `scaffold-${payload.name}`;
      // create branch
      yield forkedRepo.createBranch('master', branchName);

      // update list
      yield forkedRepo.writeFile(
        branchName,
        `scaffolds/${payload.name}/index.yml`,
        yaml.safeDump(payload),
        'submit new scaffold',
        {
          encode: 'utf-8',
        },
      );

      // pr
      const pullRequestResult = yield scaffoldRepo.createPullRequest({
        title: `add scaffold ${payload.name} to antd scaffold`,
        head: `${user}:${branchName}`,
        base: 'master',
        body: yaml.safeDump(payload),
      });

      // eslint-disable-next-line
      console.log('>> pullRequestResult', pullRequestResult);

      // const master = yield forkedRepo.getBranch('master');
      // const masterSHA = master.data.commit.sha;
      // createTree
    },
  },

  reducers: {
    saveRepo(state, { payload }) {
      return { ...state, repo: payload };
    },
  },
};
<|endoftext|>


<commit_before>/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @flow
 */
'use strict';

var React = require('react-native');
var ViewExample = require('./ViewExample');
var {
  PixelRatio,
  ScrollView,
  StyleSheet,
  Text,
  TouchableHighlight,
  View,
} = React;

var EmptyPage = React.createClass({

  render: function() {
    return (
      <View style={styles.emptyPage}>
        <Text style={styles.emptyPageText}>
          {this.props.text}
        </Text>
      </View>
    );
  },

});

var NavigatorIOSExample = React.createClass({

  statics: {
    title: '<NavigatorIOS>',
    description: 'iOS navigation capabilities',
  },

  render: function() {
    var recurseTitle = 'Recurse Navigation';
    if (!this.props.topExampleRoute) {
      recurseTitle += ' - more examples here';
    }
    return (
      <ScrollView style={styles.list}>
        <View style={styles.line}/>
        <View style={styles.group}>
          <View style={styles.row}>
            <Text style={styles.rowNote}>
              See <UIExplorerApp> for top-level usage.
            </Text>
          </View>
        </View>
        <View style={styles.line}/>
        <View style={styles.groupSpace}/>
        <View style={styles.line}/>
        <View style={styles.group}>
          {this._renderRow(recurseTitle, () => {
            this.props.navigator.push({
              title: NavigatorIOSExample.title,
              component: NavigatorIOSExample,
              backButtonTitle: 'Custom Back',
              passProps: {topExampleRoute: this.props.topExampleRoute || this.props.route},
            });
          })}
          {this._renderRow('Push View Example', () => {
            this.props.navigator.push({
              title: 'Very Long Custom View Example Title',
              component: ViewExample,
            });
          })}
          {this._renderRow('Custom Right Button', () => {
            this.props.navigator.push({
              title: NavigatorIOSExample.title,
              component: EmptyPage,
              rightButtonTitle: 'Cancel',
              onRightButtonPress: () => this.props.navigator.pop(),
              passProps: {
                text: 'This page has a right button in the nav bar',
              }
            });
          })}
          {this._renderRow('Pop', () => {
            this.props.navigator.pop();
          })}
          {this._renderRow('Pop to top', () => {
            this.props.navigator.popToTop();
          })}
          {this._renderRow('Replace here', () => {
            var prevRoute = this.props.route;
            this.props.navigator.replace({
              title: 'New Navigation',
              component: EmptyPage,
              rightButtonTitle: 'Undo',
              onRightButtonPress: () => this.props.navigator.replace(prevRoute),
              passProps: {
                text: 'The component is replaced, but there is currently no ' +
                  'way to change the right button or title of the current route',
              }
            });
          })}
          {this._renderReplacePrevious()}
          {this._renderReplacePreviousAndPop()}
          {this._renderPopToTopNavExample()}
        </View>
        <View style={styles.line}/>
      </ScrollView>
    );
  },

  _renderPopToTopNavExample: function() {
    if (!this.props.topExampleRoute) {
      return null;
    }
    return this._renderRow('Pop to top NavigatorIOSExample', () => {
      this.props.navigator.popToRoute(this.props.topExampleRoute);
    });
  },

  _renderReplacePrevious: function() {
    if (!this.props.topExampleRoute) {
      // this is to avoid replacing the UIExplorerList at the top of the stack
      return null;
    }
    return this._renderRow('Replace previous', () => {
      this.props.navigator.replacePrevious({
        title: 'Replaced',
        component: EmptyPage,
        passProps: {
          text: 'This is a replaced "previous" page',
        },
        wrapperStyle: styles.customWrapperStyle,
      });
    });
  },

  _renderReplacePreviousAndPop: function() {
    if (!this.props.topExampleRoute) {
      // this is to avoid replacing the UIExplorerList at the top of the stack
      return null;
    }
    return this._renderRow('Replace previous and pop', () => {
      this.props.navigator.replacePreviousAndPop({
        title: 'Replaced and Popped',
        component: EmptyPage,
        passProps: {
          text: 'This is a replaced "previous" page',
        },
        wrapperStyle: styles.customWrapperStyle,
      });
    });
  },

  _renderRow: function(title: string, onPress: Function) {
    return (
      <View>
        <TouchableHighlight onPress={onPress}>
          <View style={styles.row}>
            <Text style={styles.rowText}>
              {title}
            </Text>
          </View>
        </TouchableHighlight>
        <View style={styles.separator} />
      </View>
    );
  },
});

var styles = StyleSheet.create({
  customWrapperStyle: {
    backgroundColor: '#bbdddd',
  },
  emptyPage: {
    flex: 1,
    paddingTop: 64,
  },
  emptyPageText: {
    margin: 10,
  },
  list: {
    backgroundColor: '#eeeeee',
    marginTop: 10,
  },
  group: {
    backgroundColor: 'white',
  },
  groupSpace: {
    height: 15,
  },
  line: {
    backgroundColor: '#bbbbbb',
    height: 1 / PixelRatio.get(),
  },
  row: {
    backgroundColor: 'white',
    justifyContent: 'center',
    paddingHorizontal: 15,
    paddingVertical: 15,
  },
  separator: {
    height: 1 / PixelRatio.get(),
    backgroundColor: '#bbbbbb',
    marginLeft: 15,
  },
  rowNote: {
    fontSize: 17,
  },
  rowText: {
    fontSize: 17,
    fontWeight: '500',
  },
});

module.exports = NavigatorIOSExample;
<commit_msg>[UIExplorer] Fixed 'Push View Example' in NavigatorIOS example<commit_after>/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @flow
 */
'use strict';

var React = require('react-native');
var ViewExample = require('./ViewExample');
var createExamplePage = require('./createExamplePage');
var {
  PixelRatio,
  ScrollView,
  StyleSheet,
  Text,
  TouchableHighlight,
  View,
} = React;

var EmptyPage = React.createClass({

  render: function() {
    return (
      <View style={styles.emptyPage}>
        <Text style={styles.emptyPageText}>
          {this.props.text}
        </Text>
      </View>
    );
  },

});

var NavigatorIOSExample = React.createClass({

  statics: {
    title: '<NavigatorIOS>',
    description: 'iOS navigation capabilities',
  },

  render: function() {
    var recurseTitle = 'Recurse Navigation';
    if (!this.props.topExampleRoute) {
      recurseTitle += ' - more examples here';
    }
    return (
      <ScrollView style={styles.list}>
        <View style={styles.line}/>
        <View style={styles.group}>
          <View style={styles.row}>
            <Text style={styles.rowNote}>
              See <UIExplorerApp> for top-level usage.
            </Text>
          </View>
        </View>
        <View style={styles.line}/>
        <View style={styles.groupSpace}/>
        <View style={styles.line}/>
        <View style={styles.group}>
          {this._renderRow(recurseTitle, () => {
            this.props.navigator.push({
              title: NavigatorIOSExample.title,
              component: NavigatorIOSExample,
              backButtonTitle: 'Custom Back',
              passProps: {topExampleRoute: this.props.topExampleRoute || this.props.route},
            });
          })}
          {this._renderRow('Push View Example', () => {
            this.props.navigator.push({
              title: 'Very Long Custom View Example Title',
              component: createExamplePage(null, ViewExample),
            });
          })}
          {this._renderRow('Custom Right Button', () => {
            this.props.navigator.push({
              title: NavigatorIOSExample.title,
              component: EmptyPage,
              rightButtonTitle: 'Cancel',
              onRightButtonPress: () => this.props.navigator.pop(),
              passProps: {
                text: 'This page has a right button in the nav bar',
              }
            });
          })}
          {this._renderRow('Pop', () => {
            this.props.navigator.pop();
          })}
          {this._renderRow('Pop to top', () => {
            this.props.navigator.popToTop();
          })}
          {this._renderRow('Replace here', () => {
            var prevRoute = this.props.route;
            this.props.navigator.replace({
              title: 'New Navigation',
              component: EmptyPage,
              rightButtonTitle: 'Undo',
              onRightButtonPress: () => this.props.navigator.replace(prevRoute),
              passProps: {
                text: 'The component is replaced, but there is currently no ' +
                  'way to change the right button or title of the current route',
              }
            });
          })}
          {this._renderReplacePrevious()}
          {this._renderReplacePreviousAndPop()}
          {this._renderPopToTopNavExample()}
        </View>
        <View style={styles.line}/>
      </ScrollView>
    );
  },

  _renderPopToTopNavExample: function() {
    if (!this.props.topExampleRoute) {
      return null;
    }
    return this._renderRow('Pop to top NavigatorIOSExample', () => {
      this.props.navigator.popToRoute(this.props.topExampleRoute);
    });
  },

  _renderReplacePrevious: function() {
    if (!this.props.topExampleRoute) {
      // this is to avoid replacing the UIExplorerList at the top of the stack
      return null;
    }
    return this._renderRow('Replace previous', () => {
      this.props.navigator.replacePrevious({
        title: 'Replaced',
        component: EmptyPage,
        passProps: {
          text: 'This is a replaced "previous" page',
        },
        wrapperStyle: styles.customWrapperStyle,
      });
    });
  },

  _renderReplacePreviousAndPop: function() {
    if (!this.props.topExampleRoute) {
      // this is to avoid replacing the UIExplorerList at the top of the stack
      return null;
    }
    return this._renderRow('Replace previous and pop', () => {
      this.props.navigator.replacePreviousAndPop({
        title: 'Replaced and Popped',
        component: EmptyPage,
        passProps: {
          text: 'This is a replaced "previous" page',
        },
        wrapperStyle: styles.customWrapperStyle,
      });
    });
  },

  _renderRow: function(title: string, onPress: Function) {
    return (
      <View>
        <TouchableHighlight onPress={onPress}>
          <View style={styles.row}>
            <Text style={styles.rowText}>
              {title}
            </Text>
          </View>
        </TouchableHighlight>
        <View style={styles.separator} />
      </View>
    );
  },
});

var styles = StyleSheet.create({
  customWrapperStyle: {
    backgroundColor: '#bbdddd',
  },
  emptyPage: {
    flex: 1,
    paddingTop: 64,
  },
  emptyPageText: {
    margin: 10,
  },
  list: {
    backgroundColor: '#eeeeee',
    marginTop: 10,
  },
  group: {
    backgroundColor: 'white',
  },
  groupSpace: {
    height: 15,
  },
  line: {
    backgroundColor: '#bbbbbb',
    height: 1 / PixelRatio.get(),
  },
  row: {
    backgroundColor: 'white',
    justifyContent: 'center',
    paddingHorizontal: 15,
    paddingVertical: 15,
  },
  separator: {
    height: 1 / PixelRatio.get(),
    backgroundColor: '#bbbbbb',
    marginLeft: 15,
  },
  rowNote: {
    fontSize: 17,
  },
  rowText: {
    fontSize: 17,
    fontWeight: '500',
  },
});

module.exports = NavigatorIOSExample;
<|endoftext|>


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

/**
 * External dependencies
 */
import { storiesOf } from '@storybook/react';

/**
 * Internal dependencies
 */
import SetupWrapper from '../assets/js/components/setup/setup-wrapper';
import { SetupMain as AnalyticsSetup } from '../assets/js/modules/analytics/components/setup/index';
import * as fixtures from '../assets/js/modules/analytics/datastore/__fixtures__';

import { STORE_NAME, ACCOUNT_CREATE, PROFILE_CREATE, PROVISIONING_SCOPE } from '../assets/js/modules/analytics/datastore/constants';
import { STORE_NAME as CORE_SITE } from '../assets/js/googlesitekit/datastore/site/constants';
import { STORE_NAME as CORE_USER } from '../assets/js/googlesitekit/datastore/user/constants';
import { STORE_NAME as CORE_MODULES } from '../assets/js/googlesitekit/modules/datastore/constants';
import { WithTestRegistry, createTestRegistry, provideModules } from '../tests/js/utils';
import { generateGTMAnalyticsPropertyStory } from './utils/generate-gtm-analytics-property-story';

function Setup( props ) {
	return (
		<WithTestRegistry { ...props }>
			<SetupWrapper moduleSlug="analytics" />
		</WithTestRegistry>
	);
}

function usingGenerateGTMAnalyticsPropertyStory( args ) {
	return generateGTMAnalyticsPropertyStory( {
		...args,
		Component: Setup,
		setUp: ( registry ) => {
			global._googlesitekitLegacyData.setup.moduleToSetup = 'analytics';
			registry.dispatch( CORE_MODULES ).registerModule( 'analytics', {
				setupComponent: AnalyticsSetup,
			} );
		},
	} );
}

storiesOf( 'Analytics Module/Setup', module )
	.addDecorator( ( storyFn ) => {
		global._googlesitekitLegacyData.setup.moduleToSetup = 'analytics';
		const registry = createTestRegistry();
		provideModules( registry, [ {
			slug: 'analytics',
			active: true,
			connected: true,
		} ] );
		registry.dispatch( CORE_MODULES ).registerModule( 'analytics', {
			setupComponent: AnalyticsSetup,
		} );

		return storyFn( registry );
	} )
	.add( 'Loading', ( registry ) => {
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );

		return <Setup registry={ registry } />;
	} )
	.add( 'Start', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );

		return <Setup registry={ registry } />;
	} )
	.add( 'Start (with matched property)', ( registry ) => {
		const { accounts, properties, profiles, matchedProperty } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
		registry.dispatch( STORE_NAME ).receiveMatchedProperty( matchedProperty );

		return <Setup registry={ registry } />;
	} )
	.add( 'Create new view', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		// eslint-disable-next-line sitekit/camelcase-acronyms
		const { accountId, webPropertyId } = profiles[ 0 ];
		// eslint-disable-next-line sitekit/camelcase-acronyms
		const { internalWebPropertyId } = properties.find( ( property ) => webPropertyId === property.id );
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
		registry.dispatch( STORE_NAME ).setSettings( {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: webPropertyId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			internalWebPropertyID: internalWebPropertyId,
			profileID: PROFILE_CREATE,
			anonymizeIP: true,
			useSnippet: true,
			trackingDisabled: [ 'loggedinUsers' ],
		} );

		return <Setup registry={ registry } />;
	} )
	.add( 'Create Account Legacy (no accounts)', ( registry ) => {
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( [] );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );

		return <Setup registry={ registry } />;
	} )
	.add( 'Create Account Legacy (new account option)', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetSettings( {
			accountID: ACCOUNT_CREATE,
		} );

		return <Setup registry={ registry } />;
	} )
	.add( 'Create Account (scope not granted)', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( CORE_SITE ).receiveSiteInfo( {
			usingProxy: true,
			referenceSiteURL: 'http://example.com',
			timezone: 'America/Detroit',
			siteName: 'My Site Name',
		} );
		registry.dispatch( CORE_USER ).receiveGetAuthentication( {
			authenticated: true,
			requiredScopes: [],
			grantedScopes: [],
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetSettings( {
			accountID: ACCOUNT_CREATE,
		} );

		return <Setup registry={ registry } />;
	} )
	.add( 'Create Account (scope granted)', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( CORE_SITE ).receiveSiteInfo( {
			usingProxy: true,
			referenceSiteURL: 'http://example.com',
			timezone: 'America/Detroit',
			siteName: 'My Site Name',
		} );
		registry.dispatch( CORE_USER ).receiveGetAuthentication( {
			authenticated: true,
			requiredScopes: [],
			grantedScopes: [ PROVISIONING_SCOPE ],
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetSettings( {
			accountID: ACCOUNT_CREATE,
		} );

		return <Setup registry={ registry } />;
	} )
	.add( 'Existing Tag w/ access', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		const existingTag = {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			propertyID: properties[ 0 ].id,
		};

		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( existingTag.propertyID );
		registry.dispatch( STORE_NAME ).receiveGetTagPermission( {
			accountID: existingTag.accountID,
			permission: true,
		}, { propertyID: existingTag.propertyID } );

		return <Setup registry={ registry } />;
	} )
	.add( 'Existing Tag w/o access', ( registry ) => {
		const existingTag = {
			accountID: '12345678',
			propertyID: 'UA-12345678-1',
		};
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( existingTag.propertyID );
		registry.dispatch( STORE_NAME ).receiveGetTagPermission( {
			accountID: existingTag.accountID,
			permission: false,
		}, { propertyID: existingTag.propertyID } );

		return <Setup registry={ registry } />;
	} )
	.add( 'No Tag, GTM property w/ access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: false, gtmPermission: true } ) )
	.add( 'No Tag, GTM property w/o access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: false, gtmPermission: false } ) )
	.add( 'Existing Tag w/ access, GTM property w/ access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: true, gtmPermission: true, gaPermission: true } ) )
	.add( 'Existing Tag w/ access, GTM property w/o access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: true, gtmPermission: false, gaPermission: true } ) )
	.add( 'Existing Tag w/o access, GTM property w/ access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: true, gtmPermission: true, gaPermission: false } ) )
	.add( 'Existing Tag w/o access, GTM property w/o access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: true, gtmPermission: false, gaPermission: false } ) )
	.add( 'Nothing selected', () => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		const setupRegistry = ( { dispatch } ) => {
			dispatch( STORE_NAME ).receiveGetSettings( {} );
			dispatch( STORE_NAME ).receiveGetAccounts( accounts );
			// eslint-disable-next-line sitekit/camelcase-acronyms
			dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
			dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
				// eslint-disable-next-line sitekit/camelcase-acronyms
				accountID: properties[ 0 ].accountId,
				// eslint-disable-next-line sitekit/camelcase-acronyms
				propertyID: profiles[ 0 ].webPropertyId,
			} );
		};

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

/**
 * External dependencies
 */
import { storiesOf } from '@storybook/react';

/**
 * Internal dependencies
 */
import SetupWrapper from '../assets/js/components/setup/setup-wrapper';
import { SetupMain as AnalyticsSetup } from '../assets/js/modules/analytics/components/setup/index';
import * as fixtures from '../assets/js/modules/analytics/datastore/__fixtures__';

import { STORE_NAME, ACCOUNT_CREATE, PROFILE_CREATE, PROVISIONING_SCOPE } from '../assets/js/modules/analytics/datastore/constants';
import { STORE_NAME as CORE_SITE } from '../assets/js/googlesitekit/datastore/site/constants';
import { STORE_NAME as CORE_USER } from '../assets/js/googlesitekit/datastore/user/constants';
import { STORE_NAME as CORE_MODULES } from '../assets/js/googlesitekit/modules/datastore/constants';
import { WithTestRegistry, createTestRegistry, provideModules } from '../tests/js/utils';
import { generateGTMAnalyticsPropertyStory } from './utils/generate-gtm-analytics-property-story';

function Setup( props ) {
	return (
		<WithTestRegistry { ...props }>
			<SetupWrapper moduleSlug="analytics" />
		</WithTestRegistry>
	);
}

function usingGenerateGTMAnalyticsPropertyStory( args ) {
	return generateGTMAnalyticsPropertyStory( {
		...args,
		Component: Setup,
		setUp: ( registry ) => {
			global._googlesitekitLegacyData.setup.moduleToSetup = 'analytics';
			registry.dispatch( CORE_MODULES ).registerModule( 'analytics', {
				setupComponent: AnalyticsSetup,
			} );
		},
	} );
}

storiesOf( 'Analytics Module/Setup', module )
	.addDecorator( ( storyFn ) => {
		global._googlesitekitLegacyData.setup.moduleToSetup = 'analytics';
		const registry = createTestRegistry();
		provideModules( registry, [ {
			slug: 'analytics',
			active: true,
			connected: true,
		} ] );
		registry.dispatch( CORE_MODULES ).registerModule( 'analytics', {
			setupComponent: AnalyticsSetup,
		} );

		return storyFn( registry );
	} )
	.add( 'Loading', ( registry ) => {
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );

		return <Setup registry={ registry } />;
	} )
	.add( 'Start', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );

		return <Setup registry={ registry } />;
	} )
	.add( 'Start (with matched property)', ( registry ) => {
		const { accounts, properties, profiles, matchedProperty } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
		registry.dispatch( STORE_NAME ).receiveMatchedProperty( matchedProperty );

		return <Setup registry={ registry } />;
	} )
	.add( 'Create new view', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		// eslint-disable-next-line sitekit/camelcase-acronyms
		const { accountId, webPropertyId } = profiles[ 0 ];
		// eslint-disable-next-line sitekit/camelcase-acronyms
		const { internalWebPropertyId } = properties.find( ( property ) => webPropertyId === property.id );
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
		registry.dispatch( STORE_NAME ).setSettings( {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: webPropertyId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			internalWebPropertyID: internalWebPropertyId,
			profileID: PROFILE_CREATE,
			anonymizeIP: true,
			useSnippet: true,
			trackingDisabled: [ 'loggedinUsers' ],
		} );

		return <Setup registry={ registry } />;
	} )
	.add( 'Create Account Legacy (no accounts)', ( registry ) => {
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( [] );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );

		return <Setup registry={ registry } />;
	} )
	.add( 'Create Account Legacy (new account option)', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetSettings( {
			accountID: ACCOUNT_CREATE,
		} );

		return <Setup registry={ registry } />;
	} )
	.add( 'Create Account (scope not granted)', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( CORE_SITE ).receiveSiteInfo( {
			usingProxy: true,
			referenceSiteURL: 'http://example.com',
			timezone: 'America/Detroit',
			siteName: 'My Site Name',
		} );
		registry.dispatch( CORE_USER ).receiveGetAuthentication( {
			authenticated: true,
			requiredScopes: [],
			grantedScopes: [],
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetSettings( {
			accountID: ACCOUNT_CREATE,
		} );

		return <Setup registry={ registry } />;
	} )
	.add( 'Create Account (scope granted)', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( CORE_SITE ).receiveSiteInfo( {
			usingProxy: true,
			referenceSiteURL: 'http://example.com',
			timezone: 'America/Detroit',
			siteName: 'My Site Name',
		} );
		registry.dispatch( CORE_USER ).receiveGetAuthentication( {
			authenticated: true,
			requiredScopes: [],
			grantedScopes: [ PROVISIONING_SCOPE ],
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetSettings( {
			accountID: ACCOUNT_CREATE,
		} );

		return <Setup registry={ registry } />;
	} )
	.add( 'Existing Tag w/ access', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		const existingTag = {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			propertyID: properties[ 0 ].id,
		};

		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( existingTag.propertyID );
		registry.dispatch( STORE_NAME ).receiveGetTagPermission( {
			accountID: existingTag.accountID,
			permission: true,
		}, { propertyID: existingTag.propertyID } );

		return <Setup registry={ registry } />;
	} )
	.add( 'Existing Tag w/o access', ( registry ) => {
		const existingTag = {
			accountID: '12345678',
			propertyID: 'UA-12345678-1',
		};
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );
		registry.dispatch( STORE_NAME ).receiveGetExistingTag( existingTag.propertyID );
		registry.dispatch( STORE_NAME ).receiveGetTagPermission( {
			accountID: existingTag.accountID,
			permission: false,
		}, { propertyID: existingTag.propertyID } );

		return <Setup registry={ registry } />;
	} )
	.add( 'No Tag, GTM property w/ access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: false, gtmPermission: true } ) )
	.add( 'No Tag, GTM property w/o access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: false, gtmPermission: false } ) )
	.add( 'Existing Tag w/ access, GTM property w/ access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: true, gtmPermission: true, gaPermission: true } ) )
	.add( 'Existing Tag w/ access, GTM property w/o access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: true, gtmPermission: false, gaPermission: true } ) )
	.add( 'Existing Tag w/o access, GTM property w/ access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: true, gtmPermission: true, gaPermission: false } ) )
	.add( 'Existing Tag w/o access, GTM property w/o access', usingGenerateGTMAnalyticsPropertyStory( { useExistingTag: true, gtmPermission: false, gaPermission: false } ) )
	.add( 'Nothing selected', ( registry ) => {
		const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
		registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
		registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts );
		// eslint-disable-next-line sitekit/camelcase-acronyms
		registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
		registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
			// eslint-disable-next-line sitekit/camelcase-acronyms
			accountID: properties[ 0 ].accountId,
			// eslint-disable-next-line sitekit/camelcase-acronyms
			propertyID: profiles[ 0 ].webPropertyId,
		} );

		return <Setup registry={ registry } />;
	} )
;
<|endoftext|>


<commit_before>var paypal = require('paypal-rest-sdk');
var express = require('express');
var router = express.Router();
var beautify = require('js-beautify').js_beautify;

//
// Initialize PayPal
//
paypal.configure({
  mode: process.env.PAYPAL_MODE || 'sandbox',
  client_id: process.env.PAYPAL_CLIENT_ID || '',
  client_secret: process.env.PAYPAL_CLIENT_SECRET || ''
});

router.get('/webhooks', function(req, res, next) {
  paypal.notification.webhook.list(function (err, result) {
    if (err) {
      res.render('notifications/webhooks', {
        title: 'Notification Webhooks',
        error: err,
        errorStr: beautify(JSON.stringify(err), { indent_size: 2 }),
      });
    } else {
      res.render('notifications/webhooks', {
        title: 'Notification Webhooks',
        error: {},
        data: {
          webhooks: result,
          webhooksStr: beautify(JSON.stringify(result), { indent_size: 2 })
        }
      });
    }
  });
});

router.get('/webhook_events', function(req, res, next) {
  var pageSizeParam = req.query['page_size'] || 'created';

  paypal.notification.webhookEvent.list({ page_size: pageSizeParam }, function (err, result) {
    if (err) {
      res.render('notifications/webhook_events', {
        title: 'Notification Webhook Events',
        error: err,
        errorStr: beautify(JSON.stringify(err), { indent_size: 2 }),
      });
    } else {
      res.render('notifications/webhook_events', {
        title: 'Notification Webhook Events',
        error: {},
        data: {
          webhookEvents: result,
          webhookEventsStr: beautify(JSON.stringify(result), { indent_size: 2 })
        }
      });
    }
  });
});

router.get('/webhook_event_types', function(req, res, next) {
  paypal.notification.webhookEventType.list(function (err, result) {
    if (err) {
      res.render('notifications/webhook_event_types', {
        title: 'Notification Webhook Event Types',
        error: err,
        errorStr: beautify(JSON.stringify(err), { indent_size: 2 }),
      });
    } else {
      res.render('notifications/webhook_event_types', {
        title: 'Notification Webhook Event Types',
        error: {},
        data: {
          webhookEventTypes: result,
          webhookEventTypesStr: beautify(JSON.stringify(result), { indent_size: 2 })
        }
      });
    }
  });
});

/*
 * ex) curl "http://localhost:3000/notifications/webhook/listener" -d "foo=bar"
 */
router.post('/webhook/listener', function(req, res, next) {
  console.log(req.body);
  console.log(req.body.id);
  res.send('OK');
});

module.exports = router;

<commit_msg>Add logging code<commit_after>var paypal = require('paypal-rest-sdk');
var express = require('express');
var router = express.Router();
var beautify = require('js-beautify').js_beautify;

//
// Initialize PayPal
//
paypal.configure({
  mode: process.env.PAYPAL_MODE || 'sandbox',
  client_id: process.env.PAYPAL_CLIENT_ID || '',
  client_secret: process.env.PAYPAL_CLIENT_SECRET || ''
});

router.get('/webhooks', function(req, res, next) {
  paypal.notification.webhook.list(function (err, result) {
    if (err) {
      res.render('notifications/webhooks', {
        title: 'Notification Webhooks',
        error: err,
        errorStr: beautify(JSON.stringify(err), { indent_size: 2 }),
      });
    } else {
      res.render('notifications/webhooks', {
        title: 'Notification Webhooks',
        error: {},
        data: {
          webhooks: result,
          webhooksStr: beautify(JSON.stringify(result), { indent_size: 2 })
        }
      });
    }
  });
});

router.get('/webhook_events', function(req, res, next) {
  var pageSizeParam = req.query['page_size'] || 'created';

  paypal.notification.webhookEvent.list({ page_size: pageSizeParam }, function (err, result) {
    if (err) {
      res.render('notifications/webhook_events', {
        title: 'Notification Webhook Events',
        error: err,
        errorStr: beautify(JSON.stringify(err), { indent_size: 2 }),
      });
    } else {
      res.render('notifications/webhook_events', {
        title: 'Notification Webhook Events',
        error: {},
        data: {
          webhookEvents: result,
          webhookEventsStr: beautify(JSON.stringify(result), { indent_size: 2 })
        }
      });
    }
  });
});

router.get('/webhook_event_types', function(req, res, next) {
  paypal.notification.webhookEventType.list(function (err, result) {
    if (err) {
      res.render('notifications/webhook_event_types', {
        title: 'Notification Webhook Event Types',
        error: err,
        errorStr: beautify(JSON.stringify(err), { indent_size: 2 }),
      });
    } else {
      res.render('notifications/webhook_event_types', {
        title: 'Notification Webhook Event Types',
        error: {},
        data: {
          webhookEventTypes: result,
          webhookEventTypesStr: beautify(JSON.stringify(result), { indent_size: 2 })
        }
      });
    }
  });
});

/*
 * ex) curl "http://localhost:3000/notifications/webhook/listener" -d "foo=bar"
 */
router.post('/webhook/listener', function(req, res, next) {
  console.log(req.body);
  console.log(req.body.id);
  console.log(req.body.resource.id);
  res.send('OK');
});

module.exports = router;

<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Children, PropTypes } from 'react';
import classnames from 'classnames';
import iconsMap from '../index-icons';

const CLASS_ROOT = 'anchor';

const Anchor = props => {

  let icon;
  if (props.icon) {
    let CustomIcon  = iconsMap[props.icon];
    if (! CustomIcon) {
      console.warn(
        `Warning: Anchor is unable to find the icon named ${props.icon}`
      );
    } else {
      icon = <CustomIcon />;
    }
  } else if (props.primary) {
    let LinkNextIcon = iconsMap.LinkNext;
    icon = <LinkNextIcon />;
  }

  if (icon && !props.primary && !props.label) {
    icon = <span className={`${CLASS_ROOT}__icon`}>{icon};
  }

  let classes = classnames(
    CLASS_ROOT,
    props.className,
    {
      [`${CLASS_ROOT}--disabled`]: props.disabled,
      [`${CLASS_ROOT}--icon`]: icon,
      [`${CLASS_ROOT}--primary`]: props.primary,
      [`${CLASS_ROOT}--icon-label`]: icon && props.label && !props.primary
    }
  );

  let children = Children.map(props.children, child => {
    if (child && child.type && child.type.icon) {
      child = <span className={`${CLASS_ROOT}__icon`}>{child};
    }

    return child;
  });

  if (!children) {
    children = props.label;
  }

  return (
    <props.tag id={props.id} className={classes}
      href={props.href}
      target={props.target}
      onClick={props.onClick}>
      {icon}
      {children}
    </props.tag>
  );
};

Anchor.propTypes = {
  icon: PropTypes.string,
  disabled: PropTypes.bool,
  href: PropTypes.string,
  id: PropTypes.string,
  label: PropTypes.node,
  onClick: PropTypes.func,
  primary: PropTypes.bool,
  tag: PropTypes.string,
  target: PropTypes.string
};

Anchor.defaultProps = {
  tag: 'a'
};

Anchor.displayName = 'Anchor';

export default Anchor;
<commit_msg>removing !props.primary check<commit_after>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Children, PropTypes } from 'react';
import classnames from 'classnames';
import iconsMap from '../index-icons';

const CLASS_ROOT = 'anchor';

const Anchor = props => {

  let icon;
  if (props.icon) {
    let CustomIcon  = iconsMap[props.icon];
    if (! CustomIcon) {
      console.warn(
        `Warning: Anchor is unable to find the icon named ${props.icon}`
      );
    } else {
      icon = <CustomIcon />;
    }
  } else if (props.primary) {
    let LinkNextIcon = iconsMap.LinkNext;
    icon = <LinkNextIcon />;
  }

  if (icon && !props.primary && !props.label) {
    icon = <span className={`${CLASS_ROOT}__icon`}>{icon};
  }

  let classes = classnames(
    CLASS_ROOT,
    props.className,
    {
      [`${CLASS_ROOT}--disabled`]: props.disabled,
      [`${CLASS_ROOT}--icon`]: icon,
      [`${CLASS_ROOT}--primary`]: props.primary,
      [`${CLASS_ROOT}--icon-label`]: icon && props.label
    }
  );

  let children = Children.map(props.children, child => {
    if (child && child.type && child.type.icon) {
      child = <span className={`${CLASS_ROOT}__icon`}>{child};
    }

    return child;
  });

  if (!children) {
    children = props.label;
  }

  return (
    <props.tag id={props.id} className={classes}
      href={props.href}
      target={props.target}
      onClick={props.onClick}>
      {icon}
      {children}
    </props.tag>
  );
};

Anchor.propTypes = {
  icon: PropTypes.string,
  disabled: PropTypes.bool,
  href: PropTypes.string,
  id: PropTypes.string,
  label: PropTypes.node,
  onClick: PropTypes.func,
  primary: PropTypes.bool,
  tag: PropTypes.string,
  target: PropTypes.string
};

Anchor.defaultProps = {
  tag: 'a'
};

Anchor.displayName = 'Anchor';

export default Anchor;
<|endoftext|>


<commit_before>'use strict';

//exports.make_swarmie = (robot) => new Swarmie(robot);

class Swarmie {
    constructor(robotName) {
        this.robotName = robotName;
        this.robotRos = new ROSLIB.Ros({
            url : 'ws://' + robotName + ':9090'
        });
        this.laptopRos = new ROSLIB.Ros({
            url : 'ws://localhost:9090'
        });

        this.robotRos.on('connection', function() {
            console.log('Connected to robot websocket server.');
        });
        this.laptopRos.on('connection', function() {
            console.log('Connected to laptop websocket server');
        });

        this.robotRos.on('error', function(error) {
            console.log('Error connecting to websocket server: ', error);
        });

        this.robotRos.on('close', function() {
            console.log('Connection to websocket server closed.');
        });

        this.abridgeHeartbeat = this.createPassthrough(this.robotRos, this.laptopRos, '/abridge/heartbeat', 'std_msgs/String', false, false);
        this.behaviourHeartbeat = this.createPassthrough(this.robotRos, this.laptopRos, '/behaviour/heartbeat', 'std_msgs/String', false, false);
        this.cameraInfo = this.createPassthrough(this.robotRos, this.laptopRos, '/camera/camera_info', 'sensor_msgs/CameraInfo', true, false);
        this.diagnostics = this.createPassthrough(this.robotRos, this.laptopRos, '/diagnostics', 'std_msgs/Float32MultiArray', false, false);
        this.driveControl = this.createPassthrough(this.laptopRos, this.robotRos, '/driveControl', 'geometry_msgs/Twist', false, false);
        this.fingerAngle = this.createPassthrough(this.laptopRos, this.robotRos, '/fingerAngle/cmd', 'std_msgs/Float32', false, false);
        this.fixVelocity = this.createPassthrough(this.robotRos, this.laptopRos, '/fix_velocity', 'geometry_msgs/TwistWithCovarianceStamped', false, false);
        this.imu = this.createPassthrough(this.robotRos, this.laptopRos, '/imu_throttle', 'sensor_msgs/Imu', false, false);
        this.joystick = this.createPassthrough(this.laptopRos, this.robotRos, '/joystick', 'sensor_msgs/Joy', false, false);
        this.mode = this.createPassthrough(this.laptopRos, this.robotRos, '/mode', 'std_msgs/UInt8', false, false);
        this.navsol = this.createPassthrough(this.robotRos, this.laptopRos, '/navsol_throttle', 'ublox_msgs/NavSOL', false, false);
        this.odom = this.createPassthrough(this.robotRos, this.laptopRos, '/odom_throttle', 'nav_msgs/Odometry', false, false);
        this.odomEkf = this.createPassthrough(this.robotRos, this.laptopRos, '/odom/ekf_throttle', 'nav_msgs/Odometry', false, false);
        this.odomFiltered = this.createPassthrough(this.robotRos, this.laptopRos, '/odom/filtered_throttle', 'nav_msgs/Odometry', false, false);
        this.odomNavsat = this.createPassthrough(this.robotRos, this.laptopRos, '/odom/navsat_throttle', 'nav_msgs/Odometry', false, false);
        this.sbridgeHeartbeat = this.createPassthrough(this.robotRos, this.laptopRos, '/sbridge/heartbeat', 'std_msgs/String', false, false);
        this.sonarCenter = this.createPassthrough(this.robotRos, this.laptopRos, '/sonarCenter_throttle', 'sensor_msgs/Range', false, false);
        this.sonarLeft = this.createPassthrough(this.robotRos, this.laptopRos, '/sonarLeft_throttle', 'sensor_msgs/Range', false, false);
        this.sonarRight = this.createPassthrough(this.robotRos, this.laptopRos, '/sonarRight_throttle', 'sensor_msgs/Range', false, false);
        this.stateMachine = this.createPassthrough(this.robotRos, this.laptopRos, '/state_machine', 'std_msgs/String', false, false);
        this.status = this.createPassthrough(this.robotRos, this.laptopRos, '/status', 'std_msgs/String', false, false);
        this.targetsImageCompressed = this.createPassthrough(this.robotRos, this.laptopRos, '/targets/image/compressed_throttle', 'sensor_msgs/CompressedImage', false, false);
        this.virtualFence = this.createPassthrough(this.laptopRos, this.robotRos, '/virtualFence', 'std_msgs/Float32MultiArray', false, true);
        this.wristAngle = this.createPassthrough(this.laptopRos, this.robotRos, '/wristAngle/cmd', 'std_msgs/Float32', false, false);
    }

    createPassthrough(sourceRosHandle, destinationRosHandle, robotSubscription, messageReceived, oneShot, global) {

        var sourceTopicName, destTopicName;

        if (global === true) {
            sourceTopicName = robotSubscription;
        } else {
            sourceTopicName = '/' + this.robotName + robotSubscription;
        }

	if(sourceTopicName.endsWith("_throttle"))
	{
	    destTopicName = sourceTopicName.slice(0, -9);
	}
	else
	{
	    destTopicName = sourceTopicName;
	}

        var passthroughHandle = {
            sourceTopic : new ROSLIB.Topic({
                ros : sourceRosHandle,
                name : sourceTopicName,
                messageType : messageReceived
            }),
            destinationTopic : new ROSLIB.Topic({
                ros : destinationRosHandle,
                name : destTopicName,
                messageType : messageReceived
            })
        };

        passthroughHandle.sourceTopic.subscribe(function(message) {
            passthroughHandle.destinationTopic.publish(message);
            if (oneShot) {
                passthroughHandle.sourceTopic.unsubscribe();
            };
        });
        return passthroughHandle;
    }
}
<commit_msg>Added passthrough in rosbridge shim<commit_after>'use strict';

//exports.make_swarmie = (robot) => new Swarmie(robot);

class Swarmie {
    constructor(robotName) {
        this.robotName = robotName;
        this.robotRos = new ROSLIB.Ros({
            url : 'ws://' + robotName + ':9090'
        });
        this.laptopRos = new ROSLIB.Ros({
            url : 'ws://localhost:9090'
        });

        this.robotRos.on('connection', function() {
            console.log('Connected to robot websocket server.');
        });
        this.laptopRos.on('connection', function() {
            console.log('Connected to laptop websocket server');
        });

        this.robotRos.on('error', function(error) {
            console.log('Error connecting to websocket server: ', error);
        });

        this.robotRos.on('close', function() {
            console.log('Connection to websocket server closed.');
        });

        this.abridgeHeartbeat = this.createPassthrough(this.robotRos, this.laptopRos, '/abridge/heartbeat', 'std_msgs/String', false, false);
        this.behaviourHeartbeat = this.createPassthrough(this.robotRos, this.laptopRos, '/behaviour/heartbeat', 'std_msgs/String', false, false);
        this.cameraInfo = this.createPassthrough(this.robotRos, this.laptopRos, '/camera/camera_info', 'sensor_msgs/CameraInfo', true, false);
        this.diagnostics = this.createPassthrough(this.robotRos, this.laptopRos, '/diagnostics', 'std_msgs/Float32MultiArray', false, false);
        this.driveControl = this.createPassthrough(this.laptopRos, this.robotRos, '/driveControl', 'geometry_msgs/Twist', false, false);
        this.fingerAngle = this.createPassthrough(this.laptopRos, this.robotRos, '/fingerAngle/cmd', 'std_msgs/Float32', false, false);
        this.fixVelocity = this.createPassthrough(this.robotRos, this.laptopRos, '/fix_velocity', 'geometry_msgs/TwistWithCovarianceStamped', false, false);
        this.imu = this.createPassthrough(this.robotRos, this.laptopRos, '/imu_throttle', 'sensor_msgs/Imu', false, false);
        this.joystick = this.createPassthrough(this.laptopRos, this.robotRos, '/joystick', 'sensor_msgs/Joy', false, false);
        this.mode = this.createPassthrough(this.laptopRos, this.robotRos, '/mode', 'std_msgs/UInt8', false, false);
        this.navsol = this.createPassthrough(this.robotRos, this.laptopRos, '/navsol_throttle', 'ublox_msgs/NavSOL', false, false);
        this.odom = this.createPassthrough(this.robotRos, this.laptopRos, '/odom_throttle', 'nav_msgs/Odometry', false, false);
        this.odomEkf = this.createPassthrough(this.robotRos, this.laptopRos, '/odom/ekf_throttle', 'nav_msgs/Odometry', false, false);
        this.odomFiltered = this.createPassthrough(this.robotRos, this.laptopRos, '/odom/filtered_throttle', 'nav_msgs/Odometry', false, false);
        this.odomNavsat = this.createPassthrough(this.robotRos, this.laptopRos, '/odom/navsat_throttle', 'nav_msgs/Odometry', false, false);
        this.sbridgeHeartbeat = this.createPassthrough(this.robotRos, this.laptopRos, '/sbridge/heartbeat', 'std_msgs/String', false, false);
        this.sonarCenter = this.createPassthrough(this.robotRos, this.laptopRos, '/sonarCenter_throttle', 'sensor_msgs/Range', false, false);
        this.sonarLeft = this.createPassthrough(this.robotRos, this.laptopRos, '/sonarLeft_throttle', 'sensor_msgs/Range', false, false);
        this.sonarRight = this.createPassthrough(this.robotRos, this.laptopRos, '/sonarRight_throttle', 'sensor_msgs/Range', false, false);
        this.stateMachine = this.createPassthrough(this.robotRos, this.laptopRos, '/state_machine', 'std_msgs/String', false, false);
        this.status = this.createPassthrough(this.robotRos, this.laptopRos, '/status', 'std_msgs/String', false, false);
        this.targetsImageCompressed = this.createPassthrough(this.robotRos, this.laptopRos, '/targets/image/compressed_throttle', 'sensor_msgs/CompressedImage', false, false);
        this.virtualFence = this.createPassthrough(this.laptopRos, this.robotRos, '/virtualFence', 'std_msgs/Float32MultiArray', false, true);
        this.wristAngle = this.createPassthrough(this.laptopRos, this.robotRos, '/wristAngle/cmd', 'std_msgs/Float32', false, false);
        this.recruitment = this.createPassthrough(this.laptopRos this.robotRos, '/detectionLocations', 'swarmie_msgs/Recruitment', false, true)
    }

    createPassthrough(sourceRosHandle, destinationRosHandle, robotSubscription, messageReceived, oneShot, global) {

        var sourceTopicName, destTopicName;

        if (global === true) {
            sourceTopicName = robotSubscription;
        } else {
            sourceTopicName = '/' + this.robotName + robotSubscription;
        }

	if(sourceTopicName.endsWith("_throttle"))
	{
	    destTopicName = sourceTopicName.slice(0, -9);
	}
	else
	{
	    destTopicName = sourceTopicName;
	}

        var passthroughHandle = {
            sourceTopic : new ROSLIB.Topic({
                ros : sourceRosHandle,
                name : sourceTopicName,
                messageType : messageReceived
            }),
            destinationTopic : new ROSLIB.Topic({
                ros : destinationRosHandle,
                name : destTopicName,
                messageType : messageReceived
            })
        };

        passthroughHandle.sourceTopic.subscribe(function(message) {
            passthroughHandle.destinationTopic.publish(message);
            if (oneShot) {
                passthroughHandle.sourceTopic.unsubscribe();
            };
        });
        return passthroughHandle;
    }
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import { connect } from 'react-redux';
import { fetchPad, fetchUser, fetchUsers, fetchPads, editPad, editReset } from 'actions';
import { each, findWhere, union, intersection, assign } from 'lodash';
import classNames from 'classnames';

import EditorTitle from 'components/EditorTitle';
import EditorContent from 'components/EditorContent';
import EditorCooperate from 'components/EditorCooperate';
import EditorTags from 'components/EditorTags';

export default class Editor extends Component {

  constructor() {
    super();
    this.state = {
      cooperator: [],
      tags: [],
      isLogged: false
    }
  }

  componentDidMount() {
    const { fetchPad, fetchUser, editReset, params } = this.props;
    fetchPad(params);
    editReset();
  }

  componentWillReceiveProps(nextProps) {
    const { isFetching, fetchPad, editReset, location: { pathname }, auth: { result: isLogged } } = this.props;
    if (pathname !== nextProps.location.pathname) {
      fetchPad(nextProps.params);
      editReset();
    }

    const { result, padData, users, edit } = nextProps;
    const data = (edit.requestData) ? assign(this.props.padData, edit.requestData) : padData;
    const { fetchUser } = this.props;
    const cooperatorList = [];
    const fetchQueue = [];

    const fetchingCooperator = (data.cooperator) ? data.cooperator.length !== this.state.cooperator.length : false;
    const isStillFetching = result && fetchingCooperator;
    const noCooperator = result && data.cooperator.length === 0;
    const noSuchPad = data.cooperator === undefined;

    if (isStillFetching || noCooperator || noSuchPad) {
      const { cooperator, tags } = data;
      each(cooperator, (value) => {
        const currentUser = findWhere(users.data, { 'id': value });
        if (currentUser) {
          cooperatorList.push(currentUser);
        } else {
          fetchQueue.push(value);
        }
      })

      if (fetchQueue.length) {
        fetchUser(fetchQueue);
      }

      this.setState({
        cooperator: cooperatorList,
        tags: (tags) ? tags : [],
        isLogged: isLogged
      })
    }
  }

  onClickSubmit() {
    const { editPad, padData: { id: padId, version } } = this.props;
    const titleState = this.refs.EditorTitle.getState();
    const contentState = this.refs.EditorContent.getState();
    const cooperatorState = this.refs.EditorCooperate.getState();
    const tagsState = this.refs.EditorTags.getState();

    const parameter = {
      padid: padId,
      version: version
    }

    if (titleState.isChanged) { parameter['title'] = titleState.title }
    if (contentState.isChanged) { parameter['content'] = contentState.content }
    if (tagsState.isChanged) { parameter['tags'] = tagsState.tags }
    if (cooperatorState.isChanged) { parameter['cooperator'] = cooperatorState.cooperatorId }

    editPad(padId, JSON.stringify(parameter));
  }

  render() {
    const { isLogged } = this.state;
    const { result: fetchResult, auth, padData, padData: { user: ownerId, cooperator }, fetchUsers, fetchPads, edit } = this.props;
    const data = (edit.requestData) ? assign(this.props.padData, edit.requestData) : padData;

    const authorityCheck = () => {
      if (auth.result) {
        const userId = auth.data.id;
        return intersection([userId], union([ownerId], cooperator)).length > 0;
      }
      return false;
    }

    const isUneditable = ! isLogged || ! fetchResult || ! authorityCheck();
    const isAuthorized = isLogged && fetchResult && authorityCheck();
    const errorOccurred = ! edit.isRequesting && edit.requestData && ! edit.result;

    let message = '';
    switch(true) {
      case ! isLogged:
        message = 'Not logged in.';
        break;
      case ! isAuthorized && fetchResult:
        message = 'Not cooperator.';
        break;
      case ! fetchResult:
        message = 'No such pad.';
        break;
      default:
        message = edit.message || '';
    }

    return (

          Pad title
          <EditorTitle
            ref="EditorTitle"
            data={ data }
            { ...this.props }
            authority={ isAuthorized }/>

          Content
          <EditorContent
            ref="EditorContent"
            data={ data }
            { ...this.props }
            authority={ isAuthorized } />

            Cooperate
            <EditorCooperate
              ref="EditorCooperate"
              data={ data }
              { ...this.props }
              fetchUsers={ fetchUsers }
              cooperator={ this.state.cooperator }
              authority={ isLogged && fetchResult } />

            Tags
            <EditorTags
              ref="EditorTags"
              data={ data }
              { ...this.props }
              fetchPads={ fetchPads }
              tags={ this.state.tags } />

            Submit
            Cancel

            { message }

    );
  }
}

Editor.propTypes = {
  isFetching: PropTypes.bool.isRequired,
  result: PropTypes.bool,
  data: PropTypes.object,
  fetchPad: PropTypes.func.isRequired
};

function mapStateToProps(state) {
  const {
    isFetching,
    result,
    data
  } = state.pad;

  return {
    isFetching: isFetching,
    result: result,
    padData: data,
    auth: state.auth,
    users: state.users,
    pads: state.pads,
    edit: state.edit
  };
}

export default connect(
  mapStateToProps,
  { fetchPad, fetchUser, fetchUsers, fetchPads, editPad, editReset }
)(Editor);
<commit_msg>Editor: submit & cancel button logic<commit_after>import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import { connect } from 'react-redux';
import { fetchPad, fetchUser, fetchUsers, fetchPads, editPad, editReset } from 'actions';
import { each, findWhere, union, intersection, assign } from 'lodash';
import classNames from 'classnames';

import EditorTitle from 'components/EditorTitle';
import EditorContent from 'components/EditorContent';
import EditorCooperate from 'components/EditorCooperate';
import EditorTags from 'components/EditorTags';

export default class Editor extends Component {

  static contextTypes = {
      history: PropTypes.object
  };

  constructor() {
    super();
    this.state = {
      cooperator: [],
      tags: [],
      isLogged: false
    }
  }

  componentDidMount() {
    const { fetchPad, fetchUser, editReset, params } = this.props;
    fetchPad(params);
    editReset();
  }

  componentWillReceiveProps(nextProps) {
    const { isFetching, fetchPad, editReset, location: { pathname } } = this.props;
    if (pathname !== nextProps.location.pathname) {
      fetchPad(nextProps.params);
      editReset();
    }

    const { result, padData, users, edit, auth: { result: isLogged } } = nextProps;
    const data = (edit.requestData) ? assign(this.props.padData, edit.requestData) : padData;

    if (edit.result) {
      const path = '/show/' + padData.id;
      this.context.history.pushState(null, path);
    }

    const { fetchUser } = this.props;
    const cooperatorList = [];
    const fetchQueue = [];

    const fetchingCooperator = (data.cooperator) ? data.cooperator.length !== this.state.cooperator.length : false;
    const isStillFetching = result && fetchingCooperator;
    const noCooperator = result && data.cooperator.length === 0;
    const noSuchPad = data.cooperator === undefined;

    if (isStillFetching || noCooperator || noSuchPad) {
      const { cooperator, tags } = data;
      each(cooperator, (value) => {
        const currentUser = findWhere(users.data, { 'id': value });
        if (currentUser) {
          cooperatorList.push(currentUser);
        } else {
          fetchQueue.push(value);
        }
      })

      if (fetchQueue.length) {
        fetchUser(fetchQueue);
      }

      this.setState({
        cooperator: cooperatorList,
        tags: (tags) ? tags : [],
        isLogged: isLogged
      })
    }
  }

  onClickSubmit() {
    const { editPad, padData: { id: padId, version } } = this.props;
    const titleState = this.refs.EditorTitle.getState();
    const contentState = this.refs.EditorContent.getState();
    const cooperatorState = this.refs.EditorCooperate.getState();
    const tagsState = this.refs.EditorTags.getState();

    const parameter = {
      padid: padId,
      version: version
    }

    if (titleState.isChanged) { parameter['title'] = titleState.title }
    if (contentState.isChanged) { parameter['content'] = contentState.content }
    if (tagsState.isChanged) { parameter['tags'] = tagsState.tags }
    if (cooperatorState.isChanged) { parameter['cooperator'] = cooperatorState.cooperatorId }

    editPad(padId, JSON.stringify(parameter));
  }

  onClickCancel() {
    const { padData: { id: padId } } = this.props;
    if (padId) {
      const path = '/show/' + padId;
      this.context.history.pushState(null, path);
    } else {
      this.context.history.pushState(null, '/');
    }
  }

  render() {
    const { isLogged } = this.state;
    const { result: fetchResult, isFetching, auth, padData, padData: { user: ownerId, cooperator }, fetchUsers, fetchPads, edit } = this.props;
    const data = (edit.requestData) ? assign(padData, edit.requestData) : padData;

    const authorityCheck = () => {
      if (auth.result) {
        const userId = auth.data.id;
        return intersection([userId], union([ownerId], cooperator)).length > 0;
      }
      return false;
    }

    const isUneditable = ! isLogged || ! fetchResult || ! authorityCheck();
    const isAuthorized = isLogged && fetchResult && authorityCheck();
    const isRequesting = edit.isRequesting;
    const errorOccurred = ! isRequesting && edit.requestData && ! edit.result;

    let message = '';
    switch(true) {
      case ! isLogged:
        message = 'Not logged in.';
        break;
      case ! isAuthorized && fetchResult:
        message = 'Not cooperator.';
        break;
      case ! fetchResult && ! isFetching:
        message = 'No such pad.';
        break;
      default:
        message = edit.message || '';
    }

    return (

          Pad title
          <EditorTitle
            ref="EditorTitle"
            data={ data }
            { ...this.props }
            authority={ isAuthorized }/>

          Content
          <EditorContent
            ref="EditorContent"
            data={ data }
            { ...this.props }
            authority={ isAuthorized } />

            Cooperate
            <EditorCooperate
              ref="EditorCooperate"
              data={ data }
              { ...this.props }
              fetchUsers={ fetchUsers }
              cooperator={ this.state.cooperator }
              authority={ isLogged && fetchResult } />

            Tags
            <EditorTags
              ref="EditorTags"
              data={ data }
              { ...this.props }
              fetchPads={ fetchPads }
              tags={ this.state.tags } />

              { isRequesting && 'Sending...' || 'Submit' }

            Cancel

            { message }

    );
  }
}

Editor.propTypes = {
  isFetching: PropTypes.bool.isRequired,
  result: PropTypes.bool,
  data: PropTypes.object,
  fetchPad: PropTypes.func.isRequired
};

function mapStateToProps(state) {
  const {
    isFetching,
    result,
    data
  } = state.pad;

  return {
    isFetching: isFetching,
    result: result,
    padData: data,
    auth: state.auth,
    users: state.users,
    pads: state.pads,
    edit: state.edit
  };
}

export default connect(
  mapStateToProps,
  { fetchPad, fetchUser, fetchUsers, fetchPads, editPad, editReset }
)(Editor);
<|endoftext|>


<commit_before>/*
 * module to build a graph, using the force d3.js library
 *
 D3's force layout uses the Barnes–Hut approximation to compute repulsive charge forces between all nodes efficiently. Links are implemented as geometric constraints on top of position Verlet integration, offering greater stability. A virtual spring between each node and the center of the chart prevents nodes from drifting into space
 *
 */

// debugging: get time for loading the module
var start =  new Date().getTime();
//console.log("graph.js start: "+ start);
var graph = "graph";

document.graph = (function startGraph() {

	// module object; add all methods and properties that should be visible globally
	var module = {};
	module.play_flag = false;

	// TODO: bind variables
	module.nextSound = undefined;
	module.nextColor = undefined;

	var width = window.innerWidth - 20;
	var height = window.innerHeight - 76;

	//var fill = d3.scale.category20();

	var force = d3.layout.force()
		.size([width, height])
		//.nodes([{}])// initialize with a single node
		.linkDistance(45).charge(-60).on("tick", tick);

	var svg = d3.select("body")
		.append("svg")
		.attr("width", width)
		.attr("height", height)
		.on("mousemove", mousemove)
		.on("mousedown", mousedown);

	svg.append("rect")
		.attr("width", width)
		.attr("height", height);

	var nodes = force.nodes(),
		links = force.links(),
		node = svg.selectAll(".node"),
		link = svg.selectAll(".link");

	module.node = node;

	var cursor = svg.append("circle")
		.attr("r", 30)
		.attr("transform", "translate(-100,-100)")
		.attr("class", "cursor");

		restart();

	function mousemove() {
		cursor.attr("transform", "translate(" + d3.mouse(this) + ")");
	}

	function mousedown() {
		var point = d3.mouse(this),
			node = { 	x : point[0],
							y : point[1],
					 sound : document.Sound.getNewSoundObjectForCurrentSound() ,
					  color   : document.plugin.getRandomColor()
			},
			n = nodes.push(node);
		// add links to any nearby nodes
		nodes.forEach(function(target) {
			var x = target.x - node.x, y = target.y - node.y;
			if (Math.sqrt(x * x + y * y) < 30) {
				links.push({source : node, target : target});
			}
		});
		restart();
	}

	function tick() {
		link.attr("x1", function(d) {return d.source.x;})
			.attr("y1", function(d) {return d.source.y;})
			.attr("x2", function(d) {return d.target.x;})
			.attr("y2", function(d) {return d.target.y;}) ;
		node.attr("cx", function(d) {return d.x;})
			.attr("cy", function(d) {return d.y;})
			.attr("style",  function(d) {return d.fill;})
	}

	function restart() {
		link = link.data(links);
		link.enter().insert("line", ".node").attr("class", "link");
		node = node.data(nodes);
		node.enter().insert("circle", ".cursor").attr("class", "node").attr("r", 7).call(force.drag);
		//node.enter().insert("circle", ".cursor").css("fill", "white").call(force.drag);
		force.start();
	}

//////////////////////// new functions
	// clear the svg content from the graph, restart graph
	function clear() {
		console.log("Function clear");
		d3.select("svg").remove();
		startGraph();
	}

	// start and stop loop functions
	var toggleLoop = function(){

		module.play_flag = !module.play_flag;

		if (module.play_flag) {
			updateLoopPosition();
			module.interval = setInterval(function () {
			var nodeIndex =  updateLoopPosition(module.currentLoopPosition);
				console.log("node index : " + nodeIndex);
				console.log("node color. : " + nodes[nodeIndex].color);
				console.log(nodes[nodeIndex].sound);

				if (document.Sound.isSoundOn) {
					nodes[nodeIndex].sound.play();
				}

			}, 700);
		}
		else {
			// if loop turned off, clear loop
			clearInterval(module.interval);
		}
	}

	//set loop
	module.currentLoopPosition=0;
	var updateLoopPosition = function (currentLoopPosition) {
		if(nodes.length <= module.currentLoopPosition){
			module.currentLoopPosition = 0;
		}
		return module.currentLoopPosition++;
	};

	module.toggleLoop = toggleLoop;
	module.clear = clear;
	return module;
})();

// debugging: get time for loading the module
var end = new Date().getTime();
//console.log("graph.js end: "+  end );
var time = end - start;
console.log("loading time for graph.js: " + time);<commit_msg>deleted toggleLoop function to avoid merge conflicts<commit_after>/*
 * module to build a graph, using the force d3.js library
 *
 D3's force layout uses the Barnes–Hut approximation to compute repulsive charge forces between all nodes efficiently. Links are implemented as geometric constraints on top of position Verlet integration, offering greater stability. A virtual spring between each node and the center of the chart prevents nodes from drifting into space
 *
 */

// debugging: get time for loading the module
var start =  new Date().getTime();
//console.log("graph.js start: "+ start);
var graph = "graph";

document.graph = (function startGraph() {

	// module object; add all methods and properties that should be visible globally
	var module = {};
	module.play_flag = false;

	// TODO: bind variables
	module.nextSound = undefined;
	module.nextColor = undefined;

	var width = window.innerWidth - 20;
	var height = window.innerHeight - 76;

	//var fill = d3.scale.category20();

	var force = d3.layout.force()
		.size([width, height])
		//.nodes([{}])// initialize with a single node
		.linkDistance(45).charge(-60).on("tick", tick);

	var svg = d3.select("body")
		.append("svg")
		.attr("width", width)
		.attr("height", height)
		.on("mousemove", mousemove)
		.on("mousedown", mousedown);

	svg.append("rect")
		.attr("width", width)
		.attr("height", height);

	var nodes = force.nodes(),
		links = force.links(),
		node = svg.selectAll(".node"),
		link = svg.selectAll(".link");

	module.node = node;

	var cursor = svg.append("circle")
		.attr("r", 30)
		.attr("transform", "translate(-100,-100)")
		.attr("class", "cursor");

		restart();

	function mousemove() {
		cursor.attr("transform", "translate(" + d3.mouse(this) + ")");
	}

	function mousedown() {
		var point = d3.mouse(this),
			node = { 	x : point[0],
							y : point[1],
					 sound : document.Sound.getNewSoundObjectForCurrentSound() ,
					  color   : document.plugin.getRandomColor()
			},
			n = nodes.push(node);
		// add links to any nearby nodes
		nodes.forEach(function(target) {
			var x = target.x - node.x, y = target.y - node.y;
			if (Math.sqrt(x * x + y * y) < 30) {
				links.push({source : node, target : target});
			}
		});
		restart();
	}

	function tick() {
		link.attr("x1", function(d) {return d.source.x;})
			.attr("y1", function(d) {return d.source.y;})
			.attr("x2", function(d) {return d.target.x;})
			.attr("y2", function(d) {return d.target.y;}) ;
		node.attr("cx", function(d) {return d.x;})
			.attr("cy", function(d) {return d.y;})
			.attr("style",  function(d) {return d.fill;})
	}

	function restart() {
		link = link.data(links);
		link.enter().insert("line", ".node").attr("class", "link");
		node = node.data(nodes);
		node.enter().insert("circle", ".cursor").attr("class", "node").attr("r", 7).call(force.drag);
		//node.enter().insert("circle", ".cursor").css("fill", "white").call(force.drag);
		force.start();
	}

//////////////////////// new functions
	// clear the svg content from the graph, restart graph
	function clear() {
		console.log("Function clear");
		d3.select("svg").remove();
		startGraph();
	}

	// start and stop loop functions
	var toggleLoop = function(){

	}

	//set loop
	module.currentLoopPosition=0;
	var updateLoopPosition = function (currentLoopPosition) {
		if(nodes.length <= module.currentLoopPosition){
			module.currentLoopPosition = 0;
		}
		return module.currentLoopPosition++;
	};

	module.toggleLoop = toggleLoop;
	module.clear = clear;
	return module;
})();

// debugging: get time for loading the module
var end = new Date().getTime();
//console.log("graph.js end: "+  end );
var time = end - start;
console.log("loading time for graph.js: " + time);<|endoftext|>