<commit_before>'use strict';

const assert = require('chai').assert
const Email = require('../')

describe('Email', () => {
  describe('#compileTemplate', () => {
    it('should build html given template data', () => {
      const email = new Email()
      const source = `<p>Hi, {{ name }}!</p>`
      const templateData = { name: 'Foo' }
      const result = email.compileTemplate(source, templateData)
      const expected = `<p>Hi, Foo!</p>`

      assert.equal(result, expected)
    })
  })

  describe('#compileInky', () => {
    it('should generate valid html', () => {
      const email = new Email()
      const source = `<button href="#" class="myClass">Button</button>`
      const result = email.compileInky(source)
      const expected = `<table class="button myClass"><tr><td><table><tr><td><a href="#">Button</a></td></tr></table></td></tr></table>`

      assert.equal(result, expected)
    })
  })

  describe('#compileSass', () => {
    it('should compile sass to css')
  })

  describe('#inlineCss', () => {
    it('should inline css', () => {
      const email = new Email()
      const source = `<style>p { color: red; }</style><div><p>content</p>`
      const result = email.inlineCss(source)
      const expected = `<div><p style="color: red;">content</p></div>`

      assert.equal(result, expected)
    })
  })

  describe('#minifyHtml', () => {
    it('should minify html', () => {
      const email = new Email()
      const source = `
  hello

world
`
      const result = email.minifyHtml(source)

      assert.equal(result, '
hello

world
')
    })
  })
})
<commit_msg>Add test placeholders for build, getTemplate, and compileSass<commit_after>'use strict';

const assert = require('chai').assert
const Email = require('../')

describe('Email', () => {
  describe('#build', () => {
    it('should be well tested')
  })

  describe('#getTemplate', () => {
    it('should be well tested')
  })

  describe('#compileTemplate', () => {
    it('should build html given template data', () => {
      const email = new Email()
      const source = `<p>Hi, {{ name }}!</p>`
      const templateData = { name: 'Foo' }
      const result = email.compileTemplate(source, templateData)
      const expected = `<p>Hi, Foo!</p>`

      assert.equal(result, expected)
    })
  })

  describe('#compileInky', () => {
    it('should generate valid html', () => {
      const email = new Email()
      const source = `<button href="#" class="myClass">Button</button>`
      const result = email.compileInky(source)
      const expected = `<table class="button myClass"><tr><td><table><tr><td><a href="#">Button</a></td></tr></table></td></tr></table>`

      assert.equal(result, expected)
    })
  })

  describe('#compileSass', () => {
    it('should compile sass to css')
  })

  describe('#inlineCss', () => {
    it('should inline css', () => {
      const email = new Email()
      const source = `<style>p { color: red; }</style><div><p>content</p>`
      const result = email.inlineCss(source)
      const expected = `<div><p style="color: red;">content</p></div>`

      assert.equal(result, expected)
    })
  })

  describe('#minifyHtml', () => {
    it('should minify html', () => {
      const email = new Email()
      const source = `
  hello

world
`
      const result = email.minifyHtml(source)

      assert.equal(result, '
hello

world
')
    })
  })
})
<|endoftext|>


<commit_before>'use strict'

var fs = require('fs')
var test = require('tape')
var postcss = require('postcss')
var shorthandExpand = require('..')

test('postcss-shorthand-expand', function (t) {
  t.plan(1)

  testFixture(t, 'input.css', 'output.css')
})

function fixture (name) {
    return fs.readFileSync('test/fixtures/' + name, 'utf8')
}

function testFixture (t, input, output) {
    t.equal(
      postcss([ shorthandExpand() ])
        .process(fixture(input)).css,
      fixture(output)
    )
}
<commit_msg>Fix formatting<commit_after>'use strict'

var fs = require('fs')
var test = require('tape')
var postcss = require('postcss')
var shorthandExpand = require('..')

test('postcss-shorthand-expand', function (t) {
  t.plan(1)

  testFixture(t, 'input.css', 'output.css')
})

function fixture (name) {
  return fs.readFileSync('test/fixtures/' + name, 'utf8')
}

function testFixture (t, input, output) {
  t.equal(
    postcss([ shorthandExpand() ])
      .process(fixture(input)).css,
    fixture(output)
  )
}
<|endoftext|>


<commit_before>/*jshint node:true, strict:false, onevar:false*/

if (!(typeof window !== 'undefined' && window.navigator && window.document)) { // Test if we are at command line
    var fs           = require('fs');
    var cp           = require('child_process');
    var createServer = require('http-server').createServer;

    // Start an HTTP Server to serve the files
    // This is needed because some tests fail intentionally in the file protocol

    var server = createServer({ root: __dirname + '/../' });
    server.listen(8081, '0.0.0.0', function () {
        var phantomjsBin = __dirname + '/../node_modules/.bin/phantomjs';
        var command = phantomjsBin + ' ' + __dirname + '/../node_modules/mocha-phantomjs/lib/mocha-phantomjs.coffee ' + 'http://localhost:8081/test/tester.html';
        var tests;

        fs.stat(phantomjsBin, function (error) {
            if (error) {
                phantomjsBin = 'phantomjs';
            }

            if (process.platform === 'win32') {
                tests = cp.spawn('cmd', ['/s', '/c', command], { customFds: [0, 1, 2] });
            } else {
                tests = cp.spawn('sh', ['-c', command], { customFds: [0, 1, 2] });
            }
            tests.on('exit', function (code) {
                process.exit(code ? 1 : 0);
            });
        });
    });

} else {
    var paths = {
        'amd-utils': '../components/amd-utils/src',
        'dejavu': '../components/dejavu/dist/amd/strict',
        'events-emitter': '../components/events-emitter/src',
        'base-adapter': '../components/base-adapter/src/adapters/jquery',
        'address': '../components/address/src',
        'dom-responder':  '../components/dom-responder/src',
        'jquery': '../node_modules/base-adapter-libs/jquery/jquery',
        'has': '../components/has/has',

        'app-config': './config',

        // Services
        'services/broadcaster': '../src/core/Broadcaster/BroadcasterFactory',
        'services/address': '../src/core/Address/AddressFactory',
        'services/state': '../src/core/StateRegistry/StateRegistryFactory'
    },
        map = {
            '*': {
                'base-adapter/src': '../components/base-adapter/src'
            }
        },
        packages = [
            {
                name: 'spoon',
                location: '../src'
            }
        ];

    require({
        baseUrl: './',
        paths: paths,
        map: map,
        packages: packages,
        waitSeconds: (window.location.protocol === 'file:' || window.location.href.indexOf('://localhost') !== -1) ? 5 : 45, // Fail early locally
        urlArgs: 'bust=' + (+new Date())
    });

    define(['base-adapter/dom/Utilities', 'has'], function (Utilities, has) {

        has.add('debug', !window.mochaPhantomJS && !!window.console && !!console.info && !!console.log);

        Utilities.ready(function () {
            require(['specs/example'], function () {
                if (window.mochaPhantomJS) {
                    mochaPhantomJS.run();
                } else {
                    mocha.run();
                }
            });
        });
    });
}<commit_msg>Update test.js.<commit_after>/*jshint strict:false, node:true, onevar:false*/

// If we are at node then we use phantomjs + mocha-phantomjs
if (!(typeof window !== 'undefined' && window.navigator && window.document)) {
    var fs           = require('fs');
    var cp           = require('child_process');
    var createServer = require('http-server').createServer;

    // Start an HTTP Server to serve the files
    // This is needed because some tests fail intentionally in the file protocol
    var server = createServer({ root: __dirname + '/../' });
    server.listen(8081, '0.0.0.0', function () {
        var phantomjsBin = __dirname + '/../node_modules/.bin/phantomjs';
        var command = phantomjsBin + ' ' + __dirname + '/../node_modules/mocha-phantomjs/lib/mocha-phantomjs.coffee ' + 'http://localhost:8081/test/tester.html';
        var tests;

        fs.stat(phantomjsBin, function (error) {
            if (error) {
                phantomjsBin = 'phantomjs';
            }

            if (process.platform === 'win32') {
                tests = cp.spawn('cmd', ['/s', '/c', command], { customFds: [0, 1, 2] });
            } else {
                tests = cp.spawn('sh', ['-c', command], { customFds: [0, 1, 2] });
            }
            tests.on('exit', function (code) {
                process.exit(code ? 1 : 0);
            });
        });
    });

} else {
    var paths = {
        'amd-utils': '../components/amd-utils/src',
        'dejavu': '../components/dejavu/dist/amd/strict',
        'events-emitter': '../components/events-emitter/src',
        'base-adapter': '../components/base-adapter/src/adapters/jquery',
        'address': '../components/address/src',
        'dom-responder':  '../components/dom-responder/src',
        'jquery': '../node_modules/base-adapter-libs/jquery/jquery',
        'has': '../components/has/has',

        'app-config': './config',

        // Services
        'services/broadcaster': '../src/core/Broadcaster/BroadcasterFactory',
        'services/address': '../src/core/Address/AddressFactory',
        'services/state': '../src/core/StateRegistry/StateRegistryFactory'
    },
        map = {
            '*': {
                'base-adapter/src': '../components/base-adapter/src'
            }
        },
        packages = [
            {
                name: 'spoon',
                location: '../src'
            }
        ];

    require({
        baseUrl: './',
        paths: paths,
        map: map,
        packages: packages,
        waitSeconds: (window.location.protocol === 'file:' || window.location.href.indexOf('://localhost') !== -1) ? 5 : 45, // Fail early locally
        urlArgs: 'bust=' + (+new Date())
    });

    define(['base-adapter/dom/Utilities', 'has'], function (Utilities, has) {

        has.add('debug', !window.mochaPhantomJS && !!window.console && !!console.info && !!console.log);

        Utilities.ready(function () {
            require(['specs/example'], function () {
                if (window.mochaPhantomJS) {
                    mochaPhantomJS.run();
                } else {
                    mocha.run();
                }
            });
        });
    });
}<|endoftext|>


<commit_before>(function(){

angular.module('crowdy')
 .controller("tagTaskController", ['$http', '$sce', '$httpParamSerializerJQLike', '$log', '$modal', '$scope', '$rootScope', '$routeParams',
         function($http, $sce, $httpParamSerializerJQLike, $log, $modal, $scope, $rootScope, $routeParams) {

    var BACKEND_SERVER = "."; // e.g. http://localhost:3000
    // Set Item template
    $scope.include = "/templates/tagging/"+ $routeParams.condition +"-index.html";
    $scope.forms = {};

    // Params
    $scope.condition = $routeParams.condition;
    if ($scope.condition === 'fast'){
        var phases = ['instructions', 'tasks', 'feedback', 'submit'];
        $scope.phase = phases.shift();
    };

    $scope.preview = ($routeParams.assignmentId === 'ASSIGNMENT_ID_NOT_AVAILABLE' );
    $scope.formSubmitTo = $sce.trustAsResourceUrl($routeParams.turkSubmitTo + "/mturk/externalSubmit");
    $scope.assignmentId = $routeParams.assignmentId;

    $rootScope.debug = $routeParams.debug;

    $scope.type = "tagging";
    $scope.taskset = {};
    $scope.taskset.tasks = []; // Initialize empty, set when it's available

    //Modal
    $scope.openModal = function (opts) {
      $modal.open({
        animation: true,
        templateUrl: 'templates/modal.html',
        controller: 'ModalInstanceCtrl',
        backdrop: 'static',
        size: 'lg',
        resolve: {
          opts: function () {
          return opts;
          }
        }
      });
    };

    $scope.toggleAnimation = function () {
      $scope.animationsEnabled = !$scope.animationsEnabled;
    };

    var postResultsToAmazon = function(results, errors){
        $scope.hiddenErrors = errors;
        // Add an action to the main form.
        // It couldn't be there before because of interference with our submit method.
        // MTurk requires a post from the client, though.
        angular.element("#turkHiddenForm").submit();
        return;
    };
    // Go to next phase in fast condition
    $scope.nextPhase = function() {
        if (phases.length === 0) {
            $log.error("Something went wrong: finished all phases and tried to keep going.");
            return;
        }
        $log.log("Switched phase from "+$scope.phase+" to " + phases[0])
        $scope.phase = phases.shift();
    };

    // Add task to end of tasks. Meant for Fast condition
    $scope.pushStagedTask = function(){
        // Validate condition
        if ($scope.condition !== 'fast') {
            $log.error("pushing staged task is meant for fast condition.");
        };

        // Check form
        if ($scope.forms.turkForm.$valid){
            // Showing checking without submit window
            $scope.forms.turkForm.check = true;
        };

        // Turn off error/warning and push next item
        $scope.forms.turkForm.check = false;
        var task = $scope.stagingTasks.shift();
        $scope.taskset.tasks.push(task);
    };

    // Construct JSON callback
    var params = {
      callback: "JSON_CALLBACK",
      user: $scope.preview ? "PREVIEWUSER" : $routeParams.workerId,
      taskset_id:$scope.preview ? "TEST" : $routeParams.assignmentId,
      hit_id: $routeParams.hit_id,
      assignment_id: $routeParams.assignment_id,
      lock: !($scope.preview)
    };

    var endpoint;
    if ($rootScope.debug) {
        endpoint = 'data/debug-image-hit.json';
       } else {
        endpoint = BACKEND_SERVER + "/hit";
       }

    // LOAD TASK
    $http.jsonp(endpoint, {params:params})
     .success(function(data){
        if (data.status && data.status===500){
            $rootScope.error = true;
            $scope.openModal({
                show: { ok: false},
                title: "Error",
                message: data.message
              });
            return;
        }

        if (data.taskset.tasks.length === 0) {
          $rootScope.error = "No tasks";
          $scope.openModal({
            show: { ok: false},
            title: "Out of tasks :(",
            message: "Sorry, we ran out of tasks that are available at the moment.
We're really sorry about that, we know it sucks."
          });
        }

        // Set taskset for Crowdy
        $scope.taskset = data.taskset;
        if ($scope.condition === 'fast') {
            // Moves items to a staging object if in
            // Fast condition. They'll be re-added as the
            // user completes more tasks.
            $scope.stagingTasks = data.taskset.tasks;
            $scope.taskset.tasks = [$scope.stagingTasks.shift()];
        } else if ($scope.condition === 'basic') {
            //do something
        } else {
            console.error("This condition is not supported.");
        }

    }).error(function(err){
        $rootScope.error = true;
        var msg, title;
        if ('message' in err){
            title = "Error";
            msg = err.message;
        } else {
            title = "Unknown error.";
            msg = "Sorry, an unknown error occurred. We don't know what happened";
        }
        $scope.openModal({
            show: {ok:false},
            title: title,
            message: msg
        });
    });

    // SAVE TASK
    $scope.submitForm = function() {
        $log.log($scope);
        if ($scope.forms.turkForm.$valid) {
          // Submit form toServer
          $http.post(BACKEND_SERVER+"/save/hit", $scope.taskset)
            .success(function(res){
                postResultsToAmazon(res, null);
            })
            .error(function(err){
                // Still send results to amazon in case of error
                $scope.taskset.err = err;
                postResultsToAmazon($scope.taskset, err);
            });
          // Submit form back to Amazon
        } else {
          // Reload masonry, in case any errors pop up
          $rootScope.$broadcast("masonry.reload");
        }
    };

  }]); //END CONTROLLER
// END ANONYMOUS FUNCTION
})();
<commit_msg>Push new tasks on Fast enter<commit_after>(function(){

angular.module('crowdy')
 .controller("tagTaskController", ['$http', '$sce', '$httpParamSerializerJQLike', '$log', '$modal', '$scope', '$rootScope', '$routeParams',
         function($http, $sce, $httpParamSerializerJQLike, $log, $modal, $scope, $rootScope, $routeParams) {

    var BACKEND_SERVER = "."; // e.g. http://localhost:3000
    // Set Item template
    $scope.include = "/templates/tagging/"+ $routeParams.condition +"-index.html";
    $scope.forms = {};

    // Params
    $scope.condition = $routeParams.condition;
    if ($scope.condition === 'fast'){
        var phases = ['instructions', 'tasks', 'feedback', 'submit'];
        $scope.phase = phases.shift();
    }

    $scope.pressEnter = function($event){
        if($event.keyCode !== 13) {
            return;
        } else {
            $log.log("Enter pressed. Pushing next task, if valid.");
            $log.log($scope);
            $scope.pushStagedTask();
        }
    };

    $scope.preview = ($routeParams.assignmentId === 'ASSIGNMENT_ID_NOT_AVAILABLE' );
    $scope.formSubmitTo = $sce.trustAsResourceUrl($routeParams.turkSubmitTo + "/mturk/externalSubmit");
    $scope.assignmentId = $routeParams.assignmentId;

    $rootScope.debug = $routeParams.debug;

    $scope.type = "tagging";
    $scope.taskset = {};
    $scope.taskset.tasks = []; // Initialize empty, set when it's available

    //Modal
    $scope.openModal = function (opts) {
      $modal.open({
        animation: true,
        templateUrl: 'templates/modal.html',
        controller: 'ModalInstanceCtrl',
        backdrop: 'static',
        size: 'lg',
        resolve: {
          opts: function () {
          return opts;
          }
        }
      });
    };

    $scope.toggleAnimation = function () {
      $scope.animationsEnabled = !$scope.animationsEnabled;
    };

    var postResultsToAmazon = function(results, errors){
        $scope.hiddenErrors = errors;
        // Add an action to the main form.
        // It couldn't be there before because of interference with our submit method.
        // MTurk requires a post from the client, though.
        angular.element("#turkHiddenForm").submit();
        return;
    };
    // Go to next phase in fast condition
    $scope.nextPhase = function() {
        if (phases.length === 0) {
            $log.error("Something went wrong: finished all phases and tried to keep going.");
            return;
        }
        $log.log("Switched phase from "+$scope.phase+" to " + phases[0]);
        $scope.phase = phases.shift();
    };

    // Add task to end of tasks. Meant for Fast condition
    $scope.pushStagedTask = function(){
        // Validate condition
        if ($scope.condition !== 'fast') {
            $log.error("pushing staged task is meant for fast condition.");
        }

        // Check form
        if (!$scope.forms.turkForm.$valid){
            // Showing checking without submit window
            $scope.forms.turkForm.check = true;
            return;
        }

        // If no more tasks left, then we push to the next phase
        if ($scope.stagingTasks.length === 0){
            $log.warn("No more tasks left!");
            $scope.nextPhase();
        }

        // Turn off error/warning and push next item
        $scope.forms.turkForm.check = false;
        var task = $scope.stagingTasks.shift();
        $scope.taskset.tasks.push(task);
    };

    // Construct JSON callback
    var params = {
      callback: "JSON_CALLBACK",
      user: $scope.preview ? "PREVIEWUSER" : $routeParams.workerId,
      taskset_id:$scope.preview ? "TEST" : $routeParams.assignmentId,
      hit_id: $routeParams.hit_id,
      assignment_id: $routeParams.assignmentId,
      lock: !($scope.preview)
    };

    var endpoint;
    if ($rootScope.debug) {
        endpoint = 'data/debug-image-hit.json';
       } else {
        endpoint = BACKEND_SERVER + "/hit";
       }

    // LOAD TASK
    $http.jsonp(endpoint, {params:params})
     .success(function(data){
        if (data.status && data.status===500){
            $rootScope.error = true;
            $scope.openModal({
                show: { ok: false},
                title: "Error",
                message: data.message
              });
            return;
        }

        if (data.taskset.tasks.length === 0) {
          $rootScope.error = "No tasks";
          $scope.openModal({
            show: { ok: false},
            title: "Out of tasks :(",
            message: "Sorry, we ran out of tasks that are available at the moment.
We're really sorry about that, we know it sucks."
          });
        }

        // Set taskset for Crowdy
        $scope.taskset = data.taskset;
        if ($scope.condition === 'fast') {
            // Moves items to a staging object if in
            // Fast condition. They'll be re-added as the
            // user completes more tasks.
            $scope.stagingTasks = data.taskset.tasks;
            $scope.taskset.tasks = [$scope.stagingTasks.shift()];
        } else if ($scope.condition === 'basic') {
            //do something
        } else {
            console.error("This condition is not supported.");
        }

    }).error(function(err){
        $rootScope.error = true;
        var msg, title;
        if ('message' in err){
            title = "Error";
            msg = err.message;
        } else {
            title = "Unknown error.";
            msg = "Sorry, an unknown error occurred. We don't know what happened";
        }
        $scope.openModal({
            show: {ok:false},
            title: title,
            message: msg
        });
    });

    // SAVE TASK
    $scope.submitForm = function() {
        // Don't submit if fast interface, unless the task phase is done
        if ($scope.condition === 'fast' && ($scope.phase !== 'feedback' && $scope.phase !== 'submit')){
            // Not ready to submit yet.
            return;
        }

        if ($scope.forms.turkForm.$valid) {
          // Submit form toServer
          $http.post(BACKEND_SERVER+"/save/hit", $scope.taskset)
            .success(function(res){
                postResultsToAmazon(res, null);
            })
            .error(function(err){
                // Still send results to amazon in case of error
                $scope.taskset.err = err;
                postResultsToAmazon($scope.taskset, err);
            });
          // Submit form back to Amazon
        } else {
          // Reload masonry, in case any errors pop up
          $rootScope.$broadcast("masonry.reload");
        }
    };

  }]); //END CONTROLLER
// END ANONYMOUS FUNCTION
})();
<|endoftext|>


<commit_before><commit_msg>data transform handler<commit_after><|endoftext|>


<commit_before>(function (context) {
  "use strict";

  var TheGraph = context.TheGraph;

  // Const
  var CURVE = TheGraph.nodeSize;

  // Edge view

  TheGraph.Edge = React.createClass({
    mixins: [
      TheGraph.mixins.Tooltip
    ],
    componentWillMount: function() {
    },
    componentDidMount: function () {
      var domNode = this.getDOMNode();

      // Dragging
      domNode.addEventListener("trackstart", this.dontPan);

      if (this.props.onEdgeSelection) {
        // Needs to be click (not tap) to get event.shiftKey
        domNode.addEventListener("tap", this.onEdgeSelection);
      }

      // Context menu
      if (this.props.showContext) {
        domNode.addEventListener("contextmenu", this.showContext);
        domNode.addEventListener("hold", this.showContext);
      }
    },
    dontPan: function (event) {
      // Don't drag under menu
      if (this.props.app.menuShown) {
        event.stopPropagation();
      }
    },
    onEdgeSelection: function (event) {
      // Don't click app
      event.stopPropagation();

      var toggle = (TheGraph.metaKeyPressed || event.pointerType==="touch");
      this.props.onEdgeSelection(this.props.key, this.props.edge, toggle);
    },
    showContext: function (event) {
      // Don't show native context menu
      event.preventDefault();

      var x = event.clientX;
      var y = event.clientY;

      // App.showContext
      this.props.showContext({
        element: this,
        type: (this.props.export ? (this.props.isIn ? "graphInport" : "graphOutport") : "edge"),
        x: x,
        y: y,
        graph: this.props.graph,
        itemKey: (this.props.export ? this.props.exportKey : null),
        item: (this.props.export ? this.props.export : this.props.edge)
      });

    },
    getContext: function (menu, options, hide) {
      return TheGraph.Menu({
        menu: menu,
        options: options,
        triggerHideContext: hide,
        label: this.props.label,
        iconColor: this.props.route
      });
    },
    shouldComponentUpdate: function (nextProps, nextState) {
      // Only rerender if changed
      return (
        nextProps.sX !== this.props.sX ||
        nextProps.sY !== this.props.sY ||
        nextProps.tX !== this.props.tX ||
        nextProps.tY !== this.props.tY ||
        nextProps.selected !== this.props.selected ||
        nextProps.route !== this.props.route
      );
    },
    getTooltipTrigger: function () {
      return this.refs.touch.getDOMNode();
    },
    shouldShowTooltip: function () {
      return true;
    },
    componentDidUpdate: function (prevProps, prevState) {
      // HACK to change SVG class https://github.com/facebook/react/issues/1139
      var groupClass = "edge"+(this.props.selected ? " selected" : "");
      this.getDOMNode().setAttribute("class", groupClass);
      var fgClass = "edge-fg stroke route"+this.props.route;
      this.refs.route.getDOMNode().setAttribute("class", fgClass);
    },
    render: function () {
      var sourceX = this.props.sX;
      var sourceY = this.props.sY;
      var targetX = this.props.tX;
      var targetY = this.props.tY;

      // Organic / curved edge
      var c1X, c1Y, c2X, c2Y;
      if (targetX-5 < sourceX) {
        if (Math.abs(targetY-sourceY) < TheGraph.nodeSize/2) {
          // Loopback
          c1X = sourceX + CURVE;
          c1Y = sourceY - CURVE;
          c2X = targetX - CURVE;
          c2Y = targetY - CURVE;
        } else {
          // Stick out some
          c1X = sourceX + CURVE;
          c1Y = sourceY + (targetY > sourceY ? CURVE : -CURVE);
          c2X = targetX - CURVE;
          c2Y = targetY + (targetY > sourceY ? -CURVE : CURVE);
        }
      } else {
        // Controls halfway between
        c1X = sourceX + (targetX - sourceX)/2;
        c1Y = sourceY;
        c2X = c1X;
        c2Y = targetY;
      }

      var path = [
        "M",
        sourceX, sourceY,
        "C",
        c1X, c1Y,
        c2X, c2Y,
        targetX, targetY
      ];
      // Make SVG path
      path = path.join(" ");

      return (
        React.DOM.g(
          {
            className: "edge",  // See componentDidUpdate
            title: this.props.label
          },
          React.DOM.path({
            className: "edge-bg",
            d: path
          }),
          React.DOM.path({
            ref: "route",
            className: "edge-fg stroke route"+this.props.route,  // See componentDidUpdate
            d: path
          }),
          React.DOM.path({
            className: "edge-touch",
            ref: "touch",
            d: path
          })
        )
      );
    }
  });

})(this);<commit_msg>point on curve function for edge animation #72<commit_after>(function (context) {
  "use strict";

  var TheGraph = context.TheGraph;

  // Const
  var CURVE = TheGraph.nodeSize;

  // Point along cubic bezier curve
  // See http://en.wikipedia.org/wiki/File:Bezier_3_big.gif
  var findPointOnCubicBezier = function (p, sx, sy, c1x, c1y, c2x, c2y, ex, ey) {
    // p is percentage from 0 to 1
    var op = 1 - t;
    // 3 green points between 4 points that define curve
    var g1x = sx * p + c1x * op;
    var g1y = sy * p + c1y * op;
    var g2x = c1x * p + c2x * op;
    var g2y = c1y * p + c2y * op;
    var g3x = c2x * p + ex * op;
    var g3y = c2y * p + ey * op;
    // 2 blue points between green points
    var b1x = g1x * p + g2x * op;
    var b1y = g1y * p + g2y * op;
    var b2x = g2x * p + g3x * op;
    var b2y = g2y * p + g3y * op;
    // Point on the curve between blue points
    var x = b1x * p + b2x * op;
    var y = b1y * p + b2y * op;
    return [x, y];
  };

  // Edge view

  TheGraph.Edge = React.createClass({
    mixins: [
      TheGraph.mixins.Tooltip
    ],
    componentWillMount: function() {
    },
    componentDidMount: function () {
      var domNode = this.getDOMNode();

      // Dragging
      domNode.addEventListener("trackstart", this.dontPan);

      if (this.props.onEdgeSelection) {
        // Needs to be click (not tap) to get event.shiftKey
        domNode.addEventListener("tap", this.onEdgeSelection);
      }

      // Context menu
      if (this.props.showContext) {
        domNode.addEventListener("contextmenu", this.showContext);
        domNode.addEventListener("hold", this.showContext);
      }
    },
    dontPan: function (event) {
      // Don't drag under menu
      if (this.props.app.menuShown) {
        event.stopPropagation();
      }
    },
    onEdgeSelection: function (event) {
      // Don't click app
      event.stopPropagation();

      var toggle = (TheGraph.metaKeyPressed || event.pointerType==="touch");
      this.props.onEdgeSelection(this.props.key, this.props.edge, toggle);
    },
    showContext: function (event) {
      // Don't show native context menu
      event.preventDefault();

      var x = event.clientX;
      var y = event.clientY;

      // App.showContext
      this.props.showContext({
        element: this,
        type: (this.props.export ? (this.props.isIn ? "graphInport" : "graphOutport") : "edge"),
        x: x,
        y: y,
        graph: this.props.graph,
        itemKey: (this.props.export ? this.props.exportKey : null),
        item: (this.props.export ? this.props.export : this.props.edge)
      });

    },
    getContext: function (menu, options, hide) {
      return TheGraph.Menu({
        menu: menu,
        options: options,
        triggerHideContext: hide,
        label: this.props.label,
        iconColor: this.props.route
      });
    },
    shouldComponentUpdate: function (nextProps, nextState) {
      // Only rerender if changed
      return (
        nextProps.sX !== this.props.sX ||
        nextProps.sY !== this.props.sY ||
        nextProps.tX !== this.props.tX ||
        nextProps.tY !== this.props.tY ||
        nextProps.selected !== this.props.selected ||
        nextProps.route !== this.props.route
      );
    },
    getTooltipTrigger: function () {
      return this.refs.touch.getDOMNode();
    },
    shouldShowTooltip: function () {
      return true;
    },
    componentDidUpdate: function (prevProps, prevState) {
      // HACK to change SVG class https://github.com/facebook/react/issues/1139
      var groupClass = "edge"+(this.props.selected ? " selected" : "");
      this.getDOMNode().setAttribute("class", groupClass);
      var fgClass = "edge-fg stroke route"+this.props.route;
      this.refs.route.getDOMNode().setAttribute("class", fgClass);
    },
    render: function () {
      var sourceX = this.props.sX;
      var sourceY = this.props.sY;
      var targetX = this.props.tX;
      var targetY = this.props.tY;

      // Organic / curved edge
      var c1X, c1Y, c2X, c2Y;
      if (targetX-5 < sourceX) {
        if (Math.abs(targetY-sourceY) < TheGraph.nodeSize/2) {
          // Loopback
          c1X = sourceX + CURVE;
          c1Y = sourceY - CURVE;
          c2X = targetX - CURVE;
          c2Y = targetY - CURVE;
        } else {
          // Stick out some
          c1X = sourceX + CURVE;
          c1Y = sourceY + (targetY > sourceY ? CURVE : -CURVE);
          c2X = targetX - CURVE;
          c2Y = targetY + (targetY > sourceY ? -CURVE : CURVE);
        }
      } else {
        // Controls halfway between
        c1X = sourceX + (targetX - sourceX)/2;
        c1Y = sourceY;
        c2X = c1X;
        c2Y = targetY;
      }

      var path = [
        "M",
        sourceX, sourceY,
        "C",
        c1X, c1Y,
        c2X, c2Y,
        targetX, targetY
      ];
      // Make SVG path
      path = path.join(" ");

      return (
        React.DOM.g(
          {
            className: "edge",  // See componentDidUpdate
            title: this.props.label
          },
          React.DOM.path({
            className: "edge-bg",
            d: path
          }),
          React.DOM.path({
            ref: "route",
            className: "edge-fg stroke route"+this.props.route,  // See componentDidUpdate
            d: path
          }),
          React.DOM.path({
            className: "edge-touch",
            ref: "touch",
            d: path
          })
        )
      );
    }
  });

})(this);<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2013-2014 CNRS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

