<commit_before>/**
 * Module for interfacing with the Kalabox container system implementation, and
 * the provider of the container system.
 *
 * NOTE: The container system and the provider are not always the same. For
 * example using docker on a Mac would use docker as the container system,
 * however it would be provided by boot2docker.
 * @module kbox.engine
 */

'use strict';

var core = require('./core.js');
var util = require('./util.js');
var helpers = util.helpers;
var _ = require('lodash');

var provider = require('./engine/provider.js');
exports.provider = provider;

var engine = null;

var makeProviderError = function(msg) {
  var providerName = null;
  if (provider) {
    providerName = provider.getName();
  }
  var msgParts = [
    'Provider',
    providerName,
    msg
  ];
  var fullErrorMsg = _.filter(msgParts).join(' ');
  return new Error(fullErrorMsg);
};

var isProviderInstalled = false;
var verifyProviderInstalled = function(callback) {
  if (isProviderInstalled) {
    callback(null);
  } else {
    provider.isInstalled(function(err, isInstalled) {
      if (err) {
        callback(err);
      } else if (!isInstalled) {
        callback(makeProviderError('is NOT installed!'));
      } else {
        isProviderInstalled = true;
        callback(null);
      }
    });
  }
};

var isProviderUp = false;
var verifyProviderUp = function(callback) {
  if (isProviderUp) {
    callback(null);
  } else {
    provider.isUp(function(err, isUp) {
      if (err) {
        callback(err);
      } else if (!isUp) {
        callback(makeProviderError('is NOT up!'));
      } else {
        isProviderUp = true;
        callback(null);
      }
    });
  }
};

var engineHasBeenInit = false;
var verifyProviderIsReady = function(callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      verifyProviderUp(function(err) {
        if (err) {
          callback(err);
        } else {
          if (!engineHasBeenInit) {
            provider.engineConfig(function(err, config) {
              if (err) {
                callback(err);
              }
              else {
                engine.init(config);
                engineHasBeenInit = true;
                callback(null);
              }
            });
          }
          else {
            callback(null);
          }
        }
      });
    }
  });
};

/**
 * Returns the name of the configured provider.
 * @returns {string} - Name of the configured provider.
 */
exports.getProviderName = function() {
  return provider.name;
};

/**
 * Retrieves the state of the engine being up.
 * @arg {function} callback
 * @arg {error} callback.error
 * @arg {boolean} callback.isUp - Boolean representing the state of the engine being up.
 * @example
 * kbox.engine.isUp(function(err, isUp) {
 *   if (err) {
 *     throw err;
 *   } else if (isUp) {
 *     console.log('It is up!');
 *   }
 * });
 */
exports.isUp = function(callback) {
  provider.isUp(callback);
};

/**
 * Initializes kalabox engine.
 * @arg {string} globalConfig - Kalabox global config to initialize with.
 * @example
 * var globalConfig = kbox.core.config.getGlobalConfig();
 * kbox.engine.init(globalConfig);
 */
exports.init = function(globalConfig) {
  if (!engine) {
    engine = require('./engine/' + globalConfig.engine + '.js');
    core.deps.register('providerModule', engine.getProviderModule());
  }
};

/**
 * Gets the engine provider into the state it needs to be in to do
 * engine things.
 * @arg {int} attempts - The amount of times to try to start the engine.
 * @arg {function} callback - Callback called when the engine has started.
 * @arg {error} callback.error
 */
exports.up = function(attempts, callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      //provider.up(attempts, callback);
      provider.up(callback);
    }
  });
};

/**
 * Turns the engine off.
 * @arg {int} attempts - The amount of times to try to stop the engine.
 * @arg {function} callback - Callback called when the engine has been stopped.
 * @arg {error} callback.error
 */
exports.down = function(attempts, callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      //provider.down(attempts, callback);
      provider.down(callback);
    }
  });
};

/**
 * Lists installed containers.
 * @arg {string} appName [optional] - App name to filter containers by.
 * @arg {function} callback - Callback called when the engine query completes.
 * @arg {error} callback.error
 * @arg {array} callback.containers - An array of container objects.
 * @example
 * kbox.engine.list(function(err, containers) {
 *   for (var i = 0; i < containers.length; ++i) {
 *     console.log(containers[i].name);
 *   }
 * });
 */
var list = exports.list = function(appName, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.list(appName, callback);
    }
  });
};

// @todo: document...
exports.exists = function(cid, callback) {
  list(function(err, containers) {
    if (err) {
      callback(err);
    } else {
      var exists = _.find(containers, function(container) {
        return container.id === cid || container.name === cid;
      });
      callback(null, exists !== undefined);
    }
  });
};

/**
 * Inspects a container and returns details.
 * @arg {string} containerId - Id of the container to inspect.
 * @arg {function} callback - Callback called when the container has been inspected.
 * @arg {error} callback.error
 * @arg {object} callback.data - Object containing the containers inspected data.
 */
exports.inspect = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.getEnsure(cid, 'inspect', function(err, container) {
        if (err) {
          callback(err);
        } else {
          engine.inspect(container, callback);
        }
      });
    }
  });
};

// @todo: document
exports.info = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.info(cid, callback);
    }
  });
};

/**
 * Creates a container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been created.
 * @arg {error} callback.error
 * @arg {object} callback.data - Object containing the created containers information.
 */
// @todo: find a good way to document createOptions, and possibly not make them docker specific.
exports.create = function(createOptions, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.create(createOptions, callback);
    }
  });
};

/**
 * Starts a container.
 * @arg {string} containerId - Id of the container to start.
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @todo Find a good way to document startOptions, and possibly not make them docker specific.
 */
exports.start = function(cid, startOptions, callback) {
  if (typeof startOptions === 'function' && callback === undefined) {
    callback = startOptions;
    startOptions = null;
  }
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.start(cid, startOptions, function(err) {
        // @todo: This short delay is to give redis a chance to get into a good state.
        // A better check would be bounded polling of redis until it is in a good state.
        setTimeout(function() {
          callback(err);
        }, 3000);
      });
    }
  });
};

/**
 * Runs a command in a container, in interactive mode
 * @arg {string} image - Name of image to run command in
 * @arg {string} cmd - Command to run
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @example
 * var image = 'kalabox/git:stable';
 * var cmd = ['git', 'status'];
 * kbox.engine.run(image, cmd, {}, {}, function(err) {
 *   if (err) {
 *     throw err;
 *   }
 *   done();
 * });
 */
exports.run = function(image, cmd, createOpts, startOpts, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.run(image, cmd, process.stdin, process.stdout,
        createOpts, startOpts, callback);
    }
  });
};

// @todo: document
var query = function(image, cmd, createOpts, startOpts, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.query(image, cmd, createOpts, startOpts, function(err, stream) {
        callback(err, stream);
      }, function() {

      });
    }
  });
};
exports.query = query;

/**
 * Queries a container and returns a string
 * @arg {string} image - Name of image to run query in
 * @arg {string} cmd - Command (query) to run
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @example
 * var image = 'kalabox/syncthing:stable';
 * var cmd = '/bin/ls';
 * kbox.engine.queryString(image, cmd, {}, {}, function(err, data) {
 *   if (err) {
 *     throw err;
 *   } else {
 *     console.log(data);
 *   }
 * });
 */
exports.queryString = function(image, cmd, createOpts, startOpts, callback) {
  query(image, cmd, createOpts, startOpts, function(err, stream) {
    if (err) {
      callback(err);
    } else {
      var buff = null;
      stream.on('data', function(data) {
        if (!buff) {
          buff = data;
        } else {
          buff = Buffer.concat([buff, data]);
        }
      });
      stream.on('end', function() {
        if (buff) {
          callback(null, buff.toString());
        } else {
          callback();
        }
      });
    }
  });
};

/**
 * Stops a container.
 * @arg {string} containerId - Id of the container to stop.
 * @arg {function} callback - Callback called when the container has been stopped.
 * @arg {error} callback.error
 * @example
 * kbox.engine.stop(containerId, function(err) {
 *   if (err) {
 *     throw err;
 *   }
 *   console.log('Container stopped!');
 * });
 */
exports.stop = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.stop(cid, callback);
    }
  });
};

/**
 * Removes a container from the engine.
 * @arg {string} containerId - Id of the container to remove.
 * @arg {function} callback - Callback called when the container has been removed.
 * @arg {error} callback.error
 */
exports.remove = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.remove(cid, callback);
    }
  });
};

/**
 * Pulls or builds the image for a container.
 * @arg {object} image - Image object to pull or build.
 * @arg {function} callback - Callback called when the image has been built.
 * @arg {error} callback.error
 */
exports.build = function(image, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      var fn = (image.build) ? 'build' : 'pull';
      engine[fn](image, callback);
    }
  });
};
<commit_msg>Ensure that exports.list function has a correct callback if no appName is passed in<commit_after>/**
 * Module for interfacing with the Kalabox container system implementation, and
 * the provider of the container system.
 *
 * NOTE: The container system and the provider are not always the same. For
 * example using docker on a Mac would use docker as the container system,
 * however it would be provided by boot2docker.
 * @module kbox.engine
 */

'use strict';

var core = require('./core.js');
var util = require('./util.js');
var helpers = util.helpers;
var _ = require('lodash');

var provider = require('./engine/provider.js');
exports.provider = provider;

var engine = null;

var makeProviderError = function(msg) {
  var providerName = null;
  if (provider) {
    providerName = provider.getName();
  }
  var msgParts = [
    'Provider',
    providerName,
    msg
  ];
  var fullErrorMsg = _.filter(msgParts).join(' ');
  return new Error(fullErrorMsg);
};

var isProviderInstalled = false;
var verifyProviderInstalled = function(callback) {
  if (isProviderInstalled) {
    callback(null);
  } else {
    provider.isInstalled(function(err, isInstalled) {
      if (err) {
        callback(err);
      } else if (!isInstalled) {
        callback(makeProviderError('is NOT installed!'));
      } else {
        isProviderInstalled = true;
        callback(null);
      }
    });
  }
};

var isProviderUp = false;
var verifyProviderUp = function(callback) {
  if (isProviderUp) {
    callback(null);
  } else {
    provider.isUp(function(err, isUp) {
      if (err) {
        callback(err);
      } else if (!isUp) {
        callback(makeProviderError('is NOT up!'));
      } else {
        isProviderUp = true;
        callback(null);
      }
    });
  }
};

var engineHasBeenInit = false;
var verifyProviderIsReady = function(callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      verifyProviderUp(function(err) {
        if (err) {
          callback(err);
        } else {
          if (!engineHasBeenInit) {
            provider.engineConfig(function(err, config) {
              if (err) {
                callback(err);
              }
              else {
                engine.init(config);
                engineHasBeenInit = true;
                callback(null);
              }
            });
          }
          else {
            callback(null);
          }
        }
      });
    }
  });
};

/**
 * Returns the name of the configured provider.
 * @returns {string} - Name of the configured provider.
 */
