<commit_before>const AWS = require('aws-sdk');
const moment = require('moment');
const BlueBirdPromise = require('bluebird');
const __ = require('lodash');
const base64 = require('base-64');
let util = require('util');

const BaseClient = require('./baseClient');

AWS.config.setPromisesDependency(BlueBirdPromise);

class APIGatewayClient extends BaseClient {

  get _apiGatewayClient() {

    if(!this._internalAPIGatewayClient) {
      const params = {
        accessKeyId: this._accessKey,
        secretAccessKey: this._secretKey,
        apiVersion: '2015-07-09',
        region: this._region
      };
      this._internalAPIGatewayClient = new AWS.APIGateway(params);
    }

    return this._internalAPIGatewayClient;
  }

  _getInvokeUrl(restApiId, stageName) {
    const region = this._region;
    return `https://${restApiId}.execute-api.${region}.amazonaws.com/${stageName}`;
  }

  _getDomainName(restApiId) {
    const region = this._region;
    return `${restApiId}.execute-api.${region}.amazonaws.com`;
  }

  lookupApiGatewayByName(name) {
    const params = {};
    return this._apiGatewayClient.getRestApis(params).promise().then(data => {
      return data.items.find(api => api.name === name);
    });
  }

  lookupStageByStageName(restApiId, stageName) {
    const params = {
      restApiId,
      stageName
    };
    return this._apiGatewayClient.getStage(params).promise();
  }

  lookupApiGatewayURL(apiName, stageName) {
    let restApiId;
    return this.lookupApiGatewayByName(apiName).then(api => {
      if(!api) {
        this.logMessage(`No API avaialble for [RestAPI Name ${apiName}]`);
        return null;
      }
      restApiId = api.id;
      // We are only looking up the StageName to make sure it exists
      return this.lookupStageByStageName(restApiId, stageName);
    }).then(stage => {
      if(!stage) {
        this.logMessage(`No Stage avaialble for [RestAPI Id ${restApiId}][StageName: ${stageName}]`);
        return null;
      }
      return this._getInvokeUrl(restApiId, stageName);
    });
  }

  lookupApiGatewayDomainName(apiName) {
    return this.lookupApiGatewayByName(apiName).then(api => {
      if(!api) {
        this.logMessage(`No API avaialble for [RestAPI Name ${apiName}]`);
        return null;
      }
      return this._getDomainName(api.id);
    });
  }

  createDeployment(restApiId, stageName, variableCollection) {
    if (util.isNullOrUndefined(stageName) || stageName === "") {
      return BlueBirdPromise.reject("stageName must be populated");
    }

    if (util.isNullOrUndefined(restApiId) || restApiId === "") {
      return BlueBirdPromise.reject("restApiId must be populated");
    }

    if (util.isNullOrUndefined(variableCollection) || variableCollection.length === 0) {
      return BlueBirdPromise.reject("variableCollection must be populated");
    }

    return BlueBirdPromise.resolve().then(() => {

      let createParams = {
        restApiId: restApiId, /* required */
        stageName: stageName, /* required */
        cacheClusterEnabled: false,
        description: '',
        variables: variableCollection
      };

      this.logMessage(`Creating Deployment. [ApiGatewayId: ${restApiId}] [StageName: ${stageName}]`);
      return this._apiGatewayClient.createDeployment(createParams).promise();
    }).then(data => {
      const params = {
        restApiId: restApiId,
        stageName: stageName,
        patchOperations: [
          {
            op: 'replace',
            path: '/*/*/logging/loglevel',
            value: 'INFO'
          },
          {
            op: 'replace',
            path: '/*/*/metrics/enabled',
            value: 'true'
          },
          {
            op: 'replace',
            path: '/*/*/logging/dataTrace',
            value: 'true'
          }]
      };
      this.logMessage(`Updating Stage. [ApiGatewayId: ${restApiId}] [StageName: ${stageName}]`);
      return this._apiGatewayClient.updateStage(params).promise();
    }).then(data => {
      this.logMessage(`Success: ${JSON.stringify(data)}`);
    }).catch(err => {
      this.logMessage(err);
      throw err;
    });
  }

  _deployApiGatewayToStage(apiGatewayId, stageName, stageFullName) {
    if (util.isNullOrUndefined(apiGatewayId)) {
      return BlueBirdPromise.reject("apiGatewayId is null or undefined");
    }

    if (util.isNullOrUndefined(stageName)) {
      return BlueBirdPromise.reject("stageName is null or undefined");
    }

    if (util.isNullOrUndefined(stageFullName)) {
      return BlueBirdPromise.reject("stageFullName is null or undefined");
    }

    this.logMessage(`Deploying to '${stageFullName}' Environment`);

    return BlueBirdPromise.resolve().then(() => {
      let params = {
        restApiId: apiGatewayId, /* required */
        stageName: stageName, /* required */
        cacheClusterEnabled: false,
        description: `${stageFullName} - ${moment.utc().format()}`,
        stageDescription: `${stageFullName} - ${moment.utc().format()}`
      };

      this._apiGatewayClient.createDeployment(params).promise();
    });
  }

  _deployApiGatewayToStageForEnvByGatewayName(environment, apiName, delayInMilliseconds = 16000) {
    let methodName = 'deployApiGatewayToStageForEnvByGatewayName';
    let unknown = "UNK";

    if (util.isNullOrUndefined(environment) ||
      util.isNullOrUndefined(environment.FullName) ||
      environment.FullName.toLocaleUpperCase() === unknown ||
      util.isNullOrUndefined(environment.ShortName) ||
      environment.ShortName.toLocaleUpperCase() === unknown) {

      return BlueBirdPromise.reject({
        plugin: methodName,
        message: `environment is not valid [environment: ${this._getObjectAsString(environment)}]`
      });
    }

    if (util.isNullOrUndefined(apiName) || apiName === '') {
      return BlueBirdPromise.reject({
        plugin: methodName,
        message: 'apiName is null or undefined'
      });
    }

    return this.lookupApiGatewayByName(apiName).delay(delayInMilliseconds).then((foundApiId)=> {
      if (util.isNullOrUndefined(foundApiId)) {
        return BlueBirdPromise.reject({
          plugin: methodName,
          message: "foundApiId is null or undefined (no match found)"
        });
      }

      this.logMessage(`Found the foundApid: ${foundApiId}`);

      return this._deployApiGatewayToStage(
        foundApiId,
        environment.ShortName,
        environment.FullName).delay(delayInMilliseconds).then((data) => {
        this.logMessage(`deployApiGatewayToStageForEnvByGatewayName was a success ${this._getObjectAsString(data)}`);
        return BlueBirdPromise.resolve(data);
      }).catch((error) => {
        return BlueBirdPromise.reject({
          plugin: methodName,
          message: this._getObjectAsString(error)
        });
      });
    }).catch((err)=> {
      return BlueBirdPromise.reject(err);
    });
  }

  _createSwagger(swaggerEntity, failOnWarnings = false) {
    this.logMessage(`createSwagger swagger for [Swagger Title: ${swaggerEntity.info.title}]`);

    var options = {
      body: JSON.stringify(swaggerEntity),
      failOnWarnings: failOnWarnings
    };

    return new BlueBirdPromise((resolve, reject) => {
      this._apiGatewayClient.importRestApi(options).promise()
      .then(data => {
        this.logMessage(`createSwagger swagger for [Swagger Title: ${swaggerEntity.info.title}] completed`);
        resolve(data);
      })
      .catch(err => {
        reject(err);
      });
    });
  }

  _overwriteSwagger(apiGatewayId, swaggerEntity, failOnWarnings = false) {
    this.logMessage(`overwriting swagger for [ApiGatewayId: ${apiGatewayId}]`);

    var options = {
      restApiId: apiGatewayId,
      body: JSON.stringify(swaggerEntity),
      failOnWarnings: failOnWarnings,
      mode: "overwrite"
    };

    return new BlueBirdPromise((resolve, reject) => {
      this._apiGatewayClient.putRestApi(options).promise()
      .then(data => {
        resolve(data);
      })
      .catch(err => {
        reject(err);
      });
    });
  }

