<commit_before>/*
 * Copyright (c) 2016 Kagilum SAS.
 *
 * This file is part of iceScrum.
 *
 * iceScrum is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License.
 *
 * iceScrum is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with iceScrum.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *
 * Vincent Barrier (vbarrier@kagilum.com)
 * Nicolas Noullet (nnoullet@kagilum.com)
 *
 */

extensibleController('planningCtrl', ['$scope', '$state', 'StoryService', 'SprintStatesByName', 'ReleaseStatesByName', 'project', function($scope, $state, StoryService, SprintStatesByName, ReleaseStatesByName, project) {
    $scope.isSelected = function(selectable) {
        if ($state.params.storyId) {
            return $state.params.storyId == selectable.id;
        } else {
            return false;
        }
    };
    $scope.hasSelected = function() {
        return $state.params.storyId != undefined;
    };
    $scope.hasPreviousVisibleSprints = function() {
        return $scope.visibleSprintOffset > 0;
    };
    $scope.hasNextVisibleSprints = function() {
        return $scope.visibleSprintMax + $scope.visibleSprintOffset + 1 <= $scope.sprints.length;
    };
    $scope.visibleSprintsPrevious = function() {
        $scope.visibleSprintOffset--;
        $scope.computeVisibleSprints();
    };
    $scope.visibleSprintsNext = function() {
        $scope.visibleSprintOffset++;
        $scope.computeVisibleSprints();
    };
    $scope.computeVisibleSprints = function() {
        $scope.visibleSprints = $scope.sprints.slice($scope.visibleSprintOffset, $scope.visibleSprintMax + $scope.visibleSprintOffset);
    };
    var getNewStoryState = function(storyId, currentStateName, keepTab) {
        var newStateName;
        var newStateParams = {storyId: storyId};
        if (_.startsWith(currentStateName, 'planning.release.sprint.multiple')) {
            newStateName = 'planning.release.sprint.multiple.story.details';
        } else if (_.startsWith(currentStateName, 'planning.release.sprint.withId')) {
            newStateName = 'planning.release.sprint.withId.story.details';
        } else if (currentStateName === 'planning.release.sprint') {
            // Special case when there is no sprintId in the state params so we must retrieve it manually
            newStateName = 'planning.release.sprint.withId.story.details';
            newStateParams.sprintId = $scope.selectedItems[0].id;
        } else {
            newStateName = 'planning.release.story.details';
            if (currentStateName === 'planning' || currentStateName == 'planning.new') { // Special case when there is no releasedID in the state params so we must retrieve it manually
                newStateParams.releaseId = $scope.selectedItems[0].id;
            }
        }
        return {name: newStateName + ($state.params.storyTabId && keepTab ? '.tab' : ''), params: newStateParams}
    };
    $scope.openReleaseUrl = function(release) {
        var stateName = 'planning.release';
        if ($state.current.name != 'planning.release.details') {
            stateName += '.details';
        }
        return $state.href(stateName, {releaseId: release ? release.id : ''});
    };
    $scope.openStoryUrl = function(storyId) {
        var newStoryState = getNewStoryState(storyId, $state.current.name);
        return $state.href(newStoryState.name, newStoryState.params);
    };
    $scope.openSprintUrl = function(sprint) {
        var stateName = 'planning.release.sprint.withId';
        if ($state.current.name != 'planning.release.sprint.withId.details') {
            stateName += '.details';
        }
        return $state.href(stateName, {sprintId: sprint.id, releaseId: sprint.parentRelease.id});
    };
    $scope.openMultipleSprintDetailsUrl = function() {
        var stateName = 'planning.release.sprint.multiple';
        if ($state.current.name != 'planning.release.sprint.multiple.details') {
            stateName += '.details';
        }
        return $state.href(stateName);
    };
    $scope.isMultipleSprint = function() {
        return _.startsWith($state.current.name, 'planning.release.sprint.multiple');
    };
    $scope.getVisibleSprintMax = function() {
        switch ($scope.application.mediaBreakpoint) {
            case 'xl':
                return 3;
            case 'lg':
                return 2;
            default:
                return 1;
        }
    };
    // Init
    $scope.viewName = 'planning';
    $scope.visibleSprintMax = $scope.getVisibleSprintMax();
    $scope.visibleSprintOffset = 0;
    $scope.visibleSprints = [];
    $scope.project = project;
    $scope.releases = project.releases;
    $scope.sprints = [];
    $scope.timelineSelected = function(selectedItems) { // Timeline -> URL
        if (selectedItems.length == 0) {
            $state.go('planning');
        } else {
            var stateName, stateParams;
            if (selectedItems.length == 1 && selectedItems[0].class == 'Release') {
                stateName = 'planning.release';
                stateParams = {releaseId: selectedItems[0].id};
            } else if (selectedItems.length == 1 && selectedItems[0].class == 'Sprint') {
                var sprint = selectedItems[0];
                stateName = 'planning.release.sprint.withId';
                stateParams = {releaseId: sprint.parentRelease.id, sprintId: sprint.id};
            } else {
                stateName = 'planning.release.sprint.multiple';
                stateParams = {releaseId: selectedItems[0].parentRelease.id, sprintListId: _.map(selectedItems, 'id')};
            }
            var currentStateName = $state.current.name;
            var sameStateName = _.endsWith(currentStateName, '.details') && currentStateName == stateName + '.details' || currentStateName == stateName;
            var sameStateParams = $state.params.sprintId == stateParams.sprintId && $state.params.releaseId == stateParams.releaseId;
            var sameState = sameStateName && sameStateParams;
            if (_.endsWith(currentStateName, '.details') && !sameState || !_.endsWith(currentStateName, '.details') && sameState) {
                stateName += '.details';
            }
            $state.go(stateName, stateParams);
        }
    };
    $scope.$watch("release.sprints_count", function(newValues) {
        var releaseId = $state.params.releaseId;
        var release = _.find($scope.releases, {id: releaseId});
        if ($state.params.sprintListId || $state.params.sprintId) {
            var missing = false;
            var ids = _.map(release.sprints, function(sprint) {
                return sprint.id.toString()
            });
            if ($state.params.sprintListId) {
                var selecteds = $state.params.sprintListId.split(",");
                missing = _.every(selecteds, function(selected) {
                    return !_.includes(ids, selected);
                });
            } else {
                missing = !_.includes(ids, $state.params.sprintId.toString());
            }
            if (missing) {
                $scope.timelineSelected([]);
            }
        }
        $scope.computeVisibleSprints();
    });
    $scope.$watchGroup([function() { return $state.$current.self.name; }, function() { return $state.params.releaseId; }, function() { return $state.params.sprintId; }, function() { return $state.params.sprintListId; }], function(newValues) {
        var stateName = newValues[0];
        var releaseId = newValues[1];
        var sprintId = newValues[2];
        var sprintListId = newValues[3];
        var release = _.find($scope.releases, {id: releaseId});
        $scope.visibleSprintOffset = 0;
        if (release && stateName.indexOf('.sprint') != -1 && stateName.indexOf('.new') == -1) {
            if (sprintId) {
                $scope.sprints = [_.find(release.sprints, {id: sprintId})];
            } else if (sprintListId) {
                var ids = _.map(sprintListId.split(','), function(id) {
                    return parseInt(id);
                });
                $scope.sprints = _.filter(release.sprints, function(sprint) {
                    return _.includes(ids, sprint.id);
                });
            } else {
                var sprint = _.find(release.sprints, function(sprint) {
                    return sprint.state == SprintStatesByName.TODO || sprint.state == SprintStatesByName.IN_PROGRESS;
                });
                if (!sprint) {
                    sprint = _.last(release.sprints);
                }
                $scope.sprints = [sprint];
            }
            $scope.selectedItems = $scope.sprints; // URL -> Timeline
        } else {
            if (!release) {
                release = _.find($scope.releases, function(release) {
                    return release.state == ReleaseStatesByName.TODO || release.state == ReleaseStatesByName.IN_PROGRESS;
                });
                if (!release) {
                    release = _.last($scope.releases);
                }
            }
            if (release) {
                if (release.sprints == null) {
                    release.sprints = [];
                }
                $scope.sprints = release.sprints;
                $scope.selectedItems = [release]; // URL -> Timeline
                var firstSprintToShowIndex = _.findIndex($scope.sprints, function(sprint) {
                    return sprint.state == SprintStatesByName.TODO || sprint.state == SprintStatesByName.IN_PROGRESS;
                });
                if (firstSprintToShowIndex == -1) {
                    firstSprintToShowIndex = $scope.sprints.length > $scope.visibleSprintMax ? $scope.sprints.length - $scope.visibleSprintMax - 1 : 0;
                }
                $scope.visibleSprintOffset = firstSprintToShowIndex;
            }
        }
        $scope.release = release;
        $scope.computeVisibleSprints();
    });
    $scope.$watch('application.mediaBreakpoint', function() {
        var oldVisible = $scope.visibleSprintMax;
        $scope.visibleSprintMax = $scope.getVisibleSprintMax();
        if (oldVisible !== $scope.visibleSprintMax) {
            $state.reload();
        }
    });
    $scope.selectableOptions = {
        notSelectableSelector: '.action, button, a',
        allowMultiple: false,
        selectionUpdated: function(selectedIds) {
            var currentStateName = $state.current.name;
            var storyIndexInStateName = currentStateName.indexOf('story');
            if (selectedIds.length == 0 && storyIndexInStateName != -1) {
                $state.go(currentStateName.slice(0, storyIndexInStateName - 1));
            } else {
                var newStoryState = getNewStoryState(selectedIds[0], currentStateName, true);
                $state.go(newStoryState.name, newStoryState.params);
            }
        }
    };
    $scope.storyListGetters = []; // Mandatory to share code between two separate substates
    $scope.findPreviousOrNextStory = StoryService.findPreviousOrNextStory($scope.storyListGetters);
}]);
<commit_msg>Always display details on click on timeline<commit_after>/*
 * Copyright (c) 2016 Kagilum SAS.
 *
 * This file is part of iceScrum.
 *
 * iceScrum is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License.
 *
 * iceScrum is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with iceScrum.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *
 * Vincent Barrier (vbarrier@kagilum.com)
 * Nicolas Noullet (nnoullet@kagilum.com)
 *
 */

