<commit_before>function DataEditController($scope, $routeParams, $window, $http, $rootScope, User, alertService) {
    //filePath = assets/materialscommons/location/name
    $scope.setupAccessToUserFile = function() {
        //alert($scope.doc.mediaType);

        $scope.fileType = determineFileType($scope.doc.mediaType);
        $scope.fileSrc = filePath($scope.fileType, $scope.doc.mediaType, $scope.doc.location, $scope.doc.name);
    }

    $http.jsonp(mcurljsonp('/user/%/datafile/%', User.u(), $routeParams.id))
        .success(function (data) {
            $scope.doc = data;
            $scope.setupAccessToUserFile();
        });
    //This obj is used in data-edit
    $scope.signed_in_user = User.u();

    $scope.review_note = "";
    $scope.marked_for_review = false;
    $scope.reviewId = null;
    $scope.predicate = 'name';
    $scope.reverse = false;
    $scope.schedule_for_self = false;

    $scope.tagchoices = new Array();
    $scope.originalTags = [];
    $http.jsonp(mcurljsonp('/tags'))
        .success(function (data) {
            data.forEach(function (item) {
                $scope.tagchoices.push(item.id);
                $scope.originalTags.push(item.id);
            })
        });

    $http.jsonp(mcurljsonp('/user/%/datafile/reviews/%', User.u(), $routeParams.id))
        .success(function (data) {
            $scope.scheduledReviews = _.filter(data, function(item) {
                if (! item.done) { return item; }
            });
        });

    $http.jsonp(mcurljsonp('/private/user/%/selected_users', User.u()))
        .success(function (data) {
            $scope.users = data;
            //console.log('selected users are : '+ $scope.users);
        })
        .error(function () {
            //console.log("error: in finding all users");
        });

    $scope.removeTag = function (index) {
        $scope.doc.tags.splice(index, 1);
    }

    $scope.addTag = function () {
        if (!$scope.doc.tags) {
            $scope.doc.tags = new Array();
        }

        if (!_.contains($scope.doc.tags, $scope.tag_to_add)) {
            $scope.doc.tags.push($scope.tag_to_add);

            $scope.msg = "Data has been tagged !"
            alertService.prepForBroadcast($scope.msg);
            $scope.$on('handleBroadcast', function() {
                $scope.message = alertService.message;
            });

        }
    }

    $scope.saveData = function () {
        $http.put(mcurl('/user/%/datafile/update/%', User.u(), $scope.doc.id), $scope.doc)
            .success(function (data) {
                $scope.addNewTags();
                //console.log('msg received is ' + data.msg) ;
                alertService.prepForBroadcast(data.msg);
                $scope.$on('handleBroadcast', function() {
                    $scope.message = alertService.message;
                });
            }).error(function (data, status, headers, config) {
               console.log('im in error part');
            });

        $window.history.back();
    }

    $scope.addNewTags = function () {
        var newtags = _.difference($scope.tagchoices, $scope.originalTags);
        var tagObj = {};
        newtags.forEach(function (item) {
            tagObj.id = item;
            $http.post(mcurl('/tag'), tagObj)
                .success(function(data){

                })
                .error(function(){

                });
        });
    }

    $scope.addReview = function () {
        var review = {};
        review.note = $scope.review_note;
        var now = new Date();
        review.type = "data";
        review.markedOnDate = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate();
        if ($scope.schedule_for_self) {
            review.owner = User.u();
        }
        else {
            review.owner = $scope.user_for_review;
        }
        review.itemName = $scope.doc.name;
        review.itemId = $scope.doc.id;
        review.who = $scope.doc.owner;
        review.done = false;
        $http.post(mcurl('/user/%/review', User.u()), review)
            .success(function (data) {
                alertService.prepForBroadcast(data.msg);
                $scope.$on('handleBroadcast', function() {
                    $scope.message = alertService.message;
                });
                $http.jsonp(mcurljsonp('/user/%/datafile/reviews/%', User.u(), $routeParams.id))
                    .success(function (data) {
                        $scope.scheduledReviews = _.filter(data, function(item){
                            if (!item.done) { return item; }
                        });
                        $scope.user_for_review = "";
                    });
            });
        $scope.schedule_for_self = false;
    }

    $scope.addReviewForOther = function() {
        $scope.review_note = $scope.review_note_other;
        $scope.review_note_other = "";
        $scope.addReview();
    }

    $scope.cancel = function () {
        $window.history.back();
    }

    $scope.addTagKeypressCallback = function (event) {
        console.log("addTagKeypressCallback");
        if (!_.contains($scope.tagchoices, $scope.new_tag)) {
            $scope.tagchoices.push($scope.new_tag);
        }

        $scope.tag_to_add = $scope.new_tag;
        $scope.addTag();
        $scope.new_tag = "";
    }

    $scope.addNoteKeypressCallback = function (event) {
        $scope.doc.notes.push($scope.new_note);
    }

    $scope.addReviewNoteKeypressCallback = function (event) {
        $scope.schedule_for_self = true;
        $scope.review_note = $scope.review_note_self;
        $scope.review_note_self = "";
        $scope.addReview();
    }

    $scope.reviewStatusChanged = function(index) {
        console.log("reviewStatusChanged = " + $scope.scheduledReviews[index]);
        $http.put(mcurl('/user/%/review/%/mark/%', User.u(), $scope.scheduledReviews[index].id,
            $scope.scheduledReviews[index].done))
            .success(function() {
               //console.log("Marked as done");
            });
    }
}

function MyDataController($scope, $http, User, $location) {

    $scope.predicate = 'name';
    $scope.reverse = false;

    $http.jsonp(mcurljsonp('/user/%/datafiles', User.u()))
        .success(function (data, status) {
            $scope.data_by_user = data;
        });

    $scope.dgroupid = "";

    $scope.editData = function (id) {
        $location.path("/data/edit/" + id);
    }

    $scope.getDatagroup = function (datagroupId) {
        if ($scope.dgroupid != datagroupId) {
            var url = mcurljsonp('/user/%/datadirs/%', User.u(), datagroupId);
            $http.jsonp(url)
                .success(function (data, status) {
                    $scope.dgroup = data;
                    $scope.dgroupid = data.id;
                });
        }
    }
}
<commit_msg>Switch to mcjsonp service.<commit_after>function DataEditController($scope, $routeParams, $window, $http, mcjsonp, User, alertService) {
    //filePath = assets/materialscommons/location/name
    $scope.setupAccessToUserFile = function () {
        //alert($scope.doc.mediaType);

        $scope.fileType = determineFileType($scope.doc.mediaType);
        $scope.fileSrc = filePath($scope.fileType, $scope.doc.mediaType, $scope.doc.location, $scope.doc.name);
    }

    mcjsonp('/user/%/datafile/%', User.u(), $routeParams.id)
        .success(function (data) {
            $scope.doc = data;
            $scope.setupAccessToUserFile();
        });
    //This obj is used in data-edit
    $scope.signed_in_user = User.u();

    $scope.review_note = "";
    $scope.marked_for_review = false;
    $scope.reviewId = null;
    $scope.predicate = 'name';
    $scope.reverse = false;
    $scope.schedule_for_self = false;

    $scope.tagchoices = new Array();
    $scope.originalTags = [];
    mcjsonp('/tags')
        .success(function (data) {
            data.forEach(function (item) {
                $scope.tagchoices.push(item.id);
                $scope.originalTags.push(item.id);
            })
        });

    mcjsonp('/user/%/datafile/reviews/%', User.u(), $routeParams.id)
        .success(function (data) {
            $scope.scheduledReviews = _.filter(data, function (item) {
                if (!item.done) {
                    return item;
                }
            });
        });

    mcjsonp('/private/user/%/selected_users', User.u())
        .success(function (data) {
            $scope.users = data;
        })
        .error(function () {
            //console.log("error: in finding all users");
        });

    $scope.removeTag = function (index) {
        $scope.doc.tags.splice(index, 1);
    }

    $scope.addTag = function () {
        if (!$scope.doc.tags) {
            $scope.doc.tags = new Array();
        }

        if (!_.contains($scope.doc.tags, $scope.tag_to_add)) {
            $scope.doc.tags.push($scope.tag_to_add);
            $scope.msg = "Data has been tagged !"
            alertService.prepForBroadcast($scope.msg);
        }
    }

    $scope.saveData = function () {
        $http.put(mcurl('/user/%/datafile/update/%', User.u(), $scope.doc.id), $scope.doc)
            .success(function (data) {
                $scope.addNewTags();
                alertService.prepForBroadcast(data.msg);
            }).error(function (data, status, headers, config) {
                console.log('im in error part');
            });

        $window.history.back();
    }

    $scope.addNewTags = function () {
        var newtags = _.difference($scope.tagchoices, $scope.originalTags);
        var tagObj = {};
        newtags.forEach(function (item) {
            tagObj.id = item;
            $http.post(mcurl('/tag'), tagObj)
                .success(function (data) {

                })
                .error(function () {

                });
        });
    }

    $scope.addReview = function () {
        var review = {};
        review.note = $scope.review_note;
        var now = new Date();
        review.type = "data";
        review.markedOnDate = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate();
        if ($scope.schedule_for_self) {
            review.owner = User.u();
        }
        else {
            review.owner = $scope.user_for_review;
        }
        review.itemName = $scope.doc.name;
        review.itemId = $scope.doc.id;
        review.who = $scope.doc.owner;
        review.done = false;
        $http.post(mcurl('/user/%/review', User.u()), review)
            .success(function (data) {
                alertService.prepForBroadcast(data.msg);
                $http.jsonp(mcurljsonp('/user/%/datafile/reviews/%', User.u(), $routeParams.id))
                    .success(function (data) {
                        $scope.scheduledReviews = _.filter(data, function (item) {
                            if (!item.done) {
                                return item;
                            }
                        });
                        $scope.user_for_review = "";
                    });
            });
        $scope.schedule_for_self = false;
    }

    $scope.addReviewForOther = function () {
        $scope.review_note = $scope.review_note_other;
        $scope.review_note_other = "";
        $scope.addReview();
    }

    $scope.cancel = function () {
        $window.history.back();
    }

    $scope.addTagKeypressCallback = function (event) {
        if (!_.contains($scope.tagchoices, $scope.new_tag)) {
            $scope.tagchoices.push($scope.new_tag);
        }

        $scope.tag_to_add = $scope.new_tag;
        $scope.addTag();
        $scope.new_tag = "";
    }

    $scope.addNoteKeypressCallback = function (event) {
        $scope.doc.notes.push($scope.new_note);
    }

    $scope.addReviewNoteKeypressCallback = function (event) {
        $scope.schedule_for_self = true;
        $scope.review_note = $scope.review_note_self;
        $scope.review_note_self = "";
        $scope.addReview();
    }

    $scope.reviewStatusChanged = function (index) {
        console.log("reviewStatusChanged = " + $scope.scheduledReviews[index]);
        $http.put(mcurl('/user/%/review/%/mark/%', User.u(), $scope.scheduledReviews[index].id,
                $scope.scheduledReviews[index].done))
            .success(function () {
                //console.log("Marked as done");
            });
    }
}