  createOrOverwriteApiSwagger(swaggerEntity, delayInMilliseconds = 16000, failOnWarnings = false){
    let methodName = 'createOrOverwriteApiSwagger';

    if (util.isNullOrUndefined(swaggerEntity)){
      return BlueBirdPromise.reject({
        plugin: methodName,
        message: `swaggerEntity is null or undefined [swaggerEntity: ${this._getObjectAsString(swaggerEntity)}]`
      });
    }

    if (!swaggerEntity.hasOwnProperty("info") || !swaggerEntity.info.hasOwnProperty("title")){
      return BlueBirdPromise.reject({
        plugin: methodName,
        message: `swaggerEntity must contain info and title [swaggerEntity: ${this._getObjectAsString(swaggerEntity)}]`
      });
    }

    if (util.isNullOrUndefined(swaggerEntity.info.title) || swaggerEntity.info.title === ""){
      return BlueBirdPromise.reject({
        plugin: methodName,
        message: `swaggerEntity.info.title is null, undefined, or empty [swaggerEntity: ${this._getObjectAsString(swaggerEntity)}]`
      });
    }

    return this.lookupApiGatewayByName(swaggerEntity.info.title).then((foundApiId)=> {
      if (util.isNullOrUndefined(foundApiId)) {
        this.logMessage(`${methodName}: creating api gateway`);
        return this._createSwagger(swaggerEntity, failOnWarnings).delay(delayInMilliseconds);
      }

      this.logMessage(`${methodName}: Found the [foundApid: ${foundApiId}]`);

      return this._overwriteSwagger(foundApiId, swaggerEntity, failOnWarnings).delay(delayInMilliseconds).then((data) => {
        this.logMessage(`${methodName} was a success ${this._getObjectAsString(data)}`);
        return BlueBirdPromise.resolve(data);
      }).catch((error) => {
        return BlueBirdPromise.reject({
          plugin: methodName,
          message: this._getObjectAsString(error)
        });
      });
    }).catch((err)=> {
      return BlueBirdPromise.reject(err);
    });
  }

  _getObjectAsString(entity) {
    return util.isNullOrUndefined(entity) ? '' : JSON.stringify(entity);
  }

}

module.exports = APIGatewayClient;
<commit_msg>fixes bug not passing id to the overwrite swaggermethod<commit_after>const AWS = require('aws-sdk');
const moment = require('moment');
const BlueBirdPromise = require('bluebird');
const __ = require('lodash');
const base64 = require('base-64');
let util = require('util');

const BaseClient = require('./baseClient');

AWS.config.setPromisesDependency(BlueBirdPromise);

class APIGatewayClient extends BaseClient {

  get _apiGatewayClient() {

    if(!this._internalAPIGatewayClient) {
      const params = {
        accessKeyId: this._accessKey,
        secretAccessKey: this._secretKey,
        apiVersion: '2015-07-09',
        region: this._region
      };
      this._internalAPIGatewayClient = new AWS.APIGateway(params);
    }

    return this._internalAPIGatewayClient;
  }

  _getInvokeUrl(restApiId, stageName) {
    const region = this._region;
    return `https://${restApiId}.execute-api.${region}.amazonaws.com/${stageName}`;
  }

  _getDomainName(restApiId) {
    const region = this._region;
    return `${restApiId}.execute-api.${region}.amazonaws.com`;
  }

  lookupApiGatewayByName(name) {
    const params = {};
    return this._apiGatewayClient.getRestApis(params).promise().then(data => {
      return data.items.find(api => api.name === name);
    });
  }

  lookupStageByStageName(restApiId, stageName) {
    const params = {
      restApiId,
      stageName
    };
    return this._apiGatewayClient.getStage(params).promise();
  }

  lookupApiGatewayURL(apiName, stageName) {
    let restApiId;
    return this.lookupApiGatewayByName(apiName).then(api => {
      if(!api) {
        this.logMessage(`No API avaialble for [RestAPI Name ${apiName}]`);
        return null;
      }
      restApiId = api.id;
      // We are only looking up the StageName to make sure it exists
      return this.lookupStageByStageName(restApiId, stageName);
    }).then(stage => {
      if(!stage) {
        this.logMessage(`No Stage avaialble for [RestAPI Id ${restApiId}][StageName: ${stageName}]`);
        return null;
      }
      return this._getInvokeUrl(restApiId, stageName);
    });
  }

  lookupApiGatewayDomainName(apiName) {
    return this.lookupApiGatewayByName(apiName).then(api => {
      if(!api) {
        this.logMessage(`No API avaialble for [RestAPI Name ${apiName}]`);
        return null;
      }
      return this._getDomainName(api.id);
    });
  }

  createDeployment(restApiId, stageName, variableCollection) {
    if (util.isNullOrUndefined(stageName) || stageName === "") {
      return BlueBirdPromise.reject("stageName must be populated");
    }

    if (util.isNullOrUndefined(restApiId) || restApiId === "") {
      return BlueBirdPromise.reject("restApiId must be populated");
    }

    if (util.isNullOrUndefined(variableCollection) || variableCollection.length === 0) {
      return BlueBirdPromise.reject("variableCollection must be populated");
    }

    return BlueBirdPromise.resolve().then(() => {

      let createParams = {
        restApiId: restApiId, /* required */
        stageName: stageName, /* required */
        cacheClusterEnabled: false,
        description: '',
        variables: variableCollection
      };

      this.logMessage(`Creating Deployment. [ApiGatewayId: ${restApiId}] [StageName: ${stageName}]`);
      return this._apiGatewayClient.createDeployment(createParams).promise();
    }).then(data => {
      const params = {
        restApiId: restApiId,
        stageName: stageName,
        patchOperations: [
          {
            op: 'replace',
            path: '/*/*/logging/loglevel',
            value: 'INFO'
          },
          {
            op: 'replace',
            path: '/*/*/metrics/enabled',
            value: 'true'
          },
          {
            op: 'replace',
            path: '/*/*/logging/dataTrace',
            value: 'true'
          }]
      };
      this.logMessage(`Updating Stage. [ApiGatewayId: ${restApiId}] [StageName: ${stageName}]`);
      return this._apiGatewayClient.updateStage(params).promise();
    }).then(data => {
      this.logMessage(`Success: ${JSON.stringify(data)}`);
    }).catch(err => {
      this.logMessage(err);
      throw err;
    });
  }

  _deployApiGatewayToStage(apiGatewayId, stageName, stageFullName) {
    if (util.isNullOrUndefined(apiGatewayId)) {
      return BlueBirdPromise.reject("apiGatewayId is null or undefined");
    }

    if (util.isNullOrUndefined(stageName)) {
      return BlueBirdPromise.reject("stageName is null or undefined");
    }

    if (util.isNullOrUndefined(stageFullName)) {
      return BlueBirdPromise.reject("stageFullName is null or undefined");
    }

    this.logMessage(`Deploying to '${stageFullName}' Environment`);

    return BlueBirdPromise.resolve().then(() => {
      let params = {
        restApiId: apiGatewayId, /* required */
        stageName: stageName, /* required */
        cacheClusterEnabled: false,
        description: `${stageFullName} - ${moment.utc().format()}`,
        stageDescription: `${stageFullName} - ${moment.utc().format()}`
      };

      this._apiGatewayClient.createDeployment(params).promise();
    });
  }

  _deployApiGatewayToStageForEnvByGatewayName(environment, apiName, delayInMilliseconds = 16000) {
    let methodName = 'deployApiGatewayToStageForEnvByGatewayName';
    let unknown = "UNK";

    if (util.isNullOrUndefined(environment) ||
      util.isNullOrUndefined(environment.FullName) ||
      environment.FullName.toLocaleUpperCase() === unknown ||
      util.isNullOrUndefined(environment.ShortName) ||
      environment.ShortName.toLocaleUpperCase() === unknown) {

      return BlueBirdPromise.reject({
        plugin: methodName,
        message: `environment is not valid [environment: ${this._getObjectAsString(environment)}]`
      });
    }

    if (util.isNullOrUndefined(apiName) || apiName === '') {
      return BlueBirdPromise.reject({
        plugin: methodName,
        message: 'apiName is null or undefined'
      });
    }

    return this.lookupApiGatewayByName(apiName).delay(delayInMilliseconds).then((foundApiId)=> {
      if (util.isNullOrUndefined(foundApiId)) {
        return BlueBirdPromise.reject({
          plugin: methodName,
          message: "foundApiId is null or undefined (no match found)"
        });
      }

      this.logMessage(`Found the foundApid: ${foundApiId}`);

      return this._deployApiGatewayToStage(
        foundApiId,
        environment.ShortName,
        environment.FullName).delay(delayInMilliseconds).then((data) => {
        this.logMessage(`deployApiGatewayToStageForEnvByGatewayName was a success ${this._getObjectAsString(data)}`);
        return BlueBirdPromise.resolve(data);
      }).catch((error) => {
        return BlueBirdPromise.reject({
          plugin: methodName,
          message: this._getObjectAsString(error)
        });
      });
    }).catch((err)=> {
      return BlueBirdPromise.reject(err);
    });
  }

  _createSwagger(swaggerEntity, failOnWarnings = false) {
    this.logMessage(`createSwagger swagger for [Swagger Title: ${swaggerEntity.info.title}]`);

    var options = {
      body: JSON.stringify(swaggerEntity),
      failOnWarnings: failOnWarnings
    };

    return new BlueBirdPromise((resolve, reject) => {
      this._apiGatewayClient.importRestApi(options).promise()
      .then(data => {
        this.logMessage(`createSwagger swagger for [Swagger Title: ${swaggerEntity.info.title}] completed`);
        resolve(data);
      })
      .catch(err => {
        reject(err);
      });
    });
  }

