<commit_before>'use strict';

// Summary:
//  Load plugins

// Set the node_modules of Rekit Studio as the NODE_PATH to find modules.
// So that plugin could use dependencies of Rekit Studio and Rekit Core.
const utils = require('./utils');
const nodeModulesPath = require.resolve('lodash').replace('/lodash/lodash.js', '');
utils.addNodePath(nodeModulesPath);
try {
  // If rekit studio is installed globally, add rekit-studio's deps to NODE_PATH
  const rsPath = require.resolve('rekit-studio/package.json').replace(/[/\\]package\.json$/, '');
  utils.addNodePath(rsPath + '/node_modules');
  utils.addNodePath(rsPath.replace(/[/\\]rekit-studio$/, ''));
} catch (err) {
  // Do nothing if not found rekit studio
}

const fs = require('fs-extra');
const path = require('path');
const spawn = require('child_process').spawn;
const _ = require('lodash');
const os = require('os');
const paths = require('./paths');
const config = require('./config');
const logger = require('./logger');
const downloadNpmPackage = require('download-npm-package');

let appliedPlugins = undefined;
let allPlugins = [];
let loaded = false;
let needFilterPlugin = true;

const DEFAULT_PLUGIN_DIR = path.join(os.homedir(), '.rekit/plugins');

const pluginsDirs = [DEFAULT_PLUGIN_DIR];
function addPluginsDir(dir) {
  pluginsDirs.push(dir);
}
function getPluginsDir() {
  return DEFAULT_PLUGIN_DIR;
}

function getPlugins(prop) {
  if (!loaded) {
    // load built-in plugins
    fs.readdirSync(path.join(__dirname, '../plugins')).forEach(d => {
      d = path.join(__dirname, '../plugins', d);
      if (fs.statSync(d).isDirectory() && fs.existsSync(path.join(d, 'index.js'))) {
        const p = require(d);
        p.root = d;
        addPlugin(p);
      }
    });
    if (fs.existsSync(DEFAULT_PLUGIN_DIR)) loadPlugins(DEFAULT_PLUGIN_DIR);
    // Load plugin from environment variable: REKIT_PLUGIN_DIR , used in plugin dev time
    // This doesn't load UI part, only for cli testing purpose
    if (process.env.REKIT_PLUGIN_DIR) {
      const d = process.env.REKIT_PLUGIN_DIR;
      if (!path.isAbsolute(d))
        throw new Error(`REKIT_PLUGIN_DIR should be absolute path, got: ${d}`);
      addPluginByPath(d, true);
    }
    sortPlugins();
    loaded = true;
  }

  filterPluginsIfNecessary();
  appliedPlugins.forEach(p => {
    if (p.initialize && !p.__initialized) {
      p.initialize();
      p.__initialized = true;
    }
  });
  return prop ? appliedPlugins.filter(_.property(prop)) : appliedPlugins;
}

function sortPlugins() {
  // Sort plugins according dep relations and Rekit config.
  const rekitConfig = config.getRekitConfig();
  const pluginOrder = rekitConfig.pluginOrder || [];

  allPlugins.sort((p1, p2) => {
    const p1Index = pluginOrder.indexOf(p1.name);
    const p2Index = pluginOrder.indexOf(p2.name);
    if (p1.dependencies && p1.dependencies.includes(p2.name)) {
      // If p1 depends on p2, load p2 first
      return 1;
    }
    if (p2.dependencies && p2.dependencies.includes(p1.name)) {
      // If p2 depends on p1, load p1 first
      return -1;
    }
    if (p1Index >= 0 && p2Index === -1) {
      // If only p1 configed, load it first
      return -1;
    }
    if (p2Index >= 0 && p1Index === -1) {
      // If only p2 configed, load it first
      return 1;
    }
    if (p1Index >= 0 && p2Index >= 0) {
      // If both configed, load before first
      return p1Index - p2Index;
    }
    // No order specified.
    return 0;
  });
}

function filterPluginsIfNecessary() {
  initPluginsIfNecessary();
  if (!needFilterPlugin) return;
  const rekitConfig = config.getRekitConfig();

  // A plugin could decide if it's fit for the current project by feature files
  logger.info('All plugins:', allPlugins.map(p => p.name));
  const appType = rekitConfig.appType;
  appliedPlugins = allPlugins.filter(
    p =>
      (!p.shouldUse || p.shouldUse(paths.getProjectRoot())) &&
      (!p.appType || _.castArray(p.appType).includes(appType)) &&
      !(rekitConfig.excludePlugins || []).map(s => s.replace('rekit-plugin', '')).includes(p.name),
  );
  logger.info('Applied plugins for appType ' + appType + ': ', appliedPlugins.map(p => p.name));
  needFilterPlugin = false;
}

function initPluginsIfNecessary() {
  allPlugins = allPlugins.map(plugin => {
    if (!plugin.inherit) return plugin;
    const newPlugin = { uiInherit: [] };
    _.castArray(plugin.inherit).forEach(name => {
      // currently only one level inherit supported?
      const p = getPlugin(name);
      if (!p) {
        throw new Error('INHERIT_PLUGIN_NOT_FOUND: ' + name + ' inherited by ' + plugin.name);
      }
      newPlugin.uiInherit.push(name);
      _.merge(newPlugin, p);
    });
    _.merge(newPlugin, plugin);
    newPlugin.__originalInherit = plugin.inherit;
    delete newPlugin.inherit; // only inherit once
    return newPlugin;
  });
}

function getPlugin(name) {
  return _.find(allPlugins, { name }) || null;
}

// Load plugin instance, plugin depends on project config
function loadPlugin(pluginRoot, noUI) {
  // noUI flag is used for loading dev plugins whose ui is from webpack dev server
  try {
    // const pkgJson = require(paths.join(pluginRoot, 'package.json'));
    const pluginInstance = { root: pluginRoot };
    // Core part
    const coreIndex = paths.join(pluginRoot, 'core/index.js');
    if (fs.existsSync(coreIndex)) {
      Object.assign(pluginInstance, require(coreIndex));
    }

    // UI part
    if (!noUI) {
      let entry = 'main.js';
      if (
        process.env.NODE_ENV === 'development' &&
        fs.existsSync(path.join(pluginRoot, 'build', 'main-dev.js'))
      ) {
        entry = 'main-dev.js';
      }
      if (fs.existsSync(path.join(pluginRoot, 'build', entry))) {
        pluginInstance.ui = {
          root: path.join(pluginRoot, 'build'),
          entry,
        };
      }
    }

    // Plugin meta defined in package.json
    const pkgJsonPath = path.join(pluginRoot, 'package.json');
    let pkgJson = null;
    if (fs.existsSync(pkgJsonPath)) {
      pkgJson = fs.readJsonSync(pkgJsonPath);

      ['appType', 'name', 'version'].forEach(key => {
        if (!pluginInstance.hasOwnProperty(key) && pkgJson.hasOwnProperty(key)) {
          if (key === 'name') {
            let name = pkgJson.name;
            if (name.startsWith('rekit-plugin')) name = name.replace('rekit-plugin-', '');
            pluginInstance.name = name;
          } else {
            pluginInstance[key] = pkgJson[key] || null;
          }
        }
      });
      if (pkgJson.rekitPlugin) {
        Object.keys(pkgJson.rekitPlugin).forEach(key => {
          if (!pluginInstance.hasOwnProperty(key)) {
            pluginInstance[key] = pkgJson.rekitPlugin[key];
          }
        });
      }
    }
    if (!pluginInstance.version) pluginInstance.version = '0.0.1';
    return pluginInstance;
  } catch (e) {
    logger.warn(`Failed to load plugin: ${pluginRoot}`, e);
  }

  return null;
}

function loadPlugins(dir) {
  // At rekit studio dev time, do not load dist plugins from dir.
  // Because Rekit Studio doesn't support it at dev time.
  if (process.env.REKIT_STUDIO_DEVELOPMENT) return;
  fs.readdirSync(dir)
    .map(d => path.join(dir, d))
    .filter(d => fs.statSync(d).isDirectory())
    .forEach(d => addPluginByPath(d));
}

// Dynamically add an plugin
function addPlugin(plugin) {
  if (!plugin) {
    return;
  }
  if (!needFilterPlugin) {
    console.warn('You are adding a plugin after getPlugins is called.');
  }
  if (!plugin.getModule) {
    plugin.getModule = mid => {
      try {
        return require(path.join(plugin.root, mid));
      } catch (err) {
        logger.debug('Faied to load module: ' + mid, err);
        return null;
      }
    };
  }
  needFilterPlugin = true;
  if (!plugin.name) {
    logger.info('plugin: ', plugin);
    throw new Error('Each plugin should have a name.');
  }
  if (_.find(allPlugins, { name: plugin.name })) {
    console.warn('You should not add a plugin with same name: ' + plugin.name);
    return;
  }
  allPlugins.push(plugin);
}

function addPluginByPath(pluginRoot, noUI) {
  addPlugin(loadPlugin(pluginRoot, noUI));
}

function removePlugin(pluginName) {
  const removed = _.remove(allPlugins, { name: pluginName });
  needFilterPlugin = true;
  if (!removed.length) console.warn('No plugin was removed: ' + pluginName);
}

function listInstalledPlugins() {
  // Only get plugins from standard rekit plugin folder
  const dir = paths.configFile('plugins2');
  const plugins = [];

  if (fs.existsSync(dir))
    fs.readdirSync(dir)
      .filter(name => /^rekit-plugin-/.test(name))
      .map(name => path.join(dir, name))
      .filter(d => fs.statSync(d).isDirectory())
      .forEach(pluginRoot => {
        try {
          const pkgJson = require(paths.join(pluginRoot, 'package.json'));
          // Plugin info
          const pluginInfo = {};
          Object.assign(pluginInfo, pkgJson);

          plugins.push(pluginInfo);
        } catch (err) {
          console.log('Failed to load plugin info: ', pluginRoot);
        }
      });

  return plugins;
}
function installPlugin(name) {
  if (!/^rekit-plugin-/.test(name)) {
    name = 'rekit-plugin-' + name;
  }
  logger.info('Installing plugin: ' + name);
  const destDir = paths.configFile('plugins/' + name);
  if (fs.existsSync(destDir)) {
    logger.info('Plugin already installed, reinstalling it...');
    fs.removeSync(destDir);
  }
  downloadNpmPackage({ arg: name, dir: paths.configFile('plugins') })
    .then(() => {
      const pkgJson = require(path.join(destDir, 'package.json'));
      if (!_.isEmpty(pkgJson.dependencies)) {
        console.log('Plugin downloaded, installing its dependencies...');
        const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
        const child = spawn(npmCmd, ['install', '--colors', '--only=production'], {
          stdio: 'inherit',
          cwd: destDir,
        });
        let failed = false;
        child.on('exit', () => {
          if (!failed) logger.info(`Plugin installed successfully: ${name}@${pkgJson.version}.`);
        });
        child.on('error', err => {
          failed = true;
          logger.error('Failed to install deps of the plugin. Remove plugin.', err);
          fs.removeSync(destDir);
        });
      } else {
        logger.info(`Plugin installed successfully: ${name}@${pkgJson.version}.`);
      }
    })
    .catch(err => {
      logger.error('Failed to download plugin.', err);
    });
}