function MyDataController($scope, mcjsonp, User, $location) {

    $scope.predicate = 'name';
    $scope.reverse = false;

    mcjsonp('/user/%/datafiles', User.u())
        .success(function (data, status) {
            $scope.data_by_user = data;
        });

    $scope.dgroupid = "";

    $scope.editData = function (id) {
        $location.path("/data/edit/" + id);
    }

    $scope.getDatagroup = function (datagroupId) {
        if ($scope.dgroupid != datagroupId) {
            mcjsonp('/user/%/datadirs/%', User.u(), datagroupId)
                .success(function (data, status) {
                    $scope.dgroup = data;
                    $scope.dgroupid = data.id;
                });
        }
    }
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var chalk = require('chalk');
var path = require('path');
var RSVP = require('rsvp');
var getProjectId = require('../getProjectId');
var utils = require('../utils');
var parseTriggers = require('../parseTriggers');
var functionsConfig = require('../functionsConfig');
var ensureDefaultCredentials = require('../ensureDefaultCredentials');
var track = require('../track');
var EmulatorController;
var controller;

function _pollOperation(op) {
  return new RSVP.Promise(function(resolve, reject) {
    var poll = function() {
      controller.client.getOperation(op[0].name)
        .then(function(results) {
          var operation = results[0];
          if (operation.done) {
            if (operation.response) {
              resolve(operation.response.value);
            } else {
              reject(operation.error || new Error('Deployment failed'));
            }
          } else {
            setTimeout(poll, 500);
          }
        })
        .catch(reject);
    };
    poll();
  });
}

function _stopEmulator() {
  delete process.env.FIREBASE_PROJECT;
  return new RSVP.Promise(function(resolve) {
    if (controller) {
      controller.stop().then(resolve);
      // Force-kill controller after 0.5 s
      setInterval(function() {
        controller.kill().then(resolve);
      }, 500);
    } else {
      resolve();
    }
  });
}

function _getPorts(options) {
  var portsConfig = {
    restPort: options.port + 2,
    grpcPort: options.port + 1,
    supervisorPort: options.port
  };
  if (_.includes(options.targets, 'hosting')) {
    return _.mapValues(portsConfig, function(port) {
      return port + 1; // bump up port numbers by 1 so hosting can be served on first port
    });
  }
  return portsConfig;
}

function _startEmulator(options) {
  var projectId = getProjectId(options);
  try {
    // Require must be inside try/catch, since it's an optional dependency. As well, require may fail if node version incompatible.
    var emulatorConfig = require('@google-cloud/functions-emulator/src/config');
    // Must set projectId here instead of later when initializing the controller,
    // otherwise emulator may crash since it is looking for a config file in /src/options.js
    emulatorConfig.set('projectId', projectId); // creates config file in a directory known to the emulator
    EmulatorController = require('@google-cloud/functions-emulator/src/cli/controller');
  } catch (err) {
    var msg = err;
    if (process.version !== 'v6.11.1') {
      msg = 'Please use Node version v6.11.1, you have ' + process.version + '\n';
    }
    utils.logWarning(chalk.yellow('functions:') + ' Cannot start emulator. ' + msg);
    return RSVP.reject();
  }
  var functionsDir = path.join(options.config.projectDir, options.config.get('functions.source'));
  var controllerConfig = _.merge({tail: true}, _getPorts(options));
  utils.logBullet(chalk.cyan.bold('functions:') + ' Preparing to emulate HTTPS functions. Support for other event types coming soon.');

  controller = new EmulatorController(controllerConfig);
  var firebaseConfig;

  ensureDefaultCredentials();
  return functionsConfig.getFirebaseConfig(projectId, options.instance)
  .then(function(result) {
    firebaseConfig = JSON.stringify(result);
    process.env.FIREBASE_PROJECT = firebaseConfig;
    return controller.start();
  }).then(function() {
    return parseTriggers(projectId, functionsDir, firebaseConfig);
  }).catch(function(e) {
    utils.logWarning(chalk.yellow('functions:') + ' Failed to load functions source code. ' +
      'Ensure that you have the latest SDK by running ' + chalk.bold('npm i --save firebase-functions') +
      ' inside the functions directory. Please note that emulation of custom config values are not supported yet. ' +
      'Run ' + chalk.bold('firebase serve --only hosting') + ' to only serve hosting files.\n\n' + e);
    return RSVP.resolve();
  }).then(function(triggers) {
    var promises = _.map(triggers, function(trigger) {
      if (trigger.httpsTrigger) {
        track('Functions Emulation (Trigger Type)', 'HTTPS');
        return controller.deploy(trigger.name, {
          localPath: functionsDir,
          triggerHttp: true
        }).catch(function() {
          return RSVP.reject({name: trigger.name});
        });
      }
      return RSVP.resolve(); // TODO: support other trigger types
    });
    return RSVP.allSettled(promises);
  }).then(function(operations) {
    var functionUrls = {};
    return RSVP.all(_.map(operations, function(operation) {
      if (operation.state === 'rejected') {
        utils.logWarning(chalk.yellow('functions:') + ' Failed to emulate ' + operation.reason.name);
        return RSVP.resolve();
      }
      if (!operation.value) {
        return RSVP.resolve(); // it was a non-HTTPS trigger
      }
      return _pollOperation(operation.value).then(function(res) {
        var funcName = _.chain(res).get('name').split('/').last().value();
        functionUrls[funcName] = res.httpsTrigger.url;
      });
    })).then(function() {
      return functionUrls;
    });
  }).then(function(functionUrls) {
    if (_.size(functionUrls) === 0) {
      utils.logBullet(chalk.cyan.bold('functions: ') + 'No HTTPS functions emulated. ' +
        'Support for other function types are coming soon.');
      return;
    }
    _.forEach(functionUrls, function(url, funcName) {
      utils.logSuccess(chalk.green.bold('functions: ') + funcName + ': ' + chalk.bold(url));
    });
  }).catch(function(e) {
    utils.logWarning(chalk.yellow('functions:') + ' Error from emulator. ' + e.stack);
    return _stopEmulator();
  });
}

module.exports = {
  start: _startEmulator,
  stop: _stopEmulator
};
<commit_msg>Modify emulator tracking. (#420)<commit_after>'use strict';

var _ = require('lodash');
var chalk = require('chalk');
var path = require('path');
var RSVP = require('rsvp');
var getProjectId = require('../getProjectId');
var utils = require('../utils');
var parseTriggers = require('../parseTriggers');
var functionsConfig = require('../functionsConfig');
var ensureDefaultCredentials = require('../ensureDefaultCredentials');
var track = require('../track');
var EmulatorController;
var controller;

function _pollOperation(op) {
  return new RSVP.Promise(function(resolve, reject) {
    var poll = function() {
      controller.client.getOperation(op[0].name)
        .then(function(results) {
          var operation = results[0];
          if (operation.done) {
            if (operation.response) {
              resolve(operation.response.value);
            } else {
              reject(operation.error || new Error('Deployment failed'));
            }
          } else {
            setTimeout(poll, 500);
          }
        })
        .catch(reject);
    };
    poll();
  });
}

function _stopEmulator() {
  delete process.env.FIREBASE_PROJECT;
  return new RSVP.Promise(function(resolve) {
    if (controller) {
      controller.stop().then(resolve);
      // Force-kill controller after 0.5 s
      setInterval(function() {
        controller.kill().then(resolve);
      }, 500);
    } else {
      resolve();
    }
  });
}

function _getPorts(options) {
  var portsConfig = {
    restPort: options.port + 2,
    grpcPort: options.port + 1,
    supervisorPort: options.port
  };
  if (_.includes(options.targets, 'hosting')) {
    return _.mapValues(portsConfig, function(port) {
      return port + 1; // bump up port numbers by 1 so hosting can be served on first port
    });
  }
  return portsConfig;
}

function _startEmulator(options) {
  var projectId = getProjectId(options);
  try {
    // Require must be inside try/catch, since it's an optional dependency. As well, require may fail if node version incompatible.
    var emulatorConfig = require('@google-cloud/functions-emulator/src/config');
    // Must set projectId here instead of later when initializing the controller,
    // otherwise emulator may crash since it is looking for a config file in /src/options.js
    emulatorConfig.set('projectId', projectId); // creates config file in a directory known to the emulator
    EmulatorController = require('@google-cloud/functions-emulator/src/cli/controller');
  } catch (err) {
    var msg = err;
    if (process.version !== 'v6.11.1') {
      msg = 'Please use Node version v6.11.1, you have ' + process.version + '\n';
    }
    utils.logWarning(chalk.yellow('functions:') + ' Cannot start emulator. ' + msg);
    return RSVP.reject();
  }
  var functionsDir = path.join(options.config.projectDir, options.config.get('functions.source'));
  var controllerConfig = _.merge({tail: true}, _getPorts(options));
  utils.logBullet(chalk.cyan.bold('functions:') + ' Preparing to emulate HTTPS functions. Support for other event types coming soon.');

  controller = new EmulatorController(controllerConfig);
  var firebaseConfig;

  ensureDefaultCredentials();
  return functionsConfig.getFirebaseConfig(projectId, options.instance)
  .then(function(result) {
    firebaseConfig = JSON.stringify(result);
    process.env.FIREBASE_PROJECT = firebaseConfig;
    return controller.start();
  }).then(function() {
    return parseTriggers(projectId, functionsDir, firebaseConfig);
  }).catch(function(e) {
    utils.logWarning(chalk.yellow('functions:') + ' Failed to load functions source code. ' +
      'Ensure that you have the latest SDK by running ' + chalk.bold('npm i --save firebase-functions') +
      ' inside the functions directory. Please note that emulation of custom config values are not supported yet. ' +
      'Run ' + chalk.bold('firebase serve --only hosting') + ' to only serve hosting files.\n\n' + e);
    return RSVP.resolve();
  }).then(function(triggers) {
    var functionsEmulated = 0;
    var promises = _.map(triggers, function(trigger) {
      if (trigger.httpsTrigger) {
        functionsEmulated += 1;
        return controller.deploy(trigger.name, {
          localPath: functionsDir,
          triggerHttp: true
        }).catch(function() {
          return RSVP.reject({name: trigger.name});
        });
      }
      return RSVP.resolve(); // TODO: support other trigger types
    });
    if (functionsEmulated > 0) {
      track('Functions Emulation', 'HTTPS', functionsEmulated);
    }
    return RSVP.allSettled(promises);
  }).then(function(operations) {
    var functionUrls = {};
    return RSVP.all(_.map(operations, function(operation) {
      if (operation.state === 'rejected') {
        utils.logWarning(chalk.yellow('functions:') + ' Failed to emulate ' + operation.reason.name);
        return RSVP.resolve();
      }
      if (!operation.value) {
        return RSVP.resolve(); // it was a non-HTTPS trigger
      }
      return _pollOperation(operation.value).then(function(res) {
        var funcName = _.chain(res).get('name').split('/').last().value();
        functionUrls[funcName] = res.httpsTrigger.url;
      });
    })).then(function() {
      return functionUrls;
    });
  }).then(function(functionUrls) {
    if (_.size(functionUrls) === 0) {
      utils.logBullet(chalk.cyan.bold('functions: ') + 'No HTTPS functions emulated. ' +
        'Support for other function types are coming soon.');
      return;
    }
    _.forEach(functionUrls, function(url, funcName) {
      utils.logSuccess(chalk.green.bold('functions: ') + funcName + ': ' + chalk.bold(url));
    });
  }).catch(function(e) {
    utils.logWarning(chalk.yellow('functions:') + ' Error from emulator. ' + e.stack);
    return _stopEmulator();
  });
}

module.exports = {
  start: _startEmulator,
  stop: _stopEmulator
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import Alert from '../../common/components/Alert'
import Button from '../../common/components/Button'

export default class AddNewPing extends Component {

    render() {
        return (

                    Add a new ping

                        <Alert type="danger" message={ this.props.errorMessage } />

                            Name

                                <input className="form-control" type='text' ref='input' id="ping-name" onKeyDown={(e) => this.handleKeyDown(e)} />

                        <fieldset className="form-group">

                                <Button type="primary" message="Add" onClick={(e) => this.handleClick(e)} />

                        </fieldset>

        )
    }

    submitForm(e) {
        const node = this.refs.input
        const name = node.value.trim()
        this.props.onAddClick(name)
        node.value = ''
    }

    handleClick(e) {
        this.submitForm(e)
    }

    handleKeyDown(evt) {
        if (evt.keyCode == 13 ) {
            return this.submitForm()
        }
    }
}

AddNewPing.propTypes = {
    onAddClick: PropTypes.func.isRequired
}
<commit_msg>Updated the add ping form to not submit with an empty value<commit_after>import React, { Component, PropTypes } from 'react'
import Alert from '../../common/components/Alert'
import Button from '../../common/components/Button'

export default class AddNewPing extends Component {

    render() {
        return (

                    Add a new ping

                        <Alert type="danger" message={ this.props.errorMessage } />

                            Name

                                <input className="form-control" type='text' ref='input' id="ping-name" onKeyDown={(e) => this.handleKeyDown(e)} />

                        <fieldset className="form-group">

                                <Button type="primary" message="Add" onClick={(e) => this.handleClick(e)} />

                        </fieldset>

        )
    }

    submitForm(e) {
        const node = this.refs.input
        const name = node.value.trim()

        if (name === '') {
            return
        }

        this.props.onAddClick(name)
        node.value = ''
    }

    handleClick(e) {
        this.submitForm(e)
    }

    handleKeyDown(evt) {
        if (evt.keyCode == 13) {
            return this.submitForm()
        }
    }
}

AddNewPing.propTypes = {
    onAddClick: PropTypes.func.isRequired
}
<|endoftext|>


<commit_before>module.exports = function(schema) {
    const promise = require('bluebird');

    return {
        defineCreateExperimentSchema,
        defineUpdateExperimentSchema,
        defineCreateExperimentTaskSchema,
        defineUpdateExperimentTaskSchema
    };

    function defineCreateExperimentSchema() {
        let createExperimentSchema = schema.defineSchema('CreateExperiment', {
            project_id: {
                type: 'string',
                nullable: false
            },

            name: {
                type: 'string',
                nullable: false
            },

            aim: {
                type: 'string',
                nullable: false
            },

            goal: {
                type: 'string',
                nullable: false
            },

            status: {
                type: 'string',
                nullable: false,
                isValidExperimentStatus: true
            },

            description: {
                type: 'string'
            }
        });

        createExperimentSchema.setDefaults({
            aim: '',
            goal: '',
            description: '',
            status: 'active'
        });
        createExperimentSchema.validateAsync = promise.promisify(createExperimentSchema.validate);
        return createExperimentSchema;
    }

    function defineUpdateExperimentSchema() {
        let updateExperimentSchema = schema.defineSchema('UpdateExperiment', {
            name: {
                type: 'string',
                nullable: true
            },

            description: {
                type: 'string',
                nullable: true
            },

            notes: {
                type: 'string',
                nullable: true
            }
        });
        updateExperimentSchema.setDefaults({});
        updateExperimentSchema.validateAsync = promise.promisify(updateExperimentSchema.validate);
        return updateExperimentSchema;
    }

    function defineCreateExperimentTaskSchema() {
        let createExperimentTaskSchema = schema.defineSchema('CreateExperimentTask', {
            name: {
                type: 'string',
                nullable: false
            },
            description: {
                type: 'string',
                nullable: false
            },
            parent_id: {
                type: 'string',
                nullable: false
            },
            index: {
                type: 'integer',
                nullable: false,
                min: 0
            }
        });

        createExperimentTaskSchema.setDefaults({parent_id: '', description: ''});
        createExperimentTaskSchema.validateAsync = promise.promisify(createExperimentTaskSchema.validate);
        return createExperimentTaskSchema;
    }

    function defineUpdateExperimentTaskSchema() {
        let updateExperimentTaskSchema = schema.defineSchema('UpdateExperimentTask', {
            name: {
                type: 'string',
                nullable: true
            },
            description: {
                type: 'string',
                nullable: true
            },
            notes: {
                type: 'string',
                nullable: true
            },
            parent_id: {
                type: 'string',
                nullable: true
            },
            flags: {
                nullable: true,
                done: {
                    type: 'boolean',
                    nullable: true
                },
                important: {
                    type: 'boolean',
                    nullable: true
                },
                error: {
                    type: 'boolean',
                    nullable: true
                },
                review: {
                    type: 'boolean',
                    nullable: true
                }
            },

            swap: {
                nullable: true,
                task_id: {
                    type: 'string',
                    nullable: true
                }
            }
        });

        updateExperimentTaskSchema.setDefaults({parent_id: ''});
        updateExperimentTaskSchema.validateAsync = promise.promisify(updateExperimentTaskSchema.validate);
        return updateExperimentTaskSchema;
    }
};<commit_msg>Rearrange to add a separate set of notes. Add REST calls for notes.<commit_after>module.exports = function(schema) {
    const promise = require('bluebird');

    return {
        defineCreateExperimentSchema,
        defineUpdateExperimentSchema,
        defineCreateExperimentTaskSchema,
        defineUpdateExperimentTaskSchema,
        defineCreateExperimentNoteSchema,
        defineUpdateExperimentNoteSchema
    };

    function defineCreateExperimentSchema() {
        let createExperimentSchema = schema.defineSchema('CreateExperiment', {
            project_id: {
                type: 'string',
                nullable: false
            },

            name: {
                type: 'string',
                nullable: false
            },

            aim: {
                type: 'string',
                nullable: false
            },

            goal: {
                type: 'string',
                nullable: false
            },

            status: {
                type: 'string',
                nullable: false,
                isValidExperimentStatus: true
            },

            description: {
                type: 'string'
            }
        });

        createExperimentSchema.setDefaults({
            aim: '',
            goal: '',
            description: '',
            status: 'active'
        });
        createExperimentSchema.validateAsync = promise.promisify(createExperimentSchema.validate);
        return createExperimentSchema;
    }

    function defineUpdateExperimentSchema() {
        let updateExperimentSchema = schema.defineSchema('UpdateExperiment', {
            name: {
                type: 'string',
                nullable: true
            },

            description: {
                type: 'string',
                nullable: true
            },

            note: {
                type: 'string',
                nullable: true
            }
        });
        updateExperimentSchema.setDefaults({});
        updateExperimentSchema.validateAsync = promise.promisify(updateExperimentSchema.validate);
        return updateExperimentSchema;
    }

    function defineCreateExperimentTaskSchema() {
        let createExperimentTaskSchema = schema.defineSchema('CreateExperimentTask', {
            name: {
                type: 'string',
                nullable: false
            },
            description: {
                type: 'string',
                nullable: false
            },
            parent_id: {
                type: 'string',
                nullable: false
            },
            index: {
                type: 'integer',
                nullable: false,
                min: 0
            }
        });

        createExperimentTaskSchema.setDefaults({parent_id: '', description: ''});
        createExperimentTaskSchema.validateAsync = promise.promisify(createExperimentTaskSchema.validate);
        return createExperimentTaskSchema;
    }

    function defineUpdateExperimentTaskSchema() {
        let updateExperimentTaskSchema = schema.defineSchema('UpdateExperimentTask', {
            name: {
                type: 'string',
                nullable: true
            },
            description: {
                type: 'string',
                nullable: true
            },
            note: {
                type: 'string',
                nullable: true
            },
            parent_id: {
                type: 'string',
                nullable: true
            },
            flags: {
                nullable: true,
                done: {
                    type: 'boolean',
                    nullable: true
                },
                important: {
                    type: 'boolean',
                    nullable: true
                },
                error: {
                    type: 'boolean',
                    nullable: true
                },
                review: {
                    type: 'boolean',
                    nullable: true
                }
            },

            swap: {
                nullable: true,
                task_id: {
                    type: 'string',
                    nullable: true
                }
            }
        });

        updateExperimentTaskSchema.setDefaults({parent_id: ''});
        updateExperimentTaskSchema.validateAsync = promise.promisify(updateExperimentTaskSchema.validate);
        return updateExperimentTaskSchema;
    }

    function defineCreateExperimentNoteSchema() {
        let createExperimentNoteSchema = schema.defineSchema('CreateExperimentNote', {
            name: {
                type: 'string',
                nullable: false
            },
            note: {
                type: 'string',
                nullable: false,
            }
        });

        createExperimentNoteSchema.setDefaults({});
        createExperimentNoteSchema.validateAsync = promise.promisify(createExperimentNoteSchema.validate);
        return createExperimentNoteSchema;
    }

    function defineUpdateExperimentNoteSchema() {
        let updateExperimentNoteSchema = schema.defineSchema('UpdateExperimentNote', {
            name: {
                type: 'string'
            },
            note: {
                type: 'string'
            }
        });

        updateExperimentNoteSchema.setDefaults({});
        updateExperimentNoteSchema.validateAsync = promise.promisify(updateExperimentNoteSchema.validate);
        return updateExperimentNoteSchema;
    }
};<|endoftext|>


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

/**
 * Transport class for IFrame.
 */
Aria.classDefinition({
    $classpath : "aria.core.transport.IFrame",
    $singleton : true,
    $statics : {
        ERROR_DURING_SUBMIT : "An error occurred while submitting the form (form.submit() raised an exception)."
    },
    $prototype : {
        /**
         * Tells if the transport object is ready or requires an initialization phase
         * @type Boolean
         */
        isReady : true,

        /**
         * Map request ids to their original requests
         * @type Object
         */
        _requests : {},

        /**
         * Initialization function. Not needed because this transport is ready at creation time
         */
        init : Aria.empty,

        /**
         * Perform a request.
         * @param {aria.core.CfgBeans.IOAsyncRequestCfg} request Request object
         * @param {aria.core.CfgBeans.Callback} callback Internal callback description
         */
        request : function (request, callback) {
            this._requests[request.id] = {
                request : request,
                cb : callback
            };

            // handle timeout
            aria.core.IO.setTimeout(request.id, request.timeout, {
                fn : this.onAbort,
                scope : this,
                args : [request]
            });

            this._createIFrame(request);
            this._submitForm(request, callback);
        },

        /**
         * Creates an iFrame to load the response of the request.
         * @param {aria.core.CfgBeans.IOAsyncRequestCfg} request
         * @protected
         */
        _createIFrame : function (request) {
            var iFrame;
            var browser = aria.core.Browser;
            var document = Aria.$frameworkWindow.document;

            // Issue when using document.createElement("iframe") in IE7
            if (browser.isIE7 || browser.isIE6) {
                var container = document.createElement("div");
                container.innerHTML = [''].join('');
                document.body.appendChild(container);
                iFrame = document.getElementById("xIFrame" + request.id);
                request.iFrameContainer = container;
            } else {
                iFrame = document.createElement("iframe");
                iFrame.src = aria.core.DownloadMgr.resolveURL("aria/core/transport/iframeSource.txt");
                iFrame.id = iFrame.name = "xIFrame" + request.id;
                iFrame.style.cssText = "display:none";
                document.body.appendChild(iFrame);
            }
            request.iFrame = iFrame;

            // Event handlers
            iFrame.onload = iFrame.onreadystatechange = this._iFrameReady;
        },

        /**
         * Updates the form to target the iframe then calls the forms submit method.
         * @param {aria.core.CfgBeans.IOAsyncRequestCfg} request
         * @param {Object} callback Internal callback description
         * @protected
         */
        _submitForm : function (request, callback) {
            var form = request.form;
            form.target = "xIFrame" + request.id;
            form.action = request.url;
            form.method = request.method;
            if (request.headers["Content-Type"]) {
                try {
                    form.enctype = request.headers["Content-Type"];
                } catch (ex) {
                    // This might throw an exception in IE if the content type is invalid.
                }
            }
            try {
                form.submit();
            } catch (er) {
                this.$logError(this.ERROR_DURING_SUBMIT, null, er);
                this._deleteRequest(request);
                aria.core.IO._handleTransactionResponse({
                    conn : {
                        status : 0,
                        responseText : null,
                        getAllResponseHeaders : function () {}
                    },
                    transaction : request.id
                }, callback, true);
            }
        },

        /**
         * load and readystatechange event handler on the iFrame.
         * @param {DOMEvent} event
         */
        _iFrameReady : function (event) {
            // This method cannot use 'this' because the scope is not aria.core.transport.IFrame when this method is
            // called. It uses oSelf instead.
            var event = event || Aria.$frameworkWindow.event;
            var iFrame = event.target || event.srcElement;
            if (!iFrame.readyState || /loaded|complete/.test(iFrame.readyState)) {
                var reqId = /^xIFrame(\d+)$/.exec(iFrame.id)[1];
                // Make sure things are async
                setTimeout(function () {
                    aria.core.transport.IFrame._sendBackResult(reqId);
                }, 4);
            }
        },

        /**
         * Sends back the results of the request
         * @param {String} id Request id
         * @protected
         */
        _sendBackResult : function (id) {
            var description = this._requests[id];
            if (!description) {
                // The request was aborted
                return;
            }
            var request = description.request;
            var callback = description.cb;

            var iFrame = request.iFrame;
            var responseText, contentDocument = iFrame.contentDocument, contentWindow;

            if (contentDocument == null) {
                var contentWindow = iFrame.contentWindow;
                if (contentWindow) {
                    contentDocument = contentWindow.document;
                }
            }
            if (contentDocument) {
                var body = contentDocument.body || contentDocument.documentElement;
                if (body) {
                    // this is for content displayed as text:
                    responseText = body.textContent || body.outerText;
                }
                var xmlDoc = contentDocument.XMLDocument;
                // In IE, contentDocument contains a transformation of the document
                // see: http://www.aspnet-answers.com/microsoft/JScript/29847637/javascript-ie-xml.aspx
                if (xmlDoc) {
                    contentDocument = xmlDoc;
                }
            }

            this._deleteRequest(request);

            var response = {
                status : 200,
                responseText : responseText,
                responseXML : contentDocument
            };

            callback.fn.call(callback.scope, false, callback.args, response);
        },

        /**
         * Delete a request freing up memory
         * @param {aria.core.CfgBeans.IOAsyncRequestCfg} request
         */
        _deleteRequest : function (request) {
            var iFrame = request.iFrame;
            if (iFrame) {
                var domEltToRemove = request.iFrameContainer || iFrame;
                domEltToRemove.parentNode.removeChild(domEltToRemove);
                // avoid leaks:
                request.iFrameContainer = null;
                request.iFrame = null;
                iFrame.onload = null;
                iFrame.onreadystatechange = null;
            }
            delete this._requests[request.id];
        },

        /**
         * Abort method. Called after the request timeout
         * @param {aria.core.CfgBeans.IOAsyncRequestCfg} request
         * @return Boolean Whether the connection was aborted or not
         */
        onAbort : function (request) {
            this._deleteRequest(request);
            return true;
        }

    }
});<commit_msg>fix #570 Wrong content type in IE 8 with asyncFormSubmit.<commit_after>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Transport class for IFrame.
 */
Aria.classDefinition({
    $classpath : "aria.core.transport.IFrame",
    $singleton : true,
    $statics : {
        ERROR_DURING_SUBMIT : "An error occurred while submitting the form (form.submit() raised an exception)."
    },
    $prototype : {
        /**
         * Tells if the transport object is ready or requires an initialization phase
         * @type Boolean
         */
        isReady : true,

        /**
         * Map request ids to their original requests
         * @type Object
         */
        _requests : {},

        /**
         * Initialization function. Not needed because this transport is ready at creation time
         */
        init : Aria.empty,

        /**
         * Perform a request.
         * @param {aria.core.CfgBeans.IOAsyncRequestCfg} request Request object
         * @param {aria.core.CfgBeans.Callback} callback Internal callback description
         */
        request : function (request, callback) {
            this._requests[request.id] = {
                request : request,
                cb : callback
            };

            // handle timeout
            aria.core.IO.setTimeout(request.id, request.timeout, {
                fn : this.onAbort,
                scope : this,
                args : [request]
            });

            this._createIFrame(request);
            this._submitForm(request, callback);
        },

        /**
         * Creates an iFrame to load the response of the request.
         * @param {aria.core.CfgBeans.IOAsyncRequestCfg} request
         * @protected
         */
        _createIFrame : function (request) {
            var iFrame;
            var browser = aria.core.Browser;
            var document = Aria.$frameworkWindow.document;

            // Issue when using document.createElement("iframe") in IE7
            if (browser.isIE7 || browser.isIE6) {
                var container = document.createElement("div");
                container.innerHTML = [''].join('');
                document.body.appendChild(container);
                iFrame = document.getElementById("xIFrame" + request.id);
                request.iFrameContainer = container;
            } else {
                iFrame = document.createElement("iframe");
                iFrame.src = aria.core.DownloadMgr.resolveURL("aria/core/transport/iframeSource.txt");
                iFrame.id = iFrame.name = "xIFrame" + request.id;
                iFrame.style.cssText = "display:none";
                document.body.appendChild(iFrame);
            }
            request.iFrame = iFrame;

            // Event handlers
            iFrame.onload = iFrame.onreadystatechange = this._iFrameReady;
        },

        /**
         * Updates the form to target the iframe then calls the forms submit method.
         * @param {aria.core.CfgBeans.IOAsyncRequestCfg} request
         * @param {Object} callback Internal callback description
         * @protected
         */
        _submitForm : function (request, callback) {
            var form = request.form;
            form.target = "xIFrame" + request.id;
            form.action = request.url;
            form.method = request.method;
            if (request.headers["Content-Type"]) {
                try {
                    // in IE 8, setting form.enctype directly does not work
                    // form.setAttribute works better (check PTR 07049566)
                    form.setAttribute("enctype", request.headers["Content-Type"]);
                } catch (ex) {
                    // This might throw an exception in IE if the content type is invalid.
                }
            }
            try {
                form.submit();
            } catch (er) {
                this.$logError(this.ERROR_DURING_SUBMIT, null, er);
                this._deleteRequest(request);
                aria.core.IO._handleTransactionResponse({
                    conn : {
                        status : 0,
                        responseText : null,
                        getAllResponseHeaders : function () {}
                    },
                    transaction : request.id
                }, callback, true);
            }
        },

        /**
         * load and readystatechange event handler on the iFrame.
         * @param {DOMEvent} event
         */
        _iFrameReady : function (event) {
            // This method cannot use 'this' because the scope is not aria.core.transport.IFrame when this method is
            // called. It uses oSelf instead.
            var event = event || Aria.$frameworkWindow.event;
            var iFrame = event.target || event.srcElement;
            if (!iFrame.readyState || /loaded|complete/.test(iFrame.readyState)) {
                var reqId = /^xIFrame(\d+)$/.exec(iFrame.id)[1];
                // Make sure things are async
                setTimeout(function () {
                    aria.core.transport.IFrame._sendBackResult(reqId);
                }, 4);
            }
        },

        /**
         * Sends back the results of the request
         * @param {String} id Request id
         * @protected
         */
        _sendBackResult : function (id) {
            var description = this._requests[id];
            if (!description) {
                // The request was aborted
                return;
            }
            var request = description.request;
            var callback = description.cb;

            var iFrame = request.iFrame;
            var responseText, contentDocument = iFrame.contentDocument, contentWindow;

            if (contentDocument == null) {
                var contentWindow = iFrame.contentWindow;
                if (contentWindow) {
                    contentDocument = contentWindow.document;
                }
            }
            if (contentDocument) {
                var body = contentDocument.body || contentDocument.documentElement;
                if (body) {
                    // this is for content displayed as text:
                    responseText = body.textContent || body.outerText;
                }
                var xmlDoc = contentDocument.XMLDocument;
                // In IE, contentDocument contains a transformation of the document
                // see: http://www.aspnet-answers.com/microsoft/JScript/29847637/javascript-ie-xml.aspx
                if (xmlDoc) {
                    contentDocument = xmlDoc;
                }
            }

            this._deleteRequest(request);

            var response = {
                status : 200,
                responseText : responseText,
                responseXML : contentDocument
            };

            callback.fn.call(callback.scope, false, callback.args, response);
        },

        /**
         * Delete a request freing up memory
         * @param {aria.core.CfgBeans.IOAsyncRequestCfg} request
         */
        _deleteRequest : function (request) {
            var iFrame = request.iFrame;
            if (iFrame) {
                var domEltToRemove = request.iFrameContainer || iFrame;
                domEltToRemove.parentNode.removeChild(domEltToRemove);
                // avoid leaks:
                request.iFrameContainer = null;
                request.iFrame = null;
                iFrame.onload = null;
                iFrame.onreadystatechange = null;
            }
            delete this._requests[request.id];
        },

        /**
         * Abort method. Called after the request timeout
         * @param {aria.core.CfgBeans.IOAsyncRequestCfg} request
         * @return Boolean Whether the connection was aborted or not
         */
        onAbort : function (request) {
            this._deleteRequest(request);
            return true;
        }

    }
});<|endoftext|>


<commit_before>import electron from 'electron';
import React from 'react';
import {Provider} from 'unstated';

import Overlay from '../components/cropper/overlay';
import Cropper from '../components/cropper';
import ActionBar from '../components/action-bar';

import CursorContainer from '../containers/cursor';
import CropperContainer from '../containers/cropper';
import ActionBarContainer from '../containers/action-bar';

const cursorContainer = new CursorContainer();
const cropperContainer = new CropperContainer();
const actionBarContainer = new ActionBarContainer();

cropperContainer.bindCursor(cursorContainer);
cropperContainer.bindActionBar(actionBarContainer);
actionBarContainer.bindCursor(cursorContainer);
actionBarContainer.bindCropper(cropperContainer);

let lastRatioLockState = null;

export default class CropperPage extends React.Component {
  remote = electron.remote || false

  dev = false;

  constructor(props) {
    super(props);

    if (!electron.ipcRenderer) {
      return;
    }

    const {ipcRenderer, remote} = electron;

    ipcRenderer.on('display', (_, display) => {
      cropperContainer.setDisplay(display);
      actionBarContainer.setDisplay(display);
    });

    ipcRenderer.on('select-app', (_, app) => {
      cropperContainer.selectApp(app);
      cropperContainer.setActive(true);
    });

    ipcRenderer.on('blur', () => {
      cropperContainer.setActive(false);
    });

    ipcRenderer.on('start-recording', () => {
      cropperContainer.setRecording();
    });

    const window = remote.getCurrentWindow();
    window.on('focus', () => {
      cropperContainer.setActive(true);
    });

    window.on('blur', event => {
      if (!event.defaultPrevented) {
        cropperContainer.setActive(false);
      }
    });
  }

  componentDidMount() {
    document.addEventListener('keydown', this.handleKeyEvent);
    document.addEventListener('keyup', this.handleKeyEvent);
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyEvent);
    document.removeEventListener('keyup', this.handleKeyEvent);
  }

  handleKeyEvent = event => {
    switch (event.key) {
      case 'Escape':
        this.remote.getCurrentWindow().close();
        break;
      case 'Shift':
        if (event.type === 'keydown' && !event.defaultPrevented) {
          lastRatioLockState = actionBarContainer.state.ratioLocked;
          actionBarContainer.toggleRatioLock(true);
        } else if (event.type === 'keyup' && lastRatioLockState !== null) {
          actionBarContainer.toggleRatioLock(lastRatioLockState);
          lastRatioLockState = null;
        }

        break;
      case 'Alt':
        cropperContainer.toggleResizeFromCenter(event.type === 'keydown');
        break;
      case 'i':
        this.remote.getCurrentWindow().setIgnoreMouseEvents(true);
        this.dev = !this.dev;
        break;
      default:
        break;
    }
  }

  render() {
    return (

        <Provider inject={[cursorContainer, cropperContainer, actionBarContainer]}>
          <Overlay>
            <Cropper/>
            <ActionBar/>
          </Overlay>
        </Provider>

    );
  }
}
<commit_msg>Fix record button focused styles for dark mode<commit_after>import electron from 'electron';
import React from 'react';
import {Provider} from 'unstated';

import Overlay from '../components/cropper/overlay';
import Cropper from '../components/cropper';
import ActionBar from '../components/action-bar';

import CursorContainer from '../containers/cursor';
import CropperContainer from '../containers/cropper';
import ActionBarContainer from '../containers/action-bar';

const cursorContainer = new CursorContainer();
const cropperContainer = new CropperContainer();
const actionBarContainer = new ActionBarContainer();

cropperContainer.bindCursor(cursorContainer);
cropperContainer.bindActionBar(actionBarContainer);
actionBarContainer.bindCursor(cursorContainer);
actionBarContainer.bindCropper(cropperContainer);

let lastRatioLockState = null;

export default class CropperPage extends React.Component {
  remote = electron.remote || false

  dev = false;

  constructor(props) {
    super(props);

    if (!electron.ipcRenderer) {
      return;
    }

    const {ipcRenderer, remote} = electron;

    ipcRenderer.on('display', (_, display) => {
      cropperContainer.setDisplay(display);
      actionBarContainer.setDisplay(display);
    });

    ipcRenderer.on('select-app', (_, app) => {
      cropperContainer.selectApp(app);
      cropperContainer.setActive(true);
    });

    ipcRenderer.on('blur', () => {
      cropperContainer.setActive(false);
    });

    ipcRenderer.on('start-recording', () => {
      cropperContainer.setRecording();
    });

    const window = remote.getCurrentWindow();
    window.on('focus', () => {
      cropperContainer.setActive(true);
    });

    window.on('blur', event => {
      if (!event.defaultPrevented) {
        cropperContainer.setActive(false);
      }
    });
  }

  componentDidMount() {
    document.addEventListener('keydown', this.handleKeyEvent);
    document.addEventListener('keyup', this.handleKeyEvent);
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyEvent);
    document.removeEventListener('keyup', this.handleKeyEvent);
  }

  handleKeyEvent = event => {
    switch (event.key) {
      case 'Escape':
        this.remote.getCurrentWindow().close();
        break;
      case 'Shift':
        if (event.type === 'keydown' && !event.defaultPrevented) {
          lastRatioLockState = actionBarContainer.state.ratioLocked;
          actionBarContainer.toggleRatioLock(true);
        } else if (event.type === 'keyup' && lastRatioLockState !== null) {
          actionBarContainer.toggleRatioLock(lastRatioLockState);
          lastRatioLockState = null;
        }

        break;
      case 'Alt':
        cropperContainer.toggleResizeFromCenter(event.type === 'keydown');
        break;
      case 'i':
        this.remote.getCurrentWindow().setIgnoreMouseEvents(true);
        this.dev = !this.dev;
        break;
      default:
        break;
    }
  }

  render() {
    return (

        <Provider inject={[cursorContainer, cropperContainer, actionBarContainer]}>
          <Overlay>
            <Cropper/>
            <ActionBar/>
          </Overlay>
        </Provider>

    );
  }
}
<|endoftext|>


<commit_before>'use strict';

var should = require('should');
var app = require('../../app');
var request = require('supertest');

describe('GET /api/commits', function() {

  it('should respond with JSON array', function(done) {
    request(app)
      .get('/api/commits')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function(err, res) {
        if (err) return done(err);
        res.body.should.be.instanceof(Array);
        done();
      });
  });
});<commit_msg>Added test that makes sure mentor can access attendacne json file<commit_after>'use strict';
import {seed} from '../../config/seed';
import {getSessionFor} from '../../auth/util.integration';
import Attendance from '../attendance/attendance.model';