<commit_msg>add exists getInfo remove update<commit_after>/*
The MIT License (MIT)

Copyright (c) 2013-2014 CNRS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

var async = require('async');
var commonFuncs = require('../lib/commonFuncs');

//check if a id_annotation exists
exports.exist = function(req, res, next) {
	Annotation.findById(req.params.id_annotation, function(error, annotation){
		if (error) res.status(400).json(error);
		else if (!annotation) res.status(400).json({message:"id_annotation don't exists"});
		else next();
	});
}

//retrieve a particular user (with id)
exports.getInfo = function(req, res){
	Annotation.findById(req.params.id_annotation, function(error, annotation){
		if (error) res.status(400).json({message:error});
    	else res.status(200).json(annotation);
	});
}

// retrieve all annotation
exports.getAll = function (req, res) {
	Annotation.find({}, function (error, annotations) {
    	if (error) res.status(400).json({error:"error", message:error});
    	if (annotations) res.status(200).json(annotations);
		else res.status(200).json([]);
	});
}

// remove a given annotation
exports.remove = function (req, res) {
	Annotation.remove({_id : req.params.id_annotation}, function (error, annotation) {
		if (!error && annotation == 1) res.status(200).json({message:"The annotation as been delete"});
		else res.status(400).json({message:error});
	});
}
//update information of a annotation
exports.update = function(req, res){
	var update = {};
	var history = {};
	var error=null;
	async.waterfall([
		function(callback) {
			if (req.body.fragment) {
				update.fragment = req.body.fragment;
				history.fragment = req.body.fragment;
			}
			if (req.body.data) {
				update.data = req.body.data;
				history.data = req.body.data;
			}
			Annotation.findById(req.params.id_annotation, function(error, annotation){
				update.history = annotation.history;
				update.history.push({date:new Date(), id_user:req.session.user._id, modification:history})
				callback(error, update);
			});
		},
		function(update, callback) {
			Annotation.findByIdAndUpdate(req.params.id_annotation, update, function (error, annotation) {
				if (error) res.status(400).json(error);
				else res.status(200).json(annotation);
			});
		},
	], function (error, trueOrFalse) {
		if (error) res.status(400).json({message:error});
	});
}

<|endoftext|>


<commit_before>/* globals UI */