  _overwriteSwagger(apiGatewayId, swaggerEntity, failOnWarnings = false) {
    this.logMessage(`overwriting swagger for [ApiGatewayId: ${apiGatewayId}]`);

    var options = {
      restApiId: apiGatewayId,
      body: JSON.stringify(swaggerEntity),
      failOnWarnings: failOnWarnings,
      mode: "overwrite"
    };

    return new BlueBirdPromise((resolve, reject) => {
      this._apiGatewayClient.putRestApi(options).promise()
      .then(data => {
        resolve(data);
      })
      .catch(err => {
        reject(err);
      });
    });
  }

  createOrOverwriteApiSwagger(swaggerEntity, delayInMilliseconds = 16000, failOnWarnings = false){
    let methodName = 'createOrOverwriteApiSwagger';

    if (util.isNullOrUndefined(swaggerEntity)){
      return BlueBirdPromise.reject({
        plugin: methodName,
        message: `swaggerEntity is null or undefined [swaggerEntity: ${this._getObjectAsString(swaggerEntity)}]`
      });
    }

    if (!swaggerEntity.hasOwnProperty("info") || !swaggerEntity.info.hasOwnProperty("title")){
      return BlueBirdPromise.reject({
        plugin: methodName,
        message: `swaggerEntity must contain info and title [swaggerEntity: ${this._getObjectAsString(swaggerEntity)}]`
      });
    }

    if (util.isNullOrUndefined(swaggerEntity.info.title) || swaggerEntity.info.title === ""){
      return BlueBirdPromise.reject({
        plugin: methodName,
        message: `swaggerEntity.info.title is null, undefined, or empty [swaggerEntity: ${this._getObjectAsString(swaggerEntity)}]`
      });
    }

    return this.lookupApiGatewayByName(swaggerEntity.info.title).then((foundApi)=> {
      if (util.isNullOrUndefined(foundApi)) {
        this.logMessage(`${methodName}: creating api gateway`);
        return this._createSwagger(swaggerEntity, failOnWarnings).delay(delayInMilliseconds);
      }

      this.logMessage(`${methodName}: Found the [foundApid: ${JSON.stringify(foundApi.id)}]`);

      return this._overwriteSwagger(foundApi.id, swaggerEntity, failOnWarnings).delay(delayInMilliseconds).then((data) => {
        this.logMessage(`${methodName} was a success ${this._getObjectAsString(data)}`);
        return BlueBirdPromise.resolve(data);
      }).catch((error) => {
        return BlueBirdPromise.reject({
          plugin: methodName,
          message: this._getObjectAsString(error)
        });
      });
    }).catch((err)=> {
      return BlueBirdPromise.reject(err);
    });
  }

  _getObjectAsString(entity) {
    return util.isNullOrUndefined(entity) ? '' : JSON.stringify(entity);
  }

}

module.exports = APIGatewayClient;
<|endoftext|>


<commit_before>exports.default = exports.autoBind = function(self, prototype) {
  const keys = Object.getOwnPropertyNames(prototype);

  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    const val = prototype[key];

    if (key !== "constructor" && typeof val === "function") {
      self[key] = val.bind(self);
    }
  }
};
<commit_msg>Gjs: Find slow methods<commit_after>const groupBy = require("lodash/groupBy");
const perf = {};

function toArray(_perf) {
  return Object.keys(_perf)
    .map(location => ({
      location,
      time: _perf[location],
    }))
    .sort((a, b) => b.time - a.time)
    .slice(0, 10);
}

exports.default = exports.autoBind = function(self, prototype) {
  const keys = Object.getOwnPropertyNames(prototype);

  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    const val = prototype[key];

    if (key !== "constructor" && typeof val === "function") {
      self[key] = val.bind(self);

      if (process.env.NODE_ENV === "development") {
        const bound = self[key];

        self[key] = function() {
          const args = Array.prototype.slice.call(arguments);
          const match = /.*app\/(.*)/.exec(new Error().stack.split("\n")[1]);
          const start = Date.now();
          const result = bound.apply(self, args);
          if (match) {
            perf[match[1]] = (perf[match[1]] || 0) + Date.now() - start;
          }
          print(JSON.stringify(toArray(perf)));
          return result;
        };
      }
    }
  }
};
<|endoftext|>


<commit_before>export function config(logEnhancerProvider, $httpProvider, toastrConfig, appConfig) {
	'ngInject';

	// Enable log
	logEnhancerProvider.logLevels = {
		'*': logEnhancerProvider.LEVEL[appConfig.logLevel]
	};

	// Setup http cache
	$httpProvider.defaults.cache = false;
	$httpProvider.useApplyAsync(true);

	// Set options third-party lib
	angular.extend(toastrConfig, {
		allowHtml: true,
		closeButton: false,
		extendedTimeOut: 0,
		positionClass: 'toast-top-right',
		preventDuplicates: true,
		progressBar: false,
		tapToDismiss: true,
		timeOut: 0
	});
}
<commit_msg>Add timeout of 3s back to 'toastr' config<commit_after>export function config(logEnhancerProvider, $httpProvider, toastrConfig, appConfig) {
	'ngInject';

	// Enable log
	logEnhancerProvider.logLevels = {
		'*': logEnhancerProvider.LEVEL[appConfig.logLevel]
	};

	// Setup http cache
	$httpProvider.defaults.cache = false;
	$httpProvider.useApplyAsync(true);

	// Set options third-party lib
	angular.extend(toastrConfig, {
		allowHtml: true,
		closeButton: false,
		extendedTimeOut: 0,
		positionClass: 'toast-top-right',
		preventDuplicates: true,
		progressBar: false,
		tapToDismiss: true,
		timeOut: 3000
	});
}
<|endoftext|>


<commit_before>/* global malarkey:false, moment:false */

import { config } from './index.config';
import { routerConfig } from './index.route';
import { runBlock } from './index.run';
import { MainController } from './main/main.controller';
import { GithubContributorService } from '../app/components/githubContributor/githubContributor.service';
import { WebDevTecService } from '../app/components/webDevTec/webDevTec.service';
import { NavbarDirective } from '../app/components/navbar/navbar.directive';
import { MalarkeyDirective } from '../app/components/malarkey/malarkey.directive';

angular.module('vyapi', ['ui.router', 'toastr'])
  .constant('malarkey', malarkey)
  .constant('moment', moment)
  .config(config)
  .config(routerConfig)
  .run(runBlock)
  .service('githubContributor', GithubContributorService)
  .service('webDevTec', WebDevTecService)
  .controller('MainController', MainController)
  .directive('acmeNavbar', NavbarDirective)
  .directive('acmeMalarkey', MalarkeyDirective);
<commit_msg>modified module.js and added login controller<commit_after>/* global malarkey:false, moment:false */

import { config } from './index.config';
import { routerConfig } from './index.route';
import { runBlock } from './index.run';
import { MainController } from './main/main.controller';
import { LoginController } from './login/login.controller';
import { GithubContributorService } from '../app/components/githubContributor/githubContributor.service';
import { WebDevTecService } from '../app/components/webDevTec/webDevTec.service';
import { NavbarDirective } from '../app/components/navbar/navbar.directive';
import { MalarkeyDirective } from '../app/components/malarkey/malarkey.directive';

angular.module('vyapi', ['ui.router', 'toastr',"firebase"])
  .constant('malarkey', malarkey)
  .constant('moment', moment)
  .config(config)
  .config(routerConfig)
  .run(runBlock)
  .service('githubContributor', GithubContributorService)
  .service('webDevTec', WebDevTecService)
  .controller('MainController', MainController)
  .controller('LoginController', LoginController)
  .directive('acmeNavbar', NavbarDirective)
  .directive('acmeMalarkey', MalarkeyDirective);
<|endoftext|>


<commit_before>// @flow
import { applyMiddleware, compose, createStore } from 'redux'
import { apiMiddleware } from 'redux-api-middleware'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'

import authTokenMiddleware from './middleware/authTokenMiddleware.js'
import themeSaverMiddleware from './middleware/themeSaverMiddleware.js'
import navigatorMiddleware from './middleware/navigatorMiddleware.js'

import rootReducer from './ducks'

// eslint-disable-next-line no-undef
const isProduction = () => process.env.NODE_ENV === 'production'

export default function configureStore(preloadedState) {
  const middlewares = [
    thunk,
    apiMiddleware,
    authTokenMiddleware,
    themeSaverMiddleware,
    navigatorMiddleware,
  ]
  const middlewareEnhancer = applyMiddleware(...middlewares)

  const enhancers = [middlewareEnhancer]

  const makeEnhancer = isProduction() ? compose : composeWithDevTools
  const composedEnhancers = makeEnhancer(...enhancers)

  const store = createStore(rootReducer, preloadedState, composedEnhancers)

  //*
  // eslint-disable-next-line no-undef
  if (process.env.NODE_ENV !== 'production' && module.hot) {
    // eslint-disable-next-line no-undef
    module.hot.accept('./ducks', () => store.replaceReducer(rootReducer))
  }
  // */
  return store
}
<commit_msg>Simplify store creation<commit_after>// @flow
import { apiMiddleware } from 'redux-api-middleware'
import { configureStore } from 'redux-starter-kit'
import thunk from 'redux-thunk'

