<commit_before>/**
 * Created by aleckim on 2017. 2. 3..
 */

"use strict";

/**
 *
 * @constructor
 */
function UnitConverter() {

}

//setUnits
UnitConverter.prototype._convertTemperature = function(from, to, val) {
    if ( from == 'C') {
        if (to == 'F') {
            return parseFloat((val/(5/9)+32).toFixed(1));
        }
    }
    else if (from =='F') {
        if (to == 'C') {
            return parseFloat(((val - 32) / (9/5)).toFixed(1));
        }
    }
    log.error('Fail to convert from '+from+" to "+to+" value="+val);
    return val;
};

UnitConverter.prototype._getBeaufort = function(ms) {
    if (ms < 0.3) {
        return 0;
    }
    else if (ms < 1.5) {
        return 1;
    }
    else if (ms < 3.3) {
        return 2;
    }
    else if (ms < 5.5) {
        return 3;
    }
    else if (ms < 8.0) {
        return 4;
    }
    else if (ms < 10.8) {
        return 5;
    }
    else if (ms < 13.9) {
        return 6;
    }
    else if (ms < 17.2) {
        return 7;
    }
    else if (ms < 20.7) {
        return 8;
    }
    else if (ms < 24.5) {
        return 9;
    }
    else if (ms < 28.4) {
        return 10;
    }
    else if (ms < 32.6) {
        return 11;
    }
    else if (ms >= 32.6) {
        return 12;
    }
};

UnitConverter.prototype._convertBeaufortToMs = function(val) {
    switch (val) {
        case 0: return 0;
        case 1: return 0.3;
        case 2: return 1.5;
        case 3: return 3.3;
        case 4: return 5.5;
        case 5: return 8.0;
        case 6: return 10.8;
        case 7: return 13.9;
        case 8: return 17.2;
        case 9: return 20.7;
        case 10: return 24.5;
        case 11: return 28.4;
        case 12: return 32.6;
    }
};

UnitConverter.prototype._convertWindSpeed = function(from, to, val) {
    var self = this;

    switch(from) {
        case 'mph':
            switch (to) {
                case 'km/h':
                    return parseFloat((val * 1.609344).toFixed(1));
                    break;
                case 'm/s':
                    return parseFloat((val * 0.44704).toFixed(1));
                    break;
                case 'bft':
                    return self._getBeaufort(parseFloat((val * 0.44704).toFixed(1)));
                    break;
                case 'kt':
                    return parseFloat((val * 0.868976).toFixed(1));
                    break;
            }
            break;
        case 'km/h':
            switch (to) {
                case 'mph':
                    return parseFloat((val * 0.621371).toFixed(1));
                    break;
                case 'm/s':
                    return parseFloat((val * 0.277778).toFixed(1));
                    break;
                case 'bft':
                    return self._getBeaufort(parseFloat((val * 0.277778).toFixed(1)));
                    break;
                case 'kt':
                    return parseFloat((val * 0.539957).toFixed(1));
                    break;
            }
            break;
        case 'm/s':
            switch (to) {
                case 'mph':
                    return parseFloat((val * 2.236936).toFixed(1));
                    break;
                case 'km/h':
                    return parseFloat((val * 3.6).toFixed(1));
                    break;
                case 'bft':
                    return self._getBeaufort(val);
                    break;
                case 'kt':
                    return parseFloat((val * 1.943844).toFixed(1));
                    break;
            }
            break;
        case 'bft':
            var ms = self._convertBeaufortToMs(val);
            switch (to) {
                case 'mph':
                    return parseFloat((ms * 2.236936).toFixed(1));
                    break;
                case 'km/h':
                    return parseFloat((ms * 3.6).toFixed(1));
                    break;
                case 'm/s':
                    return ms;
                    break;
                case 'kt':
                    return parseFloat((ms * 1.943844).toFixed(1));
                    break;
            }
            break;
        case 'kt':
            switch (to) {
                case 'mph':
                    return parseFloat((val * 1.150779).toFixed(1));
                    break;
                case 'km/h':
                    return parseFloat((val * 1.852).toFixed(1));
                    break;
                case 'm/s':
                    return parseFloat((val * 0.514444).toFixed(1));
                    break;
                case 'bft':
                    return self._getBeaufort(parseFloat((val * 0.514444).toFixed(1)));
                    break;
            }
            break;
    }
};

UnitConverter.prototype._convertPressure = function(from, to, val) {
    switch (from) {
        case 'mmHg':
            switch (to) {
                case 'inHg' :
                    return parseFloat((val*0.03937).toFixed(1));
                    break;
                case 'hPa' :
                case 'mb' :
                    return parseFloat((val*1.333224).toFixed(1));
                    break;
            }
            break;
        case 'inHg':
            switch (to) {
                case 'mmHg' :
                    return parseFloat((val*25.4).toFixed(1));
                    break;
                case 'hPa' :
                case 'mb' :
                    return parseFloat((val*33.863882).toFixed(1));
                    break;
            }
            break;
        case 'hPa':
        case 'mb':
            switch (to) {
                case 'mmHg' :
                    return parseFloat((val*0.750062).toFixed(1));
                    break;
                case 'inHg' :
                    return parseFloat((val*0.02953).toFixed(1));
                    break;
                case 'hPa' :
                case 'mb' :
                    return val;
                    break;
            }
    }
};

UnitConverter.prototype._convertDistance = function(from, to, val) {
    if (from == 'm') {
        return parseFloat((val*39.370079).toFixed(1));
    }
    else if (from =='mi') {
        return parseFloat((val*0.0254).toFixed(1));
    }
};

UnitConverter.prototype._convertPrecipitation = function(from, to, val) {
    if (from == 'mm') {
        return parseFloat((val*0.03937).toFixed(1));
    }
    else if (from =='in') {
        return parseFloat((val*25.4).toFixed(1));
    }
};

UnitConverter.prototype.convertUnits = function (from, to, val) {
    var self = this;

    if (val == undefined) {
        log.error("val is undefined!!");
        return val;
    }
    if (from == to) {
        return val;
    }

    if (from == 'C' || from == 'F') {
        return self._convertTemperature(from, to, val);
    }
    if (from == 'mph' || from == 'km/h' || from == 'm/s' || from == 'bft' || from == 'kt') {
        return self._convertWindSpeed(from, to, val);
    }
    if (from == 'mmHg' || from == 'inHg' || from == 'hPa' || from == 'mb') {
        return self._convertPressure(from, to, val);
    }
    if (from == 'm' || from == 'mi') {
        return self._convertDistance(from, to, val);
    }
    if (from == 'mm' || from == 'in') {
        return self._convertPrecipitation(from, to, val);
    }

    log.error('Fail to convert from '+from+" to "+to+" value="+val);
    return val;
};

module.exports = UnitConverter;

<commit_msg>log level 수정<commit_after>/**
 * Created by aleckim on 2017. 2. 3..
 */

"use strict";

/**
 *
 * @constructor
 */
function UnitConverter() {

}

//setUnits
UnitConverter.prototype._convertTemperature = function(from, to, val) {
    if ( from == 'C') {
        if (to == 'F') {
            return parseFloat((val/(5/9)+32).toFixed(1));
        }
    }
    else if (from =='F') {
        if (to == 'C') {
            return parseFloat(((val - 32) / (9/5)).toFixed(1));
        }
    }
    if (from == undefined) {
        log.error('Fail to convert from '+from+" to "+to+" value="+val);
    }
    else {
        log.warn('Fail to convert from '+from+" to "+to+" value="+val);
    }
    return val;
};

UnitConverter.prototype._getBeaufort = function(ms) {
    if (ms < 0.3) {
        return 0;
    }
    else if (ms < 1.5) {
        return 1;
    }
    else if (ms < 3.3) {
        return 2;
    }
    else if (ms < 5.5) {
        return 3;
    }
    else if (ms < 8.0) {
        return 4;
    }
    else if (ms < 10.8) {
        return 5;
    }
    else if (ms < 13.9) {
        return 6;
    }
    else if (ms < 17.2) {
        return 7;
    }
    else if (ms < 20.7) {
        return 8;
    }
    else if (ms < 24.5) {
        return 9;
    }
    else if (ms < 28.4) {
        return 10;
    }
    else if (ms < 32.6) {
        return 11;
    }
    else if (ms >= 32.6) {
        return 12;
    }
};

UnitConverter.prototype._convertBeaufortToMs = function(val) {
    switch (val) {
        case 0: return 0;
        case 1: return 0.3;
        case 2: return 1.5;
        case 3: return 3.3;
        case 4: return 5.5;
        case 5: return 8.0;
        case 6: return 10.8;
        case 7: return 13.9;
        case 8: return 17.2;
        case 9: return 20.7;
        case 10: return 24.5;
        case 11: return 28.4;
        case 12: return 32.6;
    }
};

UnitConverter.prototype._convertWindSpeed = function(from, to, val) {
    var self = this;

    switch(from) {
        case 'mph':
            switch (to) {
                case 'km/h':
                    return parseFloat((val * 1.609344).toFixed(1));
                    break;
                case 'm/s':
                    return parseFloat((val * 0.44704).toFixed(1));
                    break;
                case 'bft':
                    return self._getBeaufort(parseFloat((val * 0.44704).toFixed(1)));
                    break;
                case 'kt':
                    return parseFloat((val * 0.868976).toFixed(1));
                    break;
            }
            break;
        case 'km/h':
            switch (to) {
                case 'mph':
                    return parseFloat((val * 0.621371).toFixed(1));
                    break;
                case 'm/s':
                    return parseFloat((val * 0.277778).toFixed(1));
                    break;
                case 'bft':
                    return self._getBeaufort(parseFloat((val * 0.277778).toFixed(1)));
                    break;
                case 'kt':
                    return parseFloat((val * 0.539957).toFixed(1));
                    break;
            }
            break;
        case 'm/s':
            switch (to) {
                case 'mph':
                    return parseFloat((val * 2.236936).toFixed(1));
                    break;
                case 'km/h':
                    return parseFloat((val * 3.6).toFixed(1));
                    break;
                case 'bft':
                    return self._getBeaufort(val);
                    break;
                case 'kt':
                    return parseFloat((val * 1.943844).toFixed(1));
                    break;
            }
            break;
        case 'bft':
            var ms = self._convertBeaufortToMs(val);
            switch (to) {
                case 'mph':
                    return parseFloat((ms * 2.236936).toFixed(1));
                    break;
                case 'km/h':
                    return parseFloat((ms * 3.6).toFixed(1));
                    break;
                case 'm/s':
                    return ms;
                    break;
                case 'kt':
                    return parseFloat((ms * 1.943844).toFixed(1));
                    break;
            }
            break;
        case 'kt':
            switch (to) {
                case 'mph':
                    return parseFloat((val * 1.150779).toFixed(1));
                    break;
                case 'km/h':
                    return parseFloat((val * 1.852).toFixed(1));
                    break;
                case 'm/s':
                    return parseFloat((val * 0.514444).toFixed(1));
                    break;
                case 'bft':
                    return self._getBeaufort(parseFloat((val * 0.514444).toFixed(1)));
                    break;
            }
            break;
    }
};