function uninstallPlugin(name) {
  if (!/^rekit-plugin-/.test(name)) {
    name = 'rekit-plugin-' + name;
  }
  logger.info('Uninstalling plugin: ', name);
  const destDir = paths.configFile('plugins/' + name);
  if (fs.existsSync(destDir)) {
    fs.removeSync(destDir);
    logger.info('Done.');
  } else {
    logger.info('Plugin not exist: ' + name);
  }
}

module.exports = {
  getPlugins,
  getPlugin,
  loadPlugins,
  addPlugin,
  addPluginByPath,
  removePlugin,
  getPluginsDir,
  addPluginsDir,
  installPlugin,
  uninstallPlugin,
  listInstalledPlugins,
};
<commit_msg>Allow to list all plugins.<commit_after>'use strict';

// Summary:
//  Load plugins

// Set the node_modules of Rekit Studio as the NODE_PATH to find modules.
// So that plugin could use dependencies of Rekit Studio and Rekit Core.
const utils = require('./utils');
const nodeModulesPath = require.resolve('lodash').replace('/lodash/lodash.js', '');
utils.addNodePath(nodeModulesPath);
try {
  // If rekit studio is installed globally, add rekit-studio's deps to NODE_PATH
  const rsPath = require.resolve('rekit-studio/package.json').replace(/[/\\]package\.json$/, '');
  utils.addNodePath(rsPath + '/node_modules');
  utils.addNodePath(rsPath.replace(/[/\\]rekit-studio$/, ''));
} catch (err) {
  // Do nothing if not found rekit studio
}

const fs = require('fs-extra');
const path = require('path');
const spawn = require('child_process').spawn;
const _ = require('lodash');
const os = require('os');
const paths = require('./paths');
const config = require('./config');
const logger = require('./logger');
const downloadNpmPackage = require('download-npm-package');

let appliedPlugins = undefined;
let allPlugins = [];
let loaded = false;
let needFilterPlugin = true;

const DEFAULT_PLUGIN_DIR = path.join(os.homedir(), '.rekit/plugins');

const pluginsDirs = [DEFAULT_PLUGIN_DIR];
function addPluginsDir(dir) {
  pluginsDirs.push(dir);
}
function getPluginsDir() {
  return DEFAULT_PLUGIN_DIR;
}

function getPlugins(prop) {
  getAllPlugins();

  filterPluginsIfNecessary();
  appliedPlugins.forEach(p => {
    if (p.initialize && !p.__initialized) {
      p.initialize();
      p.__initialized = true;
    }
  });
  return prop ? appliedPlugins.filter(_.property(prop)) : appliedPlugins;
}

function sortPlugins() {
  // Sort plugins according dep relations and Rekit config.
  const rekitConfig = config.getRekitConfig();
  const pluginOrder = rekitConfig.pluginOrder || [];

  allPlugins.sort((p1, p2) => {
    const p1Index = pluginOrder.indexOf(p1.name);
    const p2Index = pluginOrder.indexOf(p2.name);
    if (p1.dependencies && p1.dependencies.includes(p2.name)) {
      // If p1 depends on p2, load p2 first
      return 1;
    }
    if (p2.dependencies && p2.dependencies.includes(p1.name)) {
      // If p2 depends on p1, load p1 first
      return -1;
    }
    if (p1Index >= 0 && p2Index === -1) {
      // If only p1 configed, load it first
      return -1;
    }
    if (p2Index >= 0 && p1Index === -1) {
      // If only p2 configed, load it first
      return 1;
    }
    if (p1Index >= 0 && p2Index >= 0) {
      // If both configed, load before first
      return p1Index - p2Index;
    }
    // No order specified.
    return 0;
  });
}

function filterPluginsIfNecessary() {
  initPluginsIfNecessary();
  if (!needFilterPlugin) return;
  const rekitConfig = config.getRekitConfig();

  // A plugin could decide if it's fit for the current project by feature files
  logger.info('All plugins:', allPlugins.map(p => p.name));
  const appType = rekitConfig.appType;
  appliedPlugins = allPlugins.filter(
    p =>
      (!p.shouldUse || p.shouldUse(paths.getProjectRoot())) &&
      (!p.appType || _.castArray(p.appType).includes(appType)) &&
      !(rekitConfig.excludePlugins || []).map(s => s.replace('rekit-plugin', '')).includes(p.name),
  );
  logger.info('Applied plugins for appType ' + appType + ': ', appliedPlugins.map(p => p.name));
  needFilterPlugin = false;
}

function initPluginsIfNecessary() {
  allPlugins = allPlugins.map(plugin => {
    if (!plugin.inherit) return plugin;
    const newPlugin = { uiInherit: [] };
    _.castArray(plugin.inherit).forEach(name => {
      // currently only one level inherit supported?
      const p = getPlugin(name);
      if (!p) {
        throw new Error('INHERIT_PLUGIN_NOT_FOUND: ' + name + ' inherited by ' + plugin.name);
      }
      newPlugin.uiInherit.push(name);
      _.merge(newPlugin, p);
    });
    _.merge(newPlugin, plugin);
    newPlugin.__originalInherit = plugin.inherit;
    delete newPlugin.inherit; // only inherit once
    return newPlugin;
  });
}

function getPlugin(name) {
  return _.find(allPlugins, { name }) || null;
}

// Load plugin instance, plugin depends on project config
function loadPlugin(pluginRoot, noUI) {
  // noUI flag is used for loading dev plugins whose ui is from webpack dev server
  try {
    // const pkgJson = require(paths.join(pluginRoot, 'package.json'));
    const pluginInstance = { root: pluginRoot };
    // Core part
    const coreIndex = paths.join(pluginRoot, 'core/index.js');
    if (fs.existsSync(coreIndex)) {
      Object.assign(pluginInstance, require(coreIndex));
    }

    // UI part
    if (!noUI) {
      let entry = 'main.js';
      if (
        process.env.NODE_ENV === 'development' &&
        fs.existsSync(path.join(pluginRoot, 'build', 'main-dev.js'))
      ) {
        entry = 'main-dev.js';
      }
      if (fs.existsSync(path.join(pluginRoot, 'build', entry))) {
        pluginInstance.ui = {
          root: path.join(pluginRoot, 'build'),
          entry,
        };
      }
    }

    // Plugin meta defined in package.json
    const pkgJsonPath = path.join(pluginRoot, 'package.json');
    let pkgJson = null;
    if (fs.existsSync(pkgJsonPath)) {
      pkgJson = fs.readJsonSync(pkgJsonPath);

      ['appType', 'name', 'version'].forEach(key => {
        if (!pluginInstance.hasOwnProperty(key) && pkgJson.hasOwnProperty(key)) {
          if (key === 'name') {
            let name = pkgJson.name;
            if (name.startsWith('rekit-plugin')) name = name.replace('rekit-plugin-', '');
            pluginInstance.name = name;
          } else {
            pluginInstance[key] = pkgJson[key] || null;
          }
        }
      });
      if (pkgJson.rekitPlugin) {
        Object.keys(pkgJson.rekitPlugin).forEach(key => {
          if (!pluginInstance.hasOwnProperty(key)) {
            pluginInstance[key] = pkgJson.rekitPlugin[key];
          }
        });
      }
    }
    if (!pluginInstance.version) pluginInstance.version = '0.0.1';
    return pluginInstance;
  } catch (e) {
    logger.warn(`Failed to load plugin: ${pluginRoot}`, e);
  }

  return null;
}

function loadPlugins(dir) {
  // At rekit studio dev time, do not load dist plugins from dir.
  // Because Rekit Studio doesn't support it at dev time.
  if (process.env.REKIT_STUDIO_DEVELOPMENT) return;
  fs.readdirSync(dir)
    .map(d => path.join(dir, d))
    .filter(d => fs.statSync(d).isDirectory())
    .forEach(d => addPluginByPath(d));
}

// Dynamically add an plugin
function addPlugin(plugin) {
  if (!plugin) {
    return;
  }
  if (!needFilterPlugin) {
    console.warn('You are adding a plugin after getPlugins is called.');
  }
  if (!plugin.getModule) {
    plugin.getModule = mid => {
      try {
        return require(path.join(plugin.root, mid));
      } catch (err) {
        logger.debug('Faied to load module: ' + mid, err);
        return null;
      }
    };
  }
  needFilterPlugin = true;
  if (!plugin.name) {
    logger.info('plugin: ', plugin);
    throw new Error('Each plugin should have a name.');
  }
  if (_.find(allPlugins, { name: plugin.name })) {
    console.warn('You should not add a plugin with same name: ' + plugin.name);
    return;
  }
  allPlugins.push(plugin);
}

function addPluginByPath(pluginRoot, noUI) {
  addPlugin(loadPlugin(pluginRoot, noUI));
}

function removePlugin(pluginName) {
  const removed = _.remove(allPlugins, { name: pluginName });
  needFilterPlugin = true;
  if (!removed.length) console.warn('No plugin was removed: ' + pluginName);
}

function listInstalledPlugins() {
  // Only get plugins from standard rekit plugin folder
  const dir = paths.configFile('plugins2');
  const plugins = [];

  if (fs.existsSync(dir))
    fs.readdirSync(dir)
      .filter(name => /^rekit-plugin-/.test(name))
      .map(name => path.join(dir, name))
      .filter(d => fs.statSync(d).isDirectory())
      .forEach(pluginRoot => {
        try {
          const pkgJson = require(paths.join(pluginRoot, 'package.json'));
          // Plugin info
          const pluginInfo = {};
          Object.assign(pluginInfo, pkgJson);

          plugins.push(pluginInfo);
        } catch (err) {
          console.log('Failed to load plugin info: ', pluginRoot);
        }
      });

  return plugins;
}

const getInstalledPlugins = listInstalledPlugins;

function getAllPlugins() {
  if (!loaded) {
    // load built-in plugins
    fs.readdirSync(path.join(__dirname, '../plugins')).forEach(d => {
      d = path.join(__dirname, '../plugins', d);
      if (fs.statSync(d).isDirectory() && fs.existsSync(path.join(d, 'index.js'))) {
        const p = require(d);
        p.root = d;
        addPlugin(p);
      }
    });
    if (fs.existsSync(DEFAULT_PLUGIN_DIR)) loadPlugins(DEFAULT_PLUGIN_DIR);
    // Load plugin from environment variable: REKIT_PLUGIN_DIR , used in plugin dev time
    // This doesn't load UI part, only for cli testing purpose
    if (process.env.REKIT_PLUGIN_DIR) {
      const d = process.env.REKIT_PLUGIN_DIR;
      if (!path.isAbsolute(d))
        throw new Error(`REKIT_PLUGIN_DIR should be absolute path, got: ${d}`);
      addPluginByPath(d, true);
    }
    sortPlugins();
    loaded = true;
  }

  return allPlugins;
}