var should = require('should');
var app = require('../../app');
var request = require('supertest');

describe('GET /api/commits', function() {

  it('should respond with JSON array', function(done) {
    request(app)
      .get('/api/commits')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function(err, res) {
        if (err) return done(err);
        res.body.should.be.instanceof(Array);
        done();
      });
  });
});

describe('GET /api/attendance', function() {
  before(seed);
  var session,mentorSession;
  before(() => getSessionFor('mentor').then(session => mentorSession = session));

    it('should respond with list of attendance submissions',done=>{
        mentorSession
        .get('/api/attendance')
        .expect('Content-Type', /json/)
        .end((err, res) => {
          res.body.should.be.instanceof(Array);
          done(err);
        });
    });

});
<|endoftext|>


<commit_before>export const amountToCents = amount => {
  if (amount) {
    return Math.round(Number(amount) * 100);
  }
  return 0;
};

export const amountFromCents = amount => {
  if (amount) {
    return amount / 100;
  }
  return 0;
};
<commit_msg>Typed amount conversion utils<commit_after>// @flow

export const amountToCents = (amount: number) => {
  if (amount) {
    return Math.round(Number(amount) * 100);
  }
  return 0;
};

export const amountFromCents = (amount: number) => {
  if (amount) {
    return amount / 100;
  }
  return 0;
};
<|endoftext|>