extensibleController('planningCtrl', ['$scope', '$state', 'StoryService', 'SprintStatesByName', 'ReleaseStatesByName', 'project', function($scope, $state, StoryService, SprintStatesByName, ReleaseStatesByName, project) {
    $scope.isSelected = function(selectable) {
        if ($state.params.storyId) {
            return $state.params.storyId == selectable.id;
        } else {
            return false;
        }
    };
    $scope.hasSelected = function() {
        return $state.params.storyId != undefined;
    };
    $scope.hasPreviousVisibleSprints = function() {
        return $scope.visibleSprintOffset > 0;
    };
    $scope.hasNextVisibleSprints = function() {
        return $scope.visibleSprintMax + $scope.visibleSprintOffset + 1 <= $scope.sprints.length;
    };
    $scope.visibleSprintsPrevious = function() {
        $scope.visibleSprintOffset--;
        $scope.computeVisibleSprints();
    };
    $scope.visibleSprintsNext = function() {
        $scope.visibleSprintOffset++;
        $scope.computeVisibleSprints();
    };
    $scope.computeVisibleSprints = function() {
        $scope.visibleSprints = $scope.sprints.slice($scope.visibleSprintOffset, $scope.visibleSprintMax + $scope.visibleSprintOffset);
    };
    var getNewStoryState = function(storyId, currentStateName, keepTab) {
        var newStateName;
        var newStateParams = {storyId: storyId};
        if (_.startsWith(currentStateName, 'planning.release.sprint.multiple')) {
            newStateName = 'planning.release.sprint.multiple.story.details';
        } else if (_.startsWith(currentStateName, 'planning.release.sprint.withId')) {
            newStateName = 'planning.release.sprint.withId.story.details';
        } else if (currentStateName === 'planning.release.sprint') {
            // Special case when there is no sprintId in the state params so we must retrieve it manually
            newStateName = 'planning.release.sprint.withId.story.details';
            newStateParams.sprintId = $scope.selectedItems[0].id;
        } else {
            newStateName = 'planning.release.story.details';
            if (currentStateName === 'planning' || currentStateName == 'planning.new') { // Special case when there is no releasedID in the state params so we must retrieve it manually
                newStateParams.releaseId = $scope.selectedItems[0].id;
            }
        }
        return {name: newStateName + ($state.params.storyTabId && keepTab ? '.tab' : ''), params: newStateParams}
    };
    $scope.openReleaseUrl = function(release) {
        var stateName = 'planning.release';
        if ($state.current.name != 'planning.release.details') {
            stateName += '.details';
        }
        return $state.href(stateName, {releaseId: release ? release.id : ''});
    };
    $scope.openStoryUrl = function(storyId) {
        var newStoryState = getNewStoryState(storyId, $state.current.name);
        return $state.href(newStoryState.name, newStoryState.params);
    };
    $scope.openSprintUrl = function(sprint) {
        var stateName = 'planning.release.sprint.withId';
        if ($state.current.name != 'planning.release.sprint.withId.details') {
            stateName += '.details';
        }
        return $state.href(stateName, {sprintId: sprint.id, releaseId: sprint.parentRelease.id});
    };
    $scope.openMultipleSprintDetailsUrl = function() {
        var stateName = 'planning.release.sprint.multiple';
        if ($state.current.name != 'planning.release.sprint.multiple.details') {
            stateName += '.details';
        }
        return $state.href(stateName);
    };
    $scope.isMultipleSprint = function() {
        return _.startsWith($state.current.name, 'planning.release.sprint.multiple');
    };
    $scope.getVisibleSprintMax = function() {
        switch ($scope.application.mediaBreakpoint) {
            case 'xl':
                return 3;
            case 'lg':
                return 2;
            default:
                return 1;
        }
    };
    // Init
    $scope.viewName = 'planning';
    $scope.visibleSprintMax = $scope.getVisibleSprintMax();
    $scope.visibleSprintOffset = 0;
    $scope.visibleSprints = [];
    $scope.project = project;
    $scope.releases = project.releases;
    $scope.sprints = [];
    $scope.timelineSelected = function(selectedItems) { // Timeline -> URL
        if (selectedItems.length == 0) {
            $state.go('planning');
        } else {
            var stateName, stateParams;
            if (selectedItems.length == 1 && selectedItems[0].class == 'Release') {
                stateName = 'planning.release';
                stateParams = {releaseId: selectedItems[0].id};
            } else if (selectedItems.length == 1 && selectedItems[0].class == 'Sprint') {
                var sprint = selectedItems[0];
                stateName = 'planning.release.sprint.withId';
                stateParams = {releaseId: sprint.parentRelease.id, sprintId: sprint.id};
            } else {
                stateName = 'planning.release.sprint.multiple';
                stateParams = {releaseId: selectedItems[0].parentRelease.id, sprintListId: _.map(selectedItems, 'id')};
            }
            stateName += '.details';
            $state.go(stateName, stateParams);
        }
    };
    $scope.$watch("release.sprints_count", function(newValues) {
        var releaseId = $state.params.releaseId;
        var release = _.find($scope.releases, {id: releaseId});
        if ($state.params.sprintListId || $state.params.sprintId) {
            var missing = false;
            var ids = _.map(release.sprints, function(sprint) {
                return sprint.id.toString()
            });
            if ($state.params.sprintListId) {
                var selecteds = $state.params.sprintListId.split(",");
                missing = _.every(selecteds, function(selected) {
                    return !_.includes(ids, selected);
                });
            } else {
                missing = !_.includes(ids, $state.params.sprintId.toString());
            }
            if (missing) {
                $scope.timelineSelected([]);
            }
        }
        $scope.computeVisibleSprints();
    });
    $scope.$watchGroup([function() { return $state.$current.self.name; }, function() { return $state.params.releaseId; }, function() { return $state.params.sprintId; }, function() { return $state.params.sprintListId; }], function(newValues) {
        var stateName = newValues[0];
        var releaseId = newValues[1];
        var sprintId = newValues[2];
        var sprintListId = newValues[3];
        var release = _.find($scope.releases, {id: releaseId});
        $scope.visibleSprintOffset = 0;
        if (release && stateName.indexOf('.sprint') != -1 && stateName.indexOf('.new') == -1) {
            if (sprintId) {
                $scope.sprints = [_.find(release.sprints, {id: sprintId})];
            } else if (sprintListId) {
                var ids = _.map(sprintListId.split(','), function(id) {
                    return parseInt(id);
                });
                $scope.sprints = _.filter(release.sprints, function(sprint) {
                    return _.includes(ids, sprint.id);
                });
            } else {
                var sprint = _.find(release.sprints, function(sprint) {
                    return sprint.state == SprintStatesByName.TODO || sprint.state == SprintStatesByName.IN_PROGRESS;
                });
                if (!sprint) {
                    sprint = _.last(release.sprints);
                }
                $scope.sprints = [sprint];
            }
            $scope.selectedItems = $scope.sprints; // URL -> Timeline
        } else {
            if (!release) {
                release = _.find($scope.releases, function(release) {
                    return release.state == ReleaseStatesByName.TODO || release.state == ReleaseStatesByName.IN_PROGRESS;
                });
                if (!release) {
                    release = _.last($scope.releases);
                }
            }
            if (release) {
                if (release.sprints == null) {
                    release.sprints = [];
                }
                $scope.sprints = release.sprints;
                $scope.selectedItems = [release]; // URL -> Timeline
                var firstSprintToShowIndex = _.findIndex($scope.sprints, function(sprint) {
                    return sprint.state == SprintStatesByName.TODO || sprint.state == SprintStatesByName.IN_PROGRESS;
                });
                if (firstSprintToShowIndex == -1) {
                    firstSprintToShowIndex = $scope.sprints.length > $scope.visibleSprintMax ? $scope.sprints.length - $scope.visibleSprintMax - 1 : 0;
                }
                $scope.visibleSprintOffset = firstSprintToShowIndex;
            }
        }
        $scope.release = release;
        $scope.computeVisibleSprints();
    });
    $scope.$watch('application.mediaBreakpoint', function() {
        var oldVisible = $scope.visibleSprintMax;
        $scope.visibleSprintMax = $scope.getVisibleSprintMax();
        if (oldVisible !== $scope.visibleSprintMax) {
            $state.reload();
        }
    });
    $scope.selectableOptions = {
        notSelectableSelector: '.action, button, a',
        allowMultiple: false,
        selectionUpdated: function(selectedIds) {
            var currentStateName = $state.current.name;
            var storyIndexInStateName = currentStateName.indexOf('story');
            if (selectedIds.length == 0 && storyIndexInStateName != -1) {
                $state.go(currentStateName.slice(0, storyIndexInStateName - 1));
            } else {
                var newStoryState = getNewStoryState(selectedIds[0], currentStateName, true);
                $state.go(newStoryState.name, newStoryState.params);
            }
        }
    };
    $scope.storyListGetters = []; // Mandatory to share code between two separate substates
    $scope.findPreviousOrNextStory = StoryService.findPreviousOrNextStory($scope.storyListGetters);
}]);
<|endoftext|>