import authTokenMiddleware from './middleware/authTokenMiddleware.js'
import navigatorMiddleware from './middleware/navigatorMiddleware.js'
import themeSaverMiddleware from './middleware/themeSaverMiddleware.js'

import reducer from './ducks'

// eslint-disable-next-line no-undef
const PRODUCTION = process.env.NODE_ENV === 'production'

let middleware = [
  thunk,
  apiMiddleware,
  authTokenMiddleware,
  navigatorMiddleware,
  themeSaverMiddleware,
]
if (!PRODUCTION)
  middleware = middleware.concat(
    require('redux-immutable-state-invariant').default()
  )

export default () =>
  configureStore({
    reducer,
    middleware,
    devTools: !PRODUCTION,
  })
<|endoftext|>


<commit_before>'use strict';

function formatDate(date) {
    return moment(date).format('YYYY-MM-DD');
}

function isIndividuValid(individu, situation) {
    var age = moment(situation.dateDeValeur).diff(moment(individu.dateDeNaissance), 'years');
    var handicap = individu.specificSituations.indexOf('handicap' ) >= 0;
    return individu.role != 'enfant' || age <= 25 || handicap;
}

function getEnfants(situation) {
    var enfants = _.filter(situation.individus, function(individu) {
        return isIndividuValid(individu, situation) && individu.role == 'enfant';
    });
    return _.map(enfants, 'id');
}

var foyerFiscalSchema = {
    declarants: {
        fn: function(situation) {
            return _.map(_.filter(situation.individus, function(individu) {
                return _.includes(['demandeur', 'conjoint'], individu.role);
            }), 'id');
        },
        copyTo3PreviousMonths: false,
    },
    // Today, in mes-aides, all children and only them are transmitted to Openfisca as personnes à charge
    personnes_a_charge: {
        fn: getEnfants,
        copyTo3PreviousMonths: false,
    },
    rfr: {
        fn: function (situation) {
            if (situation.ressourcesYearMoins2Captured && situation.rfr) {
                var anneeFiscaleN2 = moment(situation.dateDeValeur).subtract(2, 'years').year();
                var result = {};
                result[anneeFiscaleN2] = situation.rfr;
                return result;
            }
        },
        copyTo3PreviousMonths: false,
    },
};

var individuSchema = {
    date_naissance: {
        src: 'dateDeNaissance',
        fn: formatDate
    },
    age: {
        src: 'dateDeNaissance',
        fn: function (dateDeNaissance, individu, situation) {
            return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'years');
        }
    },
    age_en_mois: {
        src: 'dateDeNaissance',
        fn: function (dateDeNaissance, individu, situation) {
            return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'months');
        }
    },
    statut_marital: {
        src: 'statutMarital',
        values: {
            seul: 2,
            mariage: 1,
            pacs: 5,
            union_libre: 2
        }
    },
    id: {
        src: 'id',
        copyTo3PreviousMonths: false
    },
    enceinte: 'enceinte',
    ass_precondition_remplie: 'assPreconditionRemplie',
    date_arret_de_travail: {
        src: 'dateArretDeTravail',
        fn: formatDate
    },
    activite: {
        src: 'specificSituations',
        fn: function(value) {
            var returnValue;
            _.forEach({
                demandeur_emploi: 1,
                etudiant: 2,
                retraite: 3
            }, function(situationIndex, situation) {
                if (value.indexOf(situation) >= 0) {
                    returnValue = situationIndex;
                }
            });
            return returnValue;
        }
    },
    handicap: {
        src: 'specificSituations',
        fn: function(specificSituations) {
            return specificSituations.indexOf('handicap') >= 0;
        }
    },
    taux_incapacite: {
        fn: function(individu) {
            var handicap = individu.specificSituations.indexOf('handicap') >= 0;
            var tauxMap = {
                    moins50: 0.3,
                    moins80: 0.7,
                    plus80: 0.9
            };
            return handicap && tauxMap[individu.tauxIncapacite];
        }
    },
    inapte_travail: {
        src: 'specificSituations',
        fn: function(specificSituations) {
            return specificSituations.indexOf('inapte_travail') >= 0;
        }
    },
    perte_autonomie: 'perteAutonomie',
    etudiant: {
        src: 'specificSituations',
        fn: function(specificSituations) {
            return specificSituations.indexOf('etudiant') >= 0;
        }
    },
    boursier: {
        fn: function(individu) {
            return individu.boursier || individu.echelonBourse >= 0;  // backward compatibility for boursier; cannot write a migration because the exact echelon is not known
        }
    },
    echelon_bourse: 'echelonBourse',
    scolarite: {
        fn: function(individu) {
            var values = {
                'inconnue': 0,
                'college': 1,
                'lycee': 2
            };
            return values[individu.scolarite];
        }
    },
    enfant_a_charge: {
        // variable liée à l'année fiscale : on la définit sur l'année
        fn: function(individu, situation) {
            var year = moment(situation.dateDeValeur).format('YYYY');
            var result = {};
            result[year] = individu.aCharge || (! individu.fiscalementIndependant);
            return result;
        },
        copyTo3PreviousMonths: false,
    },
    enfant_place: 'place',
    garde_alternee: 'gardeAlternee',
    habite_chez_parents: 'habiteChezParents',

    /* Revenus du patrimoine */
    interets_epargne_sur_livrets: {
        src: 'epargneSurLivret',
        fn: function(value) {
            return {
                '2012-01': 0.01 * value || 0
            };
        },
        copyTo3PreviousMonths: false,
    },
    epargne_non_remuneree: {
        src: 'epargneSansRevenus',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        },
        copyTo3PreviousMonths: false
    },
    valeur_locative_immo_non_loue: {
        src: 'valeurLocativeImmoNonLoue',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        },
        copyTo3PreviousMonths: false,
    },
    valeur_locative_terrains_non_loue: {
        src: 'valeurLocativeTerrainNonLoue',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        },
        copyTo3PreviousMonths: false,
    },

    /* Activités non-salarié */
    tns_autres_revenus_type_activite: 'tns_autres_revenus_type_activite',
    tns_auto_entrepreneur_type_activite: 'autoEntrepreneurActiviteType',
    tns_micro_entreprise_type_activite: 'microEntrepriseActiviteType',
};

var familleProperties = [
    'parisien',
    'proprietaire_proche_famille',
    'rsa_isolement_recent',
];

var menageProperties = [
    'charges_locatives',
    'coloc',
    'depcom',
    'logement_chambre',
    'loyer',
    'participation_frais',
    'statut_occupation_logement',
];

angular.module('ddsCommon').constant('mappingSchemas', {
    isIndividuValid: isIndividuValid,
    foyerFiscal: foyerFiscalSchema,
    individu: individuSchema,
    forDuplication: {
        famille: familleProperties,
        menage: menageProperties,
    },
});
<commit_msg>Remove mappingSchemas.foyerFiscal<commit_after>'use strict';

function formatDate(date) {
    return moment(date).format('YYYY-MM-DD');
}

function isIndividuValid(individu, situation) {
    var age = moment(situation.dateDeValeur).diff(moment(individu.dateDeNaissance), 'years');
    var handicap = individu.specificSituations.indexOf('handicap' ) >= 0;
    return individu.role != 'enfant' || age <= 25 || handicap;
}

function getEnfants(situation) {
    var enfants = _.filter(situation.individus, function(individu) {
        return isIndividuValid(individu, situation) && individu.role == 'enfant';
    });
    return _.map(enfants, 'id');
}