UnitConverter.prototype._convertPressure = function(from, to, val) {
    switch (from) {
        case 'mmHg':
            switch (to) {
                case 'inHg' :
                    return parseFloat((val*0.03937).toFixed(1));
                    break;
                case 'hPa' :
                case 'mb' :
                    return parseFloat((val*1.333224).toFixed(1));
                    break;
            }
            break;
        case 'inHg':
            switch (to) {
                case 'mmHg' :
                    return parseFloat((val*25.4).toFixed(1));
                    break;
                case 'hPa' :
                case 'mb' :
                    return parseFloat((val*33.863882).toFixed(1));
                    break;
            }
            break;
        case 'hPa':
        case 'mb':
            switch (to) {
                case 'mmHg' :
                    return parseFloat((val*0.750062).toFixed(1));
                    break;
                case 'inHg' :
                    return parseFloat((val*0.02953).toFixed(1));
                    break;
                case 'hPa' :
                case 'mb' :
                    return val;
                    break;
            }
    }
};

UnitConverter.prototype._convertDistance = function(from, to, val) {
    if (from == 'm') {
        return parseFloat((val*39.370079).toFixed(1));
    }
    else if (from =='mi') {
        return parseFloat((val*0.0254).toFixed(1));
    }
};

UnitConverter.prototype._convertPrecipitation = function(from, to, val) {
    if (from == 'mm') {
        return parseFloat((val*0.03937).toFixed(1));
    }
    else if (from =='in') {
        return parseFloat((val*25.4).toFixed(1));
    }
};

UnitConverter.prototype.convertUnits = function (from, to, val) {
    var self = this;

    if (val == undefined) {
        log.error("val is undefined!!");
        return val;
    }
    if (from == to) {
        return val;
    }

    if (from == 'C' || from == 'F') {
        return self._convertTemperature(from, to, val);
    }
    if (from == 'mph' || from == 'km/h' || from == 'm/s' || from == 'bft' || from == 'kt') {
        return self._convertWindSpeed(from, to, val);
    }
    if (from == 'mmHg' || from == 'inHg' || from == 'hPa' || from == 'mb') {
        return self._convertPressure(from, to, val);
    }
    if (from == 'm' || from == 'mi') {
        return self._convertDistance(from, to, val);
    }
    if (from == 'mm' || from == 'in') {
        return self._convertPrecipitation(from, to, val);
    }

    log.error('Fail to convert from '+from+" to "+to+" value="+val);
    return val;
};

module.exports = UnitConverter;

<|endoftext|>


<commit_before>const sass = require('node-sass');
const fs = require('fs');
const path = require('path');
const { apps_list, get_app_path, get_public_path, get_options_for_scss } = require('./rollup/rollup.utils');

const output_path = process.argv[2];

let scss_content = process.argv[3];
scss_content = scss_content.replace(/\\n/g, '\n');

sass.render({
	data: scss_content,
	outputStyle: 'compact',
	importer: function(url) {
		if (url.startsWith('~')) {
			// strip ~ so that it can resolve from node_modules
			return {
				file: url.slice(1)
			};
		}
		// normal file, let it go
		return {
			file: url
		};
	},
	...get_options_for_scss()
}, function(err, result) {
	if (err) {
		console.error(err.formatted); // eslint-disable-line
		return;
	}

	fs.writeFile(output_path, result.css, function(err) {
		if (!err) {
			console.log(output_path); // eslint-disable-line
		}
	});
});<commit_msg>feat: compress build from theme generator<commit_after>const sass = require('node-sass');
const fs = require('fs');
const path = require('path');
const { apps_list, get_app_path, get_public_path, get_options_for_scss } = require('./rollup/rollup.utils');

const output_path = process.argv[2];

let scss_content = process.argv[3];
scss_content = scss_content.replace(/\\n/g, '\n');

sass.render({
	data: scss_content,
	outputStyle: 'compressed',
	importer: function(url) {
		if (url.startsWith('~')) {
			// strip ~ so that it can resolve from node_modules
			return {
				file: url.slice(1)
			};
		}
		// normal file, let it go
		return {
			file: url
		};
	},
	...get_options_for_scss()
}, function(err, result) {
	if (err) {
		console.error(err.formatted); // eslint-disable-line
		return;
	}

	fs.writeFile(output_path, result.css, function(err) {
		if (!err) {
			console.log(output_path); // eslint-disable-line
		}
	});
});<|endoftext|>


<commit_before>"use strict";

const Journeys = require('../../models/journeys');
const Users = require('../../models/users');

const sync = require('../../sync/sync');
const watcher = require('../../sync/watch');

const debug = require('../../util/debug');

function error(operation, journey, err) {
    console.error(`Journey: Error performing ${operation} on ${journey.uid}`, err, err.stack);
}

function success(operation, journey) {
    console.log(`Journey: Successfully performed ${operation} on ${journey.uid}`);
}

function noop(operation, journey) {
    const log = watcher.isJourneyWatched(journey.uid, journey.ssd) ? console.log : debug;
    log(`Journey: Nothing to be done for ${operation} on ${journey.uid}`);
}

function updateUsers(users, journey) {
    if (watcher.isJourneyWatched(journey.uid, journey.ssd)) {
        console.log(`Journey: Found users for watched journey ${journey.uid}-${journey.ssd}`, users);
    }
    if (!users || !users.length) {
        return Promise.resolve(false);
    }

    return Promise.all(users.map(user => sync.update(user, journey)));
}

Journeys.on('update', function(journey, updates) {
    Users.findForJourney(journey.uid, journey.ssd)
        .then((users) => updateUsers(users, journey))
        .then((updated) => updated ? success('update', journey) : noop('update', journey))
        .catch((err) => error('update', journey, err));
});<commit_msg>Less logging now<commit_after>"use strict";

const Journeys = require('../../models/journeys');
const Users = require('../../models/users');

const sync = require('../../sync/sync');
const watcher = require('../../sync/watch');

const debug = require('../../util/debug');

function error(operation, journey, err) {
    console.error(`Journey: Error performing ${operation} on ${journey.uid}`, err, err.stack);
}

function success(operation, journey) {
    console.log(`Journey: Successfully performed ${operation} on ${journey.uid}`);
}

function noop(operation, journey) {
    const log = watcher.isJourneyWatched(journey.uid, journey.ssd) ? console.log : debug;
    log(`Journey: Nothing to be done for ${operation} on ${journey.uid}`);
}

function updateUsers(users, journey) {
    if (!users || !users.length) {
        return Promise.resolve(false);
    }

    return Promise.all(users.map(user => sync.update(user, journey)));
}

Journeys.on('update', function(journey, updates) {
    Users.findForJourney(journey.uid, journey.ssd)
        .then((users) => updateUsers(users, journey))
        .then((updated) => updated ? success('update', journey) : noop('update', journey))
        .catch((err) => error('update', journey, err));
});<|endoftext|>


<commit_before>import Promise from 'bluebird';
import mongoose from 'mongoose';
import httpStatus from 'http-status';
import APIError from '../helpers/APIError';

/**
 * User Schema
 */
const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true
  },
  fileMap: {
    type: String,
    required: true
  },
  capacity: {       //user's offered capacity by MB
    type: Number,
    required: true
  }
});

/**
 * Add your
 * - pre-save hooks
 * - validations
 * - virtuals
 */

/**
 * Methods
 */
UserSchema.methods = {

};

/**
 * Statics
 */
UserSchema.statics = {
  /**
   * Get user
   * @param {ObjectId} id - The objectId of user.
   * @returns {Promise<User, APIError>}
   */
  get(username) {
    return this.findOne({username: username})
      .exec()
      .then((user) => {
        if (user) {
          return user;
        }
        const err = new APIError('No such user exists!', httpStatus.NOT_FOUND);
        return Promise.reject(err);
      });
  },

  remove(username) {
    return this.findOneaAndRemove({username: username})
      .exec();
  },

  updateCap(username, capacity) {
    return this.findOne({username: username})
      .exec()
      .then((user) => {
        if (user) {
          user.capacity= capacity;
          user.save();          //we assume that it is possible to save here
          return user;
        }
        const err = new APIError('No such user exists!', httpStatus.NOT_FOUND);
        return Promise.reject(err);
      });
  },

  updateMap(username, fileMap) {
    return this.findOne({username: username})
      .exec()
      .then((user) => {
        if (user) {
          user.fileMap = fileMap;
          user.save();          //we assume that it is possible to save here
          return user;
        }
        const err = new APIError('No such user exists!', httpStatus.NOT_FOUND);
        return Promise.reject(err);
      });
  },

  /**
   * List users in descending order of 'createdAt' timestamp.
   * @param {number} skip - Number of users to be skipped.
   * @param {number} limit - Limit number of users to be returned.
   * @returns {Promise<User[]>}
   */
  list({ skip = 0, limit = 50 } = {}) {
    return this.find()
      .skip(skip)
      .limit(limit)
      .exec();
  }
};

/**
 * @typedef User
 */
export default mongoose.model('User', UserSchema);
<commit_msg>reviewed User model<commit_after>import Promise from 'bluebird';
import mongoose from 'mongoose';
import httpStatus from 'http-status';
import APIError from '../helpers/APIError';

/**
 * User Schema
 */
const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true
  },
  fileMap: {
    type: String,
    required: true
  },
  // user's offered storage capacity in MB
  capacity: {
    type: Number,
    required: true
  }
});

/**
 * Methods
 */
UserSchema.methods.methodName = () => {

};

/**
 * Statics
 */
UserSchema.statics.get = (userId) => {
  return this.findOne({_id: userId})
    .exec()
    .then((user) => {
      if (user) {
        return user;
      }
      const err = new APIError('No such user exists!', httpStatus.NOT_FOUND);
      return Promise.reject(err);
    });
};