var C = UI.Views.Connector;

class EditForm extends C.View {
  constructor(props) {
    super(props);
    this.state = {
      events: []
    };
    if (!props.connector) {
      this.state.mode = 'connect';
    }
  }
  connect() {
    this.props.onConnect();
  }
  render() {
    return (
      <C.Page default="setup" {...this.props}>
        <C.Panel name="Setup" slug="setup">
          <UI.FormElements.Button text={this.props.connectorInstance ? 'Reauthorize' : 'Connect'} type="large" onClick={()=>{
              return this.connect();
            }} />
        </C.Panel>
        {this.props.connectorInstance ? <C.Panel name="Events" slug="events">
        <C.PageHeader
          title="Check the boxes of the events you want to subscribe to."
          subTitle="Checking a box will automatically subscribe you to that event." />
          <C.CheckboxGrid
            items={this.props.connectorPrototype.events}
            checked={this.props.connectorInstance.events}
            onChange={this.props.onSubscribe} />
        </C.Panel> : <C.Panel name="Events" slug="events">
          <C.EventsGrid.Header
            title="Events are available once you've connected." />
        </C.Panel>}
      </C.Page>
    );
  }
}

export default EditForm;
global.EditForm = EditForm;
<commit_msg>events<commit_after>/* globals UI */