<commit_before>module.exports = {
  init: init
}

var electron = require('electron')
var debug = require('debug')('webtorrent-app:ipcMain')
var ipcMain = electron.ipcMain
var windows = require('./windows')

function init () {
  ipcMain.on('addTorrentFromPaste', function (e) {
    addTorrentFromPaste()
  })

  ipcMain.on('setBounds', function (e, bounds) {
    setBounds(bounds)
  })

  ipcMain.on('setAspectRatio', function (e, aspectRatio, extraSize) {
    setAspectRatio(aspectRatio, extraSize)
  })

  ipcMain.on('setBadge', function (e, text) {
    setBadge(text)
  })

  ipcMain.on('setProgress', function (e, progress) {
    setProgress(progress)
  })

  ipcMain.on('toggleFullScreen', function (e) {
    windows.main.setFullScreen(!windows.main.isFullScreen())
  })

  ipcMain.on('log', function (e, message) {
    console.log(message)
  })
}

function addTorrentFromPaste () {
  debug('addTorrentFromPaste')
  var torrentIds = electron.clipboard.readText().split('\n')
  torrentIds.forEach(function (torrentId) {
    torrentId = torrentId.trim()
    if (torrentId.length === 0) return
    windows.main.send('addTorrent', torrentId)
  })
}