UserSchema.statics.remove = (userId) => {
  return this.findOneaAndRemove({_id: userId})
    .exec();
};

// we assume that it is possible to save here -- double check?
UserSchema.statics.updateCap = (userId, capacity) => {
  return this.findOne({_id: userId})
    .exec()
    .then((user) => {
      if (user) {
        user.capacity= capacity;
        user.save();
        return user;
      }
      const err = new APIError('No such user exists!', httpStatus.NOT_FOUND);
      return Promise.reject(err);
    });
};

UserSchema.statics.updateMap = (userId, fileMap) => {
  return this.findOne({_id: userId})
    .exec()
    .then((user) => {
      if (user) {
        user.fileMap = fileMap;
        user.save();          //we assume that it is possible to save here
        return user;
      }
      const err = new APIError('No such user exists!', httpStatus.NOT_FOUND);
      return Promise.reject(err);
    });
};

  /**
   * List users in descending order of 'createdAt' timestamp.

  list({ skip = 0, limit = 50 } = {}) {
    return this.find()
      .skip(skip)
      .limit(limit)
      .exec();
  }
};*/

export default mongoose.model('User', UserSchema);
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable consistent-return */
const BaseBlueprintGenerator = require('../generator-base-blueprint');
const writeFiles = require('./files').writeFiles;
const constants = require('../generator-constants');

let useBlueprints;

module.exports = class extends BaseBlueprintGenerator {
    constructor(args, opts) {
        super(args, opts);

        this.configOptions = this.options.configOptions || {};
        // This adds support for a `--from-cli` flag
        this.option('from-cli', {
            desc: 'Indicates the command is run from JHipster CLI',
            type: Boolean,
            defaults: false,
        });

        useBlueprints = !this.fromBlueprint && this.instantiateBlueprints('e2e', { 'client-hook': !this.skipClient });
    }

    // Public API method used by the getter and also by Blueprints
    _initializing() {
        return {
            validateFromCli() {
                this.checkInvocationFromCLI();
            },

            setupConstants() {
                // Make constants available in templates
                this.MAIN_DIR = constants.MAIN_DIR;
                this.TEST_DIR = constants.TEST_DIR;
                this.SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;
                this.ANGULAR = constants.SUPPORTED_CLIENT_FRAMEWORKS.ANGULAR;
                this.CLIENT_DIST_DIR = this.getResourceBuildDirectoryForBuildTool(this.configOptions.buildTool) + constants.CLIENT_DIST_DIR;
            },
        };
    }

    get initializing() {
        if (useBlueprints) return;
        return this._initializing();
    }

    // Public API method used by the getter and also by Blueprints
    _default() {
        return {
            setupConstants() {
                this.BUILD_DIR = this.getBuildDirectoryForBuildTool(this.buildTool);
            },
            loadSharedConfig() {
                this.loadAppConfig();
                this.loadClientConfig();
                this.loadServerConfig();
                this.loadTranslationConfig();
            },
        };
    }

    get default() {
        if (useBlueprints) return;
        return this._default();
    }

    // Public API method used by the getter and also by Blueprints
    _writing() {
        return writeFiles();
    }

    get writing() {
        if (useBlueprints) return;
        return this._writing();
    }
};
<commit_msg>Fix method order<commit_after>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable consistent-return */
const BaseBlueprintGenerator = require('../generator-base-blueprint');
const writeFiles = require('./files').writeFiles;
const constants = require('../generator-constants');

let useBlueprints;

module.exports = class extends BaseBlueprintGenerator {
    constructor(args, opts) {
        super(args, opts);

        this.configOptions = this.options.configOptions || {};
        // This adds support for a `--from-cli` flag
        this.option('from-cli', {
            desc: 'Indicates the command is run from JHipster CLI',
            type: Boolean,
            defaults: false,
        });

        useBlueprints = !this.fromBlueprint && this.instantiateBlueprints('e2e', { 'client-hook': !this.skipClient });
    }

    // Public API method used by the getter and also by Blueprints
    _initializing() {
        return {
            validateFromCli() {
                this.checkInvocationFromCLI();
            },

            setupConstants() {
                // Make constants available in templates
                this.MAIN_DIR = constants.MAIN_DIR;
                this.TEST_DIR = constants.TEST_DIR;
                this.SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;
                this.ANGULAR = constants.SUPPORTED_CLIENT_FRAMEWORKS.ANGULAR;
                this.CLIENT_DIST_DIR = this.getResourceBuildDirectoryForBuildTool(this.configOptions.buildTool) + constants.CLIENT_DIST_DIR;
            },
        };
    }

    get initializing() {
        if (useBlueprints) return;
        return this._initializing();
    }

    // Public API method used by the getter and also by Blueprints
    _default() {
        return {
            loadSharedConfig() {
                this.loadAppConfig();
                this.loadClientConfig();
                this.loadServerConfig();
                this.loadTranslationConfig();
            },
            setupConstants() {
                this.BUILD_DIR = this.getBuildDirectoryForBuildTool(this.buildTool);
            },
        };
    }

    get default() {
        if (useBlueprints) return;
        return this._default();
    }

    // Public API method used by the getter and also by Blueprints
    _writing() {
        return writeFiles();
    }

    get writing() {
        if (useBlueprints) return;
        return this._writing();
    }
};
<|endoftext|>


<commit_before>'use strict';

var yeoman = require('yeoman-generator');
var _ = require('lodash');

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

module.exports = yeoman.generators.Base.extend({
  initializing: function () {
    this.props.feature = this.name;
    this.props.controller = _.capitalize(_.deburr(this.name));
  },
  writing: function () {
    var path = 'app/src';

    this.fs.copy(
      this.templatePath('controller.js'),
      this.destinationPath(format('%s/%s/%s.controller.js', path, this.props.feature, this.props.feature))
    );

    this.fs.copyTpl(
      this.templatePath('module.js'),
      this.destinationPath(format('%s/%s/%s.module.js', path, this.props.feature, this.props.feature)),
      {
        feature: this.props.feature,
        controller: this.props.controller
      }
    );

    this.fs.copyTpl(
      this.templatePath('view.html'),
      this.destinationPath(format('%s/%s/%s.html', path, this.props.feature, this.props.feature)),
      {
        feature: this.props.feature
      }
    );

    this.fs.copyTpl(
      this.templatePath('styles.scss'),
      this.destinationPath(format('%s/%s/%s.scss', path, this.props.feature, this.props.feature)),
      {
        feature: this.props.feature
      }
    );
  }
});
<commit_msg>Update feature sub-generator<commit_after>'use strict';

var yeoman = require('yeoman-generator');
var _ = require('lodash');
var fs = require('fs');
var path = require('path');

var format = require('util').format;
var write = require('html-wiring').writeFileFromString;

module.exports = yeoman.generators.Base.extend({
  initializing: function () {
    this.props = {};
    try {
      this.props.package = require(path.join(this.destinationRoot(), './package.json'));
    }
    catch (e) {
      this.log.error(e.message);
    }
    this.props.root = path.join(this.destinationRoot(), './app/src');
    this.props.name = this.props.package.name;
    this.props.feature = this.args[0];
    this.props.controller = _.capitalize(_.deburr(this.props.feature));
  },
  writing: function () {
    this.fs.copy(
      this.templatePath('controller.js'),
      this.destinationPath(format('%s/%s/%s.controller.js', this.props.root, this.props.feature, this.props.feature))
    );

    this.fs.copyTpl(
      this.templatePath('module.js'),
      this.destinationPath(format('%s/%s/%s.module.js', this.props.root, this.props.feature, this.props.feature)),
      {
        feature: this.props.feature,
        controller: this.props.controller,
        name: this.props.name
      }
    );

    this.fs.copyTpl(
      this.templatePath('view.html'),
      this.destinationPath(format('%s/%s/%s.html', this.props.root, this.props.feature, this.props.feature)),
      {
        feature: this.props.feature
      }
    );

    this.fs.copyTpl(
      this.templatePath('styles.scss'),
      this.destinationPath(format('%s/%s/%s.scss', this.props.root, this.props.feature, this.props.feature)),
      {
        feature: this.props.feature
      }
    );

    var modulePath = path.join(this.props.root, './app.module.js');

    if (!this.fs.exists(modulePath))
      throw new Error('Can\'t find app.module.js');

    var file = this.fs.read(modulePath);

    var lines = file.split('\n');
    var cursor = _.findLastIndex(lines, function (value) {
      return _.contains(value, ']);');
    });

    var top = _.slice(lines, 0, cursor);
    var bottom = _.slice(lines, cursor);

    top[cursor - 1] += ',';
    top.push(format('  require(\'./%s/%s.module.js\')', this.props.feature, this.props.feature));

    lines = top.concat(bottom);
    file = lines.join('\n');

    write(file, modulePath);
  }
});
<|endoftext|>


<commit_before>'use strict';

var http    = require('http')
  , fs      = require('fs')
  , PORT    = 6060
  , express = require('express')
  , app     = express()
  , util    = require('util');

/*
 * use ejs to serve static files
 */
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(__dirname + '/'));

/*
 * get git log file
 * TODO seperate this into a module
 */
var gitText = {};
fs.readFile('./views/gitlog.txt', 'utf8', function (error, data) {
    if (! error) gitText = { 'content': data };
});

/*
 * read body files for later serving
 */
var bodies = {};
var subjects = {
    projects: 'Personal Projects'
    , about: 'About Me'
    , contact: 'Get in Touch'
    , home: 'Hello'
};
var files = [ 'about', 'projects', 'contact', 'home'];
for (var i = 0; i < files.length; i++) {
    bodies[files[i]] = fs.readFileSync('./views/bodies/body-' + files[i] + '.ejs', 'utf8');
}

/*
 * HTTP request routers
 */
app.get('/', function (req, res, next) {
	res.render('index.ejs', {
        subject: 'Hello',
        content: bodies['home']
    });
}, function (req, res, next) {
    logConnection(req);
    next();
});
app.get('/body/:which', function (req, res, next) {
    var which = req.params.which;

    res.status(200).json({
        data : {
            subject: subjects[which],
            content: bodies[which]
        }
    });
}, function (req, res) {
    logConnection(req);
    next();
});
app.get('/robots.txt', function (req, res) {
    logConnection(req);
    res.type('text/plain');
    res.send('#011000100110010101100101011100000010'
    + '00000110001001101111011011110111000000100001'
    + '\nUser-agent: *\nDisallow: /');
});
app.get('/getGitLog', function (req, res) {
    res.send(gitText);
    logConnection(req);
});