var individuSchema = {
    date_naissance: {
        src: 'dateDeNaissance',
        fn: formatDate
    },
    age: {
        src: 'dateDeNaissance',
        fn: function (dateDeNaissance, individu, situation) {
            return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'years');
        }
    },
    age_en_mois: {
        src: 'dateDeNaissance',
        fn: function (dateDeNaissance, individu, situation) {
            return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'months');
        }
    },
    statut_marital: {
        src: 'statutMarital',
        values: {
            seul: 2,
            mariage: 1,
            pacs: 5,
            union_libre: 2
        }
    },
    id: {
        src: 'id',
        copyTo3PreviousMonths: false
    },
    enceinte: 'enceinte',
    ass_precondition_remplie: 'assPreconditionRemplie',
    date_arret_de_travail: {
        src: 'dateArretDeTravail',
        fn: formatDate
    },
    activite: {
        src: 'specificSituations',
        fn: function(value) {
            var returnValue;
            _.forEach({
                demandeur_emploi: 1,
                etudiant: 2,
                retraite: 3
            }, function(situationIndex, situation) {
                if (value.indexOf(situation) >= 0) {
                    returnValue = situationIndex;
                }
            });
            return returnValue;
        }
    },
    handicap: {
        src: 'specificSituations',
        fn: function(specificSituations) {
            return specificSituations.indexOf('handicap') >= 0;
        }
    },
    taux_incapacite: {
        fn: function(individu) {
            var handicap = individu.specificSituations.indexOf('handicap') >= 0;
            var tauxMap = {
                    moins50: 0.3,
                    moins80: 0.7,
                    plus80: 0.9
            };
            return handicap && tauxMap[individu.tauxIncapacite];
        }
    },
    inapte_travail: {
        src: 'specificSituations',
        fn: function(specificSituations) {
            return specificSituations.indexOf('inapte_travail') >= 0;
        }
    },
    perte_autonomie: 'perteAutonomie',
    etudiant: {
        src: 'specificSituations',
        fn: function(specificSituations) {
            return specificSituations.indexOf('etudiant') >= 0;
        }
    },
    boursier: {
        fn: function(individu) {
            return individu.boursier || individu.echelonBourse >= 0;  // backward compatibility for boursier; cannot write a migration because the exact echelon is not known
        }
    },
    echelon_bourse: 'echelonBourse',
    scolarite: {
        fn: function(individu) {
            var values = {
                'inconnue': 0,
                'college': 1,
                'lycee': 2
            };
            return values[individu.scolarite];
        }
    },
    enfant_a_charge: {
        // variable liée à l'année fiscale : on la définit sur l'année
        fn: function(individu, situation) {
            var year = moment(situation.dateDeValeur).format('YYYY');
            var result = {};
            result[year] = individu.aCharge || (! individu.fiscalementIndependant);
            return result;
        },
        copyTo3PreviousMonths: false,
    },
    enfant_place: 'place',
    garde_alternee: 'gardeAlternee',
    habite_chez_parents: 'habiteChezParents',

    /* Revenus du patrimoine */
    interets_epargne_sur_livrets: {
        src: 'epargneSurLivret',
        fn: function(value) {
            return {
                '2012-01': 0.01 * value || 0
            };
        },
        copyTo3PreviousMonths: false,
    },
    epargne_non_remuneree: {
        src: 'epargneSansRevenus',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        },
        copyTo3PreviousMonths: false
    },
    valeur_locative_immo_non_loue: {
        src: 'valeurLocativeImmoNonLoue',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        },
        copyTo3PreviousMonths: false,
    },
    valeur_locative_terrains_non_loue: {
        src: 'valeurLocativeTerrainNonLoue',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        },
        copyTo3PreviousMonths: false,
    },

    /* Activités non-salarié */
    tns_autres_revenus_type_activite: 'tns_autres_revenus_type_activite',
    tns_auto_entrepreneur_type_activite: 'autoEntrepreneurActiviteType',
    tns_micro_entreprise_type_activite: 'microEntrepriseActiviteType',
};

var familleProperties = [
    'parisien',
    'proprietaire_proche_famille',
    'rsa_isolement_recent',
];

var menageProperties = [
    'charges_locatives',
    'coloc',
    'depcom',
    'logement_chambre',
    'loyer',
    'participation_frais',
    'statut_occupation_logement',
];