var C = UI.Views.Connector;

class EditForm extends C.View {
  constructor(props) {
    super(props);
    this.state = {
      events: []
    };
    if (!props.connector) {
      this.state.mode = 'connect';
    }
  }
  connect() {
    this.props.onConnect();
  }
  render() {
    return (
      <C.Page default="setup" {...this.props}>
        <C.Panel name="Setup" slug="setup">
          <UI.FormElements.Button text={this.props.connectorInstance ? 'Reauthorize' : 'Connect'} type="large" onClick={()=>{
              return this.connect();
            }} />
        </C.Panel>
        {this.props.connectorInstance ? <C.Panel name="Events" slug="events">
        <C.PageHeader
          title="Check the boxes of the events you want to subscribe to."
          subTitle="Checking a box will automatically subscribe you to that event." />
          <C.CheckboxGrid
            items={this.props.connectorInstance.events}
            checked={this.props.connectorInstance.subscribedEvents}
            onChange={this.props.onSubscribe} />
        </C.Panel> : <C.Panel name="Events" slug="events">
          <C.EventsGrid.Header
            title="Events are available once you've connected." />
        </C.Panel>}
      </C.Page>
    );
  }
}

export default EditForm;
global.EditForm = EditForm;
<|endoftext|>


<commit_before>"use strict"