function installPlugin(name) {
  if (!/^rekit-plugin-/.test(name)) {
    name = 'rekit-plugin-' + name;
  }
  logger.info('Installing plugin: ' + name);
  const destDir = paths.configFile('plugins/' + name);
  if (fs.existsSync(destDir)) {
    logger.info('Plugin already installed, reinstalling it...');
    fs.removeSync(destDir);
  }
  downloadNpmPackage({ arg: name, dir: paths.configFile('plugins') })
    .then(() => {
      const pkgJson = require(path.join(destDir, 'package.json'));
      if (!_.isEmpty(pkgJson.dependencies)) {
        console.log('Plugin downloaded, installing its dependencies...');
        const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
        const child = spawn(npmCmd, ['install', '--colors', '--only=production'], {
          stdio: 'inherit',
          cwd: destDir,
        });
        let failed = false;
        child.on('exit', () => {
          if (!failed) logger.info(`Plugin installed successfully: ${name}@${pkgJson.version}.`);
        });
        child.on('error', err => {
          failed = true;
          logger.error('Failed to install deps of the plugin. Remove plugin.', err);
          fs.removeSync(destDir);
        });
      } else {
        logger.info(`Plugin installed successfully: ${name}@${pkgJson.version}.`);
      }
    })
    .catch(err => {
      logger.error('Failed to download plugin.', err);
    });
}

function uninstallPlugin(name) {
  if (!/^rekit-plugin-/.test(name)) {
    name = 'rekit-plugin-' + name;
  }
  logger.info('Uninstalling plugin: ', name);
  const destDir = paths.configFile('plugins/' + name);
  if (fs.existsSync(destDir)) {
    fs.removeSync(destDir);
    logger.info('Done.');
  } else {
    logger.info('Plugin not exist: ' + name);
  }
}

module.exports = {
  getPlugins,
  getPlugin,
  loadPlugins,
  addPlugin,
  addPluginByPath,
  removePlugin,
  getPluginsDir,
  addPluginsDir,
  installPlugin,
  uninstallPlugin,
  listInstalledPlugins,
  getInstalledPlugins,
  getAllPlugins,
};
<|endoftext|>


<commit_before>
new FunctionNode({
	label: 'f-node',
	header: 'pink',
	background: 'f',
	position: [50,100],
	process:  {
		func: function(a, b) { return a - b; },
		stringFunc: function(a, b) { return `${a} - ${b}`; },
		params: [{label: 'a'}, {label: 'b'}],
		result: {label: 'f(a,b)'}
	},
});

new OperatorNode({
	label: 'o-node',
	header: 'lightblue',
	background: '+',
	position: [275,275],
    process:  {
		func: function(a, b) { return a + b; },
		stringFunc: function(a, b) { return `${a} + ${b}`; },
		params: [{label: 'a'}, {label: 'b'}],
		result: {label: 'result'}
	},
});

new OperatorNode({
	label: 'fake getter',
	header: 'cadetblue',
	position: [50,250],
    process:  {
		func: function(a, b) { return 1; },
		stringFunc: function(a, b) { return `1`; },
		params: [],
		result: {label: '1'}
	},
});

new OperatorNode({
	label: 'fake getter',
	header: 'cadetblue',
	position: [50,350],
    process:  {
		func: function(a, b) { return 2; },
		stringFunc: function(a, b) { return `2`; },
		params: [],
		result: {label: '2'}
	},
});

new GetterNode({
	label: 'g-node',
	header: 'lightgreen',
	background: 'a',
	position: [450,150],
});

new SetterNode({
	label: 's-node',
	header: 'navyblue',
	background: 'c',
	position: [570,292],
});

new ControlFlowNode({
	type: 'Conditional',
	label: 'cf-node',
	header: 'lightcoral',
	background: '?',
	position: [750,100],
});

new ControlFlowNode({
	type: 'ForLoop',
	label: 'cf-node',
	header: 'lightslategray',
	background: '🤢',
	position: [750,250],
});

wait(() => {
	const n1 = Node.all.n3;
	const n2 = Node.all.n4;
	const n6 = Node.all.n2;
	const n4 = Node.all.n6;
	const n11 = Node.all.n1;
	const n7 = Node.all.n7;

	new Link(n1.process.outputs.first, n6.process.inputs[0]);
	new Link(n2.process.outputs.first, n6.process.inputs[1]);
	new Link(n6.process.outputs.first, n4.process.inputs[0]);
	new Link(n6.process.outputs.first, n7.process.inputs[0]);

	new Link(n11.router.out.first, n7.router.in.first);

	n1.process.dependencies.add('a');
	n1.process.parents.add(n1);
	n1.process.outputs.first.result = 1;
	n1.process.outputs.first.stringified = '1';

	n2.process.dependencies.add('b');
	n2.process.parents.add(n2);
	n2.process.outputs.first.result = 2;
	n2.process.outputs.first.stringified = '2';

	n1.process.outputs.first.propagate(true);

	$_.newline();

	n11.router.in.first.trigger();

});<commit_msg>[cg2020] ET update triggered by data propagation.<commit_after>
new FunctionNode({
	label: 'f-node',
	header: 'pink',
	background: 'f',
	position: [50,100],
	process:  {
		func: function(a, b) { return a - b; },
		stringFunc: function(a, b) { return `${a} - ${b}`; },
		params: [{label: 'a'}, {label: 'b'}],
		result: {label: 'f(a,b)'}
	},
});

new OperatorNode({
	label: 'o-node',
	header: 'lightblue',
	background: '+',
	position: [275,275],
    process:  {
		func: function(a, b) { return a + b; },
		stringFunc: function(a, b) { return `${a} + ${b}`; },
		params: [{label: 'a'}, {label: 'b'}],
		result: {label: 'result'}
	},
});

new OperatorNode({
	label: 'fake getter',
	header: 'cadetblue',
	position: [50,250],
    process:  {
		func: function(a, b) { return 1; },
		stringFunc: function(a, b) { return `1`; },
		params: [],
		result: {label: '1'}
	},
});

new OperatorNode({
	label: 'fake getter',
	header: 'cadetblue',
	position: [50,350],
    process:  {
		func: function(a, b) { return 2; },
		stringFunc: function(a, b) { return `2`; },
		params: [],
		result: {label: '2'}
	},
});

new GetterNode({
	label: 'g-node',
	header: 'lightgreen',
	background: 'a',
	position: [450,150],
});

new SetterNode({
	label: 's-node',
	header: 'navyblue',
	background: 'c',
	position: [570,292],
});

new ControlFlowNode({
	type: 'Conditional',
	label: 'cf-node',
	header: 'lightcoral',
	background: '?',
	position: [750,100],
});

new ControlFlowNode({
	type: 'ForLoop',
	label: 'cf-node',
	header: 'lightslategray',
	background: '🤢',
	position: [750,250],
});

wait(() => {
	const n1 = Node.all.n3;
	const n2 = Node.all.n4;
	const n6 = Node.all.n2;
	const n4 = Node.all.n6;
	const n11 = Node.all.n1;
	const n7 = Node.all.n7;

	new Link(n1.process.outputs.first, n6.process.inputs[0]);
	new Link(n2.process.outputs.first, n6.process.inputs[1]);
	new Link(n6.process.outputs.first, n4.process.inputs[0]);
	new Link(n6.process.outputs.first, n7.process.inputs[0]);

	new Link(n11.router.out.first, n7.router.in.first);

	n1.process.dependencies.add('a');
	n1.process.parents.add(n1);
	n1.process.outputs.first.result = 1;
	n1.process.outputs.first.stringified = '1';

	n2.process.dependencies.add('b');
	n2.process.parents.add(n2);
	n2.process.outputs.first.result = 2;
	n2.process.outputs.first.stringified = '2';

	// <? n1.router.execute(true); fails, cf. zip accessed array[0])
	n1.process.outputs.first.propagate(true);

	// n11.router.in.first.trigger();

});<|endoftext|>