exports.getProviderName = function() {
  return provider.name;
};

/**
 * Retrieves the state of the engine being up.
 * @arg {function} callback
 * @arg {error} callback.error
 * @arg {boolean} callback.isUp - Boolean representing the state of the engine being up.
 * @example
 * kbox.engine.isUp(function(err, isUp) {
 *   if (err) {
 *     throw err;
 *   } else if (isUp) {
 *     console.log('It is up!');
 *   }
 * });
 */
exports.isUp = function(callback) {
  provider.isUp(callback);
};

/**
 * Initializes kalabox engine.
 * @arg {string} globalConfig - Kalabox global config to initialize with.
 * @example
 * var globalConfig = kbox.core.config.getGlobalConfig();
 * kbox.engine.init(globalConfig);
 */
exports.init = function(globalConfig) {
  if (!engine) {
    engine = require('./engine/' + globalConfig.engine + '.js');
    core.deps.register('providerModule', engine.getProviderModule());
  }
};

/**
 * Gets the engine provider into the state it needs to be in to do
 * engine things.
 * @arg {int} attempts - The amount of times to try to start the engine.
 * @arg {function} callback - Callback called when the engine has started.
 * @arg {error} callback.error
 */
exports.up = function(attempts, callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      //provider.up(attempts, callback);
      provider.up(callback);
    }
  });
};

/**
 * Turns the engine off.
 * @arg {int} attempts - The amount of times to try to stop the engine.
 * @arg {function} callback - Callback called when the engine has been stopped.
 * @arg {error} callback.error
 */
exports.down = function(attempts, callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      //provider.down(attempts, callback);
      provider.down(callback);
    }
  });
};

/**
 * Lists installed containers.
 * @arg {string} appName [optional] - App name to filter containers by.
 * @arg {function} callback - Callback called when the engine query completes.
 * @arg {error} callback.error
 * @arg {array} callback.containers - An array of container objects.
 * @example
 * kbox.engine.list(function(err, containers) {
 *   for (var i = 0; i < containers.length; ++i) {
 *     console.log(containers[i].name);
 *   }
 * });
 */
var list = exports.list = function(appName, callback) {
  if (callback === undefined && typeof appName === 'function') {
    callback = appName;
    appName = null;
  }
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.list(appName, callback);
    }
  });
};

// @todo: document...
exports.exists = function(cid, callback) {
  list(function(err, containers) {
    if (err) {
      callback(err);
    } else {
      var exists = _.find(containers, function(container) {
        return container.id === cid || container.name === cid;
      });
      callback(null, exists !== undefined);
    }
  });
};

/**
 * Inspects a container and returns details.
 * @arg {string} containerId - Id of the container to inspect.
 * @arg {function} callback - Callback called when the container has been inspected.
 * @arg {error} callback.error
 * @arg {object} callback.data - Object containing the containers inspected data.
 */
exports.inspect = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.getEnsure(cid, 'inspect', function(err, container) {
        if (err) {
          callback(err);
        } else {
          engine.inspect(container, callback);
        }
      });
    }
  });
};

// @todo: document
exports.info = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.info(cid, callback);
    }
  });
};

/**
 * Creates a container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been created.
 * @arg {error} callback.error
 * @arg {object} callback.data - Object containing the created containers information.
 */
// @todo: find a good way to document createOptions, and possibly not make them docker specific.
exports.create = function(createOptions, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.create(createOptions, callback);
    }
  });
};

/**
 * Starts a container.
 * @arg {string} containerId - Id of the container to start.
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @todo Find a good way to document startOptions, and possibly not make them docker specific.
 */
exports.start = function(cid, startOptions, callback) {
  if (typeof startOptions === 'function' && callback === undefined) {
    callback = startOptions;
    startOptions = null;
  }
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.start(cid, startOptions, function(err) {
        // @todo: This short delay is to give redis a chance to get into a good state.
        // A better check would be bounded polling of redis until it is in a good state.
        setTimeout(function() {
          callback(err);
        }, 3000);
      });
    }
  });
};

/**
 * Runs a command in a container, in interactive mode
 * @arg {string} image - Name of image to run command in
 * @arg {string} cmd - Command to run
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @example
 * var image = 'kalabox/git:stable';
 * var cmd = ['git', 'status'];
 * kbox.engine.run(image, cmd, {}, {}, function(err) {
 *   if (err) {
 *     throw err;
 *   }
 *   done();
 * });
 */
exports.run = function(image, cmd, createOpts, startOpts, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.run(image, cmd, process.stdin, process.stdout,
        createOpts, startOpts, callback);
    }
  });
};

// @todo: document
var query = function(image, cmd, createOpts, startOpts, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.query(image, cmd, createOpts, startOpts, function(err, stream) {
        callback(err, stream);
      }, function() {

      });
    }
  });
};
exports.query = query;

/**
 * Queries a container and returns a string
 * @arg {string} image - Name of image to run query in
 * @arg {string} cmd - Command (query) to run
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @example
 * var image = 'kalabox/syncthing:stable';
 * var cmd = '/bin/ls';
 * kbox.engine.queryString(image, cmd, {}, {}, function(err, data) {
 *   if (err) {
 *     throw err;
 *   } else {
 *     console.log(data);
 *   }
 * });
 */
exports.queryString = function(image, cmd, createOpts, startOpts, callback) {
  query(image, cmd, createOpts, startOpts, function(err, stream) {
    if (err) {
      callback(err);
    } else {
      var buff = null;
      stream.on('data', function(data) {
        if (!buff) {
          buff = data;
        } else {
          buff = Buffer.concat([buff, data]);
        }
      });
      stream.on('end', function() {
        if (buff) {
          callback(null, buff.toString());
        } else {
          callback();
        }
      });
    }
  });
};

/**
 * Stops a container.
 * @arg {string} containerId - Id of the container to stop.
 * @arg {function} callback - Callback called when the container has been stopped.
 * @arg {error} callback.error
 * @example
 * kbox.engine.stop(containerId, function(err) {
 *   if (err) {
 *     throw err;
 *   }
 *   console.log('Container stopped!');
 * });
 */
exports.stop = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.stop(cid, callback);
    }
  });
};

/**
 * Removes a container from the engine.
 * @arg {string} containerId - Id of the container to remove.
 * @arg {function} callback - Callback called when the container has been removed.
 * @arg {error} callback.error
 */
exports.remove = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.remove(cid, callback);
    }
  });
};

/**
 * Pulls or builds the image for a container.
 * @arg {object} image - Image object to pull or build.
 * @arg {function} callback - Callback called when the image has been built.
 * @arg {error} callback.error
 */
exports.build = function(image, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      var fn = (image.build) ? 'build' : 'pull';
      engine[fn](image, callback);
    }
  });
};
<|endoftext|>


<commit_before>'use babel';

export default class Workspace {
  open (workspace) {
    if (!workspace) {
      return;
    }

    atom.project.setPaths(workspace.projectPaths);

    {
      // TODO Refactor out
      const rootContainer = atom.workspace.paneContainer.getRoot();
      if (rootContainer.children) {
        for (const subPane of rootContainer.children) {
          subPane.destroy();
        }
      } else {
        rootContainer.destroy();
      }
    }

    for (const i in workspace.panes) {
      const subPane = workspace.panes[i];
      if (subPane.type === 'pane') {
        this.__createPane(subPane, i);
      } else if (subPane.type === 'paneAxis') {
        this.__createPaneAxis(subPane, i);
      }
    }
  }

  save (workspaceName) {
    if (!workspaceName) {
      return;
    }

    const projectPaths    = atom.project.getPaths();
    const rootContainer   = atom.workspace.paneContainer.getRoot();
    const panes           = this.__buildPaneMap(rootContainer);
    const workspaceToSave = { panes, projectPaths };

    let savedWorkspaces = atom.config.get('save-workspace-Workspaces') || {};
    savedWorkspaces[workspaceName] = workspaceToSave;

    atom.config.set('save-workspace-Workspaces', savedWorkspaces);
  }

  remove (workspaceName) {
    let model = atom.config.get('save-workspace-Workspaces');
    if( workspaceName in model){
      delete model[workspaceName];
      atom.config.set('save-workspace-Workspaces', model);
    }
  }

  __buildPaneMap (pane) {
    if (!pane.children) {
      return [this.__buildPaneItem(pane)];
    }

    // TODO ES6
    const panes = [];

    for (const child of pane.children) {
      panes.push(this.__buildPaneItem(child));
    }

    return panes;
  }

  __buildPaneItem (pane) {
    if (pane.children) {
      return {
        type: 'paneAxis',
        data: this.__buildPaneMap(pane),
        orientation: pane.orientation
      };
    }

    return {
      type: 'pane',
      data: this.__savePaneTabs(pane)
    };
  }

  __openTabs (tabs) {
    for (const uri of tabs) {
      atom.workspace.open(uri, {});
    }
  }

  __createPane (pane, paneIndex) {
    let newPane;

    if (paneIndex != '0' && pane.data.orientation) {
      const activePane = atom.workspace.paneContainer.getActivePane();
      if (pane.data.orientation === 'horizontal') {
        newPane = activePane.splitRight();
      } else {
        newPane = activePane.splitDown();
      }
    }

    if (newPane) {
      newPane.activate();
    }

    atom.workspace.paneForURI(pane.data.tabs[0]);
    this.__openTabs(pane.data.tabs);
  }

  __createPaneAxis (paneAxis, paneIndex) {
    if (paneIndex !== '0') {
      this.__splitPane(paneAxis)
    }

    for (const i in paneAxis.data) {
      const subPane = paneAxis.data[i];
      if (subPane.type === 'pane') {
        this.__createPane(subPane, i);
      } else if (subPane.type === 'paneAxis') {
        this.__createPaneAxis(subPane, i)
      }
    }
  }

  __splitPane (paneAxis) {
    let newPane;
    const activePane = atom.workspace.paneContainer.getActivePane();

    if (paneAxis.orientation === 'horizontal') {
      newPane = activePane.splitRight();
    } else {
      newPane = activePane.splitDown();
    }

    if (newPane) {
      newPane.activate();
    }
  }

  __savePaneTabs (pane) {
    const tabs = [];

    for (const tab of pane.items) {
      tabs.push(tab.getURI());
    }

    return {
       tabs: tabs,
       orientation: pane.parent.orientation
     };
  }
}
<commit_msg>SPIKE Pane axiseses orientation is... different?<commit_after>'use babel';

export default class Workspace {
  open (workspace) {
    if (!workspace) {
      return;
    }

    atom.project.setPaths(workspace.projectPaths);

    {
      // TODO Refactor out
      const rootContainer = atom.workspace.paneContainer.getRoot();
      if (rootContainer.children) {
        for (const subPane of rootContainer.children) {
          subPane.destroy();
        }
      } else {
        rootContainer.destroy();
      }
    }

    for (const i in workspace.panes) {
      const subPane = workspace.panes[i];
      if (subPane.type === 'pane') {
        this.__createPane(subPane, i);
      } else if (subPane.type === 'paneAxis') {
        this.__createPaneAxis(subPane, i);
      }
    }
  }