function setBounds (bounds) {
  debug('setBounds %o', bounds)
  if (windows.main && !windows.main.isFullScreen()) {
    windows.main.setBounds(bounds, true)
  }
}

function setAspectRatio (aspectRatio, extraSize) {
  debug('setAspectRatio %o %o', aspectRatio, extraSize)
  if (windows.main) {
    windows.main.setAspectRatio(aspectRatio, extraSize)
  }
}

// Display string in dock badging area (OS X)
function setBadge (text) {
  debug('setBadge %s', text)
  electron.app.dock.setBadge(String(text))
}

// Show progress bar. Valid range is [0, 1]. Remove when < 0; indeterminate when > 1.
function setProgress (progress) {
  debug('setProgress %s', progress)
  if (windows.main) {
    windows.main.setProgressBar(progress)
  }
}
<commit_msg>Don't resize window if maximized (when player is opened)<commit_after>module.exports = {
  init: init
}

var electron = require('electron')
var debug = require('debug')('webtorrent-app:ipcMain')
var ipcMain = electron.ipcMain
var windows = require('./windows')

function init () {
  ipcMain.on('addTorrentFromPaste', function (e) {
    addTorrentFromPaste()
  })

  ipcMain.on('setBounds', function (e, bounds) {
    setBounds(bounds)
  })

  ipcMain.on('setAspectRatio', function (e, aspectRatio, extraSize) {
    setAspectRatio(aspectRatio, extraSize)
  })

  ipcMain.on('setBadge', function (e, text) {
    setBadge(text)
  })

  ipcMain.on('setProgress', function (e, progress) {
    setProgress(progress)
  })

  ipcMain.on('toggleFullScreen', function (e) {
    windows.main.setFullScreen(!windows.main.isFullScreen())
  })

  ipcMain.on('log', function (e, message) {
    console.log(message)
  })
}