const Koa = require('koa');
const Router = require('koa-router');
const request = require('supertest');
const session = require('../index.js');
const {Store} = session;

class CustomStore extends Store {
    constructor() {
        super();
        this.store = {};
        this.set_count = 0
    }

    async get(sid) {
        return this.store[sid];
    }

    async set(session, opts, ctx = {}) {
        this.set_count += 1
        // for test the ctx param
        if(ctx.test_id) return ctx.test_id

        if(!opts.sid) {
            opts.sid = this.getID(24);
        }
        this.store[opts.sid] = session;
        return opts.sid;
    }

    async destroy(sid) {
        delete this.store[sid];
    }
}

describe("koa-session2", () => {
    describe("when use default store", () => {
        let app = new Koa();
        let router = new Router();

        app.use(session({
            maxAge: 5000,
        }));

        router.get('/setSession', ctx => {
            ctx.session.user = "tom";
            ctx.body = ctx.session;
        })
        .get('/getSession', ctx => {
            ctx.body = ctx.session;
        })
        .get('/updateSession', ctx => {
            ctx.session.user = 'john';
            ctx.body = ctx.session;
        })
        .get('/clearSession', ctx => {
            ctx.session = null;
            ctx.body = 'ok';
        });

        app.use(router.routes());

        const server = app.listen();

        let cookie = '';

        /**
         * @desc It should work when use default session store
         */
        it("should work", done => {
            request(server)
            .get("/setSession")
            .expect(200, (err, res) => {
                if(!err) done();
                // store cookie
                cookie = res.header['set-cookie'][0];
            });
        });

        /**
         * @desc It should set cookies in response headers
         */
        it("should set cookies", done => {
            if(/koa:sess/.test(cookie)) done();
        });

        /**
         * @desc It should get the correct session value when use coockie
         */
        it("should get the correct session", done => {
            request(server)
            .get('/getSession')
            .set('cookie', cookie)
            .expect(200, (err, res) => {
                if(err) done(err);
                if(res.body.user == 'tom') done();
            });
        });

        /**
         * @desc It should work when update session value
         */
        it("should work when update session", done => {
            request(server)
            .get('/updateSession')
            .set('cookie', cookie)
            .expect(200, (err, res) => {
                if(err) done(err);
                if(res.body.user == 'john') done();
            });
        });

        /**
         * @desc It should work when session expired
         */
        it("should work when session expired", function(done) {
            this.timeout(8000);

            // request after session's maxAge(5000)
            setTimeout(() => {
                request(server)
                .get('/getSession')
                .set('cookie', cookie)
                .expect(200, (err, res) => {
                    if(typeof res.body.user == 'undefined') done();
                });
            }, 6000);
        });

        /**
         * @desc It should get different cookie when multiple clients access
         */
        it("should work when multiple clients access", done => {

            request(server)
            .get("/setSession")
            .end((err_1, res_1) => {
                let cookie_1 = res_1.header['set-cookie'];

                // when a new client without cookie access server
                // should set a new session and new cookie to the client
                // not overwrite the old

                request(server)
                .get("/setSession")
                .end((err_2, res_2) => {
                    let cookie_2 = res_2.header['set-cookie'];

                    if(cookie_1 != cookie_2) done();
                });
            });

        });

        // get new cookie id
        cookie = "koa:sess=" + Store.prototype.getID(24)

        /**
         * @desc It should work when request with an old or not exists cookie
         */
        it("set old sessionid should be work", done => {

            request(server)
            .get("/setSession")
            .set("cookie", cookie)
            .expect(200, (err, res) => {
                if(res.body.user == 'tom') done();
            });

        });

        it("should work when clear session by setting null value", done => {
            request(server)
            .get('/clearSession')
            .set('cookie', cookie)
            .expect(200, (err, res) => {
                // should set cookie to empty
                if(/koa:sess=;/.test(res.header['set-cookie'][0])) done();
            });
        });
    });

    describe("when use custom store", () => {
        const app = new Koa();
        const router = new Router();
        const store = new CustomStore();

        app.use(session({
            store,
        }));

        router.get('/set', ctx => {
            ctx.session.user = {name: "tom"};
            ctx.body = 'done';
        })
        .get('/change', ctx => {
            ctx.session.user = {name: "jim"};
            ctx.body = 'changed';
        })
        .get('/clear', ctx => {
            ctx.session = {};
            ctx.body = 'cleared';
        });

        app.use(router.routes());
        const server = app.listen();

        let cookie;

        /**
         * @desc It should work when use custom store
         */
        it("should work", done => {
            request(server)
            .get("/set")
            .expect(200, (err, res) => {
                if(!err) done();
                cookie = res.header['set-cookie'][0];
            });
        });

        /**
         * @desc It should destory old session when set an empty object
         */
        it("should work when set an empty object", done => {
            request(server)
            .get('/clear')
            .set('cookie', cookie)
            .expect(200, (err, res) => {
                if(err) done(err);

                let sid = cookie[0].split(';')[0].split('=')[1];
                if(typeof store.store[sid] === 'undefined') done();

            });
        });

        /**
         * @desc It should update the old session when set new one
         */
        it("should work when update old session", done => {

            request(server)
            .get("/set")
            .expect(200, (err, res) => {
                let cookie = res.header['set-cookie'];
                let sid = cookie[0].split(';')[0].split('=')[1];

                // change session to refresh
                request(server).get("/change")
                .set("Cookie", cookie)
                .expect(200, (err, res) => {
                    // the old session id should be updated
                    if(store.store[sid].user.name == 'jim') done();
                });
            });

        });
    });

    describe("when session cookie exists but is not in store", () => {
        let app = new Koa();
        let router = new Router();
        let store = new CustomStore();
        let cookie;

        app.use(session({
            store
        }));

        router.get("/set", ctx => {
          ctx.session.user = {name: "tom"};
          ctx.body = "done";
        });

        app.use(router.routes())

        const server = app.listen();

        /**
         * @desc It should work
         */
        it("should work", done => {

            request(server)
            .get("/set")
            .expect(200)
            .end((err, res) => {
                if (err) return done(err);
                done();

                // save cookie for next test
                cookie = res.header["set-cookie"];
                // clear the store
                for (let key in store.store) {
                  delete store.store[key];
                }
            });

        });

        /**
         * @desc It should work even if store cleared
         */
        it("should work even if store cleared", done => {

            request(server)
            .get("/set")
            .set("Cookie", cookie)
            .expect(200)
            .end((err, res) => {
                // cookie should reset when session is not found in store
                let sid = cookie[0].split(';')[0].split('=')[1];

                if (Object.keys(store.store).length === 1 &&
                    store.store[sid].user.name == 'tom') {
                  return done();
                }
                done(new Error("error resetting cookie"));
            });

        });
    });

    describe("when pass the context to the session store", () => {
        let app = new Koa();
        let router = new Router();
        let store = new CustomStore();

        app.use(session({
            store
        }));

        router.get("/set", ctx => {
            ctx.test_id = 'the_id_in_ctx'
            ctx.session.user = {name: "tom"};
            ctx.body = "done";
        });

        app.use(router.routes())

        const server = app.listen();

        /**
         * @desc It should work
         */
        it("should work", done => {

            request(server)
            .get("/set")
            .expect(200)
            .end((err, res) => {
                if (err) return done(err);

                // if the session id is the preset one
                if(res.header["set-cookie"][0].includes('the_id_in_ctx')) done()
            });

        });
    })

    describe("when refresh session", () => {
        let app = new Koa();
        let router = new Router();
        let store = new CustomStore();

        app.use(session({
            store,
            maxAge: 5000,
        }));

        router.get("/set", ctx => {
            ctx.session.user = {name: "tom"};
            ctx.body = "done";
        })
        .get("/refresh", ctx => {
            ctx.session.refresh()
            ctx.body = 'refreshed'
        })

        app.use(router.routes())

        const server = app.listen();

        /**
         * @desc It should work
         */
        it("should work", done => {

            // set a new session
            request(server)
            .get("/set")
            .expect(200, (err, res) => {
                let cookie = res.header['set-cookie'];

                // refresh session
                request(server).get("/refresh")
                .set("Cookie", cookie)
                .expect(200, (err, res) => {
                    // the set function should be called and the set_count should be 2
                    if(store.set_count == 2) done()
                });
            });

        });
    })

});
<commit_msg>fix: testing case after set a new cookie<commit_after>"use strict"