angular.module('ddsCommon').constant('mappingSchemas', {
    isIndividuValid: isIndividuValid,
    individu: individuSchema,
    forDuplication: {
        famille: familleProperties,
        menage: menageProperties,
    },
});
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>updated feb 22<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.");
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    if (move !== null){return move;}
    else {return getInput();}
    // return /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.

    if (move !== null){return move;}
    else {return randomPlay();}
    // return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    if (playerMove==='rock'){
        if (computerMove==='rock'){
            winner = 'tie';
        }
        else if (computerMove==='scissors'){
            winner='player';
        }
        else{
            winner = 'computer';}
    }
    if (playerMove==='paper'){
        if (computerMove==='rock'){
            winner = 'player';
        }
        else if (computerMove==='scissors'){
            winner='computer';
        }
        else{
            winner = 'tie';}
    }
    if (playerMove==='scissors'){
        if (computerMove==='rock'){
            winner = 'computer';
        }
        else if (computerMove==='scissors'){
            winner='tie';
        }
        else{
            winner = 'player';}
    }

    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    // testing going well
    while (computerWins<5 && playerWins<5){
        //getInput();
        //randomPlay();
        //getPlayerMove();
        //console.log("Player selected: "+getPlayerMove(getInput()));
        //console.log("Computer selected: "+getComputerMove(randomPlay()));
        var result = getWinner(getPlayerMove(getInput()),getComputerMove(randomPlay()));
        if (result==='player'){playerWins+=1;console.log("Player won this one");}
        if (result==='computer'){computerWins+=1;console.log("Computer won this one");}
        console.log("the winner is: " + result );

    console.log(playerWins, computerWins);
    }

    if (playerWins > computerWins){return("PLayer won "+playerWins + " to " +computerWins);}
    else if (playerWins < computerWins){return("Computer won "+computerWins + " to " +playerWins);}

}
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if (
        (playerMove === 'rock' && computerMove === 'scissors') ||
        (playerMove === 'scissors' && computerMove === 'paper') ||
        (playerMove === 'paper' && computerMove === 'rock')
        ) {
        winner = 'player';
    } else if (
        (computerMove === 'rock' && playerMove === 'scissors') ||
        (computerMove === 'scissors' && playerMove === 'paper') ||
        (computerMove === 'paper' && playerMove === 'rock')
        ) {
        winner = 'computer';
    } else if (playerMove === computerMove) {
        winner = 'tie';
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;

    while ((playerWins < 5) || (computerWins < 5)) {
        if winner = 'player'{
            playerWins += 1;
        }
        else if winner = 'computer' {
            computerWins += 1;
        }
        else if winner = 'tie' {
            console.log += ('This is a tie.');
        }
        console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
        console.log('The score is currently ' + playerWins + ' to ' + computerWins);
    }

// This function should continue to play Rock Paper Scissors until either the
// player or the computer has won five times.
// After each 'round', display some text in the console indicating who played
// what, who won, and what the current scoreboard looks like.
// For example,
//  console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
//  console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
/* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Completed game<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if (
        (playerMove === 'rock' && computerMove === 'scissors') ||
        (playerMove === 'scissors' && computerMove === 'paper') ||
        (playerMove === 'paper' && computerMove === 'rock')
        ) {
        winner = 'player';
    } else if (
        (computerMove === 'rock' && playerMove === 'scissors') ||
        (computerMove === 'scissors' && playerMove === 'paper') ||
        (computerMove === 'paper' && playerMove === 'rock')
        ) {
        winner = 'computer';
    } else if (playerMove === computerMove) {
        winner = 'tie';
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    var winner;
    var computerMove;
    var playerMove;

    while ((playerWins < 5) && (computerWins < 5)) {
        playerMove = getPlayerMove();
        computerMove = getComputerMove();
        winner = getWinner(playerMove,computerMove);

        if (winner === 'player') {
            playerWins += 1;
        }
        else if (winner === 'computer') {
            computerWins += 1;
        }
        else if (winner === 'tie') {
            console.log('This is a tie.');
        }
        console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
        console.log('The score is currently ' + playerWins + ' to ' + computerWins);
    }
    return [playerWins, computerWins];

}

playToFive();<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
        if (playerMove === 'rock' && computerMove === 'scissors') {
            winner = 'player';
        }
        else if (playerMove === 'rock' && computerMove === 'paper') {
            winner = 'computer';
        }
        else if (playerMove === 'paper' && computerMove === 'scissors') {
            winner = 'computer';
        }
        else if (playerMove === 'paper' && computerMove === 'rock') {
            winner = 'computer';
        }
        else if (playerMove === 'scissors' && computerMove === 'paper') {
            winner = 'player';
        }
        else if (playerMove === 'scissors' && computerMove === 'rock') {
            winner = 'computer';
        }
        else if (playerMove === computerMove) {
            winner = 'tie';
        }
        else { console.log("Not valid dummy!") }

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>app/js/rockpaperscissors.js<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    return move || getInput();
}

function getComputerMove(move) {
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    if (playerMove === computerMove) {
        winner = 'tie';
    } else if (playerMove === 'rock') {
        if (computerMove === 'scissors') {
          winner = 'player';
        } else if (computerMove === 'paper') {
          winner = 'computer';
        } else if (computerMove === 'rock') {
          winner = 'tie'
        }
    } else if (playerMove === 'scissors') {
        if (computerMove === 'paper') {
          winner = 'player';
        } else if (computerMove === 'rock') {
          winner = 'computer';
        }
    } else if (playerMove === 'paper') {
        if (computerMove === 'rock') {
          winner = 'player';
        } else if (computerMove === 'scissors')
          winner = 'computer';
    } else {
        return "not vaild";
    }
    return winner;
}

function playToFive() {
  console.log('Let\'s play Rock Paper Scissors');
  var playerWins = 0;
  var computerWins = 0;
    while ((playerWins < 5) && (computerWins <= 5)) {
        var playerMove = getPlayerMove(getInput());
        var computerMove = getComputerMove(randomPlay());
        var winner = getWinner(playerMove, computerMove);
        console.log("Player chose " + playerMove + " while the Computer chose " + computerMove + ".");
        console.log('The winner of this round is ' + winner + ".");
        if (winner === 'player') {
            playerWins += 1;
            computerWins = computerWins;
            console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
        } else if (winner === 'computer') {
            playerWins = playerWins;
            computerWins += 1;
            console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
        } else if (winner === 'tie') {
            console.log('No winner. The score is still Player: ' + playerWins + ' to Computer: ' + computerWins + '.');
        } else {
            break;
        }
    }
  return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Completed Rock Paper Scissors exercise<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput(); /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();/* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    if(computerMove == playerMove)
    	winner = "tie";
    else if((computerMove == "rock") && (playerMove == "scissors"))
    	winner = "computer";
    else if((computerMove == "scissors") && (playerMove == "paper"))
    	winner = "computer";
    else if((computerMove == "paper") && (playerMove == "rock"))
    	winner = "computer";

    else if((playerMove == "rock") && (computerMove == "scissors"))
    	winner = "player";
    else if((playerMove == "scissors") && (computerMove == "paper"))
    	winner = "player";
    else if((playerMove == "paper") && (computerMove == "rock"))
    	winner = "player";

    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    do {
    	var playerMove = getPlayerMove();
    	var computerMove = getComputerMove();
    	var winner = getWinner(playerMove,computerMove);
    	if(winner == "player")
    		playerWins++;
    	else if (winner == "computer")
    		computerWins++;

    }
    while ((playerWins != 5) && (computerWins != 5));

    return [playerWins, computerWins];
}

playToFive();
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>modified rockpaperscissors.js<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return var move = 'getInput()';
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return var move = 'randomPlay()';
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
  console.log("Please choose either 'rock', 'paper', or 'scissors'.")
  return prompt();
}

function randomPlay() {
  var randomNumber = Math.random();
  if (randomNumber < 0.33) {
      return "rock";
  } else if (randomNumber < 0.66) {
      return "paper";
  } else {
      return "scissors";
  }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
  // Write an expression that operates on a variable called `move`
  // If a `move` has a value, your expression should evaluate to that value.
  // However, if `move` is not specified / is null, your expression should equal `getInput()`.
  return (move || getInput());
}

function getComputerMove(move) {
  // Write an expression that operates on a variable called `move`
  // If a `move` has a value, your expression should evaluate to that value.
  // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
  return (move || randomPlay());
}

function getWinner(playerMove, computerMove) {
  var winner;

  if (playerMove === 'rock' && computerMove === 'paper')
    winner = 'computerWins'
  else if (playerMove === 'paper' && computerMove === 'rock')
    winner = 'playerWins'
  else if (playerMove === 'paper' && computerMove === 'scissors')
    winner = 'computerWins'
  else if (playerMove === 'scissors' && computerMove === 'paper')
    winner = 'playerWins'
  else if (playerMove === 'rock' && computerMove === 'scissors')
    winner = 'playerWins'
  else if (playerMove === 'scissors' && computerMove === 'rock')
    winner = 'computerWins'
  else if (playerMove === 'rock' && computerMove === 'rock')
    winner = 'Tie'
  else if (playerMove === 'scissors' && computerMove === 'scissors')
    winner = 'Tie'
  else if (playerMove === 'paper' && computerMove === 'paper')
    winner = 'Tie'

  return winner;
}

function playToFive() {
  console.log("Let's play Rock, Paper, Scissors");

  var playerWins = 0;
  var computerWins = 0;

  while (playerWins < 5 && computerWins < 5) {
    var playerMove = getPlayerMove();
    var computerMove = getComputerMove();

    console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);

    var winner = getWinner(playerMove, computerMove);

    if (winner === 'playerWins')
      playerWins += 1;
    else if (winner === 'computerWins')
      computerWins += 1;

    console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
  }

  return [playerWins, computerWins];
}<commit_msg>Finished code<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
  console.log("Please choose either 'rock', 'paper', or 'scissors'.")
  return prompt();
}

function randomPlay() {
  var randomNumber = Math.random();
  if (randomNumber < 0.33) {
      return "rock";
  } else if (randomNumber < 0.66) {
      return "paper";
  } else {
      return "scissors";
  }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {

  return (move || getInput());
}

function getComputerMove(move) {

  return (move || randomPlay());
}

function getWinner(playerMove, computerMove) {
  var winner;

  if (playerMove === 'rock' && computerMove === 'paper')
    winner = 'computerWins'
  else if (playerMove === 'paper' && computerMove === 'rock')
    winner = 'playerWins'
  else if (playerMove === 'paper' && computerMove === 'scissors')
    winner = 'computerWins'
  else if (playerMove === 'scissors' && computerMove === 'paper')
    winner = 'playerWins'
  else if (playerMove === 'rock' && computerMove === 'scissors')
    winner = 'playerWins'
  else if (playerMove === 'scissors' && computerMove === 'rock')
    winner = 'computerWins'
  else if (playerMove === 'rock' && computerMove === 'rock')
    winner = 'Tie'
  else if (playerMove === 'scissors' && computerMove === 'scissors')
    winner = 'Tie'
  else if (playerMove === 'paper' && computerMove === 'paper')
    winner = 'Tie'

  return winner;
}

function playToFive() {
  console.log("Let's play Rock, Paper, Scissors");

  var playerWins = 0;
  var computerWins = 0;

  while (playerWins < 5 && computerWins < 5) {
    var playerMove = getPlayerMove();
    var computerMove = getComputerMove();

    console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);

    var winner = getWinner(playerMove, computerMove);

    if (winner === 'playerWins')
      playerWins += 1;
    else if (winner === 'computerWins')
      computerWins += 1;

    console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
  }

  return [playerWins, computerWins];
}<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    var playerMove = move;
    if (move === null) {
        playerMove = getInput();
    }
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return playerMove;
}

function getComputerMove(move) {
   var computerMove = move;
   if (move === null) {
        computerMove = randomPlay();
    }
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return computerMove;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if (playerMove == computerMove){
        winner = "tie";
    }
    if ((playerMove == "rock" && computerMove == "scissors") || (playerMove == "scissors" && computerMove == "paper") || (playerMove == "paper" && computerMove == "rock")){
        winner = "player";
    }
    if ((computerMove == "rock" && playerMove == "scissors") || (computerMove == "scissors" && playerMove == "paper") || (computerMove == "paper" && playerMove == "rock")){
        winner = "computer";
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    var whoWins = "";
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    while (playerWins < 5 || computerWins < 5) {
        whoWins = getWinner();
        if (whoWins == "player") {
            playerWins += 1;
        }
        if (whoWins == "computer") {
            computerWins += 1;
        }
        console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
        console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
    }
    return [playerWins, computerWins];
}

<commit_msg>Edit playToFive<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    var playerMove = move;
    if (move === null) {
        playerMove = getInput();
    }
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return playerMove;
}

function getComputerMove(move) {
   var computerMove = move;
   if (move === null) {
        computerMove = randomPlay();
    }
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return computerMove;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if (playerMove == computerMove){
        winner = "tie";
    }
    if ((playerMove == "rock" && computerMove == "scissors") || (playerMove == "scissors" && computerMove == "paper") || (playerMove == "paper" && computerMove == "rock")){
        winner = "player";
    }
    if ((computerMove == "rock" && playerMove == "scissors") || (computerMove == "scissors" && playerMove == "paper") || (computerMove == "paper" && playerMove == "rock")){
        winner = "computer";
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    var whoWins = "";
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    while (playerWins < 5 || computerWins < 5) {
        whoWins = getWinner();
        if (whoWins == "player") {
            playerWins += 1;
        }
        if (whoWins == "computer") {
            computerWins += 1;
        }
        console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
        if (playerWins == 5) {
            console.log('Player Won! The score is ' + playerWins + ' to ' + computerWins + '\n')
        }
        else if (computerWins == 5) {
            console.log('Computer Won! The score is ' + playerWins + ' to ' + computerWins + '\n')
        }
        else {
            console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
        }
    }
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>function LevelViewCtrl(
  $sce, $state, $stateParams, CurrentUserService, LevelService, LevelHintService,
  LevelValidationService, LoggerService, Restangular
) {
  var vm = this;

  // Init to undefined to avoid Bind Once not listening to future changes
  vm.level = undefined;
  vm.orgLevel = undefined;

  vm.validate = validate;
  vm.buyLevel = buyLevel;
  vm.requestLevelInstance = requestLevelInstance;

  var currentOrg = CurrentUserService.getOrganization();

  vm.organizationBoughtLevel = function(orgLevel) {
    return orgLevel && angular.isDefined(orgLevel.level);
  };

  init();

  /** Retrieve level info along side level instances */
  function init() {
    // Fetchs level info then decorates with all available level info
    LevelService.getLevel($stateParams.id).then(function(level) {
      vm.level = level
      loadBoughtLevel();
    });
  }

  function loadBoughtLevel() {
    // Fetches status of the level for current organization
    LevelService.getOrganizationLevel(currentOrg, vm.level)
      .then(function(orgLevel) {
        if (orgLevel._id) {
          vm.orgLevel = orgLevel;
          vm.level.bought = true;

          // Fetches running instances of the level
          LevelService.getLevelInstances({
            where: {
              level: vm.level._id
            }
          }).then(function(instances) {
            if (instances) {
              vm.level.instances = instances;
            }
          });
        }
      });
  }

  /** Validate level with passphrase and validation message */
  function validate(validation) {
    LevelValidationService.validateOrganizationLevel(validation, vm.orgLevel)
      .then(
        //SUCCESS
        function(data) {
          vm.orgLevel.has_access = false; //switch to orgLevel
          LoggerService.success('Congratulations, your validation is pending validation !');
          $state.reload();
        },
        // ERROR
        function(response) {
          LoggerService.errorFromResponse(response);
        }
      );

  }

  function buyLevel(level) {

    var currentOrg = CurrentUserService.getOrganization();

    if (currentOrg.statistics.cash - level.price < 0) {
      LoggerService.error('You do not have enough cash to buy this level');
      return false;
    }

    return LevelService.buyLevelbyOrganizationId(
      level._id, currentOrg._id
    )
    .then(buyLevelSuccess)
    .catch(function(response) {
      LoggerService.errorFromResponse(response);
    });

    function buyLevelSuccess() {
      level.bought = true;

      LoggerService.success("Level "+level.name+" succesfully bought !");
      CurrentUserService.loadOrganizationStatistics();
      loadBoughtLevel(); //use object in 201 instead of researching
    }
  }

  function requestLevelInstance(instance) {
    //TODO: Put this in a service

    return Restangular.all('level-instance-users').post({
      level_instance: instance._id,
      organization: vm.orgLevel.organization
    })
    .then(function(response) {
      return Restangular.one('level-instance-users', response.data._id)
        .get()
        .then(function(userLevelInstance) {
          var user = CurrentUserService.getUser();
          var hash = userLevelInstance.data.hash;
          var parts = instance.urls[0].url
                      .replace('http://', '').replace('/', '').split(':');

          var url = 'http://'+user.login+':'+hash+'@'+parts[0]+':'+parts[1]+'/';
          instance.grantedUrl = $sce.trustAsResourceUrl(url);

          selectInstance(instance);
        });
      LoggerService.success('New access granted to level '+vm.level.name+'.');
    })
    .catch(LoggerService.errorFromResponse);
  }

  function selectInstance(instance) {
    vm.selectedInstance = instance;
  }

}