<commit_before>// forked from https://github.com/zont/copy-and-watch/

const fs = require("fs");
const path = require("path");
const chokidar = require("chokidar");
const glob = require("fast-glob");
const globParent = require("glob-parent");
const del = require("del");
require("colors");
const debug = require("debug")("core");
const ISDEV = process.env.NODE_ENV !== "production";
// const slash = require("../utils/fixPathSlashes");
// const createDirIfNotExist = require("../utils/createDirIfNotExist.js");

module.exports = async (options, onWatchUpdate) => {
  var isWatching = false;
  // const target = options.target;
  const sourcePath = options.sourcePath;
  const buildPath = options.buildPath;
  // const sources = options.sources;
  // const parents = [...new Set(sources.map(globParent))];

  // const findTarget = from => {
  //   from = slash(from);
  //   const parent = parents
  //     .filter(p => from.indexOf(p) >= 0)
  //     .sort()
  //     .reverse()[0];
  //   return path.join(target, path.relative(parent, from));
  // };

  const copy = from => {
    const relativePath = path.relative(sourcePath, from);
    if (
      relativePath.indexOf("node_modules") !== -1 ||
      relativePath.indexOf(".git") !== -1 ||
      relativePath === "yarn.lock" ||
      relativePath === "package.json" // pkg.json is generated by installPackages.js
    ) {
      return;
    }

    // don't trigger for zero-builds folder (only in dev mode)
    if (ISDEV && relativePath.indexOf("zero-builds") !== -1) {
      return;
    }

    // const to = findTarget(from);
    // createDirIfNotExist(to);
    // const stats = fs.statSync(from);
    // if (stats.isDirectory()) {
    //   return;
    // }
    // fs.writeFileSync(to, fs.readFileSync(from));
    // debug("[COPY]".yellow, from, "to".yellow, to);
    if (isWatching && onWatchUpdate) onWatchUpdate("add", from);
  };
  const remove = from => {
    const relativePath = path.relative(sourcePath, from);
    if (
      relativePath.indexOf("node_modules") !== -1 ||
      relativePath.indexOf("zero-builds") !== -1
    ) {
      return;
    }
    if (isWatching && onWatchUpdate) onWatchUpdate("remove", from);
    // const to = findTarget(from);
    // try {
    //   fs.unlinkSync(to);
    //   debug("[DELETE]".yellow, to);
    //   if (isWatching && onWatchUpdate) onWatchUpdate("remove", to);
    // } catch (e) {}
  };
  // const rimraf = dir => {
  //   // don't remove node_modules
  //   if (dir.indexOf("node_modules") !== -1) {
  //     return;
  //   }
  //   if (fs.existsSync(dir)) {
  //     fs.readdirSync(dir).forEach(entry => {
  //       const entryPath = path.join(dir, entry);
  //       if (fs.lstatSync(entryPath).isDirectory()) {
  //         rimraf(entryPath);
  //       } else {
  //         fs.unlinkSync(entryPath);
  //       }
  //     });
  //     fs.rmdirSync(dir);
  //   }
  // };

  // clean
  if (options.clean) {
    var paths = [path.join(buildPath, "/**"), "!" + buildPath];
    if (!options.cleanModules) {
      // paths.push("!" + path.join(buildPath, "/node_modules/**"));
      //paths.push("!" + path.join(target, "/package-lock.json"));
      paths.push("!" + path.join(buildPath, "/yarn.lock"));
    }
    // if running in prod mode, also avoid deleting builds.
    //if (!ISDEV) paths.push('!'+path.join(target, '/zero-builds/**') )

    // await del(paths.map(p => slash(p)), { force: true });
  }

  // initial copy
  // sources.forEach(s =>
  //   glob.sync(s, { dot: true, ignore: ["**/.zero/**"] }).forEach(copy)
  // );

  if (onWatchUpdate) onWatchUpdate("ready");
  // watch
  if (options.watch) {
    // chokidar glob doesn't work with backward slashes
    chokidar
      .watch(path.join(sourcePath, "/**/*"), {
        ignoreInitial: true,
        ignored: "**/.zero/**"
      })
      .on("ready", () => {
        debug("[WATCHING]".yellow, sourcePath);
        isWatching = true;
      })
      .on("add", copy)
      .on("addDir", copy)
      .on("change", copy)
      .on("unlink", remove)
      .on("unlinkDir", remove)
      .on("error", e => debug("[ERROR]".red, e));
  }
};
<commit_msg>fix hmr on windows<commit_after>// forked from https://github.com/zont/copy-and-watch/

const fs = require("fs");
const path = require("path");
const chokidar = require("chokidar");
const glob = require("fast-glob");
const globParent = require("glob-parent");
const del = require("del");
require("colors");
const debug = require("debug")("core");
const ISDEV = process.env.NODE_ENV !== "production";
const slash = require("../utils/fixPathSlashes");
// const createDirIfNotExist = require("../utils/createDirIfNotExist.js");

module.exports = async (options, onWatchUpdate) => {
  var isWatching = false;
  // const target = options.target;
  const sourcePath = options.sourcePath;
  const buildPath = options.buildPath;
  // const sources = options.sources;
  // const parents = [...new Set(sources.map(globParent))];

  // const findTarget = from => {
  //   from = slash(from);
  //   const parent = parents
  //     .filter(p => from.indexOf(p) >= 0)
  //     .sort()
  //     .reverse()[0];
  //   return path.join(target, path.relative(parent, from));
  // };

  const copy = from => {
    const relativePath = path.relative(sourcePath, from);
    if (
      relativePath.indexOf("node_modules") !== -1 ||
      relativePath.indexOf(".git") !== -1 ||
      relativePath === "yarn.lock" ||
      relativePath === "package.json" // pkg.json is generated by installPackages.js
    ) {
      return;
    }

    // don't trigger for zero-builds folder (only in dev mode)
    if (ISDEV && relativePath.indexOf("zero-builds") !== -1) {
      return;
    }

    // const to = findTarget(from);
    // createDirIfNotExist(to);
    // const stats = fs.statSync(from);
    // if (stats.isDirectory()) {
    //   return;
    // }
    // fs.writeFileSync(to, fs.readFileSync(from));
    debug("[ADD]".yellow, from);
    if (isWatching && onWatchUpdate) onWatchUpdate("add", from);
  };
  const remove = from => {
    const relativePath = path.relative(sourcePath, from);
    if (
      relativePath.indexOf("node_modules") !== -1 ||
      relativePath.indexOf("zero-builds") !== -1
    ) {
      return;
    }
    debug("[REM]".yellow, from);
    if (isWatching && onWatchUpdate) onWatchUpdate("remove", from);
    // const to = findTarget(from);
    // try {
    //   fs.unlinkSync(to);
    //   debug("[DELETE]".yellow, to);
    //   if (isWatching && onWatchUpdate) onWatchUpdate("remove", to);
    // } catch (e) {}
  };
  // const rimraf = dir => {
  //   // don't remove node_modules
  //   if (dir.indexOf("node_modules") !== -1) {
  //     return;
  //   }
  //   if (fs.existsSync(dir)) {
  //     fs.readdirSync(dir).forEach(entry => {
  //       const entryPath = path.join(dir, entry);
  //       if (fs.lstatSync(entryPath).isDirectory()) {
  //         rimraf(entryPath);
  //       } else {
  //         fs.unlinkSync(entryPath);
  //       }
  //     });
  //     fs.rmdirSync(dir);
  //   }
  // };

  // clean
  if (options.clean) {
    var paths = [slash(path.join(buildPath, "/**")), "!" + buildPath];
    if (!options.cleanModules) {
      // paths.push("!" + path.join(buildPath, "/node_modules/**"));
      //paths.push("!" + path.join(target, "/package-lock.json"));
      paths.push("!" + slash(path.join(buildPath, "/yarn.lock")));
    }
    // if running in prod mode, also avoid deleting builds.
    //if (!ISDEV) paths.push('!'+path.join(target, '/zero-builds/**') )

    // await del(paths.map(p => slash(p)), { force: true });
  }

  // initial copy
  // sources.forEach(s =>
  //   glob.sync(s, { dot: true, ignore: ["**/.zero/**"] }).forEach(copy)
  // );

  // watch
  if (options.watch) {
    // chokidar glob doesn't work with backward slashes
    chokidar
      .watch(slash(path.join(sourcePath, "/**/*")), {
        ignoreInitial: true,
        ignored: "**/.zero/**"
      })
      .on("ready", () => {
        debug("[WATCHING]".yellow, sourcePath);
        isWatching = true;
        if (onWatchUpdate) onWatchUpdate("ready");
      })
      .on("add", copy)
      .on("addDir", copy)
      .on("change", copy)
      .on("unlink", remove)
      .on("unlinkDir", remove)
      .on("error", e => debug("[ERROR]".red, e));
  } else if (onWatchUpdate) {
    onWatchUpdate("ready");
  }
};
<|endoftext|>