const Koa = require('koa');
const Router = require('koa-router');
const request = require('supertest');
const session = require('../index.js');
const {Store} = session;

class CustomStore extends Store {
    constructor() {
        super();
        this.store = {};
        this.set_count = 0
    }

    async get(sid) {
        return this.store[sid];
    }

    async set(session, opts, ctx = {}) {
        this.set_count += 1
        // for test the ctx param
        if(ctx.test_id) return ctx.test_id

        if(!opts.sid) {
            opts.sid = this.getID(24);
        }
        this.store[opts.sid] = session;
        return opts.sid;
    }

    async destroy(sid) {
        delete this.store[sid];
    }
}

describe("koa-session2", () => {
    describe("when use default store", () => {
        let app = new Koa();
        let router = new Router();

        app.use(session({
            maxAge: 5000,
        }));

        router.get('/setSession', ctx => {
            ctx.session.user = "tom";
            ctx.body = ctx.session;
        })
        .get('/getSession', ctx => {
            ctx.body = ctx.session;
        })
        .get('/updateSession', ctx => {
            ctx.session.user = 'john';
            ctx.body = ctx.session;
        })
        .get('/clearSession', ctx => {
            ctx.session = null;
            ctx.body = 'ok';
        });

        app.use(router.routes());

        const server = app.listen();

        let cookie = '';

        /**
         * @desc It should work when use default session store
         */
        it("should work", done => {
            request(server)
            .get("/setSession")
            .expect(200, (err, res) => {
                if(!err) done();
                // store cookie
                cookie = res.header['set-cookie'][0];
            });
        });

        /**
         * @desc It should set cookies in response headers
         */
        it("should set cookies", done => {
            if(/koa:sess/.test(cookie)) done();
        });

        /**
         * @desc It should get the correct session value when use coockie
         */
        it("should get the correct session", done => {
            request(server)
            .get('/getSession')
            .set('cookie', cookie)
            .expect(200, (err, res) => {
                if(err) done(err);
                if(res.body.user == 'tom') done();
            });
        });

        /**
         * @desc It should work when update session value
         */
        it("should work when update session", done => {
            request(server)
            .get('/updateSession')
            .set('cookie', cookie)
            .expect(200, (err, res) => {
                if(err) done(err);
                if(res.body.user == 'john') done();
            });
        });

        /**
         * @desc It should work when session expired
         */
        it("should work when session expired", function(done) {
            this.timeout(8000);

            // request after session's maxAge(5000)
            setTimeout(() => {
                request(server)
                .get('/getSession')
                .set('cookie', cookie)
                .expect(200, (err, res) => {
                    if(typeof res.body.user == 'undefined') done();
                });
            }, 6000);
        });

        /**
         * @desc It should get different cookie when multiple clients access
         */
        it("should work when multiple clients access", done => {

            request(server)
            .get("/setSession")
            .end((err_1, res_1) => {
                let cookie_1 = res_1.header['set-cookie'];

                // when a new client without cookie access server
                // should set a new session and new cookie to the client
                // not overwrite the old

                request(server)
                .get("/setSession")
                .end((err_2, res_2) => {
                    let cookie_2 = res_2.header['set-cookie'];

                    if(cookie_1 != cookie_2) done();
                });
            });

        });

        // get new cookie id
        cookie = "koa:sess=" + Store.prototype.getID(24)

        /**
         * @desc It should work when request with an old or not exists cookie
         */
        it("set old sessionid should be work", done => {

            request(server)
            .get("/setSession")
            .set("cookie", cookie)
            .expect(200, (err, res) => {
                if(res.body.user == 'tom') done();
            });

        });

        it("should work when clear session by setting null value", done => {
            request(server)
            .get('/clearSession')
            .set('cookie', cookie)
            .expect(200, (err, res) => {
                // should set cookie to empty
                if(/koa:sess=;/.test(res.header['set-cookie'][0])) done();
            });
        });
    });

    describe("when use custom store", () => {
        const app = new Koa();
        const router = new Router();
        const store = new CustomStore();

        app.use(session({
            store,
        }));

        router.get('/set', ctx => {
            ctx.session.user = {name: "tom"};
            ctx.body = 'done';
        })
        .get('/change', ctx => {
            ctx.session.user = {name: "jim"};
            ctx.body = 'changed';
        })
        .get('/clear', ctx => {
            ctx.session = {};
            ctx.body = 'cleared';
        });

        app.use(router.routes());
        const server = app.listen();

        let cookie;

        /**
         * @desc It should work when use custom store
         */
        it("should work", done => {
            request(server)
            .get("/set")
            .expect(200, (err, res) => {
                if(!err) done();
                cookie = res.header['set-cookie'][0];
            });
        });

        /**
         * @desc It should destory old session when set an empty object
         */
        it("should work when set an empty object", done => {
            request(server)
            .get('/clear')
            .set('cookie', cookie)
            .expect(200, (err, res) => {
                if(err) done(err);

                let sid = cookie[0].split(';')[0].split('=')[1];
                if(typeof store.store[sid] === 'undefined') done();

            });
        });

        /**
         * @desc It should update the old session when set new one
         */
        it("should work when update old session", done => {

            request(server)
            .get("/set")
            .expect(200, (err, res) => {
                let cookie = res.header['set-cookie'];
                let sid = cookie[0].split(';')[0].split('=')[1];

                // change session to refresh
                request(server).get("/change")
                .set("Cookie", cookie)
                .expect(200, (err, res) => {
                    // the old session id should be updated
                    if(store.store[sid].user.name == 'jim') done();
                });
            });

        });
    });

    describe("when session cookie exists but is not in store", () => {
        let app = new Koa();
        let router = new Router();
        let store = new CustomStore();
        let cookie;

        app.use(session({
            store
        }));

        router.get("/set", ctx => {
          ctx.session.user = {name: "tom"};
          ctx.body = "done";
        });

        app.use(router.routes())

        const server = app.listen();

        /**
         * @desc It should work
         */
        it("should work", done => {

            request(server)
            .get("/set")
            .expect(200)
            .end((err, res) => {
                if (err) return done(err);
                done();

                // save cookie for next test
                cookie = res.header["set-cookie"];
                // clear the store
                for (let key in store.store) {
                  delete store.store[key];
                }
            });

        });

        /**
         * @desc It should work even if store cleared
         */
        it("should work even if store cleared", done => {

            request(server)
            .get("/set")
            .set("Cookie", cookie)
            .expect(200)
            .end((err, res) => {
                // cookie should reset when session is not found in store
                let sid = res.header["set-cookie"][0].split(';')[0].split('=')[1];

                if (Object.keys(store.store).length === 1 &&
                    store.store[sid].user.name == 'tom') {
                  return done();
                }
                done(new Error("error resetting cookie"));
            });

        });
    });

    describe("when pass the context to the session store", () => {
        let app = new Koa();
        let router = new Router();
        let store = new CustomStore();

        app.use(session({
            store
        }));

        router.get("/set", ctx => {
            ctx.test_id = 'the_id_in_ctx'
            ctx.session.user = {name: "tom"};
            ctx.body = "done";
        });

        app.use(router.routes())

        const server = app.listen();

        /**
         * @desc It should work
         */
        it("should work", done => {

            request(server)
            .get("/set")
            .expect(200)
            .end((err, res) => {
                if (err) return done(err);

                // if the session id is the preset one
                if(res.header["set-cookie"][0].includes('the_id_in_ctx')) done()
            });

        });
    })

    describe("when refresh session", () => {
        let app = new Koa();
        let router = new Router();
        let store = new CustomStore();

        app.use(session({
            store,
            maxAge: 5000,
        }));

        router.get("/set", ctx => {
            ctx.session.user = {name: "tom"};
            ctx.body = "done";
        })
        .get("/refresh", ctx => {
            ctx.session.refresh()
            ctx.body = 'refreshed'
        })

        app.use(router.routes())

        const server = app.listen();

        /**
         * @desc It should work
         */
        it("should work", done => {

            // set a new session
            request(server)
            .get("/set")
            .expect(200, (err, res) => {
                let cookie = res.header['set-cookie'];

                // refresh session
                request(server).get("/refresh")
                .set("Cookie", cookie)
                .expect(200, (err, res) => {
                    // the set function should be called and the set_count should be 2
                    if(store.set_count == 2) done()
                });
            });

        });
    })

});
<|endoftext|>