/*
 * listen on port 6060 (rerouted from 80)
 */
app.listen(PORT, function () {
	console.log('facer listening on port', PORT);
});

function logConnection(req) {
    // if not my public IP
    if (req.ip !== '67.193.120.178') {
        var info = util.format('[%s]: %s,\t%s,\t%s',
          new Date(), req.method, req.ip, req.path);
        info += '\n';
        fs.appendFile('logs/connect.log', info, function (error) {
            if (error) throw new Error(("Error writing to file: " + error));
        });
    }
}
<commit_msg>Whitespace beautification<commit_after>'use strict';

var http    = require('http')
  , fs      = require('fs')
  , PORT    = 6060
  , express = require('express')
  , app     = express()
  , util    = require('util');

/*
 * use ejs to serve static files
 */
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(__dirname + '/'));

/*
 * get git log file
 * TODO seperate this into a module
 */
var gitText = {};
fs.readFile('./views/gitlog.txt', 'utf8', function (error, data) {
    if (! error) gitText = { 'content': data };
});

/*
 * read body files for later serving
 */
var bodies = {};
var subjects = {
    projects:   'Personal Projects'
    , about:    'About Me'
    , contact:  'Get in Touch'
    , home:     'Hello'
};
var files = [ 'about', 'projects', 'contact', 'home'];
for (var i = 0; i < files.length; i++) {
    bodies[files[i]] = fs.readFileSync('./views/bodies/body-' + files[i] + '.ejs', 'utf8');
}

/*
 * HTTP request routers
 */
app.get('/', function (req, res, next) {
	res.render('index.ejs', {
        subject: 'Hello',
        content: bodies['home']
    });
}, function (req, res, next) {
    logConnection(req);
    next();
});
app.get('/body/:which', function (req, res, next) {
    var which = req.params.which;

    res.status(200).json({
        data: {
            subject: subjects[which],
            content: bodies[which]
        }
    });
}, function (req, res) {
    logConnection(req);
    next();
});
app.get('/robots.txt', function (req, res) {
    logConnection(req);
    res.type('text/plain');
    res.send('#011000100110010101100101011100000010'
    + '00000110001001101111011011110111000000100001'
    + '\nUser-agent: *\nDisallow: /');
});
app.get('/getGitLog', function (req, res) {
    res.send(gitText);
    logConnection(req);
});

/*
 * listen on port 6060 (rerouted from 80)
 */
app.listen(PORT, function () {
	console.log('facer listening on port', PORT);
});

function logConnection(req) {
    // if not my public IP
    if (req.ip !== '67.193.120.178') {
        var info = util.format('[%s]: %s,\t%s,\t%s',
          new Date(), req.method, req.ip, req.path);
        info += '\n';
        fs.appendFile('logs/connect.log', info, function (error) {
            if (error) throw new Error(("Error writing to file: " + error));
        });
    }
}
<|endoftext|>


<commit_before>// Required modules
var mongoose = require('mongoose');

var ThingSchema = mongoose.Schema({
	description: {
		type: String,
		required: true
	},
	location: {
		type: String,
		required: true
	}
});

module.exports = mongoose.model('Thing', ThingSchema);<commit_msg>Updated Thing schema<commit_after>// Required modules
var mongoose = require('mongoose');

var ThingSchema = mongoose.Schema({
	description: {
		type: String,
		required: true
	},
	location: {
		type: [Number],
		index: '2d',
		required: true
	}
});

module.exports = mongoose.model('Thing', ThingSchema);<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Web Browser
////////////////////////////////////////////////////////////////////////////////
/*global require, exports */
var	system = require('../utils/system').system,
		tool = require('../tools/tool').tool,

browser = function () {
	var executable = {'cygwin': 'cmd', 'windows': 'cmd', 'linux': 'xdg-open', 'freebsd': 'xdg-open'}[system.os] || 'open',
			self = Object.create(tool, {executable: {value: executable}});

	self.exec = function (url, handler) {
		var args = {'cygwin': ['/c', 'start ' + url], 'windows': ['/c', 'start ' + url]}[system.os] || [url];
		tool.exec.call(self, args, handler);
		return self;
	};

	return self;
}();

exports.browser = browser;

<commit_msg>Update browser.js<commit_after>////////////////////////////////////////////////////////////////////////////////
// Web Browser
////////////////////////////////////////////////////////////////////////////////
/*global require, exports */
var	system = require('../utils/system').system,
		tool = require('../tools/tool').tool,

browser = function () {
	var executable = {
		'linux': 'xdg-open',
		'freebsd': 'xdg-open',
		'darwin': 'open',
		'cygwin': 'cmd',
		'windows': 'cmd'
	}[system.os] || 'xdg-open',
	self = Object.create(tool, {executable: {value: executable}});

	self.exec = function (url, handler) {
		var args = {
			'cygwin': ['/c', 'start ' + url],
			'windows': ['/c', 'start ' + url]
		}[system.os] || [url];

		tool.exec.call(self, args, handler);
		return self;
	};

	return self;
}();

exports.browser = browser;

<|endoftext|>


<commit_before>var pattern = "*://*.wikipedia.org/*";
var isEnabled;

function redirect(requestDetails) {

	var x = convertURL(requestDetails.url);

	if (!x.redirect)
		return {};

	console.info("Redirecting from: " + requestDetails.url);
	console.info("Redirecting to: " + x.url);

	return {
		redirectUrl: x.url
	};
}

function convertURL(url) {
	var result = {
		url: url,
		redirect: true
	};

	var el = document.createElement('a'); //temp element
	el.href = url;

	var host = el.host;
	var pathname = el.pathname;
	var param = el.search;

	var lang = host.substring(0, host.indexOf('.'));
	var article = pathname.split('/')[2];

	//console.log("param: " + param + " \n" + "	article: " + article)

	result.url = "https://wikiwand.com/" + lang + "/" + article + param;

	if (param.includes('oldformat=true') ||
		param.includes('action=') ||
		param.includes('printable=yes') ||
		param.includes('writer=rl') ||
		article == "Main_Page" && lang == "en" || //main page on wikiwand.com in english(only) is bugged
		pathname == "/") { //the main page of wikipedia in english that redirects to /Main_Page

		result.redirect = false;
		result.url = url;
	}
	if (!isEnabled) {
		result.redirect = false;
	}
	return result;
}

browser.webRequest.onBeforeRequest.addListener(
	redirect, {
		urls: [pattern],
		types: ["main_frame"]
	}, ["blocking"]
);

browser.runtime.onStartup.addListener(function () {
	isEnabled = true;
});

browser.browserAction.onClicked.addListener(() => {

	isEnabled = !isEnabled;

	if (isEnabled) {
		browser.browserAction.setIcon({
			path: "icons/logo_plain.svg"
		});
	} else {
		browser.browserAction.setIcon({
			path: "icons/logo_disabled_plain.svg"
		});
	}
});<commit_msg>the browserAction's text will now change based on the state of the addon<commit_after>var pattern = "*://*.wikipedia.org/*";
var isEnabled;

function redirect(requestDetails) {

	var x = convertURL(requestDetails.url);

	if (!x.redirect)
		return {};

	console.info("Redirecting from: " + requestDetails.url);
	console.info("Redirecting to: " + x.url);

	return {
		redirectUrl: x.url
	};
}

function convertURL(url) {
	var result = {
		url: url,
		redirect: true
	};

	var el = document.createElement('a'); //temp element
	el.href = url;

	var host = el.host;
	var pathname = el.pathname;
	var param = el.search;

	var lang = host.substring(0, host.indexOf('.'));
	var article = pathname.split('/')[2];

	//console.log("param: " + param + " \n" + "	article: " + article)

	result.url = "https://wikiwand.com/" + lang + "/" + article + param;

	if (param.includes('oldformat=true') ||
		param.includes('action=') ||
		param.includes('printable=yes') ||
		param.includes('writer=rl') ||
		article == "Main_Page" && lang == "en" || //main page on wikiwand.com in english(only) is bugged
		pathname == "/") { //the main page of wikipedia in english that redirects to /Main_Page

		result.redirect = false;
		result.url = url;
	}
	if (!isEnabled) {
		result.redirect = false;
	}
	return result;
}

browser.webRequest.onBeforeRequest.addListener(
	redirect, {
		urls: [pattern],
		types: ["main_frame"]
	}, ["blocking"]
);

browser.runtime.onStartup.addListener(function () {
	isEnabled = true;
});

browser.browserAction.onClicked.addListener(() => {

	isEnabled = !isEnabled;

	if (isEnabled) {
		browser.browserAction.setIcon({
			path: "icons/logo_plain.svg"
		});
		browser.browserAction.setTitle({
			title: "Wikiwand is enabled"
		});
	} else {
		browser.browserAction.setIcon({
			path: "icons/logo_disabled_plain.svg"
		});
		browser.browserAction.setTitle({
			title: "Wikiwand is disabled"
		});
	}
});<|endoftext|>


<commit_before>/**
 * @license Copyright (c) 2010-2011 Brian Cavalier
 * LICENSE: see the LICENSE.txt file. If file is missing, this file is subject
 * to the MIT License at: http://www.opensource.org/licenses/mit-license.php.
 */

/**
 * wire/aop plugin
 * Provides AOP for components created via wire, including Decorators,
 * Introductions (mixins), and Pointcut-based Aspect Weaving.
 */