  save (workspaceName) {
    if (!workspaceName) {
      return;
    }

    const projectPaths    = atom.project.getPaths();
    const rootContainer   = atom.workspace.paneContainer.getRoot();
    const panes           = this.__buildPaneMap(rootContainer);
    const workspaceToSave = { panes, projectPaths };

    let savedWorkspaces = atom.config.get('save-workspace-Workspaces') || {};
    savedWorkspaces[workspaceName] = workspaceToSave;

    atom.config.set('save-workspace-Workspaces', savedWorkspaces);
  }

  remove (workspaceName) {
    let model = atom.config.get('save-workspace-Workspaces');
    if( workspaceName in model){
      delete model[workspaceName];
      atom.config.set('save-workspace-Workspaces', model);
    }
  }

  __buildPaneMap (pane) {
    if (!pane.children) {
      return [this.__buildPaneItem(pane)];
    }

    // TODO ES6
    const panes = [];

    for (const child of pane.children) {
      panes.push(this.__buildPaneItem(child));
    }

    return panes;
  }

  __buildPaneItem (pane) {
    if (pane.children) {
      return {
        type: 'paneAxis',
        data: this.__buildPaneMap(pane),
        orientation: pane.orientation
      };
    }

    return {
      type: 'pane',
      data: this.__savePaneTabs(pane)
    };
  }

  __openTabs (tabs) {
    for (const uri of tabs) {
      atom.workspace.open(uri, {});
    }
  }

  __createPane (pane, paneIndex) {
    let newPane;

    if (paneIndex != '0' && pane.data.orientation) {
      const activePane = atom.workspace.paneContainer.getActivePane();
      if (pane.data.orientation === 'horizontal') {
        newPane = activePane.splitRight();
      } else {
        newPane = activePane.splitDown();
      }
    }

    if (newPane) {
      newPane.activate();
    }

    atom.workspace.paneForURI(pane.data.tabs[0]);
    this.__openTabs(pane.data.tabs);
  }

  __createPaneAxis (paneAxis, paneIndex) {
    if (paneIndex !== '0') {
      this.__splitPane(paneAxis)
    }

    for (const i in paneAxis.data) {
      const subPane = paneAxis.data[i];
      if (subPane.type === 'pane') {
        this.__createPane(subPane, i);
      } else if (subPane.type === 'paneAxis') {
        this.__createPaneAxis(subPane, i)
      }
    }
  }

  __splitPane (paneAxis) {
    let newPane;
    const activePane = atom.workspace.paneContainer.getActivePane();

    if (paneAxis.orientation === 'horizontal') {
      newPane = activePane.splitDown();
    } else {
      newPane = activePane.splitRight();
    }

    if (newPane) {
      newPane.activate();
    }
  }

  __savePaneTabs (pane) {
    const tabs = [];

    for (const tab of pane.items) {
      tabs.push(tab.getURI());
    }

    return {
       tabs: tabs,
       orientation: pane.parent.orientation
     };
  }
}
<|endoftext|>