function addTorrentFromPaste () {
  debug('addTorrentFromPaste')
  var torrentIds = electron.clipboard.readText().split('\n')
  torrentIds.forEach(function (torrentId) {
    torrentId = torrentId.trim()
    if (torrentId.length === 0) return
    windows.main.send('addTorrent', torrentId)
  })
}

function setBounds (bounds) {
  debug('setBounds %o', bounds)
  if (windows.main && !windows.main.isFullScreen() && !windows.main.isMaximized()) {
    windows.main.setBounds(bounds, true)
  }
}

function setAspectRatio (aspectRatio, extraSize) {
  debug('setAspectRatio %o %o', aspectRatio, extraSize)
  if (windows.main) {
    windows.main.setAspectRatio(aspectRatio, extraSize)
  }
}

// Display string in dock badging area (OS X)
function setBadge (text) {
  debug('setBadge %s', text)
  electron.app.dock.setBadge(String(text))
}

// Show progress bar. Valid range is [0, 1]. Remove when < 0; indeterminate when > 1.
function setProgress (progress) {
  debug('setProgress %s', progress)
  if (windows.main) {
    windows.main.setProgressBar(progress)
  }
}
<|endoftext|>


<commit_before>// Create our grid module namespace
var grid = angular.module('game.grid', []);