define(['require', 'aop', 'when'], function(require, aop, when) {

	var ap, obj, tos, isArray, whenAll, chain, deferred, undef;

	ap = Array.prototype;
	obj = {};
	tos = Object.prototype.toString;

	isArray = Array.isArray || function(it) {
		return tos.call(it) == '[object Array]';
	};

    whenAll  = when.all;
    chain    = when.chain;
    deferred = when.defer;

    //
	// Decoration
	//

	function applyDecorator(target, Decorator, args) {
		args = args ? [target].concat(args) : [target];

		Decorator.apply(null, args);
	}

	function doDecorate(target, decorator, args, wire) {
		function apply(Decorator) {
            return args
                ? when(wire(args), function (resolvedArgs) {
                    applyDecorator(target, Decorator, resolvedArgs);
                })
                : applyDecorator(target, Decorator);
        }

        return when(wire.resolveRef(decorator), apply);
	}

	function decorateFacet(resolver, facet, wire) {
		var target, options, promises;

		target = facet.target;
		options = facet.options;
		promises = [];

		for(var d in options) {
			promises.push(doDecorate(target, d, options[d], wire));
		}

		chain(whenAll(promises), resolver);
	}

	//
	// Introductions
	//

	function introduce(target, src) {
		var name, s;

		for(name in src) {
			s = src[name];
			if(!(name in target) || (target[name] !== s && (!(name in obj) || obj[name] !== s))) {
				target[name] = s;
			}
		}

        return target;
	}

	function doIntroduction(target, introduction, wire) {
        return when(wire.resolveRef(introduction), function(resolved) {
            return introduce(target, resolved);
        });
	}

	function introduceFacet(resolver, facet, wire) {
		var target, intros;

		target = facet.target;
		intros = facet.options;

		if(!isArray(intros)) intros = [intros];

        chain(when.reduce(intros, function(target, intro) {
            return doIntroduction(target, intro, wire);
        }, target), resolver);
	}

	//
	// Aspect Weaving
	//

    function applyAspectCombined(target, aspect, wire, add) {
        return when(wire.resolveRef(aspect), function (aspect) {
            var pointcut = aspect.pointcut;

            if (pointcut) {
                add(target, pointcut, aspect);
            }

            return target;
        });
    }

    function applyAspectSeparate(target, aspect, wire, add) {
        var pointcut, advice;

        pointcut = aspect.pointcut;
        advice = aspect.advice;

        function applyAdvice(pointcut) {
            return when(wire.resolveRef(advice), function (aspect) {
                add(target, pointcut, aspect);
                return target;
            });
        }

        return typeof pointcut === 'string'
            ? when(wire.resolveRef(pointcut, applyAdvice))
            : applyAdvice(pointcut);
    }

    function weave(resolver, proxy, wire, options, add) {

        var target, path, aspects, applyAdvice;

        aspects = options.aspects;
        path = proxy.path;

        if (!aspects || path === undef) {
            resolver.resolve();
            return;
        }

        target = proxy.target;
        applyAdvice = applyAspectCombined;

        // Reduce will preserve order of aspects being applied
        chain(when.reduce(aspects, function(target, aspect) {
            var aspectPath;

            if (aspect.advice) {
                aspectPath = aspect.advice;
                applyAdvice = applyAspectSeparate;
            } else {
                aspectPath = aspect;
            }

            return typeof aspectPath === 'string' && aspectPath !== path
                ? applyAdvice(target, aspect, wire, add)
                : target;

        }, target), resolver);
    }

	return {
		/**
         * Creates wire/aop plugin instances.
         *
         * @param ready {Promise} promise that will be resolved when the context has been wired,
         *  rejected if there is an error during the wiring process, and will receive progress
         *  events for object creation, property setting, and initialization.
         * @param destroy {Promise} promise that will be resolved when the context has been destroyed,
         *  rejected if there is an error while destroying the context, and will receive progress
         *  events for objects being destroyed.
         * @param options {Object}
         */
		wire$plugin: function(ready, destroyed, options) {

            // Track aspects so they can be removed when the context is destroyed
            var woven = [];

            // Remove all aspects that we added in this context
            when(destroyed, function() {
                for(var i = woven.length; i >= 0; --i) {
                    woven[i].remove();
                }
            });

            /**
             * Function to add an aspect and remember it in the current context
             * so that it can be removed when the context is destroyed.
             * @param target
             * @param pointcut
             * @param aspect
             */
            function add(target, pointcut, aspect) {
                woven.push(aop.add(target, pointcut, aspect))
            }

			function makeFacet(step, callback) {
				var facet = {};

				facet[step] = function(resolver, proxy, wire) {
					callback(resolver, proxy, wire);
				};

				return facet;
			}

			// Plugin
			return {
				facets: {
					decorate:  makeFacet('configure', decorateFacet),
					introduce: makeFacet('configure', introduceFacet)
				},
				create: function(resolver, proxy, wire) {
					weave(resolver, proxy, wire, options, add);
				}
			};
		}
	};
});<commit_msg>Add missing semi, fix jsdoc param name<commit_after>/**
 * @license Copyright (c) 2010-2011 Brian Cavalier
 * LICENSE: see the LICENSE.txt file. If file is missing, this file is subject
 * to the MIT License at: http://www.opensource.org/licenses/mit-license.php.
 */

/**
 * wire/aop plugin
 * Provides AOP for components created via wire, including Decorators,
 * Introductions (mixins), and Pointcut-based Aspect Weaving.
 */
define(['require', 'aop', 'when'], function(require, aop, when) {

	var ap, obj, tos, isArray, whenAll, chain, deferred, undef;

	ap = Array.prototype;
	obj = {};
	tos = Object.prototype.toString;

	isArray = Array.isArray || function(it) {
		return tos.call(it) == '[object Array]';
	};

    whenAll  = when.all;
    chain    = when.chain;
    deferred = when.defer;

    //
	// Decoration
	//

	function applyDecorator(target, Decorator, args) {
		args = args ? [target].concat(args) : [target];

		Decorator.apply(null, args);
	}

	function doDecorate(target, decorator, args, wire) {
		function apply(Decorator) {
            return args
                ? when(wire(args), function (resolvedArgs) {
                    applyDecorator(target, Decorator, resolvedArgs);
                })
                : applyDecorator(target, Decorator);
        }

        return when(wire.resolveRef(decorator), apply);
	}

	function decorateFacet(resolver, facet, wire) {
		var target, options, promises;

		target = facet.target;
		options = facet.options;
		promises = [];

		for(var d in options) {
			promises.push(doDecorate(target, d, options[d], wire));
		}

		chain(whenAll(promises), resolver);
	}

	//
	// Introductions
	//

	function introduce(target, src) {
		var name, s;

		for(name in src) {
			s = src[name];
			if(!(name in target) || (target[name] !== s && (!(name in obj) || obj[name] !== s))) {
				target[name] = s;
			}
		}

        return target;
	}

	function doIntroduction(target, introduction, wire) {
        return when(wire.resolveRef(introduction), function(resolved) {
            return introduce(target, resolved);
        });
	}

	function introduceFacet(resolver, facet, wire) {
		var target, intros;

		target = facet.target;
		intros = facet.options;

		if(!isArray(intros)) intros = [intros];

        chain(when.reduce(intros, function(target, intro) {
            return doIntroduction(target, intro, wire);
        }, target), resolver);
	}

	//
	// Aspect Weaving
	//

    function applyAspectCombined(target, aspect, wire, add) {
        return when(wire.resolveRef(aspect), function (aspect) {
            var pointcut = aspect.pointcut;

            if (pointcut) {
                add(target, pointcut, aspect);
            }

            return target;
        });
    }

    function applyAspectSeparate(target, aspect, wire, add) {
        var pointcut, advice;

        pointcut = aspect.pointcut;
        advice = aspect.advice;

        function applyAdvice(pointcut) {
            return when(wire.resolveRef(advice), function (aspect) {
                add(target, pointcut, aspect);
                return target;
            });
        }

        return typeof pointcut === 'string'
            ? when(wire.resolveRef(pointcut, applyAdvice))
            : applyAdvice(pointcut);
    }

    function weave(resolver, proxy, wire, options, add) {

        var target, path, aspects, applyAdvice;

        aspects = options.aspects;
        path = proxy.path;

        if (!aspects || path === undef) {
            resolver.resolve();
            return;
        }

        target = proxy.target;
        applyAdvice = applyAspectCombined;

        // Reduce will preserve order of aspects being applied
        chain(when.reduce(aspects, function(target, aspect) {
            var aspectPath;

            if (aspect.advice) {
                aspectPath = aspect.advice;
                applyAdvice = applyAspectSeparate;
            } else {
                aspectPath = aspect;
            }

            return typeof aspectPath === 'string' && aspectPath !== path
                ? applyAdvice(target, aspect, wire, add)
                : target;

        }, target), resolver);
    }

	return {
		/**
         * Creates wire/aop plugin instances.
         *
         * @param ready {Promise} promise that will be resolved when the context has been wired,
         *  rejected if there is an error during the wiring process, and will receive progress
         *  events for object creation, property setting, and initialization.
         * @param destroyed {Promise} promise that will be resolved when the context has been destroyed,
         *  rejected if there is an error while destroying the context, and will receive progress
         *  events for objects being destroyed.
         * @param options {Object}
         */
		wire$plugin: function(ready, destroyed, options) {

            // Track aspects so they can be removed when the context is destroyed
            var woven = [];

            // Remove all aspects that we added in this context
            when(destroyed, function() {
                for(var i = woven.length; i >= 0; --i) {
                    woven[i].remove();
                }
            });

            /**
             * Function to add an aspect and remember it in the current context
             * so that it can be removed when the context is destroyed.
             * @param target
             * @param pointcut
             * @param aspect
             */
            function add(target, pointcut, aspect) {
                woven.push(aop.add(target, pointcut, aspect));
            }

			function makeFacet(step, callback) {
				var facet = {};

				facet[step] = function(resolver, proxy, wire) {
					callback(resolver, proxy, wire);
				};

				return facet;
			}

			// Plugin
			return {
				facets: {
					decorate:  makeFacet('configure', decorateFacet),
					introduce: makeFacet('configure', introduceFacet)
				},
				create: function(resolver, proxy, wire) {
					weave(resolver, proxy, wire, options, add);
				}
			};
		}
	};
});<|endoftext|>


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

CLASS({
  package: 'foam.u2',
  name: 'DefaultValidator',

  documentation: 'Default Element validator.',

  methods: [
    function validateNodeName(name) {
      return true;
    },

    function validateClass(cls) {

    },

    function validateAttributeName(name) {

    },

    function validateAttributeValue(value) {

    },

    function validateStyleName(name) {

    },

    function validateStyleValue(value) {

    },

    function sanitizeText(text) {
      if ( ! text ) return text;
      text = text.toString();
//      return text.replace(/[&<"']/g, function (m) {
      return text.replace(/[<"']/g, function (m) {
        switch ( m ) {
//          case '&': return '&';
          case '<': return '<';
          case '"': return '"';
          default:  return '&#039';
        }
      });
    }
  ]
});
<commit_msg>U2: Put & escaping back in Validator now that entities are supported in the template parser.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.u2',
  name: 'DefaultValidator',

  documentation: 'Default Element validator.',

  methods: [
    function validateNodeName(name) {
      return true;
    },

    function validateClass(cls) {

    },

    function validateAttributeName(name) {

    },

    function validateAttributeValue(value) {

    },

    function validateStyleName(name) {

    },

    function validateStyleValue(value) {

    },

    function sanitizeText(text) {
      if ( ! text ) return text;
      text = text.toString();
      return text.replace(/[&<"']/g, function (m) {
        switch ( m ) {
          case '&': return '&';
          case '<': return '<';
          case '"': return '"';
          default:  return '&#039';
        }
      });
    }
  ]
});
<|endoftext|>