angular
  .module('portal.levels')
  .controller('LevelViewCtrl', LevelViewCtrl);
<commit_msg>update cash on validation succesful<commit_after>function LevelViewCtrl(
  $sce, $state, $stateParams, CurrentUserService, LevelService, LevelHintService,
  LevelValidationService, LoggerService, Restangular
) {
  var vm = this;

  // Init to undefined to avoid Bind Once not listening to future changes
  vm.level = undefined;
  vm.orgLevel = undefined;

  vm.validate = validate;
  vm.buyLevel = buyLevel;
  vm.requestLevelInstance = requestLevelInstance;

  var currentOrg = CurrentUserService.getOrganization();

  vm.organizationBoughtLevel = function(orgLevel) {
    return orgLevel && angular.isDefined(orgLevel.level);
  };

  init();

  /** Retrieve level info along side level instances */
  function init() {
    // Fetchs level info then decorates with all available level info
    LevelService.getLevel($stateParams.id).then(function(level) {
      vm.level = level
      loadBoughtLevel();
    });
  }

  function loadBoughtLevel() {
    // Fetches status of the level for current organization
    LevelService.getOrganizationLevel(currentOrg, vm.level)
      .then(function(orgLevel) {
        if (orgLevel._id) {
          vm.orgLevel = orgLevel;
          vm.level.bought = true;

          // Fetches running instances of the level
          LevelService.getLevelInstances({
            where: {
              level: vm.level._id
            }
          }).then(function(instances) {
            if (instances) {
              vm.level.instances = instances;
            }
          });
        }
      });
  }

  /** Validate level with passphrase and validation message */
  function validate(validation) {
    LevelValidationService.validateOrganizationLevel(validation, vm.orgLevel)
      .then(
        //SUCCESS
        function(data) {
          vm.orgLevel.has_access = false; //switch to orgLevel
          LoggerService.success('Congratulations, your validation is pending validation !');
          CurrentUserService.loadOrganizationStatistics();
          $state.reload();
        },
        // ERROR
        function(response) {
          LoggerService.errorFromResponse(response);
        }
      );

  }

  function buyLevel(level) {

    var currentOrg = CurrentUserService.getOrganization();

    if (currentOrg.statistics.cash - level.price < 0) {
      LoggerService.error('You do not have enough cash to buy this level');
      return false;
    }

    return LevelService.buyLevelbyOrganizationId(
      level._id, currentOrg._id
    )
    .then(buyLevelSuccess)
    .catch(function(response) {
      LoggerService.errorFromResponse(response);
    });

    function buyLevelSuccess() {
      level.bought = true;

      LoggerService.success("Level "+level.name+" succesfully bought !");
      CurrentUserService.loadOrganizationStatistics();
      loadBoughtLevel(); //use object in 201 instead of researching
    }
  }

  function requestLevelInstance(instance) {
    //TODO: Put this in a service

    return Restangular.all('level-instance-users').post({
      level_instance: instance._id,
      organization: vm.orgLevel.organization
    })
    .then(function(response) {
      return Restangular.one('level-instance-users', response.data._id)
        .get()
        .then(function(userLevelInstance) {
          var user = CurrentUserService.getUser();
          var hash = userLevelInstance.data.hash;
          var parts = instance.urls[0].url
                      .replace('http://', '').replace('/', '').split(':');

          var url = 'http://'+user.login+':'+hash+'@'+parts[0]+':'+parts[1]+'/';
          instance.grantedUrl = $sce.trustAsResourceUrl(url);

          selectInstance(instance);
        });
      LoggerService.success('New access granted to level '+vm.level.name+'.');
    })
    .catch(LoggerService.errorFromResponse);
  }

  function selectInstance(instance) {
    vm.selectedInstance = instance;
  }

}

angular
  .module('portal.levels')
  .controller('LevelViewCtrl', LevelViewCtrl);
<|endoftext|>


<commit_before>import { debug } from './debug.js';
import { Utils } from './utils';

/**
 * @summary A list of all registered callback hooks
 */
export const CallbackHooks = [];

/**
 * @summary Callback hooks provide an easy way to add extra steps to common operations.
 * @namespace Callbacks
 */
export const Callbacks = {};

/**
 * @summary Register a callback
 * @param {String} hook - The name of the hook
 * @param {Function} callback - The callback function
 */
export const registerCallback = function (callback) {
  CallbackHooks.push(callback);
};

/**
 * @summary Add a callback function to a hook
 * @param {String} hook - The name of the hook
 * @param {Function} callback - The callback function
 */
export const addCallback = function (hook, callback) {

  if (!callback.name) {
    // eslint-disable-next-line no-console
    console.log(`// Warning! You are adding an unnamed callback to ${hook}. Please use the function foo () {} syntax.`);
  }

  // if callback array doesn't exist yet, initialize it
  if (typeof Callbacks[hook] === "undefined") {
    Callbacks[hook] = [];
  }

  Callbacks[hook].push(callback);
};

/**
 * @summary Remove a callback from a hook
 * @param {string} hook - The name of the hook
 * @param {string} functionName - The name of the function to remove
 */
export const removeCallback = function (hookName, callbackName) {
  Callbacks[hookName] = _.reject(Callbacks[hookName], function (callback) {
    return callback.name === callbackName;
  });
};

/**
 * @summary Successively run all of a hook's callbacks on an item
 * @param {String} hook - First argument: the name of the hook
 * @param {Object} item - Second argument: the post, comment, modifier, etc. on which to run the callbacks
 * @param {Any} args - Other arguments will be passed to each successive iteration
 * @returns {Object} Returns the item after it's been through all the callbacks for this hook
 */