// Returns a tile object
grid.factory('TileModel', function() {
  var Tile = function(tilespec) {
    this.x = tilespec.x || null;
    this.y = tilespec.y || null;
    this.img = this.getImage(tilespec.id);
    this.val = tilespec.val || 2;
    this.orientation = tilespec.orientation;
    this.meeples = null;
    this.features = tilespec.features;
  };
  Tile.prototype.getImage = function(id) {
    // Grab an image from our asset folder to set as img attribute
    return 'assets/img/Tiles/' + id.toUpperCase() + '.png';
  };
  Tile.prototype.rotateRight = function() {
    this.orientation = (this.orientation + 1) % 4;

    var temp = {};
    for (var key in this.features){
      temp[key] = this.features[key];
    }

    this.features.n = temp.w;
    this.features.e = temp.n;
    this.features.s = temp.e;
    this.features.w = temp.s;
  };
  return Tile;
});

grid.service('GridService', function(TileModel) {
  this.createEmptyGameBoard = function(boardSize) {
    var grid = [];
    var size = boardSize;
    for (var x = 0; x < size; x++) {
      grid[x] = [];
      for (var y = 0; y < size; y++) {
        grid[x][y] = null;
      }
    }
    return grid;
  };
});

grid.controller('gridCtrl', function($scope, TileModel, GridService, Player) {
  var gridSize = 13;
  $scope.orientation = 0;
  $scope.src = null;
  $scope.meepmeep = 'assets/img/Meeples/meeple_' + Player.getColor() + '.png';
  var meeplePlaced = false;

  $scope.range = function() {
    return new Array(gridSize);
  };

  $scope.rotate = function() {
    if ($scope.playerId === socket.id) {
      $scope.orientation = ($scope.orientation + 1) % 4;
      $scope.currentTile.rotateRight();
      // console.log($scope.currentTile);
    }
    // console.log($scope.grid[$scope.currentTile.y][$scope.currentTile.x]);
  };

  $scope.init = function() {
    // Create board
    $scope.grid = GridService.createEmptyGameBoard(gridSize);
    $scope.tilePlaced = false;
    placeInitialTile();

    // Dynamically size grid
    angular.element(document.querySelector('.grid-container')).css('width', gridSize * 52 + 'px');

    socket.on('nextTurn', function(gamestate) {
      if (!gamestate.lastTile) {
        $scope.currentTile = new TileModel(gamestate.nextTile);
      } else {
        $scope.currentTile = new TileModel(gamestate.nextTile);
        updateGrid(gamestate.lastTile.x, gamestate.lastTile.y, gamestate.lastTile);
        setCell(gamestate.lastTile);
      }

      $scope.currentPlayer;
      console.log('Running deckCtrl nextTurn...', gamestate.nextPlayer);
      $scope.currentPlayer = gamestate.nextPlayer;
      // Create a tile model
      $scope.playerId = gamestate.playerSocket;
      $scope.src = $scope.currentTile.img;
      $scope.$apply();
    });

    socket.on('meepDataRes', function(data) {
      $scope.numMeeps = data.numMeeps;
    });
    socket.emit('meepDataReq', { username: Player.getUsername(), numMeeps: 7 });
  };

  $scope.clickCell = function(event, x, y) {
    if ($scope.tilePlaced) {
      setMeeple(event, x, y);
    } else {
      setTile(x, y);
    }
  };

  $scope.endTurn = function() {
    if ($scope.currentTile.x !== null) {
      $scope.tilePlaced = false;
      meeplePlaced = false;
      // Need to pass state of meeple placement to others
      socket.emit('endTurn', $scope.currentTile);
    } else {
      console.log('Cannot end your turn');
    }
  };

  var setMeeple = function(event, x, y) {
    if ($scope.numMeeps > 0) {
      if (!meeplePlaced) {
        if ($scope.currentTile.x === x && $scope.currentTile.y === y) {
          var meepClass = 'meep-x-' + x + '-y-' + y;
          angular.element(event.target).append('');
          $scope.currentMeeple = angular.element(document.querySelector('.'+meepClass));
          $scope.numMeeps--;
          socket.emit('meepDataReq', { username: Player.getUsername(), numMeeps: $scope.numMeeps });
          meeplePlaced = true;
        } else {
          console.log('Can only place meeple on last tile');
        }
      } else {
        console.log('meeple alrdy placed');
      }
    } else {
      console.log('All outta meeps');
    }
  };

  $scope.cycleMeeple = function(item) {
    if ($scope.currentMeeple) {
      var itemID = angular.element(item.target).attr('id');
      $scope.currentMeeple.attr('class', itemID);
    }
  };

  var setTile = function(x, y) {
    // Check if it's current player's turn
    if ($scope.playerId === socket.id) {
      if (!cellAlreadyExists(x, y)) {
        // Get out current tile generated from nextTurn
        var tile = $scope.currentTile;
        tile.x = x;
        tile.y = y;

        if (validPlacement(tile)) {
          var tilePlaced = true;
          var meeplePlaced = false;
          // We push a new tile onto the grid at xy
          updateGrid(x, y, tile);
          // Set the background image of grid cell
          setCell(tile);
          // emit endturn
          $scope.orientation = 0;
          $scope.tilePlaced = true;
          // Call function place meeples

        } else {
          console.log('Not a valid placement.')
        }
      }
    } else {
      console.log('not your turn');
    }
  };

  var validPlacement = function(tile) {
    var canPlace = 0, northernTile, southernTile, easternTile, westernTile;

    ($scope.grid[tile.y-1] !== undefined) &&
      (northernTile = $scope.grid[tile.y-1][tile.x]);

    ($scope.grid[tile.y][tile.x+1] !== undefined) &&
      (easternTile = $scope.grid[tile.y][tile.x+1]);

    ($scope.grid[tile.y][tile.x-1] !== undefined) &&
      (westernTile = $scope.grid[tile.y][tile.x-1]);

    ($scope.grid[tile.y+1] !== undefined) &&
      (southernTile = $scope.grid[tile.y+1][tile.x]);

    if (
      (northernTile !== undefined) &&
      ((northernTile === null) || (tile.features.n === northernTile.features.s)) ) {
        canPlace += 1;
    }
    if (
      (easternTile !== undefined) &&
      ((easternTile === null) || (tile.features.e === easternTile.features.w)) ) {
        canPlace += 1;
    }
    if (
      (southernTile !== undefined) &&
      ((southernTile === null) || (tile.features.s === southernTile.features.n)) ) {
        canPlace += 1;
    }
    if (
      (westernTile !== undefined) &&
      ((westernTile === null) || (tile.features.w === westernTile.features.e)) ) {
        canPlace += 1;
    }

    if (
      northernTile === null &&
      easternTile  === null &&
      westernTile  === null &&
      southernTile === null ) {
        return false;
    } else {
      return canPlace === 4;
    }
  };

  // These functions should be moved into a factory/service
  var updateGrid = function(x, y, tile) {
    $scope.grid[y][x] = tile;
    // console.log($scope.grid[y]);
  };

  var cellAlreadyExists = function(x, y) {
    return $scope.grid[y][x] !== null;
  };

  var setCell = function(tile) {
    var id = '#' + 'x-' + tile.x + '-y-' + tile.y;
    angular.element(document).ready(function() {
      var domElement = angular.element(document.querySelector(id));
      domElement.css('background-size', 'contain');
      domElement.css('background-image', 'url(' + tile.img + ')');
      domElement.css('transform', 'rotate(' + tile.orientation*90 + 'deg)');
    });
  };

  var placeInitialTile = function() {
    var x = Math.floor($scope.grid.length/2), y = Math.floor($scope.grid.length/2);
    // var x = 0, y = 0;
    var DTile = new TileModel({
      x: x,
      y: y,
      id: 'd',
      features: {
        n: 'city',
        e: 'road',
        w: 'road',
        s: 'grass'
      },
      orientation: 0
    });
    updateGrid(x, y, DTile);
    setCell(DTile);
  };

  // Initialize game board
  $scope.init();
});<commit_msg>add id to tile, need this for server tile implementation<commit_after>// Create our grid module namespace
var grid = angular.module('game.grid', []);