<commit_before>"use strict"

var f = require('util').format;

// Extend the object
var extend = function(template, fields) {
  var object = {};
  for(var name in template) {
    object[name] = template[name];
  }

  for(var name in fields) {
   object[name] = fields[name];
  }

  return object;
}

exports['Successful reconnect when driver looses touch with entire replicaset'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    },
    // ignore: { travis:true }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];
    var die = false;

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(primary[0]);
            } else if(doc.insert) {
              request.reply({ "ok" : 1, "n" : 1 });
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(firstSecondary[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(arbiter[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 2000,
        socketTimeout: 2000,
        haInterval: 500,
        size: 500
    });

    server.on('connect', function(_server) {
      // server.__connected = true;
      // console.log("------------------------------- step 0 ")
      // console.dir(_server)

      for(var i = 0; i < 100000; i++) {
        // console.log("------------------------------- step 0 : 1 ")
        // console.log(server.insert)
        // Execute the write
        _server.insert(f("%s.inserts", configuration.db), [{a:1}], {
          writeConcern: {w:1}, ordered:true
        }, function(err, results) {
          // console.log("!!!!!!!!! RESULt")
          // if(results)console.dir(results.result)
        });
        // console.log("------------------------------- step 0 : 2 ")
      }
      // console.log("------------------------------- step 0 : 1")

      setTimeout(function() {
        // console.log("------------------------------- step 1 ")
        die = true;

        setTimeout(function() {
          // console.log("------------------------------- step 2 ")
          die = false;

          setTimeout(function() {
            // console.log("------------------------------- step 5 : 0")
            // console.dir(server.s.replicaSetState.primary)
            // console.log("------------------------------- step 6 : 0")
            // console.dir(server.s.replicaSetState.secondaries)
            // console.log("------------------------------- step 7 : 0")
            // console.dir(server.s.replicaSetState.arbiters)

            // console.log("------------------------------- step 3 ")
            _server.command('admin.$cmd', {ismaster:true}, function(err, r) {
              // console.log("------------------------------- step 4 : 1")
              // console.dir(err)
              // console.log("------------------------------- step 5 : 1")
              // console.dir(server.s.replicaSetState.primary)
              // console.log("------------------------------- step 6 : 1")
              // console.dir(server.s.replicaSetState.secondaries)
              // console.log("------------------------------- step 7 : 1")
              // console.dir(server.s.replicaSetState.arbiters)
              // console.dir(err)
              // if(r)console.dir(r.result)
              // console.log("_server.s.replicaSetState.primary != null = " + (_server.s.replicaSetState.primary != null))
              // console.log("_server.s.replicaSetState.secondaries.length = " + _server.s.replicaSetState.secondaries.length)
              // console.log("_server.s.replicaSetState.arbiters.length = " + _server.s.replicaSetState.arbiters.length)
              test.equal(null, err);
              test.ok(_server.s.replicaSetState.primary != null);
              test.equal(1, _server.s.replicaSetState.secondaries.length);
              test.equal(1, _server.s.replicaSetState.arbiters.length);

              primaryServer.destroy();
              firstSecondaryServer.destroy();
              arbiterServer.destroy();
              server.destroy();
              running = false;

              test.done();
            });
          }, 10000);
        }, 2500);
      }, 2500);
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Successfully come back from a dead replicaset that has been unavailable for a long time'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];
    var die = false;

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          if(die) {
            // console.log("------------------ die 1")
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(primary[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          if(die) {
            // console.log("------------------ die 2")
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(firstSecondary[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          if(die) {
            // console.log("------------------ die 3")
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(arbiter[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 5000,
        socketTimeout: 5000,
        haInterval: 1000,
        size: 1
    });

    server.on('connect', function(e) {
      // console.log("================================== 0")
      setTimeout(function() {
        // console.log("================================== 1")
        die = true;

        var intervalId = setInterval(function() {
          // console.log("--------------- interval 0")
          server.command('admin.$cmd', {ismaster:true}, function(err, r) {
            // console.log("--------------- interval 1")
            // console.log(err)
            // test.ok(err != null);
          });
        }, 2000);

        setTimeout(function() {
          // console.log("================================== 2")
          die = false;
          // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ALIVE")

          setTimeout(function() {
            // console.log("================================== 3")
            clearInterval(intervalId);

            server.command('admin.$cmd', {ismaster:true}, function(err, r) {
              // console.log("---------------------------------------------------------------")
              // console.dir(err)
              // console.log("server.s.replicaSetState.secondaries = " + server.s.replicaSetState.secondaries.length)
              // console.log("server.s.replicaSetState.arbiters = " + server.s.replicaSetState.arbiters.length)
              // console.log("server.s.replicaSetState.primary = " + (server.s.replicaSetState.primary != null))
              // console.dir(err)
              // console.dir(r.result)

              test.equal(null, err);
              test.ok(server.s.replicaSetState.primary != null);
              test.equal(1, server.s.replicaSetState.secondaries.length);
              test.equal(1, server.s.replicaSetState.arbiters.length);

              primaryServer.destroy();
              firstSecondaryServer.destroy();
              arbiterServer.destroy();
              server.destroy();
              running = false;

              test.done();
            });
          }, 5000);
        }, 25000);
      }, 2500);
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}
<commit_msg>more tracing<commit_after>"use strict"

var f = require('util').format;

// Extend the object
var extend = function(template, fields) {
  var object = {};
  for(var name in template) {
    object[name] = template[name];
  }

  for(var name in fields) {
   object[name] = fields[name];
  }

  return object;
}

exports['Successful reconnect when driver looses touch with entire replicaset'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    },
    // ignore: { travis:true }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];
    var die = false;

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(primary[0]);
            } else if(doc.insert) {
              request.reply({ "ok" : 1, "n" : 1 });
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(firstSecondary[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(arbiter[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 2000,
        socketTimeout: 2000,
        haInterval: 500,
        size: 500
    });

    server.on('connect', function(_server) {
      // server.__connected = true;
      // console.log("------------------------------- step 0 ")
      // console.dir(_server)

      for(var i = 0; i < 100000; i++) {
        // console.log("------------------------------- step 0 : 1 ")
        // console.log(server.insert)
        // Execute the write
        _server.insert(f("%s.inserts", configuration.db), [{a:1}], {
          writeConcern: {w:1}, ordered:true
        }, function(err, results) {
          // console.log("!!!!!!!!! RESULt")
          // if(results)console.dir(results.result)
        });
        // console.log("------------------------------- step 0 : 2 ")
      }
      // console.log("------------------------------- step 0 : 1")

      setTimeout(function() {
        // console.log("------------------------------- step 1 ")
        die = true;

        setTimeout(function() {
          // console.log("------------------------------- step 2 ")
          die = false;

          setTimeout(function() {
            // console.log("------------------------------- step 5 : 0")
            // console.dir(server.s.replicaSetState.primary)
            // console.log("------------------------------- step 6 : 0")
            // console.dir(server.s.replicaSetState.secondaries)
            // console.log("------------------------------- step 7 : 0")
            // console.dir(server.s.replicaSetState.arbiters)

            // console.log("------------------------------- step 3 ")
            _server.command('admin.$cmd', {ismaster:true}, function(err, r) {
              // console.log("------------------------------- step 4 : 1")
              // console.dir(err)
              // console.log("------------------------------- step 5 : 1")
              // console.dir(server.s.replicaSetState.primary)
              // console.log("------------------------------- step 6 : 1")
              // console.dir(server.s.replicaSetState.secondaries)
              // console.log("------------------------------- step 7 : 1")
              // console.dir(server.s.replicaSetState.arbiters)
              console.dir(err)
              if(r)console.dir(r.result)
              console.log("_server.s.replicaSetState.primary != null = " + (_server.s.replicaSetState.primary != null))
              console.log("_server.s.replicaSetState.secondaries.length = " + _server.s.replicaSetState.secondaries.length)
              console.log("_server.s.replicaSetState.arbiters.length = " + _server.s.replicaSetState.arbiters.length)
              test.equal(null, err);
              test.ok(_server.s.replicaSetState.primary != null);
              test.equal(1, _server.s.replicaSetState.secondaries.length);
              test.equal(1, _server.s.replicaSetState.arbiters.length);

              primaryServer.destroy();
              firstSecondaryServer.destroy();
              arbiterServer.destroy();
              server.destroy();
              running = false;

              test.done();
            });
          }, 10000);
        }, 2500);
      }, 2500);
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Successfully come back from a dead replicaset that has been unavailable for a long time'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];
    var die = false;

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          if(die) {
            // console.log("------------------ die 1")
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(primary[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          if(die) {
            // console.log("------------------ die 2")
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(firstSecondary[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          if(die) {
            // console.log("------------------ die 3")
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(arbiter[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 5000,
        socketTimeout: 5000,
        haInterval: 1000,
        size: 1
    });

    server.on('connect', function(e) {
      // console.log("================================== 0")
      setTimeout(function() {
        // console.log("================================== 1")
        die = true;

        var intervalId = setInterval(function() {
          // console.log("--------------- interval 0")
          server.command('admin.$cmd', {ismaster:true}, function(err, r) {
            // console.log("--------------- interval 1")
            // console.log(err)
            // test.ok(err != null);
          });
        }, 2000);

        setTimeout(function() {
          // console.log("================================== 2")
          die = false;
          // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ALIVE")

          setTimeout(function() {
            // console.log("================================== 3")
            clearInterval(intervalId);

            server.command('admin.$cmd', {ismaster:true}, function(err, r) {
              // console.log("---------------------------------------------------------------")
              // console.dir(err)
              // console.log("server.s.replicaSetState.secondaries = " + server.s.replicaSetState.secondaries.length)
              // console.log("server.s.replicaSetState.arbiters = " + server.s.replicaSetState.arbiters.length)
              // console.log("server.s.replicaSetState.primary = " + (server.s.replicaSetState.primary != null))
              // console.dir(err)
              // console.dir(r.result)

              test.equal(null, err);
              test.ok(server.s.replicaSetState.primary != null);
              test.equal(1, server.s.replicaSetState.secondaries.length);
              test.equal(1, server.s.replicaSetState.arbiters.length);

              primaryServer.destroy();
              firstSecondaryServer.destroy();
              arbiterServer.destroy();
              server.destroy();
              running = false;

              test.done();
            });
          }, 5000);
        }, 25000);
      }, 2500);
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}
<|endoftext|>


<commit_before>var engine = require('../engine').init();

engine.runInstance(34, true, function(err) {
});
<commit_msg>Delete engine.test.js<commit_after><|endoftext|>


<commit_before>(function( global ) {

function CBuffer() {
	var i = 0;
	// handle cases where "new" keyword wasn't used
	if (!( this instanceof CBuffer )) {
		if ( arguments.length > 1 || typeof arguments[0] !== 'number' ) {
			return CBuffer.apply( new CBuffer(), arguments );
		} else {
			return new CBuffer( arguments[0] );
		}
	}
	// this is the same in either scenario
	this.size = this.start = 0;
	// build CBuffer based on passed arguments
	if ( arguments.length > 1 || typeof arguments[0] !== 'number' ) {
		this.data = new Array( arguments.length );
		this.end = ( this.length = arguments.length ) - 1;
		this.push.apply( this, arguments );
	} else {
		this.data = new Array( arguments[0] );
		// force preallocation of memory to each array slot, for quicker operation on buffer
		for ( ; i < arguments[0]; i++ ) {
			this.data[i] = undefined;
		}
		this.end = ( this.length = arguments[0] ) - 1;
	}
	return this;
}

CBuffer.prototype = {
	// push item to the end
	push : function() {
		var i = 0;
		// push items to the end, wrapping and erasing existing items
		// using arguments variable directly to reduce gc footprint
		for ( ; i < arguments.length; i++ ) {
			this.data[( this.end + i + 1 ) % this.length ] = arguments[i];
		}
		// recalculate size
		if ( this.size < this.length ) {
			if ( this.size + i > this.length ) this.size = this.length;
			else this.size += i;
		}
		// recalculate end
		this.end = ( this.end + i ) % this.length;
		// recalculate start
		this.start = this.end - this.size + 1;
		if ( this.start < 0 ) this.start += this.length;
		// return number current number of items in CBuffer
		return this.size;
	},
	// pop last item
	pop : function() {
		if ( this.size === 0 ) return;
		var item = this.last();
		delete this.data[( this.size + this.start - 1 ) % this.length ];
		this.size--;
		this.end--;
		if ( this.end < 0 ) this.end += this.length;
		return item;
	},
	// shift first item
	shift : function() {
		var item;
		// check if there are any items in CBuff
		if ( this.size === 0 ) return undefined;
		// store first item for return
		item = this.data[ this.start ];
		// delete first item from memory
		delete this.data[ this.start ];
		// recalculate start of CBuff
		this.start = ( this.start + 1 ) % this.length;
		// decrement size
		this.size--;
		return item;
	},
	// loop through each item in buffer
	forEach : function( callback, context ) {
		var i = 0;
		// check if context was passed
		if ( context ) {
			for (; i < this.size; i++ ) {
				callback.call( context, this.idx( i ), i, this );
			}
		} else {
			for (; i < this.size; i++ ) {
				callback( this.idx( i ), i, this );
			}
		}
	},
	// return index of first matched element
	indexOf : function( arg, idx ) {
		if ( !idx ) idx = 0;
		for ( ; idx < this.size; idx++ ) {
			if ( this.idx( idx ) === arg ) return idx;
		}
		return -1;
	},
	// return first item in buffer
	first : function() {
		return this.data[ this.start ];
	},
	// return last item in buffer
	last : function() {
		return this.data[ this.end ];
	},
	// return specific index in buffer
	idx : function( arg ) {
		return this.data[( this.start + arg ) % this.length ];
	}
};

global.CBuffer = CBuffer;

}( this ));
<commit_msg>syntax improvements, removed unecessary conditionals<commit_after>(function( global ) {

function CBuffer() {
	var i = 0;
	// handle cases where "new" keyword wasn't used
	if (!( this instanceof CBuffer )) {
		if ( arguments.length > 1 || typeof arguments[0] !== 'number' ) {
			return CBuffer.apply( new CBuffer(), arguments );
		} else {
			return new CBuffer( arguments[0] );
		}
	}
	// this is the same in either scenario
	this.size = this.start = 0;
	// build CBuffer based on passed arguments
	if ( arguments.length > 1 || typeof arguments[0] !== 'number' ) {
		this.data = new Array( arguments.length );
		this.end = ( this.length = arguments.length ) - 1;
		this.push.apply( this, arguments );
	} else {
		this.data = new Array( arguments[0] );
		// force preallocation of memory to each array slot, for quicker operation on buffer
		for ( ; i < arguments[0]; i++ ) {
			this.data[i] = undefined;
		}
		this.end = ( this.length = arguments[0] ) - 1;
	}
	return this;
}

CBuffer.prototype = {
	// push item to the end
	push : function() {
		var i = 0;
		// push items to the end, wrapping and erasing existing items
		// using arguments variable directly to reduce gc footprint
		for ( ; i < arguments.length; i++ ) {
			this.data[( this.end + i + 1 ) % this.length ] = arguments[i];
		}
		// recalculate size
		if ( this.size < this.length ) {
			if ( this.size + i > this.length ) this.size = this.length;
			else this.size += i;
		}
		// recalculate end
		this.end = ( this.end + i ) % this.length;
		// recalculate start
		this.start = ( this.length + this.end - this.size + 1 ) % this.length;
		// return number current number of items in CBuffer
		return this.size;
	},
	// pop last item
	pop : function() {
		var item;
		if ( this.size === 0 ) return;
		item = this.data[ this.end ];
		delete this.data[( this.size + this.start - 1 ) % this.length ];
		this.size--;
		this.end = ( this.end - 1 + this.length ) % this.length;
		return item;
	},
	// remove and return first item
	shift : function() {
		var item;
		// check if there are any items in CBuff
		if ( this.size === 0 ) return;
		// store first item for return
		item = this.data[ this.start ];
		// delete first item from memory
		delete this.data[ this.start ];
		// recalculate start of CBuff
		this.start = ( this.start + 1 ) % this.length;
		// decrement size
		this.size--;
		return item;
	},
	// loop through each item in buffer
	forEach : function( callback, context ) {
		var i = 0;
		// check if context was passed
		if ( context ) {
			for (; i < this.size; i++ ) {
				callback.call( context, this.idx( i ), i, this );
			}
		} else {
			for (; i < this.size; i++ ) {
				callback( this.idx( i ), i, this );
			}
		}
	},
	// return index of first matched element
	indexOf : function( arg, idx ) {
		if ( !idx ) idx = 0;
		for ( ; idx < this.size; idx++ ) {
			if ( this.idx( idx ) === arg ) return idx;
		}
		return -1;
	},
	// return first item in buffer
	first : function() {
		return this.data[ this.start ];
	},
	// return last item in buffer
	last : function() {
		return this.data[ this.end ];
	},
	// return specific index in buffer
	idx : function( arg ) {
		return this.data[( this.start + arg ) % this.length ];
	}
};

global.CBuffer = CBuffer;

}( this ));
<|endoftext|>


<commit_before>HyperscalaConnect = (function() {
    var messageId = 0;
    var pageId = null;
    var connectionId = null;
    var handlers = {};
    var queue = [];
    var sentQueue = [];

    var sendSuccess = function(data) {
        if (data.status == 'OK') {
            respond(false);          // Send more data or wait for more data
        } else {
            console.log('Send successfully, but incorrect respond data: ' + JSON.stringify(data) + ', retrying in five seconds!');
            setTimeout(function() {
                respond(true);
            }, 5000);
        }
    };
    var sendError = function(jqXHR, textStatus, errorThrown) {
        if (errorThrown == 'Not Found') {
            console.log('Page not found. Reloading page...');
            location.reload();
        } else if (errorThrown == '') {
            console.log('Unable to connect. Retrying in five seconds...');
            setTimeout(function() {
                respond(true);
            }, 5000);
        } else {
            console.log('Receive Error: ' + textStatus + ' - ' + errorThrown + '. Unhandled failure.');
        }
    };
    var sendComplete = function(event) {
    };
    var sendSettings = {
        type: 'POST',
        url: '/hyperscala.connect/send',
        dataType: 'json',
        processData: false,
        cache: false,
        async: true,
        success: sendSuccess,
        error: sendError,
        complete: sendComplete,
        timeout: 15000
    };

    var receiveSuccess = function(data) {
        if (data.status == 'OK') {
            var allHandlers = handlers['*'];
            for (var index = 0; index < data.messages.length; index++) {
                var message = data.messages[index];
                var array = handlers[message.event];
                receive(message.event, message.data, array, false);
                receive(message.event, message.data, allHandlers, true);
            }
            request(false);
        } else {
            console.log('Received successfully, but incorrect data: ' + JSON.stringify(data) + ', retrying in five seconds!');
            setTimeout(function() {
                request(true);
            }, 5000);
        }
    };
    var receiveError = function(jqXHR, textStatus, errorThrown) {
        if (errorThrown == 'Not Found') {
            console.log('Page not found. Reloading page...');
            location.reload();
        } else if (errorThrown == '') {
            console.log('Unable to connect. Retrying in five seconds...');
            setTimeout(function() {
                request(true);
            }, 5000);
        } else {
            console.log('Receive Error: ' + textStatus + ' - ' + errorThrown + '. Unhandled failure.');
        }
    };
    var receiveComplete = function(event) {
    };
    var receiveSettings = {
        type: 'POST',
        url: '/hyperscala.connect/receive',
        dataType: 'json',
        processData: false,
        cache: false,
        async: true,
        success: receiveSuccess,
        error: receiveError,
        complete: receiveComplete,
        timeout: 60000
    };

    var init = function(pid, cid) {
        pageId = pid;
        connectionId = cid;

        request(false);          // Request data from the server
        respond(false);          // Send data to the server
    };
    var send = function(event, data) {
        queue.push({
            id: ++messageId,
            event: event,
            data: data
        });
    };
    var on = function(event, handler) {
        if (event == null) {
            event = '*';
        }
        if (handlers[event] == null) {
            handlers[event] = [];
        }
        var array = handlers[event];
        array.push(handler);
    };

    // Internal functions

    var request = function(resend) {
        var data = {
            pageId: pageId,
            connectionId: connectionId,
            timestamp: new Date().getTime(),
            resend: resend
        };
        receiveSettings.data = JSON.stringify(data);
        $.ajax(receiveSettings);
    };
    var respond = function(resend) {
        if (resend) {                       // Failure, so lets send the queue again
            sendQueue(sentQueue);
        } else if (queue.length > 0) {      // Queue isn't empty, lets send it
            sendQueue(queue);
            sentQueue = queue;
            queue = [];
        } else {                            // Queue is empty, lets check back later
            setTimeout(function() {
                respond(false);
            }, 10);
        }
    };
    /**
     * Receives an event with data and calls the handlers within the supplied array.
     *
     * @param event
     * @param data
     * @param array
     * @param includeEvent
     */
    var receive = function(event, data, array, includeEvent) {
        if (array != null) {
            for (var index = 0; index < array.length; index++) {
                var handler = array[index];
                try {
                    if (includeEvent) {
                        handler(event, data);
                    } else {
                        handler(data);
                    }
                } catch(err) {
                    console.log('Error calling handler to receive: ' + event + ' - ' + err.message + ' (' + handler + ')');
                }
            }
        }
    };
    /**
     * Sends the supplied queue to the server.
     *
     * @param queue
     */
    var sendQueue = function(queue) {
        var data = {
            pageId: pageId,
            connectionId: connectionId,
            timestamp: new Date().getTime(),
            messages: queue
        };
        sendSettings.data = JSON.stringify(data);
        $.ajax(sendSettings);
    };

    return {
        init: init,
        send: send,
        on: on
    };
})();<commit_msg>Added send / receive failure limit support. Added improvements to error handling. Added disconnect support and auto-disconnect upon page unloading. Added receive id checking on messages to validate proper order.<commit_after>HyperscalaConnect = (function() {
    var messageId = 0;
    var pageId = null;
    var connectionId = null;
    var handlers = {};
    var queue = [];
    var sentQueue = [];
    var lastReceiveId = 0;
    var disconnected = false;
    var maxRetries = 10;
    var sendFailures = 0;
    var receiveFailures = 0;

    var sendSuccess = function(data) {
        if (data.status == 'OK') {
            sendFailures = 0;
            respond(false);          // Send more data or wait for more data
        } else {
            sendFailures++;
            console.log('Send successfully, but incorrect respond data: ' + JSON.stringify(data) + ', retrying in five seconds!');
            setTimeout(function() {
                respond(true);
            }, 5000);
        }
    };
    var sendError = function(jqXHR, textStatus, errorThrown) {
        sendFailures++;
        if (errorThrown == 'Not Found') {
            console.log('Page not found. Reloading page...');
            location.reload();
        } else if (errorThrown == '') {
            console.log('Unable to connect. Retrying in five seconds...');
            setTimeout(function() {
                respond(true);
            }, 5000);
        } else {
            console.log('Receive Error: ' + textStatus + ' - ' + errorThrown + '. Unhandled failure. Reloading page in fifteen seconds...');
            disconnect();
            setTimeout(function() {
                location.reload();
            }, 15000);
        }
    };
    var sendComplete = function(event) {
    };
    var sendSettings = {
        type: 'POST',
        url: '/hyperscala.connect/send',
        dataType: 'json',
        processData: false,
        cache: false,
        async: true,
        success: sendSuccess,
        error: sendError,
        complete: sendComplete,
        timeout: 15000
    };
    var disconnect = function() {
        disconnected = true;
    };

    var receiveSuccess = function(data) {
        if (data.status == 'OK') {
            receiveFailures = 0;
            var allHandlers = handlers['*'];
            for (var index = 0; index < data.messages.length; index++) {
                var message = data.messages[index];
                var expectedId = lastReceiveId + 1;
                if (message.id == expectedId) {
                    var array = handlers[message.event];
                    lastReceiveId = expectedId;
                    receive(message.event, message.data, array, false);
                    receive(message.event, message.data, allHandlers, true);
                } else if (message.id < expectedId) {
                    console.log('Ignoring message: ' + message.event + '. Expected ID: ' + expectedId + ', Message ID: ' + message.id);
                } else if (message.id > expectedId) {
                    console.log('Lost a message, reloading in five seconds...');
                    disconnect();
                    setTimeout(function() {
                        location.reload();
                    }, 5000);
                }
            }
            request(false);
        } else {
            receiveFailures++;
            console.log('Received successfully, but incorrect data: ' + JSON.stringify(data) + ', retrying in five seconds!');
            setTimeout(function() {
                request(true);
            }, 5000);
        }
    };
    var receiveError = function(jqXHR, textStatus, errorThrown) {
        receiveFailures++;
        if (errorThrown == 'Not Found') {
            console.log('Page not found. Reloading page...');
            location.reload();
        } else if (errorThrown == '') {
            console.log('Unable to connect. Retrying in five seconds...');
            setTimeout(function() {
                request(true);
            }, 5000);
        } else {
            console.log('Receive Error: ' + textStatus + ' - ' + errorThrown + '. Unhandled failure. Reloading page in fifteen seconds...');
            disconnect();
            setTimeout(function() {
                location.reload();
            }, 15000);
        }
    };
    var receiveComplete = function(event) {
    };
    var receiveSettings = {
        type: 'POST',
        url: '/hyperscala.connect/receive',
        dataType: 'json',
        processData: false,
        cache: false,
        async: true,
        success: receiveSuccess,
        error: receiveError,
        complete: receiveComplete,
        timeout: 60000
    };

    var init = function(pid, cid) {
        pageId = pid;
        connectionId = cid;

        request(false);          // Request data from the server
        respond(false);          // Send data to the server

        $(window).unload(disconnect);       // Disconnect when the page unloads
    };
    var send = function(event, data) {
        queue.push({
            id: ++messageId,
            event: event,
            data: data
        });
    };
    var on = function(event, handler) {
        if (event == null) {
            event = '*';
        }
        if (handlers[event] == null) {
            handlers[event] = [];
        }
        var array = handlers[event];
        array.push(handler);
    };

    // Internal functions

    var request = function(resend) {
        if (!disconnected) {
            if (receiveFailures >= maxRetries) {
                console.log('Maximum receive failures reached. Disconnecting.');
                disconnect();
            } else {
                var data = {
                    pageId: pageId,
                    connectionId: connectionId,
                    timestamp: new Date().getTime(),
                    resend: resend
                };
                receiveSettings.data = JSON.stringify(data);
                $.ajax(receiveSettings);
            }
        }
    };
    var respond = function(resend) {
        if (resend) {                       // Failure, so lets send the queue again
            sendQueue(sentQueue);
        } else if (queue.length > 0) {      // Queue isn't empty, lets send it
            sendQueue(queue);
            sentQueue = queue;
            queue = [];
        } else {                            // Queue is empty, lets check back later
            setTimeout(function() {
                respond(false);
            }, 10);
        }
    };
    /**
     * Receives an event with data and calls the handlers within the supplied array.
     *
     * @param event
     * @param data
     * @param array
     * @param includeEvent
     */
    var receive = function(event, data, array, includeEvent) {
        if (array != null) {
            for (var index = 0; index < array.length; index++) {
                var handler = array[index];
                try {
                    if (includeEvent) {
                        handler(event, data);
                    } else {
                        handler(data);
                    }
                } catch(err) {
                    console.log('Error calling handler to receive: ' + event + ' - ' + err.message + ' (' + handler + ')');
                }
            }
        }
    };
    /**
     * Sends the supplied queue to the server.
     *
     * @param queue
     */
    var sendQueue = function(queue) {
        if (!disconnected) {
            if (sendFailures >= maxRetries) {
                console.log('Maximum send failures reached. Disconnecting.');
                disconnect();
            } else {
                var data = {
                    pageId: pageId,
                    connectionId: connectionId,
                    timestamp: new Date().getTime(),
                    messages: queue
                };
                sendSettings.data = JSON.stringify(data);
                $.ajax(sendSettings);
            }
        }
    };

    return {
        init: init,
        send: send,
        on: on
    };
})();<|endoftext|>


<commit_before>//
//  CanvasCamera.js
//  PhoneGap iOS Cordova Plugin to capture Camera streaming into a HTML5 Canvas or an IMG tag.
//
//  Created by Diego Araos <d@wehack.it> on 12/29/12.
//
//  MIT License

cordova.define("cordova/plugin/CanvasCamera", function(require, exports, module) {
    var exec = require('cordova/exec');
    var CanvasCamera = function(){
        var _orientation = 'landscape';
        var _obj = null;
        var _context = null;
        var _camImage = null;

        var _x = 0;
        var _y = 0;
        var _width = 0;
        var _height = 0;
    };

    CanvasCamera.prototype.initialize = function(obj) {
        var _this = this;
        this._obj = obj;

        this._context = obj.getContext("2d");

        this._camImage = new Image();

        this._camImage.onload = function() {
            console.log("_this._context.clearRect"+_this._width+","+_this._height);
            _this._context.clearRect(0, 0, _this._width, _this._height);
            if (window.orientation == 90
               || window.orientation == -90)
            {
                _this._context.save();
                // rotate 90
                console.log("_this._context.translate"+(_this._width/2)+","+ (_this._height/2));
                _this._context.translate(_this._width/2, _this._height/2);
                _this._context.rotate((90 - window.orientation) *Math.PI/180);
                _this._context.drawImage(_this._camImage, 0, 0, 352, 288, -_this._width/2, -_this._height/2, _this._width, _this._height);
                //
                _this._context.restore();
            }
            else
            {
                console.log("comes in else");
                _this._context.save();
                // rotate 90
                _this._context.translate(_this._width/2, _this._height/2);
                _this._context.rotate((90 - window.orientation)*Math.PI/180);
                _this._context.drawImage(_this._camImage, 0, 0, 352, 288, -_this._height/2, -_this._width/2, _this._height, _this._width);
                //
                _this._context.restore();
            }
        };

        // register orientation change event
        window.addEventListener('orientationchange', this.doOrientationChange);
        this.doOrientationChange();
    };

    CanvasCamera.prototype.start = function(options) {
        cordova.exec(false, false, "CanvasCamera", "startCapture", [options]);
    };

    CanvasCamera.prototype.capture = function(data) {
        this._camImage.src = data;
    };

    CanvasCamera.prototype.setFlashMode = function(flashMode) {
        cordova.exec(function(){}, function(){}, "CanvasCamera", "setFlashMode", [flashMode]);
    };

    CanvasCamera.prototype.setCameraPosition = function(cameraPosition) {
        cordova.exec(function(){}, function(){}, "CanvasCamera", "setCameraPosition", [cameraPosition]);
    };

    CanvasCamera.prototype.doOrientationChange = function() {
        console.log('doOrientationChange');
        switch(window.orientation)
        {
            case -90:
            case 90:
                this._orientation = 'landscape';
                break;
            default:
                this._orientation = 'portrait';
                break;
        }
        console.log('window.innerWidth'+window.innerWidth);
        console.log('window.innerHeight'+window.innerHeight);

        var windowWidth = window.innerWidth;
        var windowHeight = window.innerHeight;
        var pixelRatio = window.devicePixelRatio || 1; /// get pixel ratio of device

        this._obj.width = windowWidth;// * pixelRatio;   /// resolution of canvas
        this._obj.height = windowHeight;// * pixelRatio;
        console.log('this._obj.width'+this._obj.width);

        this._obj.style.width = windowWidth + 'px';   /// CSS size of canvas
        this._obj.style.height = windowHeight + 'px';
        console.log('this._obj.style.width'+this._obj.style.width);

        this._x = 0;
        this._y = 0;
        this._width = windowWidth;
        this._height = windowHeight;
        console.log('this._width'+this._width+" this._height"+this._height);
    };

    CanvasCamera.prototype.takePicture = function(onsuccess) {
        cordova.exec(onsuccess, function(){}, "CanvasCamera", "captureImage", []);
    };

    var myplugin = new CanvasCamera();
    module.exports = myplugin;
});

var CanvasCamera = cordova.require("cordova/plugin/CanvasCamera");

var DestinationType = {
    DATA_URL : 0,
    FILE_URI : 1
};

var PictureSourceType = {
    PHOTOLIBRARY : 0,
    CAMERA : 1,
    SAVEDPHOTOALBUM : 2
};

var EncodingType = {
    JPEG : 0,
    PNG : 1
};

var CameraPosition = {
    BACK : 0,
    FRONT : 1
};

var CameraPosition = {
    BACK : 1,
    FRONT : 2
};

var FlashMode = {
    OFF : 0,
    ON : 1,
    AUTO : 2
};

CanvasCamera.DestinationType = DestinationType;
CanvasCamera.PictureSourceType = PictureSourceType;
CanvasCamera.EncodingType = EncodingType;
CanvasCamera.CameraPosition = CameraPosition;
CanvasCamera.FlashMode = FlashMode;

module.exports = CanvasCamera;
<commit_msg>Update CanvasCamera.js<commit_after>//
//  CanvasCamera.js
//  PhoneGap iOS Cordova Plugin to capture Camera streaming into a HTML5 Canvas or an IMG tag.
//
//  Created by Diego Araos <d@wehack.it> on 12/29/12.
//
//  MIT License

cordova.define("cordova/plugin/CanvasCamera", function(require, exports, module) {
    var exec = require('cordova/exec');
    var CanvasCamera = function(){
        var _orientation = 'landscape';
        var _obj = null;
        var _context = null;
        var _camImage = null;

        var _x = 0;
        var _y = 0;
        var _width = 0;
        var _height = 0;
    };

    CanvasCamera.prototype.initialize = function(obj) {
        var _this = this;
        this._obj = obj;

        this._context = obj.getContext("2d");

        this._camImage = new Image();

        this._camImage.onload = function() {
            console.log("_this._context.clearRect"+_this._width+","+_this._height);
            _this._context.clearRect(0, 0, _this._width, _this._height);
            if (window.orientation == 90
               || window.orientation == -90)
            {
                _this._context.save();
                // rotate 90
                console.log("_this._context.translate"+(_this._width/2)+","+ (_this._height/2));
                _this._context.translate(_this._width/2, _this._height/2);
                _this._context.rotate((90 - window.orientation) *Math.PI/180);
                _this._context.drawImage(_this._camImage, 0, 0, 352, 288, -_this._width/2, -_this._height/2, _this._width, _this._height);
                //
                _this._context.restore();
            }
            else
            {
                console.log("comes in else");
                _this._context.save();
                // rotate 90
                _this._context.translate(_this._width/2, _this._height/2);
                _this._context.rotate((90 - window.orientation)*Math.PI/180);
                _this._context.drawImage(_this._camImage, 0, 0, 352, 288, -_this._height/2, -_this._width/2, _this._height, _this._width);
                //
                _this._context.restore();
            }
        };

        // register orientation change event
        window.addEventListener('orientationchange', this.doOrientationChange);
        this.doOrientationChange();
    };

    CanvasCamera.prototype.start = function(options) {
        cordova.exec(false, false, "CanvasCamera", "startCapture", [options]);
    };

    CanvasCamera.prototype.capture = function(data) {
        this._camImage.src = data;
    };

    CanvasCamera.prototype.setFlashMode = function(flashMode) {
        cordova.exec(function(){}, function(){}, "CanvasCamera", "setFlashMode", [flashMode]);
    };

    CanvasCamera.prototype.setCameraPosition = function(cameraPosition) {
        cordova.exec(function(){}, function(){}, "CanvasCamera", "setCameraPosition", [cameraPosition]);
    };

    CanvasCamera.prototype.doOrientationChange = function() {
        console.log('doOrientationChange');
        switch(window.orientation)
        {
            case -90:
            case 90:
                this._orientation = 'landscape';
                break;
            default:
                this._orientation = 'portrait';
                break;
        }
        console.log('window.innerWidth'+window.innerWidth);
        console.log('window.innerHeight'+window.innerHeight);

        //var windowWidth = window.innerWidth;
        //var windowHeight = window.innerHeight;

        var windowWidth = 200;
        var windowHeight = 200;

        var pixelRatio = window.devicePixelRatio || 1; /// get pixel ratio of device

        this._obj.width = windowWidth;// * pixelRatio;   /// resolution of canvas
        this._obj.height = windowHeight;// * pixelRatio;
        console.log('this._obj.width'+this._obj.width);

        this._obj.style.width = windowWidth + 'px';   /// CSS size of canvas
        this._obj.style.height = windowHeight + 'px';
        console.log('this._obj.style.width'+this._obj.style.width);

        this._x = 0;
        this._y = 0;
        this._width = windowWidth;
        this._height = windowHeight;
        console.log('this._width'+this._width+" this._height"+this._height);
    };

    CanvasCamera.prototype.takePicture = function(onsuccess) {
        cordova.exec(onsuccess, function(){}, "CanvasCamera", "captureImage", []);
    };

    var myplugin = new CanvasCamera();
    module.exports = myplugin;
});

var CanvasCamera = cordova.require("cordova/plugin/CanvasCamera");

var DestinationType = {
    DATA_URL : 0,
    FILE_URI : 1
};

var PictureSourceType = {
    PHOTOLIBRARY : 0,
    CAMERA : 1,
    SAVEDPHOTOALBUM : 2
};

var EncodingType = {
    JPEG : 0,
    PNG : 1
};

var CameraPosition = {
    BACK : 0,
    FRONT : 1
};

var CameraPosition = {
    BACK : 1,
    FRONT : 2
};

var FlashMode = {
    OFF : 0,
    ON : 1,
    AUTO : 2
};

CanvasCamera.DestinationType = DestinationType;
CanvasCamera.PictureSourceType = PictureSourceType;
CanvasCamera.EncodingType = EncodingType;
CanvasCamera.CameraPosition = CameraPosition;
CanvasCamera.FlashMode = FlashMode;

module.exports = CanvasCamera;
<|endoftext|>


<commit_before>'use strict';

var SessionModel = require('../models/session-model');

/**
 * API endpoints to read from the database and inject new data
 */

module.exports = function(app, jwtAuth) {

  var api = '/api/0_0_1/data';

  /**
   * Create single new data event
   */

  app.post(api, function(req, res) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    console.log('POST recorded: ' + JSON.stringify(req.body));
    var newEvent = new SessionModel(req.body);
    newEvent.save(function(err, dbResponse) {
      console.log(dbResponse);
      if (err) return res.status(500).json(err);
      return res.status(200).json(dbResponse);
    });
  });

  /**
   * Read all data (authenticated)
   */

  app.get(api, jwtAuth, function(req, res) {
    SessionModel.find({}, function(err, dbResponse) {
      if (err) return res.status(500).json(err);
      return res.status(200).json(dbResponse);
    });
  });

  /**
   * Update single piece of data
   */

  app.put(api + '/:id', function(req, res) {
    var data = req.body;
    delete data._id;
    SessionModel.findOneAndUpdate({ '_id': req.params.id }, data, function(err, dbResponse) {
      if (err) {
        return res.status(500).json(err);
      }
      return res.status(202).json(dbResponse);
    });
  });

  /**
   * Delete single piece of data
   */

  app.delete(api + '/delete/:id', function(req, res) {
    SessionModel.remove({ '_id': req.params.id }, function(err) {
      if (err) {
        return res.status(500).json(err);
      }
      return res.status(200).json({
        'message': 'deleted'
      });
    });
  });

  /**
   * For development only: delete all data!!1111
   */

  app.delete(api + '/deleteAll', function(req, res) {
    SessionModel.remove({}, function(err) {
      if (err) {
        return res.status(500).json(err);
      }
      return res.status(200).json({
        'message': 'deleted'
      });
    });
  });

};<commit_msg>remove custom headers in data post route<commit_after>'use strict';

var SessionModel = require('../models/session-model');

/**
 * API endpoints to read from the database and inject new data
 */

module.exports = function(app, jwtAuth) {

  var api = '/api/0_0_1/data';

  /**
   * Create single new data event
   */

  app.post(api, function(req, res) {

    // res.header('Access-Control-Allow-Origin', '*');
    // res.header('Access-Control-Allow-Credentials', true);
    // res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    // res.header('Access-Control-Allow-Headers', 'Content-Type');

    console.log('POST recorded: ' + JSON.stringify(req.body));

    // var newEvent = new SessionModel(req.body);
    // newEvent.save(function(err, dbResponse) {
    //   console.log(dbResponse);
    //   if (err) return res.status(500).json(err);
    //   return res.status(200).json(dbResponse);
    // });
  });

  /**
   * Read all data (authenticated)
   */

  app.get(api, jwtAuth, function(req, res) {
    SessionModel.find({}, function(err, dbResponse) {
      if (err) return res.status(500).json(err);
      return res.status(200).json(dbResponse);
    });
  });

  /**
   * Update single piece of data
   */

  app.put(api + '/:id', function(req, res) {
    var data = req.body;
    delete data._id;
    SessionModel.findOneAndUpdate({ '_id': req.params.id }, data, function(err, dbResponse) {
      if (err) {
        return res.status(500).json(err);
      }
      return res.status(202).json(dbResponse);
    });
  });

  /**
   * Delete single piece of data
   */

  app.delete(api + '/delete/:id', function(req, res) {
    SessionModel.remove({ '_id': req.params.id }, function(err) {
      if (err) {
        return res.status(500).json(err);
      }
      return res.status(200).json({
        'message': 'deleted'
      });
    });
  });

  /**
   * For development only: delete all data!!1111
   */

  app.delete(api + '/deleteAll', function(req, res) {
    SessionModel.remove({}, function(err) {
      if (err) {
        return res.status(500).json(err);
      }
      return res.status(200).json({
        'message': 'deleted'
      });
    });
  });

};<|endoftext|>