<commit_before>var express = require('express');
var DataStore = require('../modules/regard-data-store.js');
var Investigation = require('../schemas/investigation.js');

var router = express.Router();

router.post('/register', function (req, res, next) {
  var queryName = req.body.query.id;
  var queryDefinition = req.body.query.queryDefinition;

  var dataStore = new DataStore(req.body.investigation.organization, req.body.investigation.product);

  dataStore.registerQuery(queryName, queryDefinition).done(function (response) {
    res.send(response);
  }, next);
});

module.exports = router;
<commit_msg>Query engine doesn't send a response<commit_after>var express = require('express');
var DataStore = require('../modules/regard-data-store.js');
var Investigation = require('../schemas/investigation.js');

var router = express.Router();

router.post('/register', function (req, res, next) {
  var queryName = req.body.query.id;
  var queryDefinition = req.body.query.queryDefinition;

  var dataStore = new DataStore(req.body.investigation.organization, req.body.investigation.product);

  dataStore.registerQuery(queryName, queryDefinition).done(function () {
    res.send(201); // created
  }, next);
});

module.exports = router;
<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict';
var path = require('path');
var assert = require('assert');
var assign = require('object-assign');
var pathExists = require('path-exists');
var rimraf = require('rimraf');
var vinylFile = require('vinyl-file');
var sass = require('../');

var defaultOptions = {
	quiet: true,
	// normalize compilation results on Windows systems
	unixNewlines: true
};

// load the expected result file from the compiled results directory
var loadExpectedFile = function (relativePath, base) {
	base = base || 'result';
	var file = path.join(base, relativePath);
	return vinylFile.readSync(file, {base: base});
};

var sortByRelative = function (a, b) {
	return a.relative.localeCompare(b.relative);
};

var compilesSource = function (source, expected) {
	var files = [];

	before(function (done) {
		sass(source, defaultOptions)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', function () {
			files.sort(sortByRelative);
			done();
		});
	});

	it('creates the correct number of files', function () {
		assert.equal(files.length, expected.length);
	});

	it('creates files at the correct path', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			assert.equal(file.relative, expected[i].relative);
		});
	});

	it('creates correct file contents', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			assert.deepEqual(
				file.contents.toString(),
				expected[i].contents.toString()
			);
		});
	});
};

describe('single file', function () {
	this.timeout(20000);
	var source = 'source/file.scss';
	var expected = [loadExpectedFile('file.css')];

	compilesSource(source, expected);
});

describe('multiple files', function () {
	this.timeout(20000);
	var source = 'source/**/*.scss';
	var expected = [
		loadExpectedFile('directory with spaces/file with spaces.css'),
		loadExpectedFile('directory/file.css'),
		loadExpectedFile('file.css'),
		loadExpectedFile('warnings.css')
	];

	compilesSource(source, expected);
});

describe('array sources', function () {
	this.timeout(20000);
	var source = [
		'source/file.scss',
		'source/directory with spaces/file with spaces.scss'
	];
	var expected = [
		loadExpectedFile('file with spaces.css', 'result/directory with spaces'),
		loadExpectedFile('file.css')
	];

	compilesSource(source, expected);
});

describe('concurrently run tasks', function () {
	this.timeout(20000);
	var aFiles = [];
	var bFiles = [];
	var cFiles = [];
	var counter = 0;

	var isDone = function (done) {
		counter++;

		if (counter === 3) {
			done();
		}
	};

	before(function (done) {
		sass('source/file.scss', defaultOptions)
		.on('data', function (data) {
			aFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});

		sass('source/directory/file.scss', defaultOptions)
		.on('data', function (data) {
			bFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});

		sass('source/directory with spaces/file with spaces.scss', defaultOptions)
		.on('data', function (data) {
			cFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});
	});

	it('don\'t intermix result files', function () {
		assert.equal(aFiles.length, 1);
		assert.equal(bFiles.length, 1);
		assert.equal(cFiles.length, 1);
	});
});

describe('sourcemap', function () {
	this.timeout(20000);
	var files = [];
	var options = assign({}, defaultOptions, {sourcemap: true});

	before(function (done) {
		sass('source/file.scss', options)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', done);
	});

	it('doesn\'t stream Sass sourcemap files', function () {
		assert.equal(files.length, 1);
	});

	it('removes Sass sourcemap comment', function () {
		assert(
			files[0].contents.toString().indexOf('sourceMap') === -1,
			'File contains sourcemap comment'
		);
	});

	it('adds a vinyl sourcemap', function () {
		assert.equal(typeof files[0].sourceMap, 'object');
		assert.equal(files[0].sourceMap.version, 3);
	});

	it('includes the correct sources', function () {
		assert.deepEqual(
			files[0].sourceMap.sources,
			['_partial.scss', 'file.scss', 'directory/_nested-partial.scss']
		);
	});

	describe('compiling files from glob source', function () {
		var expected = [
			['_partial.scss'],
			['_partial.scss', 'file.scss', 'directory/_nested-partial.scss']
		];

		before(function (done) {
			files = [];

			sass('source/**/file.scss', options)
			.on('data', function (data) {
				files.push(data);
			})
			.on('end', function () {
				files.sort(sortByRelative);
				done();
			});
		});

		it('includes the correct sources', function () {
			files.forEach(function (file, i) {
				assert.deepEqual(file.sourceMap.sources, expected[i]);
			});
		});
	});

	describe('compiling files and directories with spaces', function () {
		var expected = ['file with spaces.scss'];

		before(function (done) {
			files = [];

			sass('source/directory with spaces/file with spaces.scss', options)
			.on('data', function (data) {
				files.push(data);
			})
			.on('end', done);
		});

		it('includes the correct sources', function () {
			assert.deepEqual(files[0].sourceMap.sources, expected);
		});
	});
});

describe('options', function () {
	this.timeout(20000);

	describe('emitCompileError', function () {
		var error;

		before(function (done) {
			var options = assign({}, defaultOptions, {emitCompileError: true});

			sass('special/error.scss', options)
			.on('data', function () {})
			.on('error', function (err) {
				error = err;
			})
			.on('end', done);
		});

		it('emits a gulp error when Sass compilation fails', function () {
			assert(error instanceof Error);
			assert.equal(
				error.message,
				'Sass compilation failed. See console output for more information.'
			);
		});
	});

	describe('base (for colliding sources)', function () {
		var files = [];
		var expected = [
			loadExpectedFile('directory/file.css'),
			loadExpectedFile('file.css')
		];
		var options = assign({}, defaultOptions, {base: 'source'});

		before(function (done) {
			sass(['source/file.scss', 'source/directory/file.scss'], options)
			.on('data', function (data) {
				files.push(data);
			})
			.on('end', function () {
				files.sort(sortByRelative);
				done();
			});
		});

		it('creates correct number of files', function () {
			assert.equal(files.length, expected.length);
		});

		it('creates file at correct path', function () {
			assert(files.length);
			files.forEach(function (file, i) {
				assert.equal(file.relative, expected[i].relative);
			});
		});

		it('creates correct file contents', function () {
			assert(files.length);
			files.forEach(function (file, i) {
				assert.deepEqual(
					file.contents.toString(),
					expected[i].contents.toString()
				);
			});
		});
	});

	describe('tempDir', function () {
		it('compiles files to the specified directory', function (done) {
			var source = 'source/file.scss';
			var tempDir = './custom-temp-dir';
			var options = assign({}, defaultOptions, {tempDir: tempDir});

			assert.equal(
				pathExists.sync(tempDir),
				false,
				'The temporary directory already exists, and would create false positives.'
			);

			sass(source, options)

			.on('data', function () {
				assert(pathExists.sync(tempDir));
			})

			// clean up if tests are run locally
			.on('end', function () {
				rimraf(tempDir, done);
			});
		});
	});
});