export const runCallbacks = function () {

  // the first argument is the name of the hook or an array of functions
  const hook = arguments[0];
  // find registered hook
  const registeredHook = CallbackHooks.find(({ name }) => name === hook);
  // the second argument is the item on which to iterate; wrap it with promise if hook is async
  const item = registeredHook && registeredHook.runs === 'async'
    ? Promise.resolve(arguments[1])
    : arguments[1];
  // successive arguments are passed to each iteration
  const args = Array.prototype.slice.call(arguments).slice(2);
  // flag used to detect the callback that initiated the async context
  let asyncContext = Utils.isPromise(item);

  const callbacks = Array.isArray(hook) ? hook : Callbacks[hook];

  if (typeof callbacks !== "undefined" && !!callbacks.length) { // if the hook exists, and contains callbacks to run

    const runCallback = (accumulator, callback) => {
      debug(`\x1b[32m>> Running callback [${callback.name}] on hook [${hook}]\x1b[0m`);
      const newArguments = [accumulator].concat(args);

      try {
        const result = callback.apply(this, newArguments);

        // if callback is only supposed to run once, remove it
        if (callback.runOnce) {
          removeCallback(hook, callback.name);
        }

        if (typeof result === 'undefined') {
          // if result of current iteration is undefined, don't pass it on
          // debug(`// Warning: Sync callback [${callback.name}] in hook [${hook}] didn't return a result!`)
          return accumulator;
        } else if (Utils.isPromise(result)) {
          if (registeredHook && registeredHook.runs === 'sync') {
            console.log(`// Warning! Async callback [${callback.name}] executed in sync hook [${hook}], its value is being skipped.`);
            return accumulator;
          } else if (!asyncContext) {
            debug(`\x1b[32m>> Started async context in hook [${hook}] by [${callback.name}]\x1b[0m`);
            asyncContext = true;
          }
        }
        return result;
      } catch (error) {
        // eslint-disable-next-line no-console
        console.log(`\x1b[31m// error at callback [${callback.name}] in hook [${hook}]\x1b[0m`);
        // eslint-disable-next-line no-console
        console.log(error);
        if (error.break || error.data && error.data.break) {
          throw error;
        }
        // pass the unchanged accumulator to the next iteration of the loop
        return accumulator;
      }
    };

    return callbacks.reduce(function (accumulator, callback) {
      if (Utils.isPromise(accumulator)) {
        return new Promise((resolve, reject) => {
          accumulator
            .then(result => {
              try {
                // run this callback once we have the previous value
                resolve(runCallback(result, callback));
              } catch (error) {
                // error will be thrown only for breaking errors, so throw it up in the promise chain
                reject(error);
              }
            })
            .catch(reject);
        });
      } else {
        return runCallback(accumulator, callback);
      }
    }, item);

  } else { // else, just return the item unchanged
    return item;
  }
};

/**
 * @summary Successively run all of a hook's callbacks on an item, in async mode (only works on server)
 * @param {String} hook - First argument: the name of the hook
 * @param {Any} args - Other arguments will be passed to each successive iteration
 */
export const runCallbacksAsync = function () {

  // the first argument is the name of the hook or an array of functions
  var hook = arguments[0];
  // successive arguments are passed to each iteration
  var args = Array.prototype.slice.call(arguments).slice(1);

  const callbacks = Array.isArray(hook) ? hook : Callbacks[hook];

  if (Meteor.isServer && typeof callbacks !== "undefined" && !!callbacks.length) {

    // use defer to avoid holding up client
    Meteor.defer(function () {
      // run all post submit server callbacks on post object successively
      callbacks.forEach(function (callback) {
        debug(`\x1b[32m>> Running async callback [${callback.name}] on hook [${hook}]\x1b[0m`);
        callback.apply(this, args);
      });
    });

  }

};<commit_msg>update documentation<commit_after>import { debug } from './debug.js';
import { Utils } from './utils';

/**
 * @summary A list of all registered callback hooks
 */
export const CallbackHooks = [];

/**
 * @summary Callback hooks provide an easy way to add extra steps to common operations.
 * @namespace Callbacks
 */
export const Callbacks = {};

/**
 * @summary Register a callback
 * @param {String} hook - The name of the hook
 * @param {Function} callback - The callback function
 */
export const registerCallback = function (callback) {
  CallbackHooks.push(callback);
};

/**
 * @summary Add a callback function to a hook
 * @param {String} hook - The name of the hook
 * @param {Function} callback - The callback function
 */
export const addCallback = function (hook, callback) {

  if (!callback.name) {
    // eslint-disable-next-line no-console
    console.log(`// Warning! You are adding an unnamed callback to ${hook}. Please use the function foo () {} syntax.`);
  }

  // if callback array doesn't exist yet, initialize it
  if (typeof Callbacks[hook] === "undefined") {
    Callbacks[hook] = [];
  }

  Callbacks[hook].push(callback);
};

/**
 * @summary Remove a callback from a hook
 * @param {string} hook - The name of the hook
 * @param {string} functionName - The name of the function to remove
 */
export const removeCallback = function (hookName, callbackName) {
  Callbacks[hookName] = _.reject(Callbacks[hookName], function (callback) {
    return callback.name === callbackName;
  });
};

/**
 * @summary Successively run all of a hook's callbacks on an item
 * @param {String} hook - First argument: the name of the hook
 * @param {Any|Promise<Any>} item - Second argument: the post, comment, modifier, etc. on which to run the callbacks
 * @param {Any} args - Other arguments will be passed to each successive iteration
 * @returns {Any|Promise<Any>} Returns the item after it's been through all the callbacks for this hook
 */
export const runCallbacks = function () {

  // the first argument is the name of the hook or an array of functions
  const hook = arguments[0];
  // find registered hook
  const registeredHook = CallbackHooks.find(({ name }) => name === hook);
  // the second argument is the item on which to iterate; wrap it with promise if hook is async
  const item = registeredHook && registeredHook.runs === 'async'
    ? Promise.resolve(arguments[1])
    : arguments[1];
  // successive arguments are passed to each iteration
  const args = Array.prototype.slice.call(arguments).slice(2);
  // flag used to detect the callback that initiated the async context
  let asyncContext = Utils.isPromise(item);

  const callbacks = Array.isArray(hook) ? hook : Callbacks[hook];

  if (typeof callbacks !== "undefined" && !!callbacks.length) { // if the hook exists, and contains callbacks to run

    const runCallback = (accumulator, callback) => {
      debug(`\x1b[32m>> Running callback [${callback.name}] on hook [${hook}]\x1b[0m`);
      const newArguments = [accumulator].concat(args);

      try {
        const result = callback.apply(this, newArguments);

        // if callback is only supposed to run once, remove it
        if (callback.runOnce) {
          removeCallback(hook, callback.name);
        }

        if (typeof result === 'undefined') {
          // if result of current iteration is undefined, don't pass it on
          // debug(`// Warning: Sync callback [${callback.name}] in hook [${hook}] didn't return a result!`)
          return accumulator;
        } else if (Utils.isPromise(result)) {
          if (registeredHook && registeredHook.runs === 'sync') {
            console.log(`// Warning! Async callback [${callback.name}] executed in sync hook [${hook}], its value is being skipped.`);
            return accumulator;
          } else if (!asyncContext) {
            debug(`\x1b[32m>> Started async context in hook [${hook}] by [${callback.name}]\x1b[0m`);
            asyncContext = true;
          }
        }
        return result;
      } catch (error) {
        // eslint-disable-next-line no-console
        console.log(`\x1b[31m// error at callback [${callback.name}] in hook [${hook}]\x1b[0m`);
        // eslint-disable-next-line no-console
        console.log(error);
        if (error.break || error.data && error.data.break) {
          throw error;
        }
        // pass the unchanged accumulator to the next iteration of the loop
        return accumulator;
      }
    };

    return callbacks.reduce(function (accumulator, callback) {
      if (Utils.isPromise(accumulator)) {
        return new Promise((resolve, reject) => {
          accumulator
            .then(result => {
              try {
                // run this callback once we have the previous value
                resolve(runCallback(result, callback));
              } catch (error) {
                // error will be thrown only for breaking errors, so throw it up in the promise chain
                reject(error);
              }
            })
            .catch(reject);
        });
      } else {
        return runCallback(accumulator, callback);
      }
    }, item);

  } else { // else, just return the item unchanged
    return item;
  }
};

/**
 * @summary Successively run all of a hook's callbacks on an item, in async mode (only works on server)
 * @param {String} hook - First argument: the name of the hook
 * @param {Any} args - Other arguments will be passed to each successive iteration
 */
export const runCallbacksAsync = function () {

  // the first argument is the name of the hook or an array of functions
  var hook = arguments[0];
  // successive arguments are passed to each iteration
  var args = Array.prototype.slice.call(arguments).slice(1);

  const callbacks = Array.isArray(hook) ? hook : Callbacks[hook];

  if (Meteor.isServer && typeof callbacks !== "undefined" && !!callbacks.length) {

    // use defer to avoid holding up client
    Meteor.defer(function () {
      // run all post submit server callbacks on post object successively
      callbacks.forEach(function (callback) {
        debug(`\x1b[32m>> Running async callback [${callback.name}] on hook [${hook}]\x1b[0m`);
        callback.apply(this, args);
      });
    });

  }

};<|endoftext|>