<commit_before>import ui.View as View;
import ui.ScrollView as ScrollView;
import ui.GestureView as GestureView;

import .AdventureMapBackgroundView;
import .AdventureMapPathsView;
import .AdventureMapNodesView;
import .AdventureMapDoodadsView;

exports = Class(ScrollView, function (supr) {
	this.init = function (opts) {
		this._tileWidth = opts.tileSettings.tileWidth;
		this._tileHeight = opts.tileSettings.tileHeight;

		this._totalWidth = opts.gridSettings.width * this._tileWidth;
		this._totalHeight = opts.gridSettings.height * this._tileHeight;

		var scale = opts.scale || 0.5;

		opts = merge(
			opts,
			{
				scrollX: true,
				scrollY: true,
				scrollBounds: {
					minX: 0,
					minY: 0,
					maxX: this._totalWidth * scale,
					maxY: this._totalHeight * scale
				},
				bounce: false
			}
		);

		supr(this, 'init', [opts]);

		this._tileSettings = opts.tileSettings;
		this._adventureMapLayers = [];
		this._inputLayerIndex = opts.inputLayerIndex;

		this._content = new GestureView({
			superview: this,
			x: 0,
			y: 0,
			width: this._totalWidth,
			height: this._totalHeight,
			scale: scale
		});

		var ctors = [
				AdventureMapBackgroundView,
				AdventureMapPathsView,
				AdventureMapNodesView,
				AdventureMapDoodadsView
			];
		for (var i = 0; i < ctors.length; i++) {
			this._adventureMapLayers.push(new ctors[i]({
				superview: this._content,
				adventureMapView: this,
				x: 0,
				y: 0,
				width: this._totalWidth,
				height: this._totalHeight,
				map: opts.map,
				gridSettings: opts.gridSettings,
				tileCtor: ctors[i],
				tileSettings: opts.tileSettings,
				gridSettings: opts.gridSettings,
				nodeSettings: opts.nodeSettings,
				pathSettings: opts.pathSettings,
				editMode: opts.editMode,
				blockEvents: opts.editMode ? (i !== 0) : (i < 2)
			}));
		}
	};

	this.onUpdate = function (data) {
		for (var i = 0; i < 4; i++) {
			var adventureMapLayer = this._adventureMapLayers[i];
			adventureMapLayer && adventureMapLayer.onUpdate && adventureMapLayer.onUpdate(data);
		}
	};

	this.getAdventureMapLayers = function () {
		return this._adventureMapLayers;
	};

	this.setScale = function (scale) {
		this._content.style.scale = scale;

		this.setScrollBounds({
			minX: 0,
			minY: 0,
			maxX: this._totalWidth * scale,
			maxY: this._totalHeight * scale
		});
		this.scrollTo(offsetX, offsetY, 0);
	};

	this.refreshTile = function (tileX, tileY) {
		var adventureMapLayers = this._adventureMapLayers;
		var i = this._adventureMapLayers.length;

		while (i) {
			this._adventureMapLayers[--i].refreshTile(tileX, tileY);
		}
	};

	this.focusNodeById = function (node) {
		var scale = this._content.style.scale;
		var x = Math.max((node.tileX * this._tileSettings.tileWidth) * scale - this.style.width * 0.5, 0);
		var y = Math.max((node.tileY * this._tileSettings.tileHeight) * scale - this.style.height * 0.5, 0);

		this.scrollTo(x, y, 300);
	};

	this.removeItemViews = function () {
		this._adventureMapLayers[3].removeItemViews();
	};
});<commit_msg>fixed crash on undefined variables<commit_after>import ui.View as View;
import ui.ScrollView as ScrollView;
import ui.GestureView as GestureView;

import .AdventureMapBackgroundView;
import .AdventureMapPathsView;
import .AdventureMapNodesView;
import .AdventureMapDoodadsView;

exports = Class(ScrollView, function (supr) {
	this.init = function (opts) {
		this._tileWidth = opts.tileSettings.tileWidth;
		this._tileHeight = opts.tileSettings.tileHeight;

		this._totalWidth = opts.gridSettings.width * this._tileWidth;
		this._totalHeight = opts.gridSettings.height * this._tileHeight;

		var scale = opts.scale || 0.5;

		opts = merge(
			opts,
			{
				scrollX: true,
				scrollY: true,
				scrollBounds: {
					minX: 0,
					minY: 0,
					maxX: this._totalWidth * scale,
					maxY: this._totalHeight * scale
				},
				bounce: false
			}
		);

		supr(this, 'init', [opts]);

		this._tileSettings = opts.tileSettings;
		this._adventureMapLayers = [];
		this._inputLayerIndex = opts.inputLayerIndex;

		this._content = new GestureView({
			superview: this,
			x: 0,
			y: 0,
			width: this._totalWidth,
			height: this._totalHeight,
			scale: scale
		});

		var ctors = [
				AdventureMapBackgroundView,
				AdventureMapPathsView,
				AdventureMapNodesView,
				AdventureMapDoodadsView
			];
		for (var i = 0; i < ctors.length; i++) {
			this._adventureMapLayers.push(new ctors[i]({
				superview: this._content,
				adventureMapView: this,
				x: 0,
				y: 0,
				width: this._totalWidth,
				height: this._totalHeight,
				map: opts.map,
				gridSettings: opts.gridSettings,
				tileCtor: ctors[i],
				tileSettings: opts.tileSettings,
				gridSettings: opts.gridSettings,
				nodeSettings: opts.nodeSettings,
				pathSettings: opts.pathSettings,
				editMode: opts.editMode,
				blockEvents: opts.editMode ? (i !== 0) : (i < 2)
			}));
		}
	};

	this.onUpdate = function (data) {
		for (var i = 0; i < 4; i++) {
			var adventureMapLayer = this._adventureMapLayers[i];
			adventureMapLayer && adventureMapLayer.onUpdate && adventureMapLayer.onUpdate(data);
		}
	};

	this.getAdventureMapLayers = function () {
		return this._adventureMapLayers;
	};

	this.setScale = function (scale) {
		this._content.style.scale = scale;

		this.setScrollBounds({
			minX: 0,
			minY: 0,
			maxX: this._totalWidth * scale,
			maxY: this._totalHeight * scale
		});
		this.scrollTo(this.style.x * scale, this.style.y * scale, 0);
	};

	this.refreshTile = function (tileX, tileY) {
		var adventureMapLayers = this._adventureMapLayers;
		var i = this._adventureMapLayers.length;

		while (i) {
			this._adventureMapLayers[--i].refreshTile(tileX, tileY);
		}
	};

	this.focusNodeById = function (node) {
		var scale = this._content.style.scale;
		var x = Math.max((node.tileX * this._tileSettings.tileWidth) * scale - this.style.width * 0.5, 0);
		var y = Math.max((node.tileY * this._tileSettings.tileHeight) * scale - this.style.height * 0.5, 0);

		this.scrollTo(x, y, 300);
	};

	this.removeItemViews = function () {
		this._adventureMapLayers[3].removeItemViews();
	};
});<|endoftext|>


<commit_before>import 'isomorphic-fetch';
import { get, post, remove } from 'utils/request';
import sortBy from 'lodash/sortBy';

import { getFieldUrl, getFields } from 'utils/datasets/fields';

export default class DatasetsService {
  constructor(options = {}) {
    if (!options.language) {
      throw new Error('options.language param is required.');
    }

    this.opts = options;
  }