// Returns a tile object
grid.factory('TileModel', function() {
  var Tile = function(tilespec) {
    this.id = tilespec.id;
    this.x = tilespec.x || null;
    this.y = tilespec.y || null;
    this.img = this.getImage(tilespec.id);
    this.val = tilespec.val || 2;
    this.orientation = tilespec.orientation;
    this.meeples = null;
    this.features = tilespec.features;
  };
  Tile.prototype.getImage = function(id) {
    // Grab an image from our asset folder to set as img attribute
    return 'assets/img/Tiles/' + id.toUpperCase() + '.png';
  };
  Tile.prototype.rotateRight = function() {
    this.orientation = (this.orientation + 1) % 4;

    var temp = {};
    for (var key in this.features){
      temp[key] = this.features[key];
    }

    this.features.n = temp.w;
    this.features.e = temp.n;
    this.features.s = temp.e;
    this.features.w = temp.s;
  };
  return Tile;
});

grid.service('GridService', function(TileModel) {
  this.createEmptyGameBoard = function(boardSize) {
    var grid = [];
    var size = boardSize;
    for (var x = 0; x < size; x++) {
      grid[x] = [];
      for (var y = 0; y < size; y++) {
        grid[x][y] = null;
      }
    }
    return grid;
  };
});

grid.controller('gridCtrl', function($scope, TileModel, GridService, Player) {
  var gridSize = 13;
  $scope.orientation = 0;
  $scope.src = null;
  $scope.meepmeep = 'assets/img/Meeples/meeple_' + Player.getColor() + '.png';
  var meeplePlaced = false;

  $scope.range = function() {
    return new Array(gridSize);
  };

  $scope.rotate = function() {
    if ($scope.playerId === socket.id) {
      $scope.orientation = ($scope.orientation + 1) % 4;
      $scope.currentTile.rotateRight();
      // console.log($scope.currentTile);
    }
    // console.log($scope.grid[$scope.currentTile.y][$scope.currentTile.x]);
  };

  $scope.init = function() {
    // Create board
    $scope.grid = GridService.createEmptyGameBoard(gridSize);
    $scope.tilePlaced = false;
    placeInitialTile();

    // Dynamically size grid
    angular.element(document.querySelector('.grid-container')).css('width', gridSize * 52 + 'px');

    socket.on('nextTurn', function(gamestate) {
      if (!gamestate.lastTile) {
        $scope.currentTile = new TileModel(gamestate.nextTile);
      } else {
        $scope.currentTile = new TileModel(gamestate.nextTile);
        updateGrid(gamestate.lastTile.x, gamestate.lastTile.y, gamestate.lastTile);
        setCell(gamestate.lastTile);
      }

      $scope.currentPlayer;
      console.log('Running deckCtrl nextTurn...', gamestate.nextPlayer);
      $scope.currentPlayer = gamestate.nextPlayer;
      // Create a tile model
      $scope.playerId = gamestate.playerSocket;
      $scope.src = $scope.currentTile.img;
      $scope.$apply();
    });

    socket.on('meepDataRes', function(data) {
      $scope.numMeeps = data.numMeeps;
    });
    socket.emit('meepDataReq', { username: Player.getUsername(), numMeeps: 7 });
  };

  $scope.clickCell = function(event, x, y) {
    if ($scope.tilePlaced) {
      setMeeple(event, x, y);
    } else {
      setTile(x, y);
    }
  };

  $scope.endTurn = function() {
    if ($scope.currentTile.x !== null) {
      $scope.tilePlaced = false;
      meeplePlaced = false;
      // Need to pass state of meeple placement to others
      socket.emit('endTurn', $scope.currentTile);
    } else {
      console.log('Cannot end your turn');
    }
  };

  var setMeeple = function(event, x, y) {
    if ($scope.numMeeps > 0) {
      if (!meeplePlaced) {
        if ($scope.currentTile.x === x && $scope.currentTile.y === y) {
          var meepClass = 'meep-x-' + x + '-y-' + y;
          angular.element(event.target).append('');
          $scope.currentMeeple = angular.element(document.querySelector('.'+meepClass));
          $scope.numMeeps--;
          socket.emit('meepDataReq', { username: Player.getUsername(), numMeeps: $scope.numMeeps });
          meeplePlaced = true;
        } else {
          console.log('Can only place meeple on last tile');
        }
      } else {
        console.log('meeple alrdy placed');
      }
    } else {
      console.log('All outta meeps');
    }
  };

  $scope.cycleMeeple = function(item) {
    if ($scope.currentMeeple) {
      var itemID = angular.element(item.target).attr('id');
      $scope.currentMeeple.attr('class', itemID);
    }
  };

  var setTile = function(x, y) {
    // Check if it's current player's turn
    if ($scope.playerId === socket.id) {
      if (!cellAlreadyExists(x, y)) {
        // Get out current tile generated from nextTurn
        var tile = $scope.currentTile;
        tile.x = x;
        tile.y = y;

        if (validPlacement(tile)) {
          var tilePlaced = true;
          var meeplePlaced = false;
          // We push a new tile onto the grid at xy
          updateGrid(x, y, tile);
          // Set the background image of grid cell
          setCell(tile);
          // emit endturn
          $scope.orientation = 0;
          $scope.tilePlaced = true;
          // Call function place meeples

        } else {
          console.log('Not a valid placement.')
        }
      }
    } else {
      console.log('not your turn');
    }
  };

  var validPlacement = function(tile) {
    var canPlace = 0, northernTile, southernTile, easternTile, westernTile;

    ($scope.grid[tile.y-1] !== undefined) &&
      (northernTile = $scope.grid[tile.y-1][tile.x]);

    ($scope.grid[tile.y][tile.x+1] !== undefined) &&
      (easternTile = $scope.grid[tile.y][tile.x+1]);

    ($scope.grid[tile.y][tile.x-1] !== undefined) &&
      (westernTile = $scope.grid[tile.y][tile.x-1]);

    ($scope.grid[tile.y+1] !== undefined) &&
      (southernTile = $scope.grid[tile.y+1][tile.x]);

    if (
      (northernTile !== undefined) &&
      ((northernTile === null) || (tile.features.n === northernTile.features.s)) ) {
        canPlace += 1;
    }
    if (
      (easternTile !== undefined) &&
      ((easternTile === null) || (tile.features.e === easternTile.features.w)) ) {
        canPlace += 1;
    }
    if (
      (southernTile !== undefined) &&
      ((southernTile === null) || (tile.features.s === southernTile.features.n)) ) {
        canPlace += 1;
    }
    if (
      (westernTile !== undefined) &&
      ((westernTile === null) || (tile.features.w === westernTile.features.e)) ) {
        canPlace += 1;
    }

    if (
      northernTile === null &&
      easternTile  === null &&
      westernTile  === null &&
      southernTile === null ) {
        return false;
    } else {
      return canPlace === 4;
    }
  };

  // These functions should be moved into a factory/service
  var updateGrid = function(x, y, tile) {
    $scope.grid[y][x] = tile;
    // console.log($scope.grid[y]);
  };

  var cellAlreadyExists = function(x, y) {
    return $scope.grid[y][x] !== null;
  };

  var setCell = function(tile) {
    var id = '#' + 'x-' + tile.x + '-y-' + tile.y;
    angular.element(document).ready(function() {
      var domElement = angular.element(document.querySelector(id));
      domElement.css('background-size', 'contain');
      domElement.css('background-image', 'url(' + tile.img + ')');
      domElement.css('transform', 'rotate(' + tile.orientation*90 + 'deg)');
    });
  };

  var placeInitialTile = function() {
    var x = Math.floor($scope.grid.length/2), y = Math.floor($scope.grid.length/2);
    // var x = 0, y = 0;
    var DTile = new TileModel({
      x: x,
      y: y,
      id: 'd',
      features: {
        n: 'city',
        e: 'road',
        w: 'road',
        s: 'grass'
      },
      orientation: 0
    });
    updateGrid(x, y, DTile);
    setCell(DTile);
  };

  // Initialize game board
  $scope.init();
});<|endoftext|>