<commit_before>/*
 * feathers-errors
 * https://github.com/feathersjs/feathers-errors
 *
 * Copyright (c) 2014 Eric Kryski
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var errors = require('./error-types');
var html = fs.readFileSync(path.resolve(__dirname, '..', 'public/error.html')).toString();

/**
* Escape the given string of `html`.
*
* @param {String} html
* @return {String}
* @api private
*/
var escapeHTML = function(html){
  return String(html)
    .replace(/&(?!\w+;)/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"');
};

exports = module.exports = function () {
  return function () {
    var app = this;

    // Enable the errors Plugin
    app.enable('feathers errors');

    // Set the available errors on the app for convenience
    app.errors = errors;
  };
};

exports.types = errors;

/**
 * Convenience method for a 404 middleware
 * See http://expressjs.com/guide.html#error-handling
 * @param  {Error} err - An error
 * @param  {Object} req - the request object
 * @param  {Object} res - the response object
 * @param  {Function} next - callback to call for next step in middleware chain
 */
exports.missing = function(req, res, next) {
  next(new errors.NotFound('Page not found.'));
};

/**
 * The error handler middleware.
 * See http://expressjs.com/guide.html#error-handling
 * @param  {Error} err - An error
 * @param  {Object} req - the request object
 * @param  {Object} res - the response object
 * @param  {Function} next - callback to call for next step in middleware chain
 *
 */

/* jshint unused:false */
exports.handler = function(err, req, res, next) {
  if (typeof err === 'string' || !(err instanceof errors.AbstractError)) {
    err = new errors.GeneralError(err);
  }

  var statusCode = typeof err.code === 'number' ? err.code : 500;

  res.status(statusCode);

  if (req.app.log === 'function') {
    req.app.log(req.url, err.stack || err);
  }

  res.format({
    'text/html': function(){
      console.log('VIEWS', req.app.get('views'));

      // If we have a rendering engine don't show the
      // default feathers error page.
      if (req.app.get('view engine') !== undefined) {
        if (err.code === 404) {
          return res.redirect('/404');
        }

        return res.redirect('/500');
      }

      var stack = (err.stack || '')
          .split('\n')
          .slice(1)
          .map(function(v) {
             return '
' + v + '
';
           })
          .join('');

      var errorPage = html
          .replace('{stack}', stack)
          .replace('{title}', err.message)
          .replace('{statusCode}', err.code)
          .replace(/\{error\}/g, escapeHTML(err.toString().replace(/\n/g, '
')));
      res.send(errorPage);
    },

    'application/json': function(){
      res.json({
        'code': err.code,
        'name': err.name,
        'message': err.message
      });
    },

    'text/plain': function(){
      res.send(err.message);
    }
  });
};<commit_msg>removing a console log there<commit_after>/*
 * feathers-errors
 * https://github.com/feathersjs/feathers-errors
 *
 * Copyright (c) 2014 Eric Kryski
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var errors = require('./error-types');
var html = fs.readFileSync(path.resolve(__dirname, '..', 'public/error.html')).toString();

/**
* Escape the given string of `html`.
*
* @param {String} html
* @return {String}
* @api private
*/
var escapeHTML = function(html){
  return String(html)
    .replace(/&(?!\w+;)/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"');
};

exports = module.exports = function () {
  return function () {
    var app = this;

    // Enable the errors Plugin
    app.enable('feathers errors');

    // Set the available errors on the app for convenience
    app.errors = errors;
  };
};

exports.types = errors;

/**
 * Convenience method for a 404 middleware
 * See http://expressjs.com/guide.html#error-handling
 * @param  {Error} err - An error
 * @param  {Object} req - the request object
 * @param  {Object} res - the response object
 * @param  {Function} next - callback to call for next step in middleware chain
 */
exports.missing = function(req, res, next) {
  next(new errors.NotFound('Page not found.'));
};

/**
 * The error handler middleware.
 * See http://expressjs.com/guide.html#error-handling
 * @param  {Error} err - An error
 * @param  {Object} req - the request object
 * @param  {Object} res - the response object
 * @param  {Function} next - callback to call for next step in middleware chain
 *
 */

/* jshint unused:false */
exports.handler = function(err, req, res, next) {
  if (typeof err === 'string' || !(err instanceof errors.AbstractError)) {
    err = new errors.GeneralError(err);
  }

  var statusCode = typeof err.code === 'number' ? err.code : 500;

  res.status(statusCode);

  if (req.app.log === 'function') {
    req.app.log(req.url, err.stack || err);
  }

  res.format({
    'text/html': function(){
      // If we have a rendering engine don't show the
      // default feathers error page.
      if (req.app.get('view engine') !== undefined) {
        if (err.code === 404) {
          return res.redirect('/404');
        }

        return res.redirect('/500');
      }

      var stack = (err.stack || '')
          .split('\n')
          .slice(1)
          .map(function(v) {
             return '
' + v + '
';
           })
          .join('');

      var errorPage = html
          .replace('{stack}', stack)
          .replace('{title}', err.message)
          .replace('{statusCode}', err.code)
          .replace(/\{error\}/g, escapeHTML(err.toString().replace(/\n/g, '
')));
      res.send(errorPage);
    },

    'application/json': function(){
      res.json({
        'code': err.code,
        'name': err.name,
        'message': err.message
      });
    },

    'text/plain': function(){
      res.send(err.message);
    }
  });
};<|endoftext|>


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

var util = require('util');

function ProtocolError(message) {
    Error.call(this);
    this.message = message;
    this.name = 'ProtocolError';
}
util.inherits(ProtocolError, Error);

function TypeError(message) {
    ProtocolError.call(this, message);
    this.message = message;
    this.name = 'TypeError';
}

util.inherits(TypeError, ProtocolError);

function ConnectionError(message, condition, connection) {
    Error.call(this, message);
    this.message = message;
    this.name = 'ConnectionError';
    this.condition = condition;
    this.description = message;
    this.connection = connection;
}

util.inherits(ConnectionError, Error);

ConnectionError.prototype.toJSON = function () {
    return {
        type: this.name,
        code: this.condition,
        message: this.description
    };
};

module.exports = {
    ProtocolError: ProtocolError,
    TypeError: TypeError,
    ConnectionError: ConnectionError
};
<commit_msg>Make ConnectionError.connection not enumerable<commit_after>/*
 * Copyright 2015 Red Hat Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

var util = require('util');

function ProtocolError(message) {
    Error.call(this);
    this.message = message;
    this.name = 'ProtocolError';
}
util.inherits(ProtocolError, Error);

function TypeError(message) {
    ProtocolError.call(this, message);
    this.message = message;
    this.name = 'TypeError';
}

util.inherits(TypeError, ProtocolError);

function ConnectionError(message, condition, connection) {
    Error.call(this, message);
    this.message = message;
    this.name = 'ConnectionError';
    this.condition = condition;
    this.description = message;
    Object.defineProperty(this, 'connection', { value: connection, enumerable: false });
}

util.inherits(ConnectionError, Error);

ConnectionError.prototype.toJSON = function () {
    return {
        type: this.name,
        code: this.condition,
        message: this.description
    };
};

module.exports = {
    ProtocolError: ProtocolError,
    TypeError: TypeError,
    ConnectionError: ConnectionError
};
<|endoftext|>


<commit_before>/**
 * Setup the user (DOM) event flow.
 *
 * @private
 * @param {object} The moule instnace.
*/
module.exports = function (instance, template, options, dom, data) {
    for (var event in template.events) {
        for (var i = 0, l = template.events[event].length; i < l; ++i) {
            handleEvent(instance, template, dom, data, event, template.events[event][i]);
        }
    }
};

function handleEvent (instance, template, dom, data, event, listener) {

    // handle element config
    if (listener.element) {
        listener.selector = "[data-element='" + listener.element + "']";
        delete listener.element;
    }

    var elms = dom.querySelectorAll(listener.selector || listener.sel);
    if (elms) {

        Array.from(elms).forEach(function (elm) {
            elm.addEventListener(listener.on, function (domEvent) {

                // dont prevent default browser actions
                if (!listener.dontPrevent) {
                    domEvent.preventDefault();
                }

                domEvent.data = data;
                domEvent.domItem = elm;
                domEvent.template = template.to;

                // create event stream
                var eventStream = template.streams[event];
                if (!eventStream) {
                    eventStream = instance.flow(event);
                    var handler = function (err) {
                        eventStream.i.end();
                        delete template.streams[event];
                    };

                    // cache stream
                    template.streams[event] = eventStream;

                    eventStream.o.on('error', handler);
                    eventStream.o.on('end', handler);
                    eventStream.o.on('data', function nirvana () {});
                }

                eventStream.i.write(domEvent);

                if (listener.end) {
                    eventStream.i.on('ready', eventStream.i.end.bind(eventStream.i));
                }
            });
        });
    }
}
<commit_msg>Added event option to prevent domEvent data append.<commit_after>/**
 * Setup the user (DOM) event flow.
 *
 * @private
 * @param {object} The moule instnace.
*/
module.exports = function (instance, template, options, dom, data) {
    for (var event in template.events) {
        for (var i = 0, l = template.events[event].length; i < l; ++i) {
            handleEvent(instance, template, dom, data, event, template.events[event][i]);
        }
    }
};

function handleEvent (instance, template, dom, data, event, listener) {

    // handle element config
    if (listener.element) {
        listener.selector = "[data-element='" + listener.element + "']";
        delete listener.element;
    }

    var elms = dom.querySelectorAll(listener.selector || listener.sel);
    if (elms) {

        Array.from(elms).forEach(function (elm) {
            elm.addEventListener(listener.on, function (domEvent) {

                // dont prevent default browser actions
                if (!listener.dontPrevent) {
                    domEvent.preventDefault();
                }

                // create event stream
                var eventStream = template.streams[event];
                if (!eventStream) {
                    eventStream = instance.flow(event);
                    var handler = function (err) {
                        eventStream.i.end();
                        delete template.streams[event];
                    };

                    // cache stream
                    template.streams[event] = eventStream;

                    eventStream.o.on('error', handler);
                    eventStream.o.on('end', handler);
                    eventStream.o.on('data', function nirvana () {});
                }

                var eventData = listener.noDomData ? {} : domEvent;
                eventData.data = data;
                eventData.domItem = elm;
                eventData.template = template.to;

                eventStream.i.write(eventData);

                if (listener.end) {
                    eventStream.i.on('ready', eventStream.i.end.bind(eventStream.i));
                }
            });
        });
    }
}
<|endoftext|>


<commit_before>/**
 * Policy mappings (ACL)
 *
 * Policies are simply Express middleware functions which run **before** your controllers.
 * You can apply one or more policies to a given controller, or protect just one of its actions.
 *
 * Any policy file (e.g. `authenticated.js`) can be dropped into the `/policies` folder,
 * at which point it can be accessed below by its filename, minus the extension, (e.g. `authenticated`)
 *
 * For more information on policies, check out:
 * http://sailsjs.org/#documentation
 */

module.exports.policies = {

  // Default policy for all controllers and actions
  // (`true` allows public access)
  '*': true,

  PhotoController: {
    '*': ['isAuthenticated', 'isAdmin'],
    //destroy: 'isWallOwner', TODO
    destroy: true,
    find: true,
    create: true,
    upload: true,
  },

  WallController: {
    '*': ['isAuthenticated', 'isAdmin'],
    //destroy: 'isWallOwner', TODO
    destroy: true,
    find: true,
    photos: true,
    myWalls: 'isAuthenticated',
    create: 'isAuthenticated',
    findOneByTitle: true
  },

  UserController: {
    '*': ['isAuthenticated', 'isAdmin'],
    login: true,
    find: true,
    create: true,
  },

};

/**
 * Here's what the `isNiceToAnimals` policy from above might look like:
 * (this file would be located at `policies/isNiceToAnimals.js`)
 *
 * We'll make some educated guesses about whether our system will
 * consider this user someone who is nice to animals.
 *
 * Besides protecting rabbits (while a noble cause, no doubt),
 * here are a few other example use cases for policies:
 *
 *	+ cookie-based authentication
 *	+ role-based access control
 *	+ limiting file uploads based on MB quotas
 *	+ OAuth
 *	+ BasicAuth
 *	+ or any other kind of authentication scheme you can imagine
 *
 */

/*
module.exports = function isNiceToAnimals (req, res, next) {

	// `req.session` contains a set of data specific to the user making this request.
	// It's kind of like our app's "memory" of the current user.

	// If our user has a history of animal cruelty, not only will we
	// prevent her from going even one step further (`return`),
	// we'll go ahead and redirect her to PETA (`res.redirect`).
	if ( req.session.user.hasHistoryOfAnimalCruelty ) {
		return res.redirect('http://PETA.org');
	}

	// If the user has been seen frowning at puppies, we have to assume that
	// they might end up being mean to them, so we'll
	if ( req.session.user.frownsAtPuppies ) {
		return res.redirect('http://www.dailypuppy.com/');
	}

	// Finally, if the user has a clean record, we'll call the `next()` function
	// to let them through to the next policy or our controller
	next();
};
*/
<commit_msg>Removed auth<commit_after>/**
 * Policy mappings (ACL)
 *
 * Policies are simply Express middleware functions which run **before** your controllers.
 * You can apply one or more policies to a given controller, or protect just one of its actions.
 *
 * Any policy file (e.g. `authenticated.js`) can be dropped into the `/policies` folder,
 * at which point it can be accessed below by its filename, minus the extension, (e.g. `authenticated`)
 *
 * For more information on policies, check out:
 * http://sailsjs.org/#documentation
 */

module.exports.policies = {

  // Default policy for all controllers and actions
  // (`true` allows public access)
  '*': true,

  PhotoController: {
    '*': ['isAuthenticated', 'isAdmin'],
    //destroy: 'isWallOwner', TODO
    destroy: true,
    find: true,
    create: true,
    upload: true,
  },

  WallController: {
    '*': ['isAuthenticated', 'isAdmin'],
    //destroy: 'isWallOwner', TODO
    destroy: true,
    find: true,
    photos: true,
    myWalls: true,
    create: true,
    findOneByTitle: true
  },

  UserController: {
    '*': ['isAuthenticated', 'isAdmin'],
    login: true,
    find: true,
    create: true,
  },

};

/**
 * Here's what the `isNiceToAnimals` policy from above might look like:
 * (this file would be located at `policies/isNiceToAnimals.js`)
 *
 * We'll make some educated guesses about whether our system will
 * consider this user someone who is nice to animals.
 *
 * Besides protecting rabbits (while a noble cause, no doubt),
 * here are a few other example use cases for policies:
 *
 *	+ cookie-based authentication
 *	+ role-based access control
 *	+ limiting file uploads based on MB quotas
 *	+ OAuth
 *	+ BasicAuth
 *	+ or any other kind of authentication scheme you can imagine
 *
 */

/*
module.exports = function isNiceToAnimals (req, res, next) {

	// `req.session` contains a set of data specific to the user making this request.
	// It's kind of like our app's "memory" of the current user.

	// If our user has a history of animal cruelty, not only will we
	// prevent her from going even one step further (`return`),
	// we'll go ahead and redirect her to PETA (`res.redirect`).
	if ( req.session.user.hasHistoryOfAnimalCruelty ) {
		return res.redirect('http://PETA.org');
	}

	// If the user has been seen frowning at puppies, we have to assume that
	// they might end up being mean to them, so we'll
	if ( req.session.user.frownsAtPuppies ) {
		return res.redirect('http://www.dailypuppy.com/');
	}

	// Finally, if the user has a clean record, we'll call the `next()` function
	// to let them through to the next policy or our controller
	next();
};
*/
<|endoftext|>


<commit_before>/**
 * Full page
 */
(function () {
	'use strict';
	/**
	 * Full scroll main function
	 */
	var fullScroll = function () {
		/**
		 * Main div
		 * @type {Object}
		 */
		var main = document.getElementById('main');
		/**
		 * Sections div
		 * @type {Array}
		 */
		var sections = main.getElementsByTagName('section');

		/**
		 * Full page scroll configurations
		 * @type {Object}
		 */
		var defaults = {
			container : main,
		    sections : sections,
		    animateTime : 0.6,
		    animateType : 'ease',
		    maxPosition: sections.length - 1
		};

		this.defaults = defaults;
		/**
		 * Init build
		 */
		this.init();
	};

	/**
	 * Init plugin
	 */
	fullScroll.prototype.init = function () {
		this.buildSections()
			.buildDots()
			.addEvents();

		this.currentPosition = 0;
	};

	/**
	 * Build sections
	 * @return {Object} this(fullScroll)
	 */
	fullScroll.prototype.buildSections = function () {
		var sections = this.defaults.sections;
		for (var i = 0; i < sections.length; i++) {
			sections[i].setAttribute('data-index', i);
		}
		return this;
	};

	/**
	 * Build dots navigation
	 * @return {Object} this (fullScroll)
	 */
	fullScroll.prototype.buildDots = function () {

		this.ul = document.createElement('ul');
		this.ul.classList.add('dots');
		var _self = this;
		var sections = this.defaults.sections;

		var dotsClick = function () {
			var dataIndex = this.getAttribute('data-index');
 			_self.moveScroll(2, null, dataIndex);
		};

		for (var i = 0; i < sections.length; i++) {
			var li = document.createElement('li');
			var a = document.createElement('a');

			a.addEventListener('click', dotsClick);

			a.setAttribute('href', '#');
			a.setAttribute('data-index', i);

			li.appendChild(a);
			_self.ul.appendChild(li);
		}

		_self.ul.childNodes[0].firstChild.classList.add('active');

		document.body.appendChild(_self.ul);

		return this;
	};

	/**
	 * Add Events
	 * @return {Object} this(fullScroll)
	 */
	fullScroll.prototype.addEvents = function () {
		var _self = this;

		function mousewheel (event){
			var direction = event.deltaY > 0 ? 1 : 0;
 			_self.moveScroll(1, direction, null);
		}

		function keyup (event) {
			var direction = event.keyCode == 40 ? 1 : event.keyCode == 38 ? 0 : null;
		}

		if (document.addEventListener) {
			document.addEventListener('mousewheel', mousewheel);
			document.addEventListener('keyup', keyup);
		} else {
			document.attachEvent('mousewheel', mousewheel);
			document.attachEvent('keyup', keyup);
		}
		return this;
	};

	/**
	 * Move scroll
	 * @param  {Object} Element  Root element
	 * @param  {Integer} Direction 1 == 'down' 0 == 'top'
	 * @param  {Integer} Type 1 == 'Top or down' 0 == 'With index'
	 */
	fullScroll.prototype.moveScroll = function (type, direction, index) {
		var _self = this;
		_self.changePosition(type, direction, index);
		_self.animateScroll();
	};

	/**
	 * Move scroll with animation
	 */
	fullScroll.prototype.animateScroll = function () {
		var animateTime = this.defaults.animateTime;
        var animateType = this.defaults.animateType;
        var position = this.currentPosition * 100;

	    this.defaults.container.style.webkitTransform = 'translateY(-' + position + '%)';
	    this.defaults.container.style.mozTransform = 'translateY(-' + position + '%)';
	    this.defaults.container.style.msTransform = 'translateY(-' + position + '%)';
	    this.defaults.container.style.transform = 'translateY(-' + position + '%)';
	    this.defaults.container.style.webkitTransition = 'all ' + animateTime + 's ' + animateType;
	    this.defaults.container.style.mozTransition = 'all ' + animateTime + 's ' + animateType;
	    this.defaults.container.style.msTransition = 'all ' + animateTime + 's ' + animateType;
	    this.defaults.container.style.transition = 'all ' + animateTime + 's ' + animateType;
   	};

   	/**
   	 * Change position of dots, menu and currentPosition variable
   	 * @param  {[type]} type      [description]
   	 * @param  {[type]} direction [description]
   	 * @param  {[type]} dataIndex [description]
   	 * @return {[type]}           [description]
   	 */
	fullScroll.prototype.changePosition = function (type, direction, dataIndex) {
		var _self = this;
		if (type == 1) {
			if (direction === 0) {
				if (_self.currentPosition > 0) {
					_self.currentPosition--;
				}
			} else if (direction == 1) {
				if (_self.currentPosition < _self.defaults.maxPosition) {
					_self.currentPosition++;
				}
			}
		} else if (type == 2) {
			_self.currentPosition = dataIndex;
		}

		for (var i = 0; i < _self.ul.childNodes.length; i++) {
			_self.ul.childNodes[i].firstChild.classList.remove('active');
			if (i == _self.currentPosition) {
				_self.ul.childNodes[i].firstChild.classList.add('active');
			}
 		}
	};

	window.fullScroll = fullScroll;

})();
<commit_msg>Move by keyup bugfix<commit_after>/**
 * Full page
 */
(function () {
	'use strict';
	/**
	 * Full scroll main function
	 */
	var fullScroll = function () {
		/**
		 * Main div
		 * @type {Object}
		 */
		var main = document.getElementById('main');
		/**
		 * Sections div
		 * @type {Array}
		 */
		var sections = main.getElementsByTagName('section');

		/**
		 * Full page scroll configurations
		 * @type {Object}
		 */
		var defaults = {
			container : main,
		    sections : sections,
		    animateTime : 0.6,
		    animateType : 'ease',
		    maxPosition: sections.length - 1
		};

		this.defaults = defaults;
		/**
		 * Init build
		 */
		this.init();
	};

	/**
	 * Init plugin
	 */
	fullScroll.prototype.init = function () {
		this.buildSections()
			.buildDots()
			.addEvents();

		this.currentPosition = 0;
	};

	/**
	 * Build sections
	 * @return {Object} this(fullScroll)
	 */
	fullScroll.prototype.buildSections = function () {
		var sections = this.defaults.sections;
		for (var i = 0; i < sections.length; i++) {
			sections[i].setAttribute('data-index', i);
		}
		return this;
	};

	/**
	 * Build dots navigation
	 * @return {Object} this (fullScroll)
	 */
	fullScroll.prototype.buildDots = function () {

		this.ul = document.createElement('ul');
		this.ul.classList.add('dots');
		var _self = this;
		var sections = this.defaults.sections;

		var dotsClick = function () {
			var dataIndex = this.getAttribute('data-index');
 			_self.moveScroll(2, null, dataIndex);
		};

		for (var i = 0; i < sections.length; i++) {
			var li = document.createElement('li');
			var a = document.createElement('a');

			a.addEventListener('click', dotsClick);

			a.setAttribute('href', '#');
			a.setAttribute('data-index', i);

			li.appendChild(a);
			_self.ul.appendChild(li);
		}

		_self.ul.childNodes[0].firstChild.classList.add('active');

		document.body.appendChild(_self.ul);

		return this;
	};

	/**
	 * Add Events
	 * @return {Object} this(fullScroll)
	 */
	fullScroll.prototype.addEvents = function () {
		var _self = this;

		function mousewheel (event){
			var direction = event.deltaY > 0 ? 1 : 0;
 			_self.moveScroll(1, direction, null);
		}

		function keyup (event) {
			var direction = event.keyCode == 40 ? 1 : event.keyCode == 38 ? 0 : null;
			_self.moveScroll(1, direction, null);
		}

		if (document.addEventListener) {
			document.addEventListener('mousewheel', mousewheel);
			document.addEventListener('keyup', keyup);
		} else {
			document.attachEvent('mousewheel', mousewheel);
			document.attachEvent('keyup', keyup);
		}
		return this;
	};

	/**
	 * Move scroll
	 * @param  {Object} Element  Root element
	 * @param  {Integer} Direction 1 == 'down' 0 == 'top'
	 * @param  {Integer} Type 1 == 'Top or down' 0 == 'With index'
	 */
	fullScroll.prototype.moveScroll = function (type, direction, index) {
		var _self = this;
		_self.changePosition(type, direction, index);
		_self.animateScroll();
	};

	/**
	 * Move scroll with animation
	 */
	fullScroll.prototype.animateScroll = function () {
		var animateTime = this.defaults.animateTime;
        var animateType = this.defaults.animateType;
        var position = this.currentPosition * 100;

	    this.defaults.container.style.webkitTransform = 'translateY(-' + position + '%)';
	    this.defaults.container.style.mozTransform = 'translateY(-' + position + '%)';
	    this.defaults.container.style.msTransform = 'translateY(-' + position + '%)';
	    this.defaults.container.style.transform = 'translateY(-' + position + '%)';
	    this.defaults.container.style.webkitTransition = 'all ' + animateTime + 's ' + animateType;
	    this.defaults.container.style.mozTransition = 'all ' + animateTime + 's ' + animateType;
	    this.defaults.container.style.msTransition = 'all ' + animateTime + 's ' + animateType;
	    this.defaults.container.style.transition = 'all ' + animateTime + 's ' + animateType;
   	};

   	/**
   	 * Change position of dots, menu and currentPosition variable
   	 * @param  {[type]} type      [description]
   	 * @param  {[type]} direction [description]
   	 * @param  {[type]} dataIndex [description]
   	 * @return {[type]}           [description]
   	 */
	fullScroll.prototype.changePosition = function (type, direction, dataIndex) {
		var _self = this;
		if (type == 1) {
			if (direction === 0) {
				if (_self.currentPosition > 0) {
					_self.currentPosition--;
				}
			} else if (direction == 1) {
				if (_self.currentPosition < _self.defaults.maxPosition) {
					_self.currentPosition++;
				}
			}
		} else if (type == 2) {
			_self.currentPosition = dataIndex;
		}

		for (var i = 0; i < _self.ul.childNodes.length; i++) {
			_self.ul.childNodes[i].firstChild.classList.remove('active');
			if (i == _self.currentPosition) {
				_self.ul.childNodes[i].firstChild.classList.add('active');
			}
 		}
	};

	window.fullScroll = fullScroll;

})();
<|endoftext|>


<commit_before>var d3 = require('d3');
var _ = require('underscore');

var axis = require('./context.js');
var callable = require('./callable.js');
var View = require('id3/lib/view.js');

var id3_id = 0;

function Figure() {
  this.x = axis();
  this.y = axis();
  this._width = null;
  this._height = null;
  this._padding = {};
  this._margin = {};
  this.index = null;
  this.layers = [];
  this.selection = null;
  this.canvas = null;
  this.dispatch = d3.dispatch('mouseover', 'width', 'height');

  // default margin
  this.margin(0);
  // default padding 5% of domain
  this.padding(.05);

  var self = this;
  this.x.on('change.figure', function(domain) {
    self.xchange(domain);
  });

  this.__call__ = function(selection) {
    this.selection = selection;

    var margin = this.margin();
    var width = this.width();
    var height = this.height();
    selection.attr('width', width+margin.left+margin.right);
    selection.attr('height', height+margin.top+margin.bottom);
    var canvas = selection.selectAll('g.canvas').data([1]);

    canvas.enter().append('svg:g')
      .attr('class', 'canvas');
    canvas
      .attr("transform", "translate("+margin.left+", "+margin.top+")");

    this.canvas = canvas;
  }

  this.xchange = function(domain) {
    this.x.domain(domain);
    var layers = this.layers;

    _.each(this.layers, function(layer) {
      layer.xview(domain);
      layer.update();
    });

    this.merge_y();
    this.redraw();
    return this;
  }

  this.merge_y = function() {
    y_domains = _.invoke(this.layers, 'yview');
    //merged y-domains
    y_min = d3.min(y_domains, function(d) { return d[0] });
    y_max = d3.max(y_domains, function(d) { return d[1] });

    var top = this.padding().top;
    var bottom = this.padding().bottom;
    var diff = y_max - y_min;

    if (top < 1) {
      top = top * diff;
    }
    if (bottom < 1) {
      bottom = bottom * diff
    }
    y_max = y_max + top;
    y_min = y_min - bottom;

    new_y = [y_min, y_max];
    this.y.domain(new_y);

    // update the layers of the merged view
    _.invoke(this.layers, 'yview', new_y);
  }

  // attempt to wait and batch multiple redraw calls into one.
  // useful for batching figure.width(width).height(height) into
  // one redraw
  var redraw_timeout;
  this.redraw = function() {
    var self = this;
    clearTimeout(redraw_timeout);
    redraw_timeout = setTimeout(function() {self._redraw()}, 100);
  };

  this._redraw = function() {
    var canvas = this.canvas;
    if (!canvas) {
      return;
    }

    // resize svg and canvas if needed
    this(this.selection);

    _.each(this.layers, function(layer) {
      layer(canvas);
    });
  }

  this.index = function(index) {
    if (!arguments.length) return this._index;
    this._index = index;
    // init x-axis
    this.x.domain([0, index.length-1]);
    return this;
  }

  this.layer = function(layer, id, redraw) {
    if (layer.data_length() != this.index().length) {
      throw new Error('Layer data length mismatch fig.length:' + this.index().length
          + id +'.data_length():' + layer.data_length());
    }
    if (!id) {
      id = 'layer_'+id3_id++;
    }
    var layers = this.layers;

    // wrap any non-Views
    if (!layer.view_wrapped) {
      layer = View().layer(layer);
    }
    layer.layer_name = id;

    layers.push(layer);
    // sync to plot
    layer.xview(this.x.domain());
    layer.yview(this.y.domain());
    layer.width(this.width());
    layer.height(this.height());

    layer.xview(this.x.domain());
    layer.update();

    // redraw figure? this can be expensive if adding many layers
    redraw = 'undefined' == typeof(redraw) ? true  : redraw;
    if (redraw) {
      this.merge_y();
      this.redraw();
    }
  }
}

Figure.prototype.width = function(width) {
  if (!arguments.length) {
    var width = this._width;
    // default to offsetWidth
    if (!width) {
      width = this.selection[0][0].offsetWidth;
      this.x.range([0, width]);
    }
    return width;
  }
  this._width = width;
  this.x.range([0, width]); // set right away so axes have access

  _.each(this.layers, function(layer) {
    layer.width(width);
  });

  // dispatch change of width
  this.dispatch.width(width);

  this.redraw();
  return this;
}

Figure.prototype.height = function(height) {
  if (!arguments.length) {
    var height = this._height;
    // default to offsetHeight
    if (!height) {
      height = this.selection[0][0].offsetHeight;
      this.y.range([height, 0]);
    }
    return height;
  }
  this._height = height;
  this.y.range([height, 0]); // set right away so axes have access
  // propogate height to layers
  _.each(this.layers, function(layer) {
    layer.height(height);
  });

  // dispatch change of height
  this.dispatch.height(height);

  this.redraw();
  return this;
}

Figure.prototype.padding = function(padding) {
  if (!arguments.length) return this._padding;
  if (typeof(padding) == 'number') {
    padding = {'top': padding, 'left': padding, 'right': padding, 'bottom': padding};
  }
  this._padding = _.extend(this._padding, padding);
  return this;
}

Figure.prototype.margin = function(margin) {
  if (!arguments.length) return this._margin;
  if (typeof(margin) == 'number') {
    margin = {'top': margin, 'left': margin, 'right': margin, 'bottom': margin};
  }
  this._margin = _.extend(this._margin, margin);
  return this;
}

Figure.prototype.on = function(type, listener) {
  this.dispatch.on(type, listener);
}

module.exports = callable(Figure);
// monkey patches
require('./axes.js');
require('./brush.js');
<commit_msg>change index to be DatetimeIndex<commit_after>var d3 = require('d3');
var _ = require('underscore');

var axis = require('./context.js');
var callable = require('./callable.js');
var View = require('id3/lib/view.js');
var DatetimeIndex = require('./date/dateindex.js').DatetimeIndex;

var id3_id = 0;

function Figure() {
  this.x = axis();
  this.y = axis();
  this._width = null;
  this._height = null;
  this._padding = {};
  this._margin = {};
  this._index = null;
  this.layers = [];
  this.selection = null;
  this.canvas = null;
  this.dispatch = d3.dispatch('mouseover', 'width', 'height');

  // default margin
  this.margin(0);
  // default padding 5% of domain
  this.padding(.05);

  var self = this;
  this.x.on('change.figure', function(domain) {
    self.xchange(domain);
  });

  this.__call__ = function(selection) {
    this.selection = selection;

    var margin = this.margin();
    var width = this.width();
    var height = this.height();
    selection.attr('width', width+margin.left+margin.right);
    selection.attr('height', height+margin.top+margin.bottom);
    var canvas = selection.selectAll('g.canvas').data([1]);

    canvas.enter().append('svg:g')
      .attr('class', 'canvas');
    canvas
      .attr("transform", "translate("+margin.left+", "+margin.top+")");

    this.canvas = canvas;
  }

  this.xchange = function(domain) {
    this.x.domain(domain);
    var layers = this.layers;

    _.each(this.layers, function(layer) {
      layer.xview(domain);
      layer.update();
    });

    this.merge_y();
    this.redraw();
    return this;
  }

  this.merge_y = function() {
    y_domains = _.invoke(this.layers, 'yview');
    //merged y-domains
    y_min = d3.min(y_domains, function(d) { return d[0] });
    y_max = d3.max(y_domains, function(d) { return d[1] });

    var top = this.padding().top;
    var bottom = this.padding().bottom;
    var diff = y_max - y_min;

    if (top < 1) {
      top = top * diff;
    }
    if (bottom < 1) {
      bottom = bottom * diff
    }
    y_max = y_max + top;
    y_min = y_min - bottom;

    new_y = [y_min, y_max];
    this.y.domain(new_y);

    // update the layers of the merged view
    _.invoke(this.layers, 'yview', new_y);
  }

  // attempt to wait and batch multiple redraw calls into one.
  // useful for batching figure.width(width).height(height) into
  // one redraw
  var redraw_timeout;
  this.redraw = function() {
    var self = this;
    clearTimeout(redraw_timeout);
    redraw_timeout = setTimeout(function() {self._redraw()}, 100);
  };

  this._redraw = function() {
    var canvas = this.canvas;
    if (!canvas) {
      return;
    }

    // resize svg and canvas if needed
    this(this.selection);

    _.each(this.layers, function(layer) {
      layer(canvas);
    });
  }

  this.index = function(index) {
    if (!arguments.length) return this._index;
    index = DatetimeIndex(index);
    this._index = index;
    // init x-axis
    this.x.domain([0, index.values.length-1]);
    return this;
  }

  this.layer = function(layer, id, redraw) {
    if (layer.data_length() != this.index().values.length) {
      throw new Error('Layer data length mismatch fig.length:' + this.index().values.length
          + id +'.data_length():' + layer.data_length());
    }
    if (!id) {
      id = 'layer_'+id3_id++;
    }
    var layers = this.layers;

    // wrap any non-Views
    if (!layer.view_wrapped) {
      layer = View().layer(layer);
    }
    layer.layer_name = id;

    layers.push(layer);
    // sync to plot
    layer.xview(this.x.domain());
    layer.yview(this.y.domain());
    layer.width(this.width());
    layer.height(this.height());

    layer.xview(this.x.domain());
    layer.update();

    // redraw figure? this can be expensive if adding many layers
    redraw = 'undefined' == typeof(redraw) ? true  : redraw;
    if (redraw) {
      this.merge_y();
      this.redraw();
    }
  }
}

Figure.prototype.width = function(width) {
  if (!arguments.length) {
    var width = this._width;
    // default to offsetWidth
    if (!width) {
      width = this.selection[0][0].offsetWidth;
      this.x.range([0, width]);
    }
    return width;
  }
  this._width = width;
  this.x.range([0, width]); // set right away so axes have access

  _.each(this.layers, function(layer) {
    layer.width(width);
  });

  // dispatch change of width
  this.dispatch.width(width);

  this.redraw();
  return this;
}

Figure.prototype.height = function(height) {
  if (!arguments.length) {
    var height = this._height;
    // default to offsetHeight
    if (!height) {
      height = this.selection[0][0].offsetHeight;
      this.y.range([height, 0]);
    }
    return height;
  }
  this._height = height;
  this.y.range([height, 0]); // set right away so axes have access
  // propogate height to layers
  _.each(this.layers, function(layer) {
    layer.height(height);
  });

  // dispatch change of height
  this.dispatch.height(height);

  this.redraw();
  return this;
}

Figure.prototype.padding = function(padding) {
  if (!arguments.length) return this._padding;
  if (typeof(padding) == 'number') {
    padding = {'top': padding, 'left': padding, 'right': padding, 'bottom': padding};
  }
  this._padding = _.extend(this._padding, padding);
  return this;
}

Figure.prototype.margin = function(margin) {
  if (!arguments.length) return this._margin;
  if (typeof(margin) == 'number') {
    margin = {'top': margin, 'left': margin, 'right': margin, 'bottom': margin};
  }
  this._margin = _.extend(this._margin, margin);
  return this;
}

Figure.prototype.on = function(type, listener) {
  this.dispatch.on(type, listener);
}

module.exports = callable(Figure);
// monkey patches
require('./axes.js');
require('./brush.js');
<|endoftext|>


<commit_before>var Filter = exports.Filter = function() {}

exports.sanitize = function(str) {
    var f = new Filter();
    return f.sanitize(str);
}

Filter.prototype.modify = function(str) {
    this.str = str;
}

Filter.prototype.sanitize = function(str) {
    this.str = str;
    return this;
}

Filter.prototype.ifNull = function(replace) {
    if (!this.str || this.str === '') {
        this.modify(replace);
    }
    return this.str;
}

Filter.prototype.toBoolean = function() {
    if (this.str == '1' || this.str == 'true' || this.str == 'yes') {
        this.modify(true);
    } else {
        this.modify(false);
    }
    return this.str;
}
<commit_msg>Updated toBoolean methods<commit_after>var Filter = exports.Filter = function() {}

exports.sanitize = function(str) {
    var f = new Filter();
    return f.sanitize(str);
}

Filter.prototype.modify = function(str) {
    this.str = str;
}

Filter.prototype.sanitize = function(str) {
    this.str = str;
    return this;
}

Filter.prototype.ifNull = function(replace) {
    if (!this.str || this.str === '') {
        this.modify(replace);
    }
    return this.str;
}

//Any string with length > 0 (except for '0' and 'false') are considered true,
//all other strings are false
Filter.prototype.toBoolean = function() {
    if (!this.str || this.str == '0' || this.str == 'false' || this.str == '') {
        this.modify(false);
    } else {
        this.modify(true);
    }
    return this.str;
}

//String must be equal to '1' or 'true' to be considered true, all other strings
//are false
Filter.prototype.toBooleanStrict = function() {
    if (this.str == '1' || this.str == 'true') {
        this.modify(true);
    } else {
        this.modify(false);
    }
    return this.str;
}
<|endoftext|>


<commit_before>$(document).ready(function() {
	if ($('#message-name').length > 0) enhanceSlides();
});
function enhanceSlides() {
	$('#message_name').focus().prev().css("color","#FFF");

    $(".next-link").click(function (e) {
      e.preventDefault();
      var currentSlide = extractSlideNum($('.quote-slide.active').attr('class'));
      var nextSlide = parseInt($(this).attr("data-slide"),10);
      findSlideWithNumber(currentSlide).fadeOut(function() {
        //$(".quote-slide").hide();
        $('.quote-slide.active').removeClass('active');
        findSlideWithNumber(nextSlide).fadeIn(function() {
          $(".slide" + nextSlide).addClass('active');
          currentSlide = nextSlide;
        });
      });
    });

    $('label').next().focus(function(e) {
      $(this).prev().css("color","#FFFFFF");
    });
    $('label').next().blur(function(e) {
      $(this).prev().css("color","#004264");
    });

    $(".submit-link").click(function (e) {
  		e.preventDefault();
  		if (validate_contact()==1) $("#contact-form").submit();
  	});

  	$(".quote-submit-link").click(function (e) {
      e.preventDefault();
      if (validate_quote() == 1) $("#quote-form").submit();
    });

    function findSlideWithNumber(num) {
   		return $('.slide'+num);
  	}

  	function extractSlideNum(slideClasses) {
    	var slidePos = slideClasses.search(/ slide/gi) + 6;
    	return parseInt(slideClasses.slice(slidePos,slidePos+1));
  	}

  	function validateEmail(email) {
		var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		return re.test(email);
	}

	function validate_contact() {
		name = $("#contact-form #message_name").val();
		email = $("#contact-form #message_email").val();
		var result = 1;
		if (name == "") {
			$("#contact-form .name .field-comment").fadeIn(500);
			$("#contact-form .name .field-comment").effect("shake", { times:3 }, 150);
			result = 5;
		} else {
			$("#contact-form .name .field-comment").fadeOut(500);
		}
		if (!validateEmail(email)) {
			$("#contact-form .email .field-comment").fadeIn(500);
			$("#contact-form .email .field-comment").effect("shake", { times:3 }, 150);
			result = 5;
		} else {
			$("#contact-form .email .field-comment").fadeOut(500);
		}
		return result;
	}

	function validate_quote() {
		name = $("#quote-form #message_name").val();
		email = $("#quote-form #message_email").val();
		var result = 1;
		if (name == "") {
			$("#quote-form .name .field-comment").fadeIn(500);
			$("#quote-form .name .field-comment").effect("shake", { times:3 }, 150);
			result = 5;
		} else {
			$("#quote-form .name .field-comment").fadeOut(500);
		}
		if (!validateEmail(email)) {
			$("#quote-form .email .field-comment").fadeIn(500);
			$("#quote-form .email .field-comment").effect("shake", { times:3 }, 150);
			result = 5;
		} else {
			$("#quote-form .email .field-comment").fadeOut(500);
		}
		if (result == 5) {
			$(".quote-slide").hide();
			$(".slide1").show();
		}
		return result;
	}
}<commit_msg>Fixed form scripts not firing<commit_after>$(document).ready(function() {
	if ($('.bluu').length > 0) enhanceSlides();
});
function enhanceSlides() {
	$('#message_name').focus().prev().css("color","#FFF");

    $(".next-link").click(function (e) {
      e.preventDefault();
      var currentSlide = extractSlideNum($('.quote-slide.active').attr('class'));
      var nextSlide = parseInt($(this).attr("data-slide"),10);
      findSlideWithNumber(currentSlide).fadeOut(function() {
        //$(".quote-slide").hide();
        $('.quote-slide.active').removeClass('active');
        findSlideWithNumber(nextSlide).fadeIn(function() {
          $(".slide" + nextSlide).addClass('active');
          currentSlide = nextSlide;
        });
      });
    });

    $('label').next().focus(function(e) {
      $(this).prev().css("color","#FFFFFF");
    });
    $('label').next().blur(function(e) {
      $(this).prev().css("color","#004264");
    });

    $(".submit-link").click(function (e) {
  		e.preventDefault();
  		if (validate_contact()==1) $("#contact-form").submit();
  	});

  	$(".quote-submit-link").click(function (e) {
      e.preventDefault();
      if (validate_quote() == 1) $("#quote-form").submit();
    });

    function findSlideWithNumber(num) {
   		return $('.slide'+num);
  	}

  	function extractSlideNum(slideClasses) {
    	var slidePos = slideClasses.search(/ slide/gi) + 6;
    	return parseInt(slideClasses.slice(slidePos,slidePos+1));
  	}

  	function validateEmail(email) {
		var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		return re.test(email);
	}

	function validate_contact() {
		name = $("#contact-form #message_name").val();
		email = $("#contact-form #message_email").val();
		var result = 1;
		if (name == "") {
			$("#contact-form .name .field-comment").fadeIn(500);
			$("#contact-form .name .field-comment").effect("shake", { times:3 }, 150);
			result = 5;
		} else {
			$("#contact-form .name .field-comment").fadeOut(500);
		}
		if (!validateEmail(email)) {
			$("#contact-form .email .field-comment").fadeIn(500);
			$("#contact-form .email .field-comment").effect("shake", { times:3 }, 150);
			result = 5;
		} else {
			$("#contact-form .email .field-comment").fadeOut(500);
		}
		return result;
	}

	function validate_quote() {
		name = $("#quote-form #message_name").val();
		email = $("#quote-form #message_email").val();
		var result = 1;
		if (name == "") {
			$("#quote-form .name .field-comment").fadeIn(500);
			$("#quote-form .name .field-comment").effect("shake", { times:3 }, 150);
			result = 5;
		} else {
			$("#quote-form .name .field-comment").fadeOut(500);
		}
		if (!validateEmail(email)) {
			$("#quote-form .email .field-comment").fadeIn(500);
			$("#quote-form .email .field-comment").effect("shake", { times:3 }, 150);
			result = 5;
		} else {
			$("#quote-form .email .field-comment").fadeOut(500);
		}
		if (result == 5) {
			$(".quote-slide").hide();
			$(".slide1").show();
		}
		return result;
	}
}<|endoftext|>


<commit_before>var glob = require('glob');
var spawn = require('child_process').spawn;
var fs = require('fs');
var path = require('path');
var readline = require('readline');

module.exports = FixMe;

function FixMe() { }

FixMe.prototype.runEngine = function(){
  var analysisFiles = [],
      config = {
        include_paths: ["./"],
        strings: ["FIXME", "TODO", "HACK", "XXX", "BUG"]
      },
      self = this;

  if (fs.existsSync('/config.json')) {
    var userConfig = JSON.parse(fs.readFileSync('/config.json'));

    config.include_paths = userConfig.include_paths;

    if (userConfig.config) {
      for (var prop in userConfig.config) {
        config[prop] = userConfig.config[prop];
      }
    }
  }

  self.find(config.include_paths, config.strings);
}

FixMe.prototype.find = function(files, strings){
  var fixmeStrings = '(' + strings.join('|') + ')';
  var grep = spawn('grep', ['-nHwoEr', fixmeStrings].concat(files));
  var output = "";
  var self = this;

  readline.createInterface({ input: grep.stdout }).on('line', function(line) {
    var cols = line.split(":");
    var fileName = cols[0].replace(/^\/code\//, '');
    var lineNum = parseInt(cols[1]);
    var matchedString = cols[2];

    if (matchedString !== undefined){
      var issue = JSON.stringify({
        "type": "issue",
        "check_name": matchedString,
        "description": matchedString + " found",
        "categories": ["Bug Risk"],
        "location":{
          "path": fileName,
          "lines": {
            "begin": lineNum,
            "end": lineNum
          }
        }
      });

      console.log(issue+'\0');
    }
  });
}
<commit_msg>Consistency fixes<commit_after>var fs = require('fs');
var glob = require('glob');
var path = require('path');
var readline = require('readline');
var spawn = require('child_process').spawn;

function FixMe() {}

FixMe.prototype.runEngine = function() {
  var analysisFiles = [];
  var config = {
    include_paths: ['./'],
    strings: ['FIXME', 'TODO', 'HACK', 'XXX', 'BUG']
  };

  if (fs.existsSync('/config.json')) {
    var userConfig = JSON.parse(fs.readFileSync('/config.json'));

    config.include_paths = userConfig.include_paths;

    if (userConfig.config) {
      for (var prop in userConfig.config) {
        config[prop] = userConfig.config[prop];
      }
    }
  }

  this.find(config.include_paths, config.strings);
}

FixMe.prototype.find = function(files, strings) {
  var fixmeStrings = '(' + strings.join('|') + ')';
  var grep = spawn('grep', ['-nHwoEr', fixmeStrings].concat(files));
  var output = '';

  readline.createInterface({ input: grep.stdout }).on('line', function(line) {
    var cols = line.split(':');
    var fileName = cols[0].replace(/^\/code\//, '');
    var lineNum = parseInt(cols[1]);
    var matchedString = cols[2];

    if (matchedString !== undefined){
      var issue = JSON.stringify({
        'type': 'issue',
        'check_name': matchedString,
        'description': matchedString + ' found',
        'categories': ['Bug Risk'],
        'location':{
          'path': fileName,
          'lines': {
            'begin': lineNum,
            'end': lineNum
          }
        }
      });

      console.log(issue + '\0');
    }
  });
}

module.exports = FixMe;
<|endoftext|>


<commit_before>var _ = require('underscore'),
    cp = require('child_process'),
    EventEmitter = require('events').EventEmitter,
    util = require('util');

var numCPUs = require('os').cpus().length,
    queue = [],
    activeTasks = 0,
    totalWorkers = 0,
    isBackground;

exports = module.exports = function(module, options) {
  EventEmitter.call(this);

  this.module = module;
  this.options = _.extend({workers: numCPUs, keepAlive: 500}, options);
  this.workers = [];
  this.totalWorkers = 0;
  this.cullTimeout = undefined;
};
util.inherits(exports, EventEmitter);

exports.prototype.sendAll = function(message) {
  _.each(this.workers, function(worker) {
    worker.process.send(message);
  });
};
exports.prototype.send = function(message, callback) {
  var self = this;

  callback = callback || function() {};

  function fork() {
    totalWorkers++;
    self.totalWorkers++;

    var execArgv = process.execArgv;
    if (_.contains(execArgv, '--prof')) {
      execArgv = _.clone(execArgv);

      var logFile = _.find(execArgv, function(arg) { return /^--logfile=.*/.test(arg); }) || '--logfile=v8.log',
          location = execArgv.indexOf(logFile);

      if (self.options.logId) {
        logFile = logFile + '.' + self.options.logId + '.' + self.totalWorkers;
      } else {
        logFile = logFile + '.' + totalWorkers;
      }
      if (location >= 0) {
        execArgv.splice(location, 1, logFile);
      } else {
        execArgv.push(logFile);
      }
    }

    // Node 0.11 supports passing the execArgv option to fork but we don't want to break compatibility
    // so we're going to emulate the fork logic in the mean time.
    worker = {
      callback: false,
      process: cp.spawn(
          process.execPath,
          execArgv.concat([__dirname + '/worker'], execArgv),
          {stdio: [0, 1, 2, 'ipc']})
    };
    worker.process.send(self.module);
    function processMessage(msg) {
      activeTasks--;

      var callback = worker.callback;
      worker.callback = undefined;

      // Check for process culling
      worker.cullTimeout = setTimeout(function() {
        // Kill
        worker.process.kill();
        self.workers = _.without(self.workers, worker);
      }, self.options.keepAlive);

      if (queue.length) {
        var queued = queue.shift();
        queued.pool.send(queued.message, queued.callback);
      }

      // Dispatch
      process.nextTick(function() {
        var err;
        if (msg.err) {
          err = new Error(msg.err);
          if (msg.stack) {
            err.stack = msg.stack;
          }
        }

        // Kill the worker as we don't know what state it might be in
        if (msg.fatal) {
          worker.process.removeAllListeners('exit');
          worker.process.kill();
          self.workers = _.without(self.workers, worker);
        }

        if (!callback) {
          self.emit('error', err || new Error('Out of band data: ' + msg.data));
        } else {
          callback(err, msg.data);
        }
      });
    }

    worker.process.on('exit', function (code, signal) {
      if (code === null) {
        //process wasn't killed properly
        var error = new Error('Worker exited unexpectedly');
        processMessage({
          fatal: true,
          err: error.message,
          stack: error.stack
        });
      }
    });
    worker.process.on('message', processMessage);
    self.workers.push(worker);
  }

  // If we are in interactive mode, i.e. watch, leave at least one core free so the machine doesn't
  // lag and annoy the developer.
  // Creating a minimum number of CPUs to prevent starvation on machines with less cores
  var exceedsGlobal = (activeTasks + (isBackground ? 1 : 0) >= Math.max(numCPUs, 2)),
      worker = !exceedsGlobal && _.find(this.workers, function(worker) { return !worker.callback; });
  if (!worker) {
    if (!exceedsGlobal && this.workers.length < this.options.workers) {
      // Fork!
      fork();
    } else {
      // Queue!
      queue.push({pool: self, message: message, callback: callback});
      return;
    }
  }

  activeTasks++;

  clearTimeout(worker.cullTimeout);
  worker.callback = callback;
  worker.process.send(message);
};

/**
 * Set to true to attempt to leave at least one core available to prevent starvation.
 *
 * This is useful for watch mode when the developer might be doing other things while the build is
 * running.
 */
exports.isBackground = function(background) {
  isBackground = background;
};
<commit_msg>allow capturing child stdout<commit_after>var _ = require('underscore'),
    cp = require('child_process'),
    EventEmitter = require('events').EventEmitter,
    util = require('util');

var numCPUs = require('os').cpus().length,
    queue = [],
    activeTasks = 0,
    totalWorkers = 0,
    isBackground;

exports = module.exports = function(module, options) {
  EventEmitter.call(this);

  this.module = module;
  this.options = _.extend({workers: numCPUs, keepAlive: 500}, options);
  this.workers = [];
  this.totalWorkers = 0;
  this.cullTimeout = undefined;
};
util.inherits(exports, EventEmitter);

exports.prototype.sendAll = function(message) {
  _.each(this.workers, function(worker) {
    worker.process.send(message);
  });
};
exports.prototype.send = function(message, callback) {
  var self = this;

  callback = callback || function() {};

  function fork() {
    totalWorkers++;
    self.totalWorkers++;

    var execArgv = process.execArgv;
    if (_.contains(execArgv, '--prof')) {
      execArgv = _.clone(execArgv);

      var logFile = _.find(execArgv, function(arg) { return /^--logfile=.*/.test(arg); }) || '--logfile=v8.log',
          location = execArgv.indexOf(logFile);

      if (self.options.logId) {
        logFile = logFile + '.' + self.options.logId + '.' + self.totalWorkers;
      } else {
        logFile = logFile + '.' + totalWorkers;
      }
      if (location >= 0) {
        execArgv.splice(location, 1, logFile);
      } else {
        execArgv.push(logFile);
      }
    }

    // Node 0.11 supports passing the execArgv option to fork but we don't want to break compatibility
    // so we're going to emulate the fork logic in the mean time.
    worker = {
      callback: false,
      process: cp.spawn(
          process.execPath,
          execArgv.concat([__dirname + '/worker'], execArgv),
          {stdio: ['pipe', 'pipe', 'pipe', 'ipc']})
    };
    if(self.options.stdout){
      worker.process.stdout.on('data',self.options.stdout);
    }
    worker.process.send(self.module);
    function processMessage(msg) {
      activeTasks--;

      var callback = worker.callback;
      worker.callback = undefined;

      // Check for process culling
      worker.cullTimeout = setTimeout(function() {
        // Kill
        worker.process.kill();
        self.workers = _.without(self.workers, worker);
      }, self.options.keepAlive);

      if (queue.length) {
        var queued = queue.shift();
        queued.pool.send(queued.message, queued.callback);
      }

      // Dispatch
      process.nextTick(function() {
        var err;
        if (msg.err) {
          err = new Error(msg.err);
          if (msg.stack) {
            err.stack = msg.stack;
          }
        }

        // Kill the worker as we don't know what state it might be in
        if (msg.fatal) {
          worker.process.removeAllListeners('exit');
          worker.process.kill();
          self.workers = _.without(self.workers, worker);
        }

        if (!callback) {
          self.emit('error', err || new Error('Out of band data: ' + msg.data));
        } else {
          callback(err, msg.data);
        }
      });
    }

    worker.process.on('exit', function (code, signal) {
      if (code === null) {
        //process wasn't killed properly
        var error = new Error('Worker exited unexpectedly');
        processMessage({
          fatal: true,
          err: error.message,
          stack: error.stack
        });
      }
    });
    worker.process.on('message', processMessage);
    self.workers.push(worker);
  }

  // If we are in interactive mode, i.e. watch, leave at least one core free so the machine doesn't
  // lag and annoy the developer.
  // Creating a minimum number of CPUs to prevent starvation on machines with less cores
  var exceedsGlobal = (activeTasks + (isBackground ? 1 : 0) >= Math.max(numCPUs, 2)),
      worker = !exceedsGlobal && _.find(this.workers, function(worker) { return !worker.callback; });
  if (!worker) {
    if (!exceedsGlobal && this.workers.length < this.options.workers) {
      // Fork!
      fork();
    } else {
      // Queue!
      queue.push({pool: self, message: message, callback: callback});
      return;
    }
  }

  activeTasks++;

  clearTimeout(worker.cullTimeout);
  worker.callback = callback;
  worker.process.send(message);
};

/**
 * Set to true to attempt to leave at least one core available to prevent starvation.
 *
 * This is useful for watch mode when the developer might be doing other things while the build is
 * running.
 */
exports.isBackground = function(background) {
  isBackground = background;
};
<|endoftext|>


<commit_before>var repl = require('repl');
var vm = require('vm')
var inherits = require('util').inherits;
var Q = require('q');
var Fiber = require('fibers');

function ChoirREPLServer(prompt, source, eval_, useGlobal, ignoreUndefined) {
  repl.REPLServer.call(this, prompt, source, eval_, useGlobal, ignoreUndefined);

  this.magics = [];
  this.eval = fiber_eval;
  this.choir_eval = choir_eval;
  this.inner_eval = inner_eval;
}

inherits(ChoirREPLServer, repl.REPLServer);
exports.ChoirREPLServer = ChoirREPLServer;

ChoirREPLServer.prototype.install_magic = function(magic) {
  this.magics.push(magic);
}

ChoirREPLServer.prototype.run = function(code) {
    /*
     * Run code as if it was placed in REPL input
     */
    // wrap code to mimic repl wrapped
    code = '('+code+'\n)';
    // skip choir_eval since we don't need callback handling
    return this.inner_eval(code, this.context);
}

function inner_eval(code, context, file) {
  // remove parens and newline
  var bare_code = code.substr(1, code.length-3);
  // attempt to get a result from each magic
  var result;
  for (var i = 0; i < this.magics.length; i++) {
    var magic = this.magics[i];
    var result = magic.eval(bare_code, context);
    if (typeof(result) !== 'undefined') {
      return result;
    }
  }

  if (context === global) {
    throw "We do not support global repl";
  }
  result = vm.runInContext(code, context, file);

  return result;
}

var fiber_eval = function(code, context, file, cb) {
  var self = this;
  Fiber(function() {
    self.choir_eval(code, context, file, cb);
  }).run();
}

var choir_eval = function(code, context, file, cb) {
  var err, result;
  try {
    result = inner_eval.call(this, code, context, file);
  } catch (e) {
    err = e;
  }
  if (err && process.domain && !isSyntaxError(err)) {
    process.domain.emit('error', err);
    process.domain.exit();
  }
  else {
    if (Q.isPromise(result) && result.pause_repl) {
      this.rli.pause();
      result.then(function(data) {
        result.pause_repl = false; // only pause repl once
        cb(err, data);
      }).catch(function(error) {
        cb(error, data)
      });
    }
    else
    {
      cb(err, result);
    }
  }

  // save me obi-wan
  var self = this;
  setTimeout(function() {self.rli.resume()}, 5000);
}

exports.start = function(prompt, source, eval_, useGlobal, ignoreUndefined) {
  var repl = new ChoirREPLServer(prompt, source, eval_, useGlobal, ignoreUndefined);
  if (!exports.repl) exports.repl = repl;
  return repl;
};
<commit_msg>base repl no longer wraps input with parens<commit_after>var repl = require('repl');
var vm = require('vm')
var inherits = require('util').inherits;
var Q = require('q');
var Fiber = require('fibers');

function ChoirREPLServer(prompt, source, eval_, useGlobal, ignoreUndefined) {
  repl.REPLServer.call(this, prompt, source, eval_, useGlobal, ignoreUndefined);

  this.magics = [];
  this.eval = fiber_eval;
  this.choir_eval = choir_eval;
  this.inner_eval = inner_eval;
}

inherits(ChoirREPLServer, repl.REPLServer);
exports.ChoirREPLServer = ChoirREPLServer;

ChoirREPLServer.prototype.install_magic = function(magic) {
  this.magics.push(magic);
}

ChoirREPLServer.prototype.run = function(code) {
    /*
     * Run code as if it was placed in REPL input
     */
    // add new line to mimic repl.
    code = code+'\n';
    // skip choir_eval since we don't need callback handling
    return this.inner_eval(code, this.context);
}

function inner_eval(code, context, file) {
  // remove ending new line
  var bare_code = code.substr(0, code.length-1);
  // attempt to get a result from each magic
  var result;
  for (var i = 0; i < this.magics.length; i++) {
    var magic = this.magics[i];
    var result = magic.eval(bare_code, context);
    if (typeof(result) !== 'undefined') {
      return result;
    }
  }

  if (context === global) {
    throw "We do not support global repl";
  }
  result = vm.runInContext(code, context, file);

  return result;
}

var fiber_eval = function(code, context, file, cb) {
  var self = this;
  Fiber(function() {
    self.choir_eval(code, context, file, cb);
  }).run();
}

var choir_eval = function(code, context, file, cb) {
  var err, result;
  try {
    result = inner_eval.call(this, code, context, file);
  } catch (e) {
    err = e;
  }
  if (err && process.domain && !isSyntaxError(err)) {
    process.domain.emit('error', err);
    process.domain.exit();
  }
  else {
    if (Q.isPromise(result) && result.pause_repl) {
      this.rli.pause();
      result.then(function(data) {
        result.pause_repl = false; // only pause repl once
        cb(err, data);
      }).catch(function(error) {
        cb(error, data)
      });
    }
    else
    {
      cb(err, result);
    }
  }

  // save me obi-wan
  var self = this;
  setTimeout(function() {self.rli.resume()}, 5000);
}

exports.start = function(prompt, source, eval_, useGlobal, ignoreUndefined) {
  var repl = new ChoirREPLServer(prompt, source, eval_, useGlobal, ignoreUndefined);
  if (!exports.repl) exports.repl = repl;
  return repl;
};
<|endoftext|>