  // GET ALL DATA
  fetchAdminData({ applications = [process.env.APPLICATIONS], includes, filters } = {}) {
    const qParams = {
      application: applications.join(','),
      language: this.opts.language,
      ...!!includes && { includes },
      'page[size]': 9999999,
      env: process.env.API_ENV,
      ...filters
    };

    console.log(qParams, filters);

    return new Promise((resolve, reject) => {
      get({
        url: `${process.env.WRI_API_URL}/dataset?${Object.keys(qParams).map(k => `${k}=${qParams[k]}`).join('&')}`,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: ({ data }) => {
          const datasets = data.map(dataset => ({ ...dataset.attributes, id: dataset.id }));
          resolve(sortBy(datasets, 'name'));
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  fetchAllData({ applications = [process.env.APPLICATIONS], includes, filters, env = process.env.API_ENV } = {}) {
    const qParams = {
      application: applications.join(','),
      language: this.opts.language,
      ...!!includes && { includes },
      'page[size]': 9999999,
      ...filters,
      env
    };

    return new Promise((resolve, reject) => {
      get({
        url: `${process.env.WRI_API_URL}/dataset?${Object.keys(qParams).map(k => `${k}=${qParams[k]}`).join('&')}`,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: ({ data }) => {
          const datasets = data.map(dataset => ({ ...dataset.attributes, id: dataset.id }));
          resolve(sortBy(datasets, 'name'));
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  fetchData({ id, applications = [process.env.APPLICATIONS], includes, filters }) {
    const qParams = {
      application: applications.join(','),
      language: this.opts.language,
      includes,
      ...filters
    };

    return new Promise((resolve, reject) => {
      get({
        url: `${process.env.WRI_API_URL}/dataset/${id}?${Object.keys(qParams).map(k => `${k}=${qParams[k]}`).join('&')}`,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (response) => {
          resolve({
            ...response.data.attributes,
            id: response.data.id
          });
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  saveData({ type, body, id = '' }) {
    return new Promise((resolve, reject) => {
      post({
        url: `${process.env.WRI_API_URL}/dataset/${id}`,
        type,
        body,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (response) => {
          resolve({
            ...response.data.attributes,
            id: response.data.id
          });
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  saveMetadata({ type, body, id = '' }) {
    return new Promise((resolve, reject) => {
      post({
        url: `${process.env.WRI_API_URL}/dataset/${id}/metadata`,
        type,
        body,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (response) => {
          resolve({
            ...response.data.attributes,
            id: response.data.id
          });
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  deleteData(id) {
    return new Promise((resolve, reject) => {
      remove({
        url: `${process.env.WRI_API_URL}/dataset/${id}`,
        headers: [{
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: () => {
          resolve();
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  fetchFields({ id, provider, type, tableName }) {
    const url = getFieldUrl(id, provider, type, tableName);
    return new Promise((resolve, reject) => {
      get({
        url,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (data) => {
          resolve(getFields(data, provider, type));
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }
}
<commit_msg>remove console.log<commit_after>import 'isomorphic-fetch';
import { get, post, remove } from 'utils/request';
import sortBy from 'lodash/sortBy';

import { getFieldUrl, getFields } from 'utils/datasets/fields';

export default class DatasetsService {
  constructor(options = {}) {
    if (!options.language) {
      throw new Error('options.language param is required.');
    }

    this.opts = options;
  }

  // GET ALL DATA
  fetchAdminData({ applications = [process.env.APPLICATIONS], includes, filters } = {}) {
    const qParams = {
      application: applications.join(','),
      language: this.opts.language,
      ...!!includes && { includes },
      'page[size]': 9999999,
      env: process.env.API_ENV,
      ...filters
    };

    return new Promise((resolve, reject) => {
      get({
        url: `${process.env.WRI_API_URL}/dataset?${Object.keys(qParams).map(k => `${k}=${qParams[k]}`).join('&')}`,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: ({ data }) => {
          const datasets = data.map(dataset => ({ ...dataset.attributes, id: dataset.id }));
          resolve(sortBy(datasets, 'name'));
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  fetchAllData({ applications = [process.env.APPLICATIONS], includes, filters, env = process.env.API_ENV } = {}) {
    const qParams = {
      application: applications.join(','),
      language: this.opts.language,
      ...!!includes && { includes },
      'page[size]': 9999999,
      ...filters,
      env
    };

    return new Promise((resolve, reject) => {
      get({
        url: `${process.env.WRI_API_URL}/dataset?${Object.keys(qParams).map(k => `${k}=${qParams[k]}`).join('&')}`,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: ({ data }) => {
          const datasets = data.map(dataset => ({ ...dataset.attributes, id: dataset.id }));
          resolve(sortBy(datasets, 'name'));
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  fetchData({ id, applications = [process.env.APPLICATIONS], includes, filters }) {
    const qParams = {
      application: applications.join(','),
      language: this.opts.language,
      includes,
      ...filters
    };

    return new Promise((resolve, reject) => {
      get({
        url: `${process.env.WRI_API_URL}/dataset/${id}?${Object.keys(qParams).map(k => `${k}=${qParams[k]}`).join('&')}`,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (response) => {
          resolve({
            ...response.data.attributes,
            id: response.data.id
          });
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  saveData({ type, body, id = '' }) {
    return new Promise((resolve, reject) => {
      post({
        url: `${process.env.WRI_API_URL}/dataset/${id}`,
        type,
        body,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (response) => {
          resolve({
            ...response.data.attributes,
            id: response.data.id
          });
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  saveMetadata({ type, body, id = '' }) {
    return new Promise((resolve, reject) => {
      post({
        url: `${process.env.WRI_API_URL}/dataset/${id}/metadata`,
        type,
        body,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (response) => {
          resolve({
            ...response.data.attributes,
            id: response.data.id
          });
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  deleteData(id) {
    return new Promise((resolve, reject) => {
      remove({
        url: `${process.env.WRI_API_URL}/dataset/${id}`,
        headers: [{
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: () => {
          resolve();
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  fetchFields({ id, provider, type, tableName }) {
    const url = getFieldUrl(id, provider, type, tableName);
    return new Promise((resolve, reject) => {
      get({
        url,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (data) => {
          resolve(getFields(data, provider, type));
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }
}
<|endoftext|>


<commit_before>/* global Kiwi, _, helixPi */
'use strict';

var HelixPiEditor = HelixPiEditor || {};

HelixPiEditor.Editor = new Kiwi.State('Editor');

HelixPiEditor.Editor.create = function () {
  this.entity = new Kiwi.GameObjects.Sprite(
    this,
    this.textures.entity,
    100,
    100,
    true
  );

  this.addChild(this.entity);
  this.entity.input.enableDrag();
  this.entity.input.onDragStopped.add(this.droppedEntity, this);

  this.game.input.keyboard.onKeyDown.add(
    this.onPress,
    this
  );

  this.frameText = new Kiwi.GameObjects.TextField(this, 'test', 10, 10, '#FFF');

  this.addChild(this.frameText);

  this.currentFrame = 0;
  this.currentKeyFrame = 0;
  this.highestFrame = 0;

  this.positions = [];
  this.line = {destroy: function () {}};
  this.progressIndicator = {destroy: function () {}};

  this.nextKeyFrameButton = new Kiwi.HUD.Widget.Button(
    this.game,
    'Next Keyframe',
    this.game.stage.width - 130,
    5
  );
  this.game.huds.defaultHUD.addWidget(this.nextKeyFrameButton);
  styleButton(this.nextKeyFrameButton);

  this.prevKeyFrameButton = new Kiwi.HUD.Widget.Button(
    this.game,
    'Prev Keyframe',
    this.game.stage.width - 250,
    5
  );
  this.game.huds.defaultHUD.addWidget(this.prevKeyFrameButton);
  styleButton(this.prevKeyFrameButton);

  this.createProgramButton = new Kiwi.HUD.Widget.Button(
    this.game,
    'Create Program',
    this.game.stage.width - 250,
    40
  );
  this.game.huds.defaultHUD.addWidget(this.createProgramButton);
  styleButton(this.createProgramButton);

  this.nextKeyFrameButton.input.onDown.add(this.nextKeyFrame, this);
  this.prevKeyFrameButton.input.onDown.add(this.prevKeyFrame, this);

  function styleButton (button) {
    _.assign(
      button.style,
      {
        color: 'white',
        backgroundColor: 'gray',
        padding: '5px',
        'border-radius': '3px',
        'font-family': 'Arial'
      }
    )
  }

  this.api = function (entity) {
    return {
      move: function (coordinates) {
        entity.x += coordinates.x;
        entity.y += coordinates.y;
      },

      getPosition: function () {
        return {
          x: entity.x,
          y: entity.y
        };
      }
    };
  };

  this.compiledApi = this.api(this.entity);
};

HelixPiEditor.Editor.update = function () {
  Kiwi.State.prototype.update.call(this);

  this.frameText.text = ['Frame: ', this.currentKeyFrame].join('');

  if (this.play) {
    var compiledApi = this.compiledApi;
    _.each(this.codeToPlay, function (instruction) {
      instruction(compiledApi);
    });

    this.displayProgressIndicator(this.currentKeyFrame / (this.highestFrame * 60));
    this.currentKeyFrame += 1;
  }
};

HelixPiEditor.Editor.displayProgressIndicator = function (progress) {
  var indicatorHeight = 60;
  this.progressIndicator.destroy();

  this.progressIndicator = new Kiwi.Plugins.Primitives.Line({
    state: this,
    points: [
      [this.game.stage.width * progress, this.game.stage.height - indicatorHeight],
      [this.game.stage.width * progress, this.game.stage.height]
    ],
    strokeColor: [1, 1, 1],
    strokeWidth: 4
  });

  this.addChild(this.progressIndicator);
};

HelixPiEditor.Editor.createScenario = function () {
  var startPosition = this.positions[0];
  var expectedPositions = this.positions.slice(1, this.highestFrame + 1);

  return {
    startingPosition: function () {
      return JSON.parse(JSON.stringify(startPosition));
    },

    expectedPositions: expectedPositions.map(function (expectedPosition, index) {
      expectedPosition.frame = index * 60;

      return expectedPosition;
    }),

    fitness: function (expectedPosition, entity) {
      var distance = {
        x: Math.abs(expectedPosition.x - entity.x),
        y: Math.abs(expectedPosition.y - entity.y)
      };

      return 1000 - Math.pow((distance.x + distance.y), 1.4);
    }
  };
};

HelixPiEditor.Editor.savePosition = function () {
  if (this.currentKeyFrame > this.highestFrame) {
    this.highestFrame = this.currentKeyFrame;
  }

  this.positions[this.currentKeyFrame] = {
    x: this.entity.x + this.entity.width / 2,
    y: this.entity.y + this.entity.height / 2
  };

  this.updatePath();
};

HelixPiEditor.Editor.updatePath = function () {
  this.line.destroy();
  this.line = new Kiwi.Plugins.Primitives.Line({
    state: this,
    points: this.positions.slice(0, this.highestFrame + 1)
      .map(function (position) { return [position.x, position.y]; }),

    strokeColor: [1, 1, 1],
    strokeWidth: 4
  });
  this.addChild(this.line);
};

HelixPiEditor.Editor.loadPosition = function () {
  if (!this.positions[this.currentKeyFrame]) {
    return;
  }

  this.entity.x = this.positions[this.currentKeyFrame].x - this.entity.width / 2;
  this.entity.y = this.positions[this.currentKeyFrame].y - this.entity.height / 2;
};

HelixPiEditor.Editor.nextKeyFrame = function () {
  this.savePosition();
  this.currentKeyFrame += 1;
  this.loadPosition();
}

HelixPiEditor.Editor.prevKeyFrame = function () {
  this.savePosition();
  this.currentKeyFrame -= 1;
  this.loadPosition();
}

HelixPiEditor.Editor.onPress = function (keyCode) {
  if (keyCode === Kiwi.Input.Keycodes.RIGHT) {
    this.nextKeyFrame();
  }

  if (keyCode === Kiwi.Input.Keycodes.LEFT) {
    this.prevKeyFrame();
  }

  if (keyCode === Kiwi.Input.Keycodes.R) {
    this.results = helixPi(this.createScenario(), this.api);
    this.currentKeyFrame = 0;
    this.currentFrame = 0;
    this.loadPosition();
    this.play = true;
    this.codeToPlay = this.results[0].individual;
    console.log(this.results[0].fitness);
  }
};

HelixPiEditor.Editor.droppedEntity = function ()  {
  this.savePosition();
}
<commit_msg>Add create program button<commit_after>/* global Kiwi, _, helixPi */
'use strict';

var HelixPiEditor = HelixPiEditor || {};

HelixPiEditor.Editor = new Kiwi.State('Editor');

HelixPiEditor.Editor.create = function () {
  this.entity = new Kiwi.GameObjects.Sprite(
    this,
    this.textures.entity,
    100,
    100,
    true
  );

  this.addChild(this.entity);
  this.entity.input.enableDrag();
  this.entity.input.onDragStopped.add(this.droppedEntity, this);

  this.game.input.keyboard.onKeyDown.add(
    this.onPress,
    this
  );

  this.frameText = new Kiwi.GameObjects.TextField(this, 'test', 10, 10, '#FFF');

  this.addChild(this.frameText);

  this.currentFrame = 0;
  this.currentKeyFrame = 0;
  this.highestFrame = 0;

  this.positions = [];
  this.line = {destroy: function () {}};
  this.progressIndicator = {destroy: function () {}};

  this.nextKeyFrameButton = new Kiwi.HUD.Widget.Button(
    this.game,
    'Next Keyframe',
    this.game.stage.width - 130,
    5
  );
  this.game.huds.defaultHUD.addWidget(this.nextKeyFrameButton);
  styleButton(this.nextKeyFrameButton);

  this.prevKeyFrameButton = new Kiwi.HUD.Widget.Button(
    this.game,
    'Prev Keyframe',
    this.game.stage.width - 250,
    5
  );
  this.game.huds.defaultHUD.addWidget(this.prevKeyFrameButton);
  styleButton(this.prevKeyFrameButton);

  this.createProgramButton = new Kiwi.HUD.Widget.Button(
    this.game,
    'Create Program',
    this.game.stage.width - 250,
    40
  );
  this.game.huds.defaultHUD.addWidget(this.createProgramButton);
  styleButton(this.createProgramButton);

  this.nextKeyFrameButton.input.onDown.add(this.nextKeyFrame, this);
  this.prevKeyFrameButton.input.onDown.add(this.prevKeyFrame, this);
  this.createProgramButton.input.onDown.add(this.createProgram, this);

  function styleButton (button) {
    _.assign(
      button.style,
      {
        color: 'white',
        backgroundColor: 'gray',
        padding: '5px',
        'border-radius': '3px',
        'font-family': 'Arial'
      }
    )
  }

  this.api = function (entity) {
    return {
      move: function (coordinates) {
        entity.x += coordinates.x;
        entity.y += coordinates.y;
      },

      getPosition: function () {
        return {
          x: entity.x,
          y: entity.y
        };
      }
    };
  };

  this.compiledApi = this.api(this.entity);
};

HelixPiEditor.Editor.update = function () {
  Kiwi.State.prototype.update.call(this);

  this.frameText.text = ['Frame: ', this.currentKeyFrame].join('');

  if (this.play) {
    var compiledApi = this.compiledApi;
    _.each(this.codeToPlay, function (instruction) {
      instruction(compiledApi);
    });

    this.displayProgressIndicator(this.currentFrame / (this.highestFrame * 60));
    this.currentFrame += 1;
  }
};

HelixPiEditor.Editor.displayProgressIndicator = function (progress) {
  var indicatorHeight = 60;
  this.progressIndicator.destroy();

  this.progressIndicator = new Kiwi.Plugins.Primitives.Line({
    state: this,
    points: [
      [this.game.stage.width * progress, this.game.stage.height - indicatorHeight],
      [this.game.stage.width * progress, this.game.stage.height]
    ],
    strokeColor: [1, 1, 1],
    strokeWidth: 4
  });

  this.addChild(this.progressIndicator);
};

HelixPiEditor.Editor.createScenario = function () {
  var startPosition = this.positions[0];
  var expectedPositions = this.positions.slice(1, this.highestFrame + 1);

  return {
    startingPosition: function () {
      return JSON.parse(JSON.stringify(startPosition));
    },

    expectedPositions: expectedPositions.map(function (expectedPosition, index) {
      expectedPosition.frame = index * 60;

      return expectedPosition;
    }),

    fitness: function (expectedPosition, entity) {
      var distance = {
        x: Math.abs(expectedPosition.x - entity.x),
        y: Math.abs(expectedPosition.y - entity.y)
      };

      return 1000 - Math.pow((distance.x + distance.y), 1.4);
    }
  };
};

HelixPiEditor.Editor.savePosition = function () {
  if (this.currentKeyFrame > this.highestFrame) {
    this.highestFrame = this.currentKeyFrame;
  }

  this.positions[this.currentKeyFrame] = {
    x: this.entity.x + this.entity.width / 2,
    y: this.entity.y + this.entity.height / 2
  };

  this.updatePath();
};

HelixPiEditor.Editor.updatePath = function () {
  this.line.destroy();
  this.line = new Kiwi.Plugins.Primitives.Line({
    state: this,
    points: this.positions.slice(0, this.highestFrame + 1)
      .map(function (position) { return [position.x, position.y]; }),

    strokeColor: [1, 1, 1],
    strokeWidth: 4
  });
  this.addChild(this.line);
};

HelixPiEditor.Editor.loadPosition = function () {
  if (!this.positions[this.currentKeyFrame]) {
    return;
  }

  this.entity.x = this.positions[this.currentKeyFrame].x - this.entity.width / 2;
  this.entity.y = this.positions[this.currentKeyFrame].y - this.entity.height / 2;
};

HelixPiEditor.Editor.nextKeyFrame = function () {
  this.savePosition();
  this.currentKeyFrame += 1;
  this.loadPosition();
}

HelixPiEditor.Editor.prevKeyFrame = function () {
  this.savePosition();
  this.currentKeyFrame -= 1;
  this.loadPosition();
}

HelixPiEditor.Editor.onPress = function (keyCode) {
  if (keyCode === Kiwi.Input.Keycodes.RIGHT) {
    this.nextKeyFrame();
  }

  if (keyCode === Kiwi.Input.Keycodes.LEFT) {
    this.prevKeyFrame();
  }

  if (keyCode === Kiwi.Input.Keycodes.R) {
    this.createProgram();
  }
};

HelixPiEditor.Editor.droppedEntity = function ()  {
  this.savePosition();
}

HelixPiEditor.Editor.createProgram = function () {
  this.results = helixPi(this.createScenario(), this.api);
  this.currentKeyFrame = 0;
  this.currentFrame = 0;
  this.loadPosition();
  this.play = true;
  this.codeToPlay = this.results[0].individual;
}
<|endoftext|>


<commit_before>//------------
// houston_factory.js
//------------
// a composable event engine for mediating
// the interactions between node.js modules

var HoustonFactory;

HoustonFactory = {

	var Houston;

	// Creates a Houston instance and populates it with modules and rule sets
	createHouston: function(){

		Houston = require('./houston.js');
		console.log('Creating modules');
		this.createModules('./database/');
		console.log('Creating rule sets');
		this.createRulesets('.');

	};

	// Create modules for Houston
	// @param {String} moduleDir the directory to look for modules
	createModules: function(moduleDir){
		var fs = require('fs');
		//Comment this out if you want to just manually require each service
		//this will just require every service defined in the database folder.

		fs.readdirSync(moduleDir).forEach(function(file) {
			var filename = file.stripFileDesignation();
			try {
				var module = require(file);
			} catch (e){
				console.log("error creating module " + filename);
				return;
			}
			Houston.registerModule(filename, module);
		});
	};

	// Create the rulesets from the given directory location
	// @param {String} rulesetDir the directory to look for rulesets
	createRulesets = function(rulesetDir){

	 	var HoustonRuleSetParser = require('./houston_ruleset_parser.js');
	 	var fs = require('fs');
	 	var path = require('path');
	 	fs.readdirSync(rulesetDir).forEach(function(file){

	 		// get file extension
	 		var ext = path.extname(file).split('.');
	 		ext = ext[ext.length - 1];

	 		// get contents of file
	 		var contents = fs.readFileSync(file);
	 		var json;
 			if(ext === "hrs"){
 				try {
 					json = Houston.HoustonRuleSetParser.parser(contents);
 				} catch (e){
 					console.log("error creating rulesets from hrs file " + file + ": " + e);
 					return;
 				}
 			} else if(ext === "json"){
 				try {
 					json = JSON.parse(contents);
					} catch (e){
						console.log("error creating rulesets from hrs file " + file + ": " + e);
						return;
 				}
 			} else {
 				return;
 			}
 			var jsonArray = [].concat(json);
	 		for (var i = jsonArray.length - 1; i >= 0; i--) {
	 			Houston.addRulset(jsonArray[i]);
	 		};
	 	});

	};

}

module.exports = HoustonFactory;<commit_msg>houston factory working<commit_after>//------------
// houston_factory.js
//------------
// a composable event engine for mediating
// the interactions between node.js modules

/**
 * @namespace
 */
var HoustonFactory;

HoustonFactory = {
	// Creates a Houston instance and populates it with modules and rule sets
	createHouston: function(){

		this.Houston = require('./houston.js');
		//console.log(this.Houston);
		//console.log('Creating modules');
		this.createModules('./database/');
		//console.log('Creating rule sets');
		this.createRulesets('./rulesets/');

		return this.Houston;
	},

	// Create modules for Houston
	// @param {String} moduleDir the directory to look for modules
	createModules: function(moduleDir){
		var me = this;
		var fs = require('fs');
		//Comment this out if you want to just manually require each service
		//this will just require every service defined in the database folder.

		fs.readdirSync(moduleDir).forEach(function(file) {
			var fileparts = file.split('.');
			var filename = fileparts[0];
			try {
				//console.log(file);

				var module = require(moduleDir + file);
			} catch (e){
				console.log("error creating module " + filename + ": " + e);
				return;
			}

			me.Houston.registerModule(filename, module);
		});
	},

	// Create the rulesets from the given directory location
	// @param {String} rulesetDir the directory to look for rulesets
	createRulesets: function(rulesetDir){
		var me = this;

	 	var HoustonRuleSetParser = require('./houston_ruleset_parser.js');
	 	var fs = require('fs');
	 	var path = require('path');
	 	fs.readdirSync(rulesetDir).forEach(function(file){

	 		// get file extension
	 		var fileparts = file.split(".");
	 		var ext = fileparts[1];

	 		// get contents of file
	 		var contents = fs.readFileSync(file);
	 		var json;
 			if(ext === "hrs"){
 				try {
 					json = Houston.HoustonRuleSetParser.parser(contents);
 				} catch (e){
 					console.log("error creating rulesets from hrs file " + file + ": " + e);
 					return;
 				}
 			} else if(ext === "json"){
 				try {
 					json = JSON.parse(contents);
				} catch (e){
					console.log("error creating rulesets from hrs file " + file + ": " + e);
					return;
 				}
 			} else {
 				return;
 			}
 			var jsonArray = [].concat(json);
	 		for (var i = jsonArray.length - 1; i >= 0; i--) {
	 			me.Houston.addRuleset(jsonArray[i]);
	 		};
	 	});
		console.log(me.Houston);
	}

}

module.exports = HoustonFactory;

var hf = HoustonFactory;
var houston = hf.createHouston();
houston.trigger('onTwitter', 'twitter');<|endoftext|>