<commit_before>(function($) {

$.widget("mapbender.mbZoomBar", {
    options: {
        target: null,
        stepSize: 50,
        stepByPixel: false,
        position: [0, 0],
        draggable: true},

    mapDiv: null,
    map: null,
    zoomslider: null,
    navigationHistoryControl: null,
    zoomBoxControl: null,

    _create: function() {
        if(!Mapbender.checkTarget("mbZoomBar", this.options.target)){
            return;
        }
        var self = this;
        Mapbender.elementRegistry.onElementReady(this.options.target, $.proxy(self._setup, self));
    },

    _setup: function() {
        this.mapDiv = $('#' + this.options.target);
        this.map = this.mapDiv.data('mapbenderMbMap').map.olMap;
        this._setupSlider();
        this._setupZoomButtons();
        this._setupPanButtons();
        this.map.events.register('zoomend', this, this._zoom2Slider);
        this._zoom2Slider();

        if(this.options.draggable === true) {
            this.element.addClass("iconMove").draggable({
                containment: this.element.closest('.region'),
                start: function() {
                    $(this).css("right", "inherit").add('dragging');
                }
            });
        }
        $(this.element).find('.iconZoomMin').bind("click" ,$.proxy(this._worldZoom, this));

        this._trigger('ready');
        this._ready();
    },

    _destroy: $.noop,

    _worldZoom: function(e) {
        this.map.zoomToMaxExtent();
    },

    _setupSlider: function() {
        this.zoomslider = this.element.find('.zoomSlider .zoomSliderLevels')
            .hide()
            .empty();

        var levelsNumber = this.map.getNumZoomLevels();
        for(var i = 0; i < levelsNumber; i++) {
            var resolution = this.map.getResolutionForZoom(levelsNumber - i - 1);
            var scale = Math.round(OpenLayers.Util.getScaleFromResolution(resolution, this.map.units));
            this.zoomslider.append($('

'));
            this.zoomslider.append($('

'));
        }

        this.zoomslider.find('li').last()
            .addClass('iconZoomLevelSelected')
            .append($('

'));

        var step = [
            this.zoomslider.find('li').last().width(),
            this.zoomslider.find('li').last().height()];

        this.zoomslider.sortable({
                axis: 'y', // TODO: Orientation
                containment: this.zoomslider,
                grid: step,
                handle: 'div',
                tolerance: 'pointer',
                stop: $.proxy(this._slider2Zoom, this)
            });
        this.zoomslider.show();

        var self = this;
        this.zoomslider.find('li').click(function() {
            var li = $(this);
            var index = li.index();
            var position = self.map.getNumZoomLevels() - 1 - index;
            self.map.zoomTo(position);
        });
    },

    _click: function(call) {
        if(this.element.hasClass('dragging')) {
            this.element.removeClass('dragging');
            return false;
        }
        call();
    },

    _setupZoomButtons: function() {
        var self = this;

        this.navigationHistoryControl =
            new OpenLayers.Control.NavigationHistory();
        this.map.addControl(this.navigationHistoryControl);

        this.zoomBoxControl = new OpenLayers.Control();
        OpenLayers.Util.extend(this.zoomBoxControl, {
            handler: null,
            autoActivate: false,

            draw: function() {
                this.handler = new OpenLayers.Handler.Box(this, {
                    done: $.proxy(self._zoomToBox, self) }, {
                    keyMask: OpenLayers.Handler.MOD_NONE});
            },

            CLASS_NAME: 'Mapbender.Control.ZoomBox',
            displayClass: 'MapbenderControlZoomBox'
        });

        this.map.addControl(this.zoomBoxControl);
        this.element.find('.zoomBox').bind('click', function() {
            $(this).toggleClass('activeZoomIcon');
            if($(this).hasClass('activeZoomIcon')) {
                self.zoomBoxControl.activate();
            } else {
                self.zoomBoxControl.deactivate();
            }
        });

        this.element.find(".history .historyPrev").bind("click", function(){
            self.navigationHistoryControl.previous.trigger();
        });
        this.element.find(".history .historyNext").bind("click", function(){
            self.navigationHistoryControl.next.trigger();
        });

        this.element.find('.zoomSlider .iconZoomIn').bind('click',
            $.proxy(this.map.zoomIn, this.map));
        this.element.find('.zoomSlider .iconZoomOut').bind('click',
            $.proxy(this.map.zoomOut, this.map));
    },

    _zoomToBox: function(position) {
        var zoom, center;
        if(position instanceof OpenLayers.Bounds) {
            var minXY = this.map.getLonLatFromPixel(
                new OpenLayers.Pixel(position.left, position.bottom));
            var maxXY = this.map.getLonLatFromPixel(
                new OpenLayers.Pixel(position.right, position.top));
            var bounds = new OpenLayers.Bounds(minXY.lon, minXY.lat,
                maxXY.lon, maxXY.lat);
            zoom = this.map.getZoomForExtent(bounds);
            center = bounds.getCenterLonLat();
        } else {
            zoom = this.map.getZoom() + 1;
            center = this.map.getLonLatFromPixel(position);
        }

        this.map.setCenter(center, zoom);

        this.zoomBoxControl.deactivate();
        this.element.find('.zoomBox').removeClass('activeZoomIcon');
    },

    _setupPanButtons: function() {
        var self = this;
        var pan = $.proxy(this.map.pan, this.map);
        var stepSize = {
            x: parseInt(this.options.stepSize),
            y: parseInt(this.options.stepSize)};

        if(this.options.stepByPixel === "false") {
            stepSize = {
                x: Math.max(Math.min(stepSize.x, 100), 0) / 100.0 *
                    this.map.getSize().w,
                y: Math.max(Math.min(stepSize.x, 100), 0) / 100.0 *
                    this.map.getSize().h};
        }

        this.element.find(".panUp").bind("click", function(){pan(0, -stepSize.y);});
        this.element.find(".panRight").bind("click", function(){pan(+stepSize.x, 0);})
        this.element.find(".panDown").bind("click", function(){pan(0, +stepSize.y);})
        this.element.find(".panLeft").bind("click", function(){pan(-stepSize.x, 0);})
    },

    /**
     * Set map zoom level from slider
     */
    _slider2Zoom: function() {
        var position = this.zoomslider.find('li.active').index(),
            index = this.map.getNumZoomLevels() - 1 - position;

        this.map.zoomTo(index);
    },

    /**
     * Set slider to reflect map zoom level
     */
    _zoom2Slider: function() {
        var position = this.map.getNumZoomLevels() - 1 - this.map.getZoom();

        this.zoomslider.find('.iconZoomLevelSelected')
            .removeClass('iconZoomLevelSelected')
            .empty();
        this.zoomslider.find('li').eq(position)
            .addClass('iconZoomLevelSelected')
            .append($('

'));
    },
    /**
         *
         */
        ready: function(callback) {
            if(this.readyState === true) {
                callback();
            } else {
                this.readyCallbacks.push(callback);
            }
        },
        /**
         *
         */
        _ready: function() {
            for(callback in this.readyCallbacks) {
                callback();
                delete(this.readyCallbacks[callback]);
            }
            this.readyState = true;
        }
});

})(jQuery);
<commit_msg>Fix doublets zoom level dots<commit_after>(function($) {

$.widget("mapbender.mbZoomBar", {
    options: {
        target: null,
        stepSize: 50,
        stepByPixel: false,
        position: [0, 0],
        draggable: true},

    mapDiv: null,
    map: null,
    zoomslider: null,
    navigationHistoryControl: null,
    zoomBoxControl: null,

    _create: function() {
        if(!Mapbender.checkTarget("mbZoomBar", this.options.target)){
            return;
        }
        var self = this;
        Mapbender.elementRegistry.onElementReady(this.options.target, $.proxy(self._setup, self));
    },

    _setup: function() {
        this.mapDiv = $('#' + this.options.target);
        this.map = this.mapDiv.data('mapbenderMbMap').map.olMap;
        this._setupSlider();
        this._setupZoomButtons();
        this._setupPanButtons();
        this.map.events.register('zoomend', this, this._zoom2Slider);
        this._zoom2Slider();

        if(this.options.draggable === true) {
            this.element.addClass("iconMove").draggable({
                containment: this.element.closest('.region'),
                start: function() {
                    $(this).css("right", "inherit").add('dragging');
                }
            });
        }
        $(this.element).find('.iconZoomMin').bind("click" ,$.proxy(this._worldZoom, this));

        this._trigger('ready');
        this._ready();
    },

    _destroy: $.noop,

    _worldZoom: function(e) {
        this.map.zoomToMaxExtent();
    },

    _setupSlider: function() {
        this.zoomslider = this.element.find('.zoomSlider .zoomSliderLevels')
            .hide()
            .empty();

        var levelsNumber = this.map.getNumZoomLevels();
        for(var i = 0; i < levelsNumber; i++) {
            var resolution = this.map.getResolutionForZoom(levelsNumber - i - 1);
            var scale = Math.round(OpenLayers.Util.getScaleFromResolution(resolution, this.map.units));
            this.zoomslider.append($('
'));
        }

        this.zoomslider.find('li').last()
            .addClass('iconZoomLevelSelected')
            .append($('

'));

        var step = [
            this.zoomslider.find('li').last().width(),
            this.zoomslider.find('li').last().height()];

        this.zoomslider.sortable({
                axis: 'y', // TODO: Orientation
                containment: this.zoomslider,
                grid: step,
                handle: 'div',
                tolerance: 'pointer',
                stop: $.proxy(this._slider2Zoom, this)
            });
        this.zoomslider.show();

        var self = this;
        this.zoomslider.find('li').click(function() {
            var li = $(this);
            var index = li.index();
            var position = self.map.getNumZoomLevels() - 1 - index;
            self.map.zoomTo(position);
        });
    },

    _click: function(call) {
        if(this.element.hasClass('dragging')) {
            this.element.removeClass('dragging');
            return false;
        }
        call();
    },

    _setupZoomButtons: function() {
        var self = this;

        this.navigationHistoryControl =
            new OpenLayers.Control.NavigationHistory();
        this.map.addControl(this.navigationHistoryControl);

        this.zoomBoxControl = new OpenLayers.Control();
        OpenLayers.Util.extend(this.zoomBoxControl, {
            handler: null,
            autoActivate: false,

            draw: function() {
                this.handler = new OpenLayers.Handler.Box(this, {
                    done: $.proxy(self._zoomToBox, self) }, {
                    keyMask: OpenLayers.Handler.MOD_NONE});
            },

            CLASS_NAME: 'Mapbender.Control.ZoomBox',
            displayClass: 'MapbenderControlZoomBox'
        });

        this.map.addControl(this.zoomBoxControl);
        this.element.find('.zoomBox').bind('click', function() {
            $(this).toggleClass('activeZoomIcon');
            if($(this).hasClass('activeZoomIcon')) {
                self.zoomBoxControl.activate();
            } else {
                self.zoomBoxControl.deactivate();
            }
        });

        this.element.find(".history .historyPrev").bind("click", function(){
            self.navigationHistoryControl.previous.trigger();
        });
        this.element.find(".history .historyNext").bind("click", function(){
            self.navigationHistoryControl.next.trigger();
        });

        this.element.find('.zoomSlider .iconZoomIn').bind('click',
            $.proxy(this.map.zoomIn, this.map));
        this.element.find('.zoomSlider .iconZoomOut').bind('click',
            $.proxy(this.map.zoomOut, this.map));
    },

    _zoomToBox: function(position) {
        var zoom, center;
        if(position instanceof OpenLayers.Bounds) {
            var minXY = this.map.getLonLatFromPixel(
                new OpenLayers.Pixel(position.left, position.bottom));
            var maxXY = this.map.getLonLatFromPixel(
                new OpenLayers.Pixel(position.right, position.top));
            var bounds = new OpenLayers.Bounds(minXY.lon, minXY.lat,
                maxXY.lon, maxXY.lat);
            zoom = this.map.getZoomForExtent(bounds);
            center = bounds.getCenterLonLat();
        } else {
            zoom = this.map.getZoom() + 1;
            center = this.map.getLonLatFromPixel(position);
        }

        this.map.setCenter(center, zoom);

        this.zoomBoxControl.deactivate();
        this.element.find('.zoomBox').removeClass('activeZoomIcon');
    },

    _setupPanButtons: function() {
        var self = this;
        var pan = $.proxy(this.map.pan, this.map);
        var stepSize = {
            x: parseInt(this.options.stepSize),
            y: parseInt(this.options.stepSize)};

        if(this.options.stepByPixel === "false") {
            stepSize = {
                x: Math.max(Math.min(stepSize.x, 100), 0) / 100.0 *
                    this.map.getSize().w,
                y: Math.max(Math.min(stepSize.x, 100), 0) / 100.0 *
                    this.map.getSize().h};
        }

        this.element.find(".panUp").bind("click", function(){pan(0, -stepSize.y);});
        this.element.find(".panRight").bind("click", function(){pan(+stepSize.x, 0);})
        this.element.find(".panDown").bind("click", function(){pan(0, +stepSize.y);})
        this.element.find(".panLeft").bind("click", function(){pan(-stepSize.x, 0);})
    },

    /**
     * Set map zoom level from slider
     */
    _slider2Zoom: function() {
        var position = this.zoomslider.find('li.active').index(),
            index = this.map.getNumZoomLevels() - 1 - position;

        this.map.zoomTo(index);
    },

    /**
     * Set slider to reflect map zoom level
     */
    _zoom2Slider: function() {
        var position = this.map.getNumZoomLevels() - 1 - this.map.getZoom();

        this.zoomslider.find('.iconZoomLevelSelected')
            .removeClass('iconZoomLevelSelected')
            .empty();
        this.zoomslider.find('li').eq(position)
            .addClass('iconZoomLevelSelected')
            .append($('

'));
    },
    /**
         *
         */
        ready: function(callback) {
            if(this.readyState === true) {
                callback();
            } else {
                this.readyCallbacks.push(callback);
            }
        },
        /**
         *
         */
        _ready: function() {
            for(callback in this.readyCallbacks) {
                callback();
                delete(this.readyCallbacks[callback]);
            }
            this.readyState = true;
        }
});

})(jQuery);
<|endoftext|>


<commit_before><commit_msg>default refresh goes to intro<commit_after><|endoftext|>


<commit_before>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

var semver = require('semver');

/**
 * The registered module cache.
 */
var registered = {};

/**
 * The installed module cache.
 */
var installedModules = {};

/**
 * The module name lookup cache.
 */
var lookupCache = {};

/**
 * Object to store loaded and loading bundles.
 * "0" means "already loaded".
 * Array means "loading", array contains callbacks.
 */
var installedBundles = {};

/**
 * Define a module that can be synchronously required.
 *
 * @param name - The version-mangled fully qualified name of the module.
 *   For example, "foo@1.0.1/lib/bar/baz.js".
 *
 * @param callback - The callback function for invoking the module.
 */
function defineModule(name, callback) {
  if (!(name in registered)) {
    registered[name] = callback;
  }
}

/**
 * Synchrnously require a module that has already been loaded.
 *
 * @param name - The semver-mangled fully qualified name of the module.
 *   For example, "foo@^1.1.0/lib/bar/baz.js".
 *
 * @returns The exports of the requested module, if registered.  The module
 *   selected is the registered module that maximally satisfies the semver
 *   range of the request.
 */
function requireModule(name) {
  // Check if module is in cache.
  var moduleId = findModuleId(name);
  if(installedModules[moduleId]) {
    return installedModules[moduleId].exports;
  }

  // Create a new module (and put it into the cache).
  var module = installedModules[moduleId] = {
    exports: {},
    id: moduleId,
    loaded: false
  };

  // Execute the module function.
  registered[moduleId].call(module.exports, module, module.exports, requireModule);

  // Flag the module as loaded.
  module.loaded = true;

  // Return the exports of the module.
  return module.exports;
}

/**
 * Ensure a bundle is loaded on a page.
 *
 * @param path - The public path of the bundle (e.g. "lab/jupyter.bundle.js").
 *
 * @param callback - The callback invoked when the bundle has loaded.
 */
function ensureBundle(path, callback) {
  // "0" is the signal for "already loaded"
  if (installedBundles[path] === 0) {
    return callback.call(null, requireModule);
  }

  // An array means "currently loading".
  if (Array.isArray(installedBundles[path])) {
    installedBundles[path].push(callback);
    return;
  }

  // Start bundle loading.
  installedBundles[path] = [callback];
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.charset = 'utf-8';
  script.async = true;
  script.onload = function() {
    var callbacks = installedBundles[path];
    while(callbacks.length)
      callbacks.shift().call(null, requireModule);
    installedBundles[path] = 0;
  }
  head.appendChild(script);
  script.src = path;
}

/**
 * Find a module matching a given module request.
 *
 * @param name - The semver-mangled fully qualified name of the module.
 *   For example, "foo@^1.1.0/lib/bar/baz.js".
 *
 * @returns The matching defined module name, if registered.  A match is
 *   the registered name that maximally satisfies the semver range of the
 *   request.
 */
function findModuleId(name) {
  // Use the cached id if available.
  if (lookupCache[name]) {
    return lookupCache[name];
  }
  var modules = Object.keys(registered);
  // Get the package name, semver string, and module name.
  var parts = name.match(/(^.*?)@(.*?)(\/.*$)/) || name.match(/(^.*?)@(.*?)$/);
  if (!parts) {
    throw Error('Invalid module name ' + name);
  }
  if (parts.length === 2) {
    parts.push('');
  }
  var matches = [];
  var versions = [];
  for (var i = 0; i < modules.length; i++) {
    var mod = modules[i];
    var modParts = mod.match(/(^.*?)@(.*?)(\/.*$)/) || mod.match(/(^.*?)@(.*?)$/);
    if (!modParts) {
      continue;
    }
    if (modParts.length === 2) {
      modParts.push('');
    }
    if (modParts[1] === parts[1] && modParts[3] === parts[3]) {
      matches.push(mod);
      versions.push(modParts[2]);
    }
  };

  if (!matches.length) {
    throw Error('No module found matching: ' + name);
    return;
  }
  var index = 0;
  if (matches.length > 1) {
    var best = semver.maxSatisfying(versions, parts[2]);
    if (!best) {
      throw new Error('No module found satisying: ' + name);
    }
    index = versions.indexOf(best);
  }
  lookupCache[name] = matches[index];
  return matches[index];
}

// Add the ensure function to the require module for internal use within
// the modules.
requireModule.e = ensureBundle;

module.exports = {
  define: defineModule,
  ensure: ensureBundle,
  require: requireModule
}
<commit_msg>Add a requireBundles function and do not expose the other requires<commit_after>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

var semver = require('semver');

/**
 * The registered module cache.
 */
var registered = {};

/**
 * The installed module cache.
 */
var installedModules = {};

/**
 * The module name lookup cache.
 */
var lookupCache = {};

/**
 * Object to store loaded and loading bundles.
 * "0" means "already loaded".
 * Array means "loading", array contains callbacks.
 */
var installedBundles = {};

/**
 * Define a module that can be synchronously required.
 *
 * @param name - The version-mangled fully qualified name of the module.
 *   For example, "foo@1.0.1/lib/bar/baz.js".
 *
 * @param callback - The callback function for invoking the module.
 */
function defineModule(name, callback) {
  if (!(name in registered)) {
    registered[name] = callback;
  }
}

/**
 * Synchrnously require a module that has already been loaded.
 *
 * @param name - The semver-mangled fully qualified name of the module.
 *   For example, "foo@^1.1.0/lib/bar/baz.js".
 *
 * @returns The exports of the requested module, if registered.  The module
 *   selected is the registered module that maximally satisfies the semver
 *   range of the request.
 */
function requireModule(name) {
  // Check if module is in cache.
  var moduleId = findModuleId(name);
  if(installedModules[moduleId]) {
    return installedModules[moduleId].exports;
  }

  // Create a new module (and put it into the cache).
  var module = installedModules[moduleId] = {
    exports: {},
    id: moduleId,
    loaded: false
  };

  // Execute the module function.
  registered[moduleId].call(module.exports, module, module.exports, requireModule);

  // Flag the module as loaded.
  module.loaded = true;

  // Return the exports of the module.
  return module.exports;
}

/**
 * Ensure a bundle is loaded on a page.
 *
 * @param path - The public path of the bundle (e.g. "lab/jupyter.bundle.js").
 *
 * @param callback - The callback invoked when the bundle has loaded.
 */
function ensureBundle(path, callback) {
  // "0" is the signal for "already loaded"
  if (installedBundles[path] === 0) {
    return callback.call(null, requireModule);
  }

  // An array means "currently loading".
  if (Array.isArray(installedBundles[path])) {
    installedBundles[path].push(callback);
    return;
  }

  // Start bundle loading.
  installedBundles[path] = [callback];
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.charset = 'utf-8';
  script.async = true;
  script.onload = function() {
    var callbacks = installedBundles[path];
    while(callbacks.length)
      callbacks.shift().call(null, requireModule);
    installedBundles[path] = 0;
  }
  head.appendChild(script);
  script.src = path;
}

/**
 * Ensure a list of bundles are loaded on the page.
 *
 * @param paths - The public paths of the bundles. (e.g. "lab/foo.bundle.js").
 *
 * @returns A promise that resolves with the require function when all the
 *   bundles have loaded.
 */
function requireBundles(paths) {
  var promises = paths.map(function(path) {
    return new Promise(function (resolve, reject) {
      ensureBundle(path, resolve);
    });
  });
  return Promise.all(promises).then(function () {
    return requireModule;
  });
}

/**
 * Find a module matching a given module request.
 *
 * @param name - The semver-mangled fully qualified name of the module.
 *   For example, "foo@^1.1.0/lib/bar/baz.js".
 *
 * @returns The matching defined module name, if registered.  A match is
 *   the registered name that maximally satisfies the semver range of the
 *   request.
 */
function findModuleId(name) {
  // Use the cached id if available.
  if (lookupCache[name]) {
    return lookupCache[name];
  }
  var modules = Object.keys(registered);
  // Get the package name, semver string, and module name.
  var parts = name.match(/(^.*?)@(.*?)(\/.*$)/) || name.match(/(^.*?)@(.*?)$/);
  if (!parts) {
    throw Error('Invalid module name ' + name);
  }
  if (parts.length === 2) {
    parts.push('');
  }
  var matches = [];
  var versions = [];
  for (var i = 0; i < modules.length; i++) {
    var mod = modules[i];
    var modParts = mod.match(/(^.*?)@(.*?)(\/.*$)/) || mod.match(/(^.*?)@(.*?)$/);
    if (!modParts) {
      continue;
    }
    if (modParts.length === 2) {
      modParts.push('');
    }
    if (modParts[1] === parts[1] && modParts[3] === parts[3]) {
      matches.push(mod);
      versions.push(modParts[2]);
    }
  };

  if (!matches.length) {
    throw Error('No module found matching: ' + name);
    return;
  }
  var index = 0;
  if (matches.length > 1) {
    var best = semver.maxSatisfying(versions, parts[2]);
    if (!best) {
      throw new Error('No module found satisying: ' + name);
    }
    index = versions.indexOf(best);
  }
  lookupCache[name] = matches[index];
  return matches[index];
}

// Add the ensure function to the require module for internal use within
// the modules.
requireModule.e = ensureBundle;

module.exports = {
  define: defineModule,
  requireBundles: requireBundles
}
<|endoftext|>


<commit_before>
var algs = {
  sha1   : require('sha.js/sha1'),
  sha256 : require('sha.js/sha256'),
  md5    : toConstructor(require('./md5'))
}

function toConstructor (fn) {
  return function () {
    var buffers = []
    var m= {
      update: function (data, enc) {
        if(!Buffer.isBuffer(data)) data = new Buffer(data, enc)
        buffers.push(data)
        return this
      },
      digest: function (enc) {
        var buf = Buffer.concat(buffers)
        var r = fn(buf)
        buffers = null
        return enc ? r.toString(enc) : r
      }
    }
    return m
  }
}

module.exports = function (alg) {
  return new algs[alg]()
}
<commit_msg>work with sha.js@3.0.0<commit_after>var createHash = require('sha.js')
var algs = {
  md5    : toConstructor(require('./md5'))
}

function toConstructor (fn) {
  return function () {
    var buffers = []
    var m= {
      update: function (data, enc) {
        if(!Buffer.isBuffer(data)) data = new Buffer(data, enc)
        buffers.push(data)
        return this
      },
      digest: function (enc) {
        var buf = Buffer.concat(buffers)
        var r = fn(buf)
        buffers = null
        return enc ? r.toString(enc) : r
      }
    }
    return m
  }
}

module.exports = function (alg) {
  if(algs[alg]) return new algs[alg]()
  return createHash(alg)
}
<|endoftext|>


<commit_before><commit_msg>cerner copy updates (#21415)<commit_after><|endoftext|>


<commit_before>'use strict';

module.exports = {
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['mocha'],

    // list of files to exclude
    exclude: [],

    preprocessors: {
//        '**/src/**/*.js': 'coverage'
    },

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['minimalist'],

//    coverageReporter: {
//        type: 'lcovonly',
//        dir : 'coverage/'
//
//    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    reportSlowerThan: 10000,

    transports: ['xhr-polling']  // (flashsockets are buggy on ie8-9)
};<commit_msg>chore: reactivate web sockets for testing (xml-polling everywhere seems to abort to make some http requests to abort)<commit_after>'use strict';

module.exports = {
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['mocha'],

    // list of files to exclude
    exclude: [],

    preprocessors: {
//        '**/src/**/*.js': 'coverage'
    },

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['minimalist'],

//    coverageReporter: {
//        type: 'lcovonly',
//        dir : 'coverage/'
//
//    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    reportSlowerThan: 10000,

    transports: ['websocket', 'xhr-polling']  // (flashsockets are buggy on ie8-9)
};<|endoftext|>


<commit_before><commit_msg>Remove console statement. Move initialization logic for controller into init() method.<commit_after><|endoftext|>


<commit_before>'use strict';
// Karma configuration
// Generated on Tue Sep 10 2013 18:12:14 GMT+0200 (CEST)

var files = require('./files.conf.js');
var conf = require('./karma.shared.conf.js');

module.exports = function(config) {

    conf.files = files.testFilesBuild;

    conf.browserStack = {
        username: process.env.BROWSER_STACK_USERNAME,
        accessKey: process.env.BROWSER_STACK_ACCESS_KEY,
        project: process.env.TRAVIS_REPO_SLUG || 'stimuli@local',
        build: process.env.TRAVIS_BUILD_NUMBER,
        startTunnel: true,
        retryLimit: 5,
        timeout: 600
    };
    conf.captureTimeout = 90000; // 1 min 30
    conf.logLevel = config.LOG_INFO;
    conf.reportSlowerThan = 30000;
    conf.disconnectTolerance = 5;
    conf.autoWatch = false;
    conf.singleRun = true;
    conf.disableCompression = true;
    conf.serverPort = 9876;
    conf.serverHost = '127.0.0.1';
    conf.clientHost = '127.0.0.1';
    conf.clientPort = 8080;
    conf.transports = ['xhr-polling'];
    conf.customLaunchers = {

        BS_FIREFOX: {
            base: 'BrowserStack',
            browser: 'firefox',
            browser_version: '24.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_CHROME: {
            base: 'BrowserStack',
            browser: 'chrome',
            browser_version: '29.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_IE8: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '8.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_IE9: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '9.0',
            os: 'Windows',
            os_version: '7'
        },

        BS_IE10: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '10.0',
            os: 'Windows',
            os_version: '8'
        },

        BS_IE11: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '11.0',
            os: 'Windows',
            os_version: '7'
        },

        BS_SAFARI51: {
            base: 'BrowserStack',
            browser: 'safari',
            browser_version: '5.1',
            os: 'OS X',
            os_version: 'Snow Leopard'
        },

        BS_SAFARI6: {
            base: 'BrowserStack',
            browser: 'safari',
            browser_version: '6.0',
            os: 'OS X',
            os_version: 'Mountain Lion'
        },

        BS_OPERA16: {
            base: 'BrowserStack',
            os: 'OS X',
            browser: 'opera',
            os_version: 'Mountain Lion',
            browser_version: '16.0'
        },

        BS_ANDROID_4: {
            base: 'BrowserStack',
            os: 'android',
            device: 'Samsung Galaxy Nexus',
            browser: 'Android Browser',
            os_version: '4.0',
            browser_version: null
        },

        BS_ANDROID_41: {
            base: 'BrowserStack',
            os: 'android',
            device: 'Motorola Razr Maxx HD',
            browser: 'Android Browser',
            os_version: '4.1',
            browser_version: null
        },

        BS_ANDROID_42: {
            base: 'BrowserStack',
            os: 'android',
            device: 'LG Nexus 4',
            browser: 'Android Browser',
            os_version: '4.2',
            browser_version: null
        },

        BS_IOS_6: {
            base: 'BrowserStack',
            os: 'ios',
            device: 'iPad 3rd (6.0)',
            browser: 'Mobile Safari',
            os_version: '6.0',
            browser_version: null
        }

    };

    config.set(conf);

};
<commit_msg>chore: Android 4.1 testing get rid off Razr Maxx HD and Galaxy Note II instead<commit_after>'use strict';
// Karma configuration
// Generated on Tue Sep 10 2013 18:12:14 GMT+0200 (CEST)

var files = require('./files.conf.js');
var conf = require('./karma.shared.conf.js');

module.exports = function(config) {

    conf.files = files.testFilesBuild;

    conf.browserStack = {
        username: process.env.BROWSER_STACK_USERNAME,
        accessKey: process.env.BROWSER_STACK_ACCESS_KEY,
        project: process.env.TRAVIS_REPO_SLUG || 'stimuli@local',
        build: process.env.TRAVIS_BUILD_NUMBER,
        startTunnel: true,
        retryLimit: 5,
        timeout: 600
    };
    conf.captureTimeout = 90000; // 1 min 30
    conf.logLevel = config.LOG_INFO;
    conf.reportSlowerThan = 30000;
    conf.disconnectTolerance = 5;
    conf.autoWatch = false;
    conf.singleRun = true;
    conf.disableCompression = true;
    conf.serverPort = 9876;
    conf.serverHost = '127.0.0.1';
    conf.clientHost = '127.0.0.1';
    conf.clientPort = 8080;
    conf.transports = ['xhr-polling'];
    conf.customLaunchers = {

        BS_FIREFOX: {
            base: 'BrowserStack',
            browser: 'firefox',
            browser_version: '24.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_CHROME: {
            base: 'BrowserStack',
            browser: 'chrome',
            browser_version: '29.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_IE8: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '8.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_IE9: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '9.0',
            os: 'Windows',
            os_version: '7'
        },

        BS_IE10: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '10.0',
            os: 'Windows',
            os_version: '8'
        },

        BS_IE11: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '11.0',
            os: 'Windows',
            os_version: '7'
        },

        BS_SAFARI51: {
            base: 'BrowserStack',
            browser: 'safari',
            browser_version: '5.1',
            os: 'OS X',
            os_version: 'Snow Leopard'
        },

        BS_SAFARI6: {
            base: 'BrowserStack',
            browser: 'safari',
            browser_version: '6.0',
            os: 'OS X',
            os_version: 'Mountain Lion'
        },

        BS_OPERA16: {
            base: 'BrowserStack',
            os: 'OS X',
            browser: 'opera',
            os_version: 'Mountain Lion',
            browser_version: '16.0'
        },

        BS_ANDROID_4: {
            base: 'BrowserStack',
            os: 'android',
            device: 'Samsung Galaxy Nexus',
            browser: 'Android Browser',
            os_version: '4.0',
            browser_version: null
        },

        BS_ANDROID_41: {
            base: 'BrowserStack',
            os: 'android',
            device: 'Samsung Galaxy Note II',
            browser: 'Android Browser',
            os_version: '4.1',
            browser_version: null
        },

        BS_ANDROID_42: {
            base: 'BrowserStack',
            os: 'android',
            device: 'LG Nexus 4',
            browser: 'Android Browser',
            os_version: '4.2',
            browser_version: null
        },

        BS_IOS_6: {
            base: 'BrowserStack',
            os: 'ios',
            device: 'iPad 3rd (6.0)',
            browser: 'Mobile Safari',
            os_version: '6.0',
            browser_version: null
        }

    };

    config.set(conf);

};
<|endoftext|>


<commit_before>//
// Implementations of primitive methods
// This is loaded at the very end, everything is already available
// If this gets too long, split it in multiple files
//

ProtoObject._addClassMethods({
	basicNew: function() { return this._newInstance(); },
	_new: function() { return this.basicNew().initialize(); },
	name: function() { return this._classname; }
});
ProtoObject._addInstanceMethods({
	_equals_equals: function(anObject) { return bool(this === anObject); },
	identityHash: function() { return number(this.instanceNumber$); },
});

_Object._addInstanceMethods({
	doesNotUnderstand_: function(message) {
		// TODO implement this correctly
		var msg = this + "(instance of " + this._class().name() +
				") did not understand " + _unboxObject(message.selector());
		Exception.signal_(string(msg));
	},
	_class: function() { return this.__class; },
	halt: function() { debugger; },
});

Exception._addInstanceMethods({
	signal: function() {
		alert(_unboxObject(this.messageText()));
		throw this;
	}
});

_String._addInstanceMethods({
	// This is not actually a primitive function, but behaves in the same way the #, method does
	_comma: function(anotherString) { return string(this.original$ + anotherString.original$) },
	_equals: function(anotherString) { return bool(this.original$ == anotherString.original$) },
	isEmpty: function() { return bool(this.original$.length == 0) },
	size: function() { return number(this.original$.length); },
	at_: function(num) { return character(this.original$[num.original$ - 1]);},
});

ByteString._addInstanceMethods({
	at_: function(num) { return character(this.original$[num.original$ - 1]); }
});

/*
at_ should also be defined in:
ByteSymbol
WideString
WideSymbol
*/

_Number._addInstanceMethods({
	printString: function() { return string(this.original$.toString()); }
});

Float._addInstanceMethods({
	_plus: function(other) { return number(this.original$ + other.original$); },
	_minus: function(other) { return number(this.original$ - other.original$); },
	_times: function(other) { return number(this.original$ * other.original$); },
	_slash: function(other) { return number(this.original$ / other.original$); },
	floor: function() { return number(Math.floor(this.original$)); },
	rounded: function() { return number(Math.round(this.original$)); },
	_less: function(other) {
		return bool(this.original$ < other.original$);
	},
	_greater: function(other) {
		return bool(this.original$ > other.original$);
	},
	_less_equals: function(other) {
		return bool(this.original$ <= other.original$);
	},
	_greater_equals: function(other) {
		return bool(this.original$ >= other.original$);
	},
	_equals: function(other) {
		return bool(this.original$ == other.original$);
	},
	_tilde_equals: function(other) {
	  return bool(this.original$ != other.original$);
	},
	timesRepeat_: function(aBlock){
		for (var i = 0; i < this.original$; i++) {
			aBlock.value();
		}
		return this;
	},
	truncated: function() {
		return number(Math.floor(this.original$));
	},
	roundTo_: function(quantum) {
		var result = _unboxObject((this._slash(quantum)).rounded()._times(quantum));
        var decimalCount = 0;
        while (decimalCount <= 21 && _unboxObject(quantum).toFixed(decimalCount) != _unboxObject(quantum)) {
            decimalCount++;
        };
        return number(result.toFixed(decimalCount));
	}
});

Point._addInstanceMethods({
	_times: function(aNumber){
		return (this.x()._times(aNumber))._at(this.y()._times(aNumber));
	}
});

// We distinct an evaluated$-function and an original$-function in case of blocks.
// evaluated$ is the version, that is evaluated in the squeak-world, original$ is the function inside javascript
var _blockValueFunction_ = function() {
	return this.evaluated$.apply(this, arguments); };

// Helpers to implement Block-Closure-primitives
var _toArray = function(iterable) {
	if (!iterable) return [];
	if (iterable.toArray) return iterable.toArray();
	var length = iterable.length, results = new Array(length);
	while (length--) results[length] = iterable[length];
	return results;
}
var _curried = function(func, boundArgs) {
	// Return a function with the first parameters bound to boundArgs. Function itself will be bound to this.
	return function() { return func.apply(this, boundArgs.concat(_toArray(arguments))); };
}
var _createInstance_ = function() {
	// This is done to enable varargs-parameters for constructor-parameters
	// First bind all constructor-parameters, then call the curried function without arguments
	// Bind the function to the function itself. Seemed necessary.
	// Constructor-arguments are determined polymorphically (set in boxing.js -> boundBlock() and squeaky.js -> block())
	var args = this.constructorArguments$(arguments);
	return _boxObject(new (_curried(this.original$, args)) ());
}

BlockClosure._addInstanceMethods({
	value: _blockValueFunction_,
	value_: _blockValueFunction_,
	value_value_: _blockValueFunction_,
	value_value_value_: _blockValueFunction_,
	value_value_value_value_: _blockValueFunction_,

	whileTrue_: function(anotherBlock) {
		while (this.value() === _true) {
			anotherBlock.value();
		}
		return nil;
	},
	whileTrue: function(anotherBlock) {
		while (this.value() === _true)
			anotherBlock.value();
		return nil;
	},
	whileFalse_: function() {
		while (this.value() === _false) {
			anotherBlock.value();
		}
		return nil;
	},
	whileFalse: function() {
		while (this.value() === _false) ;
		return nil;
	},

	// Up to 9 parameters for direct constructor call
	jsNew: _createInstance_,
	jsNew_: _createInstance_,
	jsNew_with_: _createInstance_,
	jsNew_with_with_: _createInstance_,
	jsNew_with_with_with_: _createInstance_,
	jsNew_with_with_with_with_: _createInstance_,
	jsNew_with_with_with_with_with_: _createInstance_,
	jsNew_with_with_with_with_with_with_: _createInstance_,
	jsNew_with_with_with_with_with_with_with_: _createInstance_,
	jsNew_with_with_with_with_with_with_with_with_: _createInstance_,

	// Any arguments as array
	jsNewWithArgs: function(args) {
		_createInstance_.apply(this, args);
	}
});

_Array._addInstanceMethods({
	_privateGet: function(index) {
		return _boxObject(this.original$[index]);
	},
	_privateSet: function(index, obj) {
		this.original$[index] = _unboxObject(obj);
	},

	size: function(){
		return number(this.original$.length);
	},
	at_put_: function(idx, val){
		this._privateSet(idx.original$ - 1, val);
		return val;
	},
	at_: function(idx){
		return this._privateGet(idx.original$ - 1);
	},
	isEmpty: function(){
		return bool(this.original$.length == 0);
	},

	/* this is actually not a primitive and should be implemented by squeak.
	   it is only implemented here to work around a hardly tracable bug, probably in out blocks
	   and nonlocal return */
	includes_: function(anElement) {
		for (index in this.original$) {
			if (this._privateGet(index)._equals(anElement))
				return _true;
		}
		return _false;
	},
	asObject : function () {
		// creates Prototype from object literal
		// Can only be called on arrays containing only Associations (understanding key()/value())
		var newObject = {};
		for (index in this.original$) {
			var anAssociation = this._privateGet(index);
			newObject[_unboxObject(anAssociation.key())] = _unboxObject(anAssociation.value());
		}
		return newObject(object);
	}
});
_Array._addClassMethods({
	new_: function(size) {
		// Not filling the indices of the array with 'nil', because of autoboxing
		return array(new Array(size.original$));
	}
});
<commit_msg>fixed typo in Object->asObject<commit_after>//
// Implementations of primitive methods
// This is loaded at the very end, everything is already available
// If this gets too long, split it in multiple files
//

ProtoObject._addClassMethods({
	basicNew: function() { return this._newInstance(); },
	_new: function() { return this.basicNew().initialize(); },
	name: function() { return this._classname; }
});
ProtoObject._addInstanceMethods({
	_equals_equals: function(anObject) { return bool(this === anObject); },
	identityHash: function() { return number(this.instanceNumber$); },
});

_Object._addInstanceMethods({
	doesNotUnderstand_: function(message) {
		// TODO implement this correctly
		var msg = this + "(instance of " + this._class().name() +
				") did not understand " + _unboxObject(message.selector());
		Exception.signal_(string(msg));
	},
	_class: function() { return this.__class; },
	halt: function() { debugger; },
});

Exception._addInstanceMethods({
	signal: function() {
		alert(_unboxObject(this.messageText()));
		throw this;
	}
});

_String._addInstanceMethods({
	// This is not actually a primitive function, but behaves in the same way the #, method does
	_comma: function(anotherString) { return string(this.original$ + anotherString.original$) },
	_equals: function(anotherString) { return bool(this.original$ == anotherString.original$) },
	isEmpty: function() { return bool(this.original$.length == 0) },
	size: function() { return number(this.original$.length); },
	at_: function(num) { return character(this.original$[num.original$ - 1]);},
});

ByteString._addInstanceMethods({
	at_: function(num) { return character(this.original$[num.original$ - 1]); }
});

/*
at_ should also be defined in:
ByteSymbol
WideString
WideSymbol
*/

_Number._addInstanceMethods({
	printString: function() { return string(this.original$.toString()); }
});

Float._addInstanceMethods({
	_plus: function(other) { return number(this.original$ + other.original$); },
	_minus: function(other) { return number(this.original$ - other.original$); },
	_times: function(other) { return number(this.original$ * other.original$); },
	_slash: function(other) { return number(this.original$ / other.original$); },
	floor: function() { return number(Math.floor(this.original$)); },
	rounded: function() { return number(Math.round(this.original$)); },
	_less: function(other) {
		return bool(this.original$ < other.original$);
	},
	_greater: function(other) {
		return bool(this.original$ > other.original$);
	},
	_less_equals: function(other) {
		return bool(this.original$ <= other.original$);
	},
	_greater_equals: function(other) {
		return bool(this.original$ >= other.original$);
	},
	_equals: function(other) {
		return bool(this.original$ == other.original$);
	},
	_tilde_equals: function(other) {
	  return bool(this.original$ != other.original$);
	},
	timesRepeat_: function(aBlock){
		for (var i = 0; i < this.original$; i++) {
			aBlock.value();
		}
		return this;
	},
	truncated: function() {
		return number(Math.floor(this.original$));
	},
	roundTo_: function(quantum) {
		var result = _unboxObject((this._slash(quantum)).rounded()._times(quantum));
        var decimalCount = 0;
        while (decimalCount <= 21 && _unboxObject(quantum).toFixed(decimalCount) != _unboxObject(quantum)) {
            decimalCount++;
        };
        return number(result.toFixed(decimalCount));
	}
});

Point._addInstanceMethods({
	_times: function(aNumber){
		return (this.x()._times(aNumber))._at(this.y()._times(aNumber));
	}
});

// We distinct an evaluated$-function and an original$-function in case of blocks.
// evaluated$ is the version, that is evaluated in the squeak-world, original$ is the function inside javascript
var _blockValueFunction_ = function() {
	return this.evaluated$.apply(this, arguments); };

// Helpers to implement Block-Closure-primitives
var _toArray = function(iterable) {
	if (!iterable) return [];
	if (iterable.toArray) return iterable.toArray();
	var length = iterable.length, results = new Array(length);
	while (length--) results[length] = iterable[length];
	return results;
}
var _curried = function(func, boundArgs) {
	// Return a function with the first parameters bound to boundArgs. Function itself will be bound to this.
	return function() { return func.apply(this, boundArgs.concat(_toArray(arguments))); };
}
var _createInstance_ = function() {
	// This is done to enable varargs-parameters for constructor-parameters
	// First bind all constructor-parameters, then call the curried function without arguments
	// Bind the function to the function itself. Seemed necessary.
	// Constructor-arguments are determined polymorphically (set in boxing.js -> boundBlock() and squeaky.js -> block())
	var args = this.constructorArguments$(arguments);
	return _boxObject(new (_curried(this.original$, args)) ());
}

BlockClosure._addInstanceMethods({
	value: _blockValueFunction_,
	value_: _blockValueFunction_,
	value_value_: _blockValueFunction_,
	value_value_value_: _blockValueFunction_,
	value_value_value_value_: _blockValueFunction_,

	whileTrue_: function(anotherBlock) {
		while (this.value() === _true) {
			anotherBlock.value();
		}
		return nil;
	},
	whileTrue: function(anotherBlock) {
		while (this.value() === _true)
			anotherBlock.value();
		return nil;
	},
	whileFalse_: function() {
		while (this.value() === _false) {
			anotherBlock.value();
		}
		return nil;
	},
	whileFalse: function() {
		while (this.value() === _false) ;
		return nil;
	},

	// Up to 9 parameters for direct constructor call
	jsNew: _createInstance_,
	jsNew_: _createInstance_,
	jsNew_with_: _createInstance_,
	jsNew_with_with_: _createInstance_,
	jsNew_with_with_with_: _createInstance_,
	jsNew_with_with_with_with_: _createInstance_,
	jsNew_with_with_with_with_with_: _createInstance_,
	jsNew_with_with_with_with_with_with_: _createInstance_,
	jsNew_with_with_with_with_with_with_with_: _createInstance_,
	jsNew_with_with_with_with_with_with_with_with_: _createInstance_,

	// Any arguments as array
	jsNewWithArgs: function(args) {
		_createInstance_.apply(this, args);
	}
});

_Array._addInstanceMethods({
	_privateGet: function(index) {
		return _boxObject(this.original$[index]);
	},
	_privateSet: function(index, obj) {
		this.original$[index] = _unboxObject(obj);
	},

	size: function(){
		return number(this.original$.length);
	},
	at_put_: function(idx, val){
		this._privateSet(idx.original$ - 1, val);
		return val;
	},
	at_: function(idx){
		return this._privateGet(idx.original$ - 1);
	},
	isEmpty: function(){
		return bool(this.original$.length == 0);
	},

	/* this is actually not a primitive and should be implemented by squeak.
	   it is only implemented here to work around a hardly tracable bug, probably in out blocks
	   and nonlocal return */
	includes_: function(anElement) {
		for (index in this.original$) {
			if (this._privateGet(index)._equals(anElement))
				return _true;
		}
		return _false;
	},
	asObject : function () {
		// creates Prototype from object literal
		// Can only be called on arrays containing only Associations (understanding key()/value())
		var newObject = {};
		for (index in this.original$) {
			var anAssociation = this._privateGet(index);
			newObject[_unboxObject(anAssociation.key())] = _unboxObject(anAssociation.value());
		}
		return newObject;
	}
});
_Array._addClassMethods({
	new_: function(size) {
		// Not filling the indices of the array with 'nil', because of autoboxing
		return array(new Array(size.original$));
	}
});
<|endoftext|>


<commit_before>require('../../lib/keyboard.polyfill');

var MAX_DELTA = 0.2,
    PROXY_FLAG = '__keyboard-controls-proxy';

var KeyboardEvent = window.KeyboardEvent;

/**
 * Keyboard Controls component.
 *
 * Stripped-down version of: https://github.com/donmccurdy/aframe-keyboard-controls
 *
 * Bind keyboard events to components, or control your entities with the WASD keys.
 *
 * Why use KeyboardEvent.code? "This is set to a string representing the key that was pressed to
 * generate the KeyboardEvent, without taking the current keyboard layout (e.g., QWERTY vs.
 * Dvorak), locale (e.g., English vs. French), or any modifier keys into account. This is useful
 * when you care about which physical key was pressed, rather thanwhich character it corresponds
 * to. For example, if you’re a writing a game, you might want a certain set of keys to move the
 * player in different directions, and that mapping should ideally be independent of keyboard
 * layout. See: https://developers.google.com/web/updates/2016/04/keyboardevent-keys-codes
 *
 * @namespace wasd-controls
 * keys the entity moves and if you release it will stop. Easing simulates friction.
 * to the entity when pressing the keys.
 * @param {bool} [enabled=true] - To completely enable or disable the controls
 */
module.exports = {
  schema: {
    enabled:           { default: true },
    debug:             { default: false }
  },

  init: function () {
    this.dVelocity = new THREE.Vector3();
    this.localKeys = {};
    this.listeners = {
      keydown: this.onKeyDown.bind(this),
      keyup: this.onKeyUp.bind(this),
      blur: this.onBlur.bind(this)
    };
    this.attachEventListeners();
  },

  /*******************************************************************
  * Movement
  */

  isVelocityActive: function () {
    return this.data.enabled && !!Object.keys(this.getKeys()).length;
  },

  getVelocityDelta: function () {
    var data = this.data,
        keys = this.getKeys();

    this.dVelocity.set(0, 0, 0);
    if (data.enabled) {
      if (keys.KeyW || keys.ArrowUp)    { this.dVelocity.z -= 1; }
      if (keys.KeyA || keys.ArrowLeft)  { this.dVelocity.x -= 1; }
      if (keys.KeyS || keys.ArrowDown)  { this.dVelocity.z += 1; }
      if (keys.KeyD || keys.ArrowRight) { this.dVelocity.x += 1; }
    }

    return this.dVelocity.clone();
  },

  /*******************************************************************
  * Events
  */

  play: function () {
    this.attachEventListeners();
  },

  pause: function () {
    this.removeEventListeners();
  },

  remove: function () {
    this.pause();
  },

  attachEventListeners: function () {
    window.addEventListener('keydown', this.listeners.keydown, false);
    window.addEventListener('keyup', this.listeners.keyup, false);
    window.addEventListener('blur', this.listeners.blur, false);
  },

  removeEventListeners: function () {
    window.removeEventListener('keydown', this.listeners.keydown);
    window.removeEventListener('keyup', this.listeners.keyup);
    window.removeEventListener('blur', this.listeners.blur);
  },

  onKeyDown: function (event) {
    this.localKeys[event.code] = true;
    this.emit(event);
  },

  onKeyUp: function (event) {
    delete this.localKeys[event.code];
    this.emit(event);
  },

  onBlur: function () {
    for (var code in this.localKeys) {
      if (this.localKeys.hasOwnProperty(code)) {
        delete this.localKeys[code];
      }
    }
  },

  emit: function (event) {
    // TODO - keydown only initially?
    // TODO - where the f is the spacebar

    // Emit original event.
    if (PROXY_FLAG in event) {
      // TODO - Method never triggered.
      this.el.emit(event.type, event);
    }

    // Emit convenience event, identifying key.
    this.el.emit(event.type + ':' + event.code, new KeyboardEvent(event.type, event));
    if (this.data.debug) console.log(event.type + ':' + event.code);
  },

  /*******************************************************************
  * Accessors
  */

  isPressed: function (code) {
    return code in this.getKeys();
  },

  getKeys: function () {
    if (this.isProxied()) {
      return this.el.sceneEl.components['proxy-controls'].getKeyboard();
    }
    return this.localKeys;
  },

  isProxied: function () {
    var proxyControls = this.el.sceneEl.components['proxy-controls'];
    return proxyControls && proxyControls.isConnected();
  }

};
<commit_msg>Delete keyboard-controls.js<commit_after><|endoftext|>


<commit_before>// Include The 'util' Module
var util = require("util");

// Our custom Error constructor
function CustomError() {
    Error.call(this);

    // Adds a stack property to the given error object
    // that will yield the stack trace at the time
    // captureStackTrace was called
    Error.captureStackTrace(this, arguments.callee);

    this.name = "CustomError";
    this.message = util.format.apply(this, arguments);
}

// Give it a new instance of the Error prototype as a prototype
CustomError.prototype = Object.create(Error.prototype);

module.exports = CustomError;<commit_msg>small fix<commit_after>// Include The 'util' Module
var util = require("util");

// Our custom Error constructor
function CustomError() {
    Error.call(this);

    // Adds a stack property to the given error object
    // that will yield the stack trace at the time
    // captureStackTrace was called
    Error.captureStackTrace(this, CustomError);

    this.name = "CustomError";
    this.message = util.format.apply(this, arguments);
}

// Give it a new instance of the Error prototype as a prototype
CustomError.prototype = Object.create(Error.prototype);

module.exports = CustomError;<|endoftext|>


<commit_before>
/*

  data-server.js

*/

var jsonServer = require("json-server");

module.exports = function(options) {

  // Set defaults
  options = Object.assign({}, options);

  return jsonServer.router(global.db.object);

}
<commit_msg>data-server: adds link to typicode work<commit_after>
/*

  data-server.js

  Exposes JSON server: see https://github.com/typicode/json-server

*/

var jsonServer = require("json-server");

module.exports = function(options) {

  // Set defaults
  options = Object.assign({}, options);

  return jsonServer.router(global.db.object);

}
<|endoftext|>


<commit_before>/**
 * MediaKeys namespace.
 */
if (typeof MediaKeys == "undefined") var MediaKeys = {};

MediaKeys.GetSingleElementByXpath = function(path, docXPath)
{
	var docElement;
	if (docXPath) docElement = MediaKeys.GetSingleElementByXpath(docXPath).contentDocument;
	else docElement = document;

	//console.log("looking for " + path + " on " + document.URL);
	return docElement.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
};<commit_msg>Missed second reference to the document in finder when adding support for iframe on Spotify.<commit_after>/**
 * MediaKeys namespace.
 */
if (typeof MediaKeys == "undefined") var MediaKeys = {};

MediaKeys.GetSingleElementByXpath = function(path, docXPath)
{
	var docElement;
	if (docXPath) docElement = MediaKeys.GetSingleElementByXpath(docXPath).contentDocument;
	else docElement = document;

	//console.log("looking for " + path + " on " + document.URL);
	return docElement.evaluate(path, docElement, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
};<|endoftext|>


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

/**
 * @overview Sets up application database for local dev
 * @requires database
 * @requires fs
 * @requires lodash/snakeCase
 * @requires lodash/sortBy
 */

'use strict';

const fs = require('fs');
const snakeCase = require('lodash/snakeCase');
const sortBy = require('lodash/sortBy');

const Database = require('../lib/database');

function importStation(station) {
  const content = fs.readFileSync(`${__dirname}/${station}`);
  return JSON.parse(content.toString('utf8'));
}

const files = fs.readdirSync(`${__dirname}`).filter(file => file !== '_setup.js');
const stations = files.map(importStation).reduce((prev, current) => prev.concat(current), []);
const database = new Database();

database.client.on('error', (err) => {
  throw new Error(`Stations import failed: ${err}`);
});

let operations = sortBy(stations, 'title').map((station, index) => {
  const key = `station:${station.title}`;
  const { longitude, latitude } = station.geolocation;
  const commands = [];

  console.log(`Importing [${key}]...`);

  /** @todo Clean up static station data */
  station.coordinates = [station.geolocation.latitude, station.geolocation.longitude];
  delete station.geolocation;

  commands.push(
      ['set', key, JSON.stringify(station)],
      ['zadd', `station.band:${station.band.toLowerCase()}`, index, key],
      ['zadd', `station.call:${station.call.toLowerCase()}`, index, key],
      ['zadd', `station.format:${station.format}`, index, key],
      ['zadd', `station.frequency:${station.frequency}`, index, key],
      ['zadd', `station.market_city:${snakeCase(station.market_city).toLowerCase()}`, index, key],
      ['zadd', `station.market_state:${snakeCase(station.market_state).toLowerCase()}`, index, key]
  );

  if (longitude && latitude) {
    commands.push(['geoadd', 'station.geolocation', longitude, latitude, key]);
  }

  if (station.urls.streams.length) {
    const streamURL = station.urls.streams.find(url => (
      url.rel === 'primary_format_stream')
    );

    if (streamURL) {
      commands.push(['set', `${key}.primary_format_stream`, streamURL.href]);
    }
  }

  return database.execute('multi', commands);
});

// Add sorted set indexes (for sorting by station attr)
['band', 'call', 'format', 'frequency', 'market_city', 'market_state', 'name', 'title'].forEach((key) => {
  console.log(`Indexing stations sorted by: ${key}...`);

  operations = operations.concat(
    sortBy(stations, key).map((station, index) => (
      database.execute('zadd', `station.${key}`, index, `station:${station.title}`)
    ))
  );
});

Promise.all(operations)
  .then(() => {
    console.log('Done.');
    database.client.quit();
  })
  .catch((err) => {
    console.error(err);
  });
<commit_msg>Removed `console.log` calls from data setup script<commit_after>/* eslint-disable no-console */

/**
 * @overview Sets up application database for local dev
 * @requires database
 * @requires fs
 * @requires lodash/snakeCase
 * @requires lodash/sortBy
 */

'use strict';

const fs = require('fs');
const snakeCase = require('lodash/snakeCase');
const sortBy = require('lodash/sortBy');

const Database = require('../lib/database');

function importStation(station) {
  const content = fs.readFileSync(`${__dirname}/${station}`);
  return JSON.parse(content.toString('utf8'));
}

const files = fs.readdirSync(`${__dirname}`).filter(file => file !== '_setup.js');
const stations = files.map(importStation).reduce((prev, current) => prev.concat(current), []);
const database = new Database();

database.client.on('error', (err) => {
  throw new Error(`Stations import failed: ${err}`);
});

let operations = sortBy(stations, 'title').map((station, index) => {
  const key = `station:${station.title}`;
  const { longitude, latitude } = station.geolocation;
  const commands = [];

  /** @todo Clean up static station data */
  station.coordinates = [station.geolocation.latitude, station.geolocation.longitude];
  delete station.geolocation;

  commands.push(
      ['set', key, JSON.stringify(station)],
      ['zadd', `station.band:${station.band.toLowerCase()}`, index, key],
      ['zadd', `station.call:${station.call.toLowerCase()}`, index, key],
      ['zadd', `station.format:${station.format}`, index, key],
      ['zadd', `station.frequency:${station.frequency}`, index, key],
      ['zadd', `station.market_city:${snakeCase(station.market_city).toLowerCase()}`, index, key],
      ['zadd', `station.market_state:${snakeCase(station.market_state).toLowerCase()}`, index, key]
  );

  if (longitude && latitude) {
    commands.push(['geoadd', 'station.geolocation', longitude, latitude, key]);
  }

  if (station.urls.streams.length) {
    const streamURL = station.urls.streams.find(url => (
      url.rel === 'primary_format_stream')
    );

    if (streamURL) {
      commands.push(['set', `${key}.primary_format_stream`, streamURL.href]);
    }
  }

  return database.execute('multi', commands);
});

// Add sorted set indexes (for sorting by station attr)
['band', 'call', 'format', 'frequency', 'market_city', 'market_state', 'name', 'title'].forEach((key) => {
  operations = operations.concat(
    sortBy(stations, key).map((station, index) => (
      database.execute('zadd', `station.${key}`, index, `station:${station.title}`)
    ))
  );
});

console.log('Loading station records...');

Promise.all(operations)
  .then(() => {
    console.log('Done.');
    database.client.quit();
  })
  .catch((err) => {
    console.error(err);
  });
<|endoftext|>