describe('caching', function () {
	this.timeout(20000);

	it('compiles an unchanged file faster the second time', function (done) {
		sass.clearCache();

		var startOne = new Date();

		sass('special/computational.scss', defaultOptions)
		.on('data', function () {})
		.on('end', function () {
			var endOne = new Date();
			var runtimeOne = endOne - startOne;

			sass('special/computational.scss', defaultOptions)
			.on('data', function () {})
			.on('end', function () {
				var runtimeTwo = new Date() - endOne;

				assert(
					// pad time to avoid potential intermittents
					runtimeOne > runtimeTwo + 50,
					'Compilation times were not decreased significantly. Caching may be broken.'
				);

				done();
			});
		});
	});
});
<commit_msg>DRY sourcemap source tests with a function<commit_after>/* eslint-env mocha */
'use strict';
var path = require('path');
var assert = require('assert');
var assign = require('object-assign');
var pathExists = require('path-exists');
var rimraf = require('rimraf');
var vinylFile = require('vinyl-file');
var sass = require('../');

var defaultOptions = {
	quiet: true,
	// normalize compilation results on Windows systems
	unixNewlines: true
};

// load the expected result file from the compiled results directory
var loadExpectedFile = function (relativePath, base) {
	base = base || 'result';
	var file = path.join(base, relativePath);
	return vinylFile.readSync(file, {base: base});
};

var sortByRelative = function (a, b) {
	return a.relative.localeCompare(b.relative);
};

var compilesSource = function (source, expected) {
	var files = [];

	before(function (done) {
		sass(source, defaultOptions)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', function () {
			files.sort(sortByRelative);
			done();
		});
	});

	it('creates the correct number of files', function () {
		assert.equal(files.length, expected.length);
	});

	it('creates files at the correct path', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			assert.equal(file.relative, expected[i].relative);
		});
	});

	it('creates correct file contents', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			assert.deepEqual(
				file.contents.toString(),
				expected[i].contents.toString()
			);
		});
	});
};

describe('single file', function () {
	this.timeout(20000);
	var source = 'source/file.scss';
	var expected = [loadExpectedFile('file.css')];

	compilesSource(source, expected);
});

describe('multiple files', function () {
	this.timeout(20000);
	var source = 'source/**/*.scss';
	var expected = [
		loadExpectedFile('directory with spaces/file with spaces.css'),
		loadExpectedFile('directory/file.css'),
		loadExpectedFile('file.css'),
		loadExpectedFile('warnings.css')
	];

	compilesSource(source, expected);
});

describe('array sources', function () {
	this.timeout(20000);
	var source = [
		'source/file.scss',
		'source/directory with spaces/file with spaces.scss'
	];
	var expected = [
		loadExpectedFile('file with spaces.css', 'result/directory with spaces'),
		loadExpectedFile('file.css')
	];

	compilesSource(source, expected);
});

describe('concurrently run tasks', function () {
	this.timeout(20000);
	var aFiles = [];
	var bFiles = [];
	var cFiles = [];
	var counter = 0;

	var isDone = function (done) {
		counter++;

		if (counter === 3) {
			done();
		}
	};

	before(function (done) {
		sass('source/file.scss', defaultOptions)
		.on('data', function (data) {
			aFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});

		sass('source/directory/file.scss', defaultOptions)
		.on('data', function (data) {
			bFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});

		sass('source/directory with spaces/file with spaces.scss', defaultOptions)
		.on('data', function (data) {
			cFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});
	});

	it('don\'t intermix result files', function () {
		assert.equal(aFiles.length, 1);
		assert.equal(bFiles.length, 1);
		assert.equal(cFiles.length, 1);
	});
});

var includesCorrectSources = function (source, expected) {
	var files = [];
	var options = assign({}, defaultOptions, {sourcemap: true});

	before(function (done) {
		sass(source, options)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', function () {
			files.sort(sortByRelative);
			done();
		});
	});

	it('includes the correct sources', function () {
		files.forEach(function (file, i) {
			assert.deepEqual(file.sourceMap.sources, expected[i]);
		});
	});
};

describe('sourcemap', function () {
	this.timeout(20000);
	describe('replaces Sass sourcemaps with vinyl sourceMaps', function () {
		var files = [];
		var options = assign({}, defaultOptions, {sourcemap: true});

		before(function (done) {
			sass('source/file.scss', options)
			.on('data', function (data) {
				files.push(data);
			})
			.on('end', done);
		});

		it('doesn\'t stream Sass sourcemap files', function () {
			assert.equal(files.length, 1);
		});

		it('removes Sass sourcemap comment', function () {
			assert(
				files[0].contents.toString().indexOf('sourceMap') === -1,
				'File contains sourcemap comment'
			);
		});

		it('adds a vinyl sourcemap', function () {
			assert.equal(typeof files[0].sourceMap, 'object');
			assert.equal(files[0].sourceMap.version, 3);
		});
	});

	describe('compiling files from a single file source', function () {
		var source = ['source/file.scss'];
		var expected = [
			['_partial.scss', 'file.scss', 'directory/_nested-partial.scss']
		];

		includesCorrectSources(source, expected);
	});

	describe('compiling files and directories with spaces', function () {
		var source = ['source/directory with spaces/file with spaces.scss'];
		var expected = [
			['file with spaces.scss']
		];

		includesCorrectSources(source, expected);
	});

	describe('compiling files from glob source', function () {
		var source = ['source/**/file.scss'];
		var expected = [
			['_partial.scss'],
			['_partial.scss', 'file.scss', 'directory/_nested-partial.scss']
		];

		includesCorrectSources(source, expected);
	});
});

describe('options', function () {
	this.timeout(20000);

	describe('emitCompileError', function () {
		var error;

		before(function (done) {
			var options = assign({}, defaultOptions, {emitCompileError: true});

			sass('special/error.scss', options)
			.on('data', function () {})
			.on('error', function (err) {
				error = err;
			})
			.on('end', done);
		});

		it('emits a gulp error when Sass compilation fails', function () {
			assert(error instanceof Error);
			assert.equal(
				error.message,
				'Sass compilation failed. See console output for more information.'
			);
		});
	});

	describe('base (for colliding sources)', function () {
		var files = [];
		var expected = [
			loadExpectedFile('directory/file.css'),
			loadExpectedFile('file.css')
		];
		var options = assign({}, defaultOptions, {base: 'source'});

		before(function (done) {
			sass(['source/file.scss', 'source/directory/file.scss'], options)
			.on('data', function (data) {
				files.push(data);
			})
			.on('end', function () {
				files.sort(sortByRelative);
				done();
			});
		});

		it('creates correct number of files', function () {
			assert.equal(files.length, expected.length);
		});

		it('creates file at correct path', function () {
			assert(files.length);
			files.forEach(function (file, i) {
				assert.equal(file.relative, expected[i].relative);
			});
		});

		it('creates correct file contents', function () {
			assert(files.length);
			files.forEach(function (file, i) {
				assert.deepEqual(
					file.contents.toString(),
					expected[i].contents.toString()
				);
			});
		});
	});

	describe('tempDir', function () {
		it('compiles files to the specified directory', function (done) {
			var source = 'source/file.scss';
			var tempDir = './custom-temp-dir';
			var options = assign({}, defaultOptions, {tempDir: tempDir});

			assert.equal(
				pathExists.sync(tempDir),
				false,
				'The temporary directory already exists, and would create false positives.'
			);

			sass(source, options)

			.on('data', function () {
				assert(pathExists.sync(tempDir));
			})

			// clean up if tests are run locally
			.on('end', function () {
				rimraf(tempDir, done);
			});
		});
	});
});

describe('caching', function () {
	this.timeout(20000);

	it('compiles an unchanged file faster the second time', function (done) {
		sass.clearCache();
		var startOne = new Date();

		sass('special/computational.scss', defaultOptions)
		.on('data', function () {})
		.on('end', function () {
			var endOne = new Date();
			var runtimeOne = endOne - startOne;

			sass('special/computational.scss', defaultOptions)
			.on('data', function () {})
			.on('end', function () {
				var runtimeTwo = new Date() - endOne;

				assert(
					// pad time to avoid potential intermittents
					runtimeOne > runtimeTwo + 50,
					'Compilation times were not decreased significantly. Caching may be broken.'
				);

				done();
			});
		});
	});
});
<|endoftext|>