<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var gutil = require('gulp-util');
var through = require('through2');

function sha1(filePath) {
	return crypto.createHash('md5')
		.update(fs.readFileSync(filePath))
		.digest("hex");
}

module.exports = function (options) {
	var contents, mainPath, reg, asset;

	asset = options.asset || process.cwd();

	reg = new RegExp('["\'\\(]\\s*([\\w\\_\/\\.\\-]*\\.('+ (options.exts ? options.exts.join('|') : 'jpg|jpeg|png|gif|cur|js|css') +'))(\\?[\\w\\_\\=\\-]+)?\\s*[\\)"\']', 'gim');

	return through.obj(function (file, enc, callback) {
		if (file.isNull()) {
			this.push(file);
			return callback();
		}

		if (file.isStream()) {
			this.emit('error', new gutil.PluginError('gulp-static-hash', 'Streams are not supported!'));
			return callback();
		}

		mainPath = path.dirname(file.path);

		contents = file.contents.toString().replace(reg, function(content, filePath, ext, version){
			var fullPath

			if(/^\//.test(filePath)){
				fullPath = path.resolve(asset, filePath.slice(1));
			}else{
				fullPath = path.resolve(asset, mainPath, filePath);
			}

			if(fs.existsSync(fullPath)){
				return content.replace(version || '', (/sv/.test(version) ? ('&sv=' + version.split('=')[1]) : '')).replace(filePath, filePath + '?v=' + sha1(fullPath));
			}else{
				return content;
			}
		});

		file.contents = new Buffer(contents);

		this.push(file);
		return callback();
	});
};<commit_msg>修改代码以通过jshint检测<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var gutil = require('gulp-util');
var through = require('through2');

function sha1(filePath) {
	return crypto.createHash('md5')
		.update(fs.readFileSync(filePath))
		.digest('hex');
}

module.exports = function (options) {
	var contents, mainPath, reg, asset;

	asset = options.asset || process.cwd();

	reg = new RegExp('["\'\\(]\\s*([\\w\\_\/\\.\\-]*\\.('+ (options.exts ? options.exts.join('|') : 'jpg|jpeg|png|gif|cur|js|css') +'))(\\?[\\w\\_\\=\\-]+)?\\s*[\\)"\']', 'gim');

	return through.obj(function (file, enc, callback) {
		if (file.isNull()) {
			this.push(file);
			return callback();
		}

		if (file.isStream()) {
			this.emit('error', new gutil.PluginError('gulp-static-hash', 'Streams are not supported!'));
			return callback();
		}

		mainPath = path.dirname(file.path);

		contents = file.contents.toString().replace(reg, function(content, filePath, ext, version){
			var fullPath;

			if(/^\//.test(filePath)){
				fullPath = path.resolve(asset, filePath.slice(1));
			}else{
				fullPath = path.resolve(asset, mainPath, filePath);
			}

			if(fs.existsSync(fullPath)){
				return content.replace(version || '', (/sv/.test(version) ? ('&sv=' + version.split('=')[1]) : '')).replace(filePath, filePath + '?v=' + sha1(fullPath));
			}else{
				return content;
			}
		});

		file.contents = new Buffer(contents);

		this.push(file);
		return callback();
	});
};<|endoftext|>


<commit_before>'use strict';

function rpg_character_affect(character, stat, effect){
    rpg_characters[character]['stats'][stat]['current'] -= effect;
    if(rpg_characters[character]['stats'][stat]['current'] <= 0){
        rpg_characters[character]['stats'][stat]['current'] = 0;

        if(stat === 'health'){
            rpg_characters[character]['dead'] = true;
        }

    }else if(rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
        rpg_characters[character]['stats'][stat]['current'] = rpg_characters[character]['stats'][stat]['max'];
        rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
    }
}

function rpg_character_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['dead'] = false;
    properties['equipment'] = properties['equipment'] || {
      'feet': void 0,
      'head': void 0,
      'legs': void 0,
      'main-hand': void 0,
      'neck': void 0,
      'off-hand': void 0,
      'torso': void 0,
    };
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 20;
    properties['height-half'] = properties['height'] / 2;
    properties['inventory'] = properties['inventory'] || [];
    properties['player'] = properties['player'] || false;
    properties['selected'] = properties['selected'] || 1;
    properties['spellbar'] = properties['spellbar'] || {
      0: void 0,
      1: void 0,
      2: void 0,
      3: void 0,
      4: void 0,
      5: void 0,
      6: void 0,
      7: void 0,
      8: void 0,
      9: void 0,
    };
    properties['spellbook'] = properties['spellbook'] || {};
    properties['team'] = properties['team'] !== void 0
      ? properties['team']
      : 1;
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 20;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['x-velocity'] = properties['x-velocity'] || 0;
    properties['y'] = properties['y'] || 0;
    properties['y-velocity'] = properties['y-velocity'] || 0;

    properties['stats'] = properties['stats'] || {};
      properties['stats']['health'] = properties['stats']['health'] || {};
        properties['stats']['health']['current'] = properties['stats']['health']['current'] !== void 0
          ? properties['stats']['health']['current']
          : 1;
        properties['stats']['health']['max'] = properties['stats']['health']['max'] || 1;

    rpg_characters.push(properties);
}

function rpg_character_handle(){
    for(var character in rpg_characters){
        if(rpg_characters[character]['dead']){
            continue;
        }

        // Regenerate character stats.
        for(var stat in rpg_characters[character]['stats']){
            if(rpg_characters[character]['stats'][stat]['regeneration'] === void 0
              || rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
                continue;
            }

            rpg_characters[character]['stats'][stat]['regeneration']['current'] += 1;
            if(rpg_characters[character]['stats'][stat]['regeneration']['current'] >= rpg_characters[character]['stats'][stat]['regeneration']['max']){
                rpg_characters[character]['stats'][stat]['current'] += 1;
                rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
            }
        }

        for(var spell in rpg_characters[character]['spellbook']){
            if(rpg_characters[character]['spellbook'][spell]['current'] < rpg_characters[character]['spellbook'][spell]['reload']){
                rpg_characters[character]['spellbook'][spell]['current'] += 1;
                continue;
            }

            if(rpg_characters[character]['spellbar'][rpg_characters[character]['selected']] !== spell){
                continue;
            }

            if(character === '0'){
                var selected = rpg_characters[0]['spellbook'][rpg_characters[0]['spellbar'][rpg_characters[0]['selected']]];

                if(mouse_lock_x > -1
                  && rpg_characters[0]['stats'][selected['costs']]['current'] >= selected['cost']){
                    selected['current'] = 0;
                    rpg_character_affect(
                      character,
                      selected['costs'],
                      selected['cost']
                    );

                    // Handle particle-creating spells.
                    if(selected['type'] === 'particle'){
                        var speeds = math_movement_speed(
                          rpg_characters[0]['x'],
                          rpg_characters[0]['y'],
                          rpg_characters[0]['x'] + mouse_x - canvas_x,
                          rpg_characters[0]['y'] + mouse_y - canvas_y
                        );
                        var particle = {};
                        for(var property in selected['particle']){
                            particle[property] = selected['particle'][property];
                        }
                        particle['dx'] = mouse_x > canvas_x ? speeds[0] : -speeds[0];
                        particle['dy'] = mouse_y > canvas_y ? speeds[1] : -speeds[1];
                        particle['x'] = rpg_characters[0]['x'];
                        particle['y'] = rpg_characters[0]['y'];

                        rpg_particle_create(particle);

                    }else if(selected['type'] === 'stat'){
                        rpg_character_affect(
                          character,
                          selected['effect']['stat'],
                          selected['effect']['damage']
                        );

                    }else if(selected['type'] === 'world-dynamic'){
                        var worlddynamic = {};
                        for(var property in selected['world-dynamic']){
                            worlddynamic[property] = selected['world-dynamic'][property];
                        }
                        worlddynamic['x'] = Math.round(rpg_characters[0]['x'] + mouse_x - canvas_x - 12.5);
                        worlddynamic['y'] = Math.round(rpg_characters[0]['y'] + mouse_y - canvas_y - 12.5);

                        rpg_world_dynamic_create(worlddynamic);
                    }
                }

            }else{
                rpg_characters[character]['spellbook'][spell]['current'] = 0;

                // Create character-created particle.
                var speeds = math_movement_speed(
                  rpg_characters[character]['x'],
                  rpg_characters[character]['y'],
                  rpg_characters[0]['x'],
                  rpg_characters[0]['y']
                );
                var particle = {};
                for(var property in rpg_characters[character]['spellbook'][spell]){
                    particle[property] = rpg_characters[character]['spellbook'][spell][property];
                }
                particle['dx'] = rpg_characters[0]['x'] > rpg_characters[character]['x'] ? speeds[0] : -speeds[0];
                particle['dy'] = rpg_characters[0]['y'] > rpg_characters[character]['y'] ? speeds[1] : -speeds[1];
                particle['owner'] = character;
                particle['x'] = rpg_characters[character]['x'];
                particle['y'] = rpg_characters[character]['y'];

                rpg_particle_create(particle);
            }

            break;
        }
    }
}

function rpg_item_create(properties, type){
    properties = properties || {};
    type = type || 'any';

    properties['equipped'] = properties['equipped'] || false;
    properties['owner'] = properties['owner'] || 'player';

    rpg_items.push(properties);
}

function rpg_item_toggle(id){
    if(rpg_items[id]['owner'] === false){
        return;
    }

    // Toggle item on character.
    rpg_items[id]['equipped'] = !rpg_items[id]['equipped'];
}

function rpg_particle_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['damage'] = properties['damage'] || 0;
    properties['dx'] = properties['dx'] || 0;
    properties['dy'] = properties['dy'] || 0;
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 10;
    properties['height-half'] = properties['height'] / 2;
    properties['lifespan'] = properties['lifespan'] !== void 0
      ? properties['lifespan']
      : 10;
    properties['owner'] = properties['owner'] !== void 0
      ? properties['owner']
      : -1;
    properties['speed-x'] = properties['speed-x'] !== void 0
      ? properties['speed-x']
      : 1;
    properties['speed-y'] = properties['speed-y'] !== void 0
      ? properties['speed-y']
      : 1;
    properties['stat'] = properties['stat'] || 'health';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 10;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_particles.push(properties);
}

function rpg_particle_handle(){
    particleloop:
    for(var particle in rpg_particles){
        rpg_particles[particle]['x'] += rpg_particles[particle]['dx'] * rpg_particles[particle]['speed-x'];
        rpg_particles[particle]['y'] += rpg_particles[particle]['dy'] * rpg_particles[particle]['speed-y'];

        if(rpg_particles[particle]['lifespan'] < 0){
            rpg_particles.splice(
              particle,
              1
            );
            continue;
        }
        rpg_particles[particle]['lifespan'] -= 1;

        for(var object in rpg_world_dynamic){
            if(!rpg_world_dynamic[object]['collision']
              || rpg_particles[particle]['x'] <= rpg_world_dynamic[object]['x']
              || rpg_particles[particle]['x'] >= rpg_world_dynamic[object]['x'] + rpg_world_dynamic[object]['width']
              || rpg_particles[particle]['y'] <= rpg_world_dynamic[object]['y']
              || rpg_particles[particle]['y'] >= rpg_world_dynamic[object]['y'] + rpg_world_dynamic[object]['height']){
                continue;
            }

            rpg_particles.splice(
              particle,
              1
            );
            continue particleloop;
        }

        // Handle collisions with characters.
        for(var character in rpg_characters){
            if(rpg_particles[particle]['owner'] === character
              || rpg_particles[particle]['x'] <= rpg_characters[character]['x'] - rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['x'] >= rpg_characters[character]['x'] + rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['y'] <= rpg_characters[character]['y'] - rpg_characters[character]['height'] / 2
              || rpg_particles[particle]['y'] >= rpg_characters[character]['y'] + rpg_characters[character]['height'] / 2){
                continue;
            }

            rpg_character_affect(
              character,
              rpg_particles[particle]['stat'],
              rpg_particles[particle]['damage']
            );

            rpg_particles.splice(
              particle,
              1
            );

            continue particleloop;
        }
    }
}

function rpg_spell_select(character, id){
    character = character || 0;

    if(id < 1){
        id = 10;

    }else if(id > 10){
        id = 1;
    }

    rpg_characters[character]['selected'] = id;

    if(character === 0){
        document.getElementById('canvas').style.cursor =
          rpg_characters[0]['spellbook'][rpg_characters[0]['spellbar'][id]]['cursor'] || 'auto';
    }
}

function rpg_world_dynamic_create(properties){
    properties = properties || {};

    properties['collision'] = properties['collision'] === void 0;
    properties['color'] = properties['color'] || '#fff';
    properties['effect'] = properties['effect'] || {};
    properties['effect-stat'] = properties['effect-stat'] || 'health';
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 25;
    properties['type'] = properties['type'] || 'stone';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 25;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_world_dynamic.push(properties);
}

var rpg_characters = [];
var rpg_items = [];
var rpg_particles = [];
var rpg_ui = 0;
var rpg_world_dynamic = [];
var rpg_world_static = [];
<commit_msg>fixed player spellcasting<commit_after>'use strict';

function rpg_character_affect(character, stat, effect){
    rpg_characters[character]['stats'][stat]['current'] -= effect;
    if(rpg_characters[character]['stats'][stat]['current'] <= 0){
        rpg_characters[character]['stats'][stat]['current'] = 0;

        if(stat === 'health'){
            rpg_characters[character]['dead'] = true;
        }

    }else if(rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
        rpg_characters[character]['stats'][stat]['current'] = rpg_characters[character]['stats'][stat]['max'];
        rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
    }
}

function rpg_character_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['dead'] = false;
    properties['equipment'] = properties['equipment'] || {
      'feet': void 0,
      'head': void 0,
      'legs': void 0,
      'main-hand': void 0,
      'neck': void 0,
      'off-hand': void 0,
      'torso': void 0,
    };
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 20;
    properties['height-half'] = properties['height'] / 2;
    properties['inventory'] = properties['inventory'] || [];
    properties['player'] = properties['player'] || false;
    properties['selected'] = properties['selected'] || 1;
    properties['spellbar'] = properties['spellbar'] || {
      0: void 0,
      1: void 0,
      2: void 0,
      3: void 0,
      4: void 0,
      5: void 0,
      6: void 0,
      7: void 0,
      8: void 0,
      9: void 0,
    };
    properties['spellbook'] = properties['spellbook'] || {};
    properties['team'] = properties['team'] !== void 0
      ? properties['team']
      : 1;
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 20;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['x-velocity'] = properties['x-velocity'] || 0;
    properties['y'] = properties['y'] || 0;
    properties['y-velocity'] = properties['y-velocity'] || 0;

    properties['stats'] = properties['stats'] || {};
      properties['stats']['health'] = properties['stats']['health'] || {};
        properties['stats']['health']['current'] = properties['stats']['health']['current'] !== void 0
          ? properties['stats']['health']['current']
          : 1;
        properties['stats']['health']['max'] = properties['stats']['health']['max'] || 1;

    rpg_characters.push(properties);
}

function rpg_character_handle(){
    for(var character in rpg_characters){
        if(rpg_characters[character]['dead']){
            continue;
        }

        // Regenerate character stats.
        for(var stat in rpg_characters[character]['stats']){
            if(rpg_characters[character]['stats'][stat]['regeneration'] === void 0
              || rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
                continue;
            }

            rpg_characters[character]['stats'][stat]['regeneration']['current'] += 1;
            if(rpg_characters[character]['stats'][stat]['regeneration']['current'] >= rpg_characters[character]['stats'][stat]['regeneration']['max']){
                rpg_characters[character]['stats'][stat]['current'] += 1;
                rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
            }
        }

        for(var spell in rpg_characters[character]['spellbook']){
            if(rpg_characters[character]['spellbook'][spell]['current'] < rpg_characters[character]['spellbook'][spell]['reload']){
                rpg_characters[character]['spellbook'][spell]['current'] += 1;
                continue;
            }

            if(rpg_characters[character]['spellbar'][rpg_characters[character]['selected']] !== spell){
                continue;
            }

            if(character === '0'){
                var selected = rpg_characters[0]['spellbook'][rpg_characters[0]['spellbar'][rpg_characters[0]['selected']]];

                if(mouse_lock_x > -1
                  && rpg_characters[0]['stats'][selected['costs']]['current'] >= selected['cost']){
                    selected['current'] = 0;
                    rpg_character_affect(
                      character,
                      selected['costs'],
                      selected['cost']
                    );

                    // Handle particle-creating spells.
                    if(selected['type'] === 'particle'){
                        var speeds = math_movement_speed(
                          rpg_characters[0]['x'],
                          rpg_characters[0]['y'],
                          rpg_characters[0]['x'] + mouse_x - canvas_x,
                          rpg_characters[0]['y'] + mouse_y - canvas_y
                        );
                        var particle = {};
                        for(var property in selected['particle']){
                            particle[property] = selected['particle'][property];
                        }
                        particle['dx'] = mouse_x > canvas_x ? speeds[0] : -speeds[0];
                        particle['dy'] = mouse_y > canvas_y ? speeds[1] : -speeds[1];
                        particle['owner'] = 0;
                        particle['x'] = rpg_characters[0]['x'];
                        particle['y'] = rpg_characters[0]['y'];

                        rpg_particle_create(particle);

                    }else if(selected['type'] === 'stat'){
                        rpg_character_affect(
                          character,
                          selected['effect']['stat'],
                          selected['effect']['damage']
                        );

                    }else if(selected['type'] === 'world-dynamic'){
                        var worlddynamic = {};
                        for(var property in selected['world-dynamic']){
                            worlddynamic[property] = selected['world-dynamic'][property];
                        }
                        worlddynamic['x'] = Math.round(rpg_characters[0]['x'] + mouse_x - canvas_x - 12.5);
                        worlddynamic['y'] = Math.round(rpg_characters[0]['y'] + mouse_y - canvas_y - 12.5);

                        rpg_world_dynamic_create(worlddynamic);
                    }
                }

            }else{
                rpg_characters[character]['spellbook'][spell]['current'] = 0;

                // Create character-created particle.
                var speeds = math_movement_speed(
                  rpg_characters[character]['x'],
                  rpg_characters[character]['y'],
                  rpg_characters[0]['x'],
                  rpg_characters[0]['y']
                );
                var particle = {};
                for(var property in rpg_characters[character]['spellbook'][spell]){
                    particle[property] = rpg_characters[character]['spellbook'][spell][property];
                }
                particle['dx'] = rpg_characters[0]['x'] > rpg_characters[character]['x'] ? speeds[0] : -speeds[0];
                particle['dy'] = rpg_characters[0]['y'] > rpg_characters[character]['y'] ? speeds[1] : -speeds[1];
                particle['owner'] = character;
                particle['x'] = rpg_characters[character]['x'];
                particle['y'] = rpg_characters[character]['y'];

                rpg_particle_create(particle);
            }

            break;
        }
    }
}

function rpg_item_create(properties, type){
    properties = properties || {};
    type = type || 'any';

    properties['equipped'] = properties['equipped'] || false;
    properties['owner'] = properties['owner'] || 'player';

    rpg_items.push(properties);
}

function rpg_item_toggle(id){
    if(rpg_items[id]['owner'] === false){
        return;
    }

    // Toggle item on character.
    rpg_items[id]['equipped'] = !rpg_items[id]['equipped'];
}

function rpg_particle_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['damage'] = properties['damage'] || 0;
    properties['dx'] = properties['dx'] || 0;
    properties['dy'] = properties['dy'] || 0;
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 10;
    properties['height-half'] = properties['height'] / 2;
    properties['lifespan'] = properties['lifespan'] !== void 0
      ? properties['lifespan']
      : 10;
    properties['owner'] = properties['owner'] !== void 0
      ? properties['owner']
      : -1;
    properties['speed-x'] = properties['speed-x'] !== void 0
      ? properties['speed-x']
      : 1;
    properties['speed-y'] = properties['speed-y'] !== void 0
      ? properties['speed-y']
      : 1;
    properties['stat'] = properties['stat'] || 'health';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 10;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_particles.push(properties);
}

function rpg_particle_handle(){
    particleloop:
    for(var particle in rpg_particles){
        rpg_particles[particle]['x'] += rpg_particles[particle]['dx'] * rpg_particles[particle]['speed-x'];
        rpg_particles[particle]['y'] += rpg_particles[particle]['dy'] * rpg_particles[particle]['speed-y'];

        if(rpg_particles[particle]['lifespan'] < 0){
            rpg_particles.splice(
              particle,
              1
            );
            continue;
        }
        rpg_particles[particle]['lifespan'] -= 1;

        for(var object in rpg_world_dynamic){
            if(!rpg_world_dynamic[object]['collision']
              || rpg_particles[particle]['x'] <= rpg_world_dynamic[object]['x']
              || rpg_particles[particle]['x'] >= rpg_world_dynamic[object]['x'] + rpg_world_dynamic[object]['width']
              || rpg_particles[particle]['y'] <= rpg_world_dynamic[object]['y']
              || rpg_particles[particle]['y'] >= rpg_world_dynamic[object]['y'] + rpg_world_dynamic[object]['height']){
                continue;
            }

            rpg_particles.splice(
              particle,
              1
            );
            continue particleloop;
        }

        // Handle collisions with characters.
        for(var character in rpg_characters){
            if(rpg_particles[particle]['owner'] === parseInt(character, 10)
              || rpg_particles[particle]['x'] <= rpg_characters[character]['x'] - rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['x'] >= rpg_characters[character]['x'] + rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['y'] <= rpg_characters[character]['y'] - rpg_characters[character]['height'] / 2
              || rpg_particles[particle]['y'] >= rpg_characters[character]['y'] + rpg_characters[character]['height'] / 2){
                continue;
            }

            rpg_character_affect(
              character,
              rpg_particles[particle]['stat'],
              rpg_particles[particle]['damage']
            );

            rpg_particles.splice(
              particle,
              1
            );

            continue particleloop;
        }
    }
}

function rpg_spell_select(character, id){
    character = character || 0;

    if(id < 1){
        id = 10;

    }else if(id > 10){
        id = 1;
    }

    rpg_characters[character]['selected'] = id;

    if(character === 0){
        document.getElementById('canvas').style.cursor =
          rpg_characters[0]['spellbook'][rpg_characters[0]['spellbar'][id]]['cursor'] || 'auto';
    }
}

function rpg_world_dynamic_create(properties){
    properties = properties || {};

    properties['collision'] = properties['collision'] === void 0;
    properties['color'] = properties['color'] || '#fff';
    properties['effect'] = properties['effect'] || {};
    properties['effect-stat'] = properties['effect-stat'] || 'health';
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 25;
    properties['type'] = properties['type'] || 'stone';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 25;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_world_dynamic.push(properties);
}

var rpg_characters = [];
var rpg_items = [];
var rpg_particles = [];
var rpg_ui = 0;
var rpg_world_dynamic = [];
var rpg_world_static = [];
<|endoftext|>


<commit_before>'use strict'

const Node = require('./lib/node');
const Loader = require('./lib/load');

// factory
module.exports = (adapter) => {

    if (!adapter.read || !adapter.mod) {
        throw new Error('Flow: No Module or MIC adapter found.');
    }

    const scope = {
        env: adapter.env,
        mod: adapter.mod,
        read: adapter.read,

        // cache must have "get", "set" and "reset" methods
        cache: adapter.cache,

        // reset cache
        reset: () => {

            if (typeof adapter.reset === 'function') {
                adapter.reset();
            }

            adapter.cache.reset();
        }
    };

    return (event, args) => {
        return Flow(scope, event, args)
    };
};

function Flow (scope, event, args) {

    // return if event name is missing
    if (!event) {
        throw new Error('Flow: Empty event.');
    }

    // return cached streams
    // TODO args for cached nodes??
    let node = scope.cache.get('s:' + event);
    if (node) {
        return node;
    }

    node = Node(scope, event);
    args = args || {};

    // handle cached event
    let parsed_event = scope.cache.get('l:' + event);
    if (parsed_event) {
        process.nextTick(() => {
            node.link(args, parsed_event);
        });

    // pipe triple stream to loader
    } else {
        scope.read(event, args).pipe(Loader(scope, node, args));
    }

    // save stream in cache
    scope.cache.set('s:' + event, node);

    return node;
}
<commit_msg>pass args to node factory<commit_after>'use strict'

const Node = require('./lib/node');
const Loader = require('./lib/load');

// factory
module.exports = (adapter) => {

    if (!adapter.read || !adapter.mod) {
        throw new Error('Flow: No Module or MIC adapter found.');
    }

    const scope = {
        env: adapter.env,
        mod: adapter.mod,
        read: adapter.read,

        // cache must have "get", "set" and "reset" methods
        cache: adapter.cache,

        // reset cache
        reset: () => {

            if (typeof adapter.reset === 'function') {
                adapter.reset();
            }

            adapter.cache.reset();
        }
    };

    return (event, args) => {
        return Flow(scope, event, args)
    };
};

function Flow (scope, event, args = {}) {

    // return if event name is missing
    if (!event) {
        throw new Error('Flow: Empty event.');
    }

    // return cached streams
    // TODO args for cached nodes??
    // TODO check if it's better, if the modules handles
    //      the reuse of streams?
    let node = scope.cache.get('s:' + event);
    if (node) {
        return node;
    }

    node = Node(scope, event, args);

    // handle cached event
    let parsed_event = scope.cache.get('l:' + event);
    if (parsed_event) {
        process.nextTick(() => node.link(args, parsed_event));

    // pipe triple stream to loader
    } else {
        scope.read(event, args).pipe(Loader(scope, node, args));
    }

    // save stream in cache
    scope.cache.set('s:' + event, node);

    return node;
}
<|endoftext|>


<commit_before>'use strict';

var hamlc = require('haml-coffee');

exports.name = 'haml-coffee';
exports.inputFormats = ['haml', 'haml-coffee'];
exports.outputFormat = 'html';

exports.compile = hamlc.compile;
<commit_msg>fix(inputformats): Add hamlc to inputformats<commit_after>'use strict';

var hamlc = require('haml-coffee');

exports.name = 'haml-coffee';
exports.inputFormats = ['haml', 'hamlc', 'haml-coffee'];
exports.outputFormat = 'html';

exports.compile = hamlc.compile;
<|endoftext|>


<commit_before>const Node = require('./Node');

class LinkedList {
  constructor() {
    this._head = null;
    this._length = 0;
  }

  get length() {
    return this._length;
  }

  isEmpty() {
    return this._length === 0;
  }

  push(data) {
    const newNode = new Node(data);

    if (this._head === null) {
      this._head = newNode;
    } else {
      newNode.next = this._head;
      this._head = newNode;
    }

    this._length += 1;
    return this;
  }

  forEach(func) {
    let reference = this._head;

    while (reference !== null) {
      reference.value = func(reference.value);
      reference = reference.next;
    }
  }

  pop() {
    if (this._head === null) {
      throw new Error('There are no nodes to pop from the list');
    }

    this._head = this._head.next;
    this._length -= 1;
  }

  toString() {
    let reference = this._head;
    let str = '';

    while (reference !== null) {
      str += `${reference.value} -> `;
      reference = reference.next;
    }

    str += 'null';

    return str;
  }
}

module.exports = LinkedList;
<commit_msg>Add: getNodeByIndex method to linked list<commit_after>const Node = require('./Node');

class LinkedList {
  constructor() {
    this._head = null;
    this._length = 0;
  }

  get length() {
    return this._length;
  }

  isEmpty() {
    return this._length === 0;
  }

  push(data) {
    const newNode = new Node(data);

    if (this._head === null) {
      this._head = newNode;
    } else {
      newNode.next = this._head;
      this._head = newNode;
    }

    this._length += 1;
    return this;
  }

  pop() {
    if (this._head === null) {
      throw new Error('There are no nodes to pop from the list');
    }

    this._head = this._head.next;
    this._length -= 1;
  }

  getNodeByIndex(index) {
    if (index < 0 || index >= this._length) {
      throw new RangeError('Index out of range');
    }

    let reference = this._head;

    for (let i = 1; i <= index; i += 1) {
      reference = reference.next;
    }

    return reference;
  }

  forEach(func) {
    let reference = this._head;

    while (reference !== null) {
      reference.value = func(reference.value);
      reference = reference.next;
    }
  }

  toString() {
    let reference = this._head;
    let str = '';

    while (reference !== null) {
      str += `${reference.value} -> `;
      reference = reference.next;
    }

    str += 'null';

    return str;
  }
}

module.exports = LinkedList;
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-full-screen'
};
<commit_msg>Correcting name of app.<commit_after>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-cli-full-screen'
};
<|endoftext|>


<commit_before>module.exports = {
    number: require('./number')
};<commit_msg>[eslint] clean definition/entity/formatter/index<commit_after>module.exports = {
    number: require('./number')
};
<|endoftext|>


<commit_before>var expect = require("expect.js");

let describe = macro {
    case {_ $description:lit { $body ... } } => {
        return syntax {
            describe($description, function() {
                $body ...
            });
        }
    }
}

let it = macro {
    case {_ $description:lit { $body ... }} => {
        return syntax {
            it($description, function() {
                $body ...
            });
        }
    }
}

describe "procedural (syntax-case) macros" {
    it "should make a literal syntax object" {
        macro m {
            case { _ () } => {
                return [makeValue (42, #{here})];
            }
        }
        expect(m()).to.be(42);
    }

    it "should work with syntax" {
        macro m {
            case { _ () } => {
                return syntax { 42 }
            }
        }
        expect(m()).to.be(42);
    }

    it "should work with #" {
        macro m {
            case { _ () } => {
                return #{ 42 }
            }
        }
        expect(m()).to.be(42);
    }

    it "should work with both rule and case definitions" {
        macro m {
            rule { $x } => { $x + 5 }
            case { _ } => { return #{ 10 } }
        }
        expect(m 10).to.be(15);
        expect(m).to.be(10);
    }

    it "should work with both rule and case definitions in a let macro" {
        let m = macro {
            rule { $x } => { $x + 5 }
            case { _ } => { return #{ 10 } }
        }
        expect(m 10).to.be(15);
        expect(m).to.be(10);
    }

    it "should handle returning a single pattern variable" {
        macro m {
            case { _ ($x:expr) } => {
                return #{ $x }
            }
        }
        expect(m(42)).to.be(42);
        expect(m(42 + 24)).to.be(42 + 24);
    }

    it "should handle a repeated pattern in the template" {
        macro m {
            case { _ ($x ...) } => {
                return #{ [$x (,) ...] }
            }
        }
        expect(m(1 2 3)).to.eql([1,2,3]);
    }

    it "should support withSyntax" {
        macro m {
            case {_ $x } => {
                return withSyntax($y = [makeValue(42, #{here})]) {
                    return #{
                        $x + $y
                    }
                }
            }
        }
        expect(m 100).to.be(142);
    }

    it "withSyntax should only modify its own scope" {
        macro test {
            case { _ $x } => {
                function foo() {
                    return #{ $x };
                }
                var x = #{ 12 };
                return withSyntax($x = x) {
                    return foo();
                }
            }
        }
        expect(test 42).to.be(42)
    }

    it "should support withSyntax with multiple patterns" {
        macro m {
            case {_ $x } => {
                return withSyntax($y = [makeValue(10, #{here})],
                                  $z = [makeValue(20, #{here})]) {
                    return #{$x + $y + $z}
                }
            }
        }
        expect(m 5).to.be(35);
    }

    it "should support withSyntax with repeaters" {
        macro m {
            case {_ $x } => {
                return withSyntax($y ... = [makeValue(10, #{here}),
                                            makePunc('+', #{here}),
                                            makeValue(20, #{here})],
                                  $z = [makeValue(30, #{here})]) {
                    return #{$x + $y ... + $z}
                }
            }
        }
        expect(m 5).to.be(65);
    }

    it "should support shorthand withSyntax form" {
        macro m {
            case {_ $x } => {
                return withSyntax($y = [makeValue(42, #{here})]) #{
                    $x + $y
                }
            }
        }
        expect(m 100).to.be(142);
    }

    it "should support let bound macros" {
        let m = macro {
            case {_ $x} => {
                return #{$x}
            }
        }

        expect(m 42).to.be(42);
    }

    it "should support let bound macros" {
        let function = macro {
            case {_ $x} => {
                return #{function foo() { return $x; } }
            }
        }

        expect((function 42)()).to.be(42);
    }

    it "should unwrap the context syntax array for makeDelim" {
        macro $delim {
            case { $$mac $val } => {
                var d = makeDelim('[]', #{$val}, #{$$mac});
                return [d];
            }
        }

        expect($delim 42).to.eql([42]);
    }

    it "should unwrap single element arrays in unwrapSyntax" {
        macro m {
            case {_ () } => {
                var num = unwrapSyntax(#{42})
                return [makeValue(num, #{here})];
            }
        }
        expect(m()).to.be(42);
    }

    it "should handle negative numbers in makeValue" {
        macro m {
            case {_ () } => {
                return [makeValue(-42, #{here})];
            }
        }
        expect(m()).to.be(-42);
    }

    it "should handle NaN in makeValue" {
        macro m {
            case {_ () } => {
                return [makeValue(0/0, #{here})];
            }
        }
        var n = m();
        expect(n).to.be.a('number');
        expect(n).not.to.equal(n);
    }

    it "should handle letstx" {
        let l = macro {
            case {_ $x } => {
                letstx $y = [makeValue(42, #{here})];
                return #{ $x + $y }
            }
        }
        expect(l 100).to.be(142);
    }

    it "should handle letstx with multiple patterns" {
        let l = macro {
            case {_ $x } => {
                letstx $y = [makeValue(42, #{here})], $z = [makeValue(100, #{here})];
                return #{ $x + $y + $z}
            }
        }
        expect(l 100).to.be(242);
    }

    it "should handle letstx with repeaters" {
        let l = macro {
            case {_ $x } => {
                letstx $y ... = [makeValue(10, #{here}),
                                            makePunc('+', #{here}),
                                            makeValue(20, #{here})],
                       $z = [makeValue(30, #{here})];
                return #{$x + $y ... + $z}
            }
        }
        expect(l 5).to.be(65);
    }

    it "should handle syntax quotes on the rhs of letstx" {
        let l = macro {
            case {_ $x } => {
                letstx $y = #{ $x + 1 };
                return #{ $y };
            }
        }
        expect(l 1).to.be(2);
    }

    it "should handle getExpr" {
        let m = macro {
            case {_ ($e ...) } => {
                var e = getExpr(#{$e ...});
                if (e.success && unwrapSyntax(e.result[0]) === 2) {
                    return #{true}
                }
                return #{false}
            }
        }
        expect(m (2 + 2)).to.be(true);
        expect(m (5 + 2)).to.be(false);
        expect(m ()).to.be(false);
        expect(m (function ())).to.be(false);

        (function() {
            // make sure the locally scoped macro `id` expands in the getExpr
            let id = macro { rule { $x } => { $x } }
            expect(m (id 2 + 2)).to.be(true);
        })();
    }

    it "should handle getId/getLit" {
        let m = macro {
            case {_ ($id ...) ($lit ...) } => {
                var i = getIdent(#{$id ...});
                var l = getLit(#{$lit ...});
                if (i.success && l.success) {
                    return #{"idlit"}
                } else if (i.success && !l.success) {
                    return #{"id"}
                } else if (l.success) {
                    return #{"lit"}
                } else {
                    return #{"other"}
                }
            }
        }
        expect (m (id foo) (100 200)).to.be("idlit")
        expect (m (id foo) (id 200)).to.be("id")
        expect (m (100 foo) (100 200)).to.be("lit")
        expect (m (100 foo) (id 200)).to.be("other")
    }

    it "should handle taking the lexical context from a delimiter" {
        let m = macro {
            case {_ $tok } => {
                letstx $foo = [makeIdent("foo", #{$tok})];
                return #{$foo}
            }
        }

        var foo = 100;
        expect(m ()).to.be(100);
    }

    it "should handle localExpand" {
        let m = macro {
            case {_ ($e ...) } => {
                var e = localExpand(#{$e ...});
                if (unwrapSyntax(e[0]) === 42) {
                    return #{true}
                }
                return #{false}
            }
        }
        let id = macro { rule { $x } => { $x } }
        expect(m (id 42)).to.be(true);
    }

}
<commit_msg>adding test for localExpand and local macros #310<commit_after>var expect = require("expect.js");

let describe = macro {
    case {_ $description:lit { $body ... } } => {
        return syntax {
            describe($description, function() {
                $body ...
            });
        }
    }
}

let it = macro {
    case {_ $description:lit { $body ... }} => {
        return syntax {
            it($description, function() {
                $body ...
            });
        }
    }
}

describe "procedural (syntax-case) macros" {
    it "should make a literal syntax object" {
        macro m {
            case { _ () } => {
                return [makeValue (42, #{here})];
            }
        }
        expect(m()).to.be(42);
    }

    it "should work with syntax" {
        macro m {
            case { _ () } => {
                return syntax { 42 }
            }
        }
        expect(m()).to.be(42);
    }

    it "should work with #" {
        macro m {
            case { _ () } => {
                return #{ 42 }
            }
        }
        expect(m()).to.be(42);
    }

    it "should work with both rule and case definitions" {
        macro m {
            rule { $x } => { $x + 5 }
            case { _ } => { return #{ 10 } }
        }
        expect(m 10).to.be(15);
        expect(m).to.be(10);
    }

    it "should work with both rule and case definitions in a let macro" {
        let m = macro {
            rule { $x } => { $x + 5 }
            case { _ } => { return #{ 10 } }
        }
        expect(m 10).to.be(15);
        expect(m).to.be(10);
    }

    it "should handle returning a single pattern variable" {
        macro m {
            case { _ ($x:expr) } => {
                return #{ $x }
            }
        }
        expect(m(42)).to.be(42);
        expect(m(42 + 24)).to.be(42 + 24);
    }

    it "should handle a repeated pattern in the template" {
        macro m {
            case { _ ($x ...) } => {
                return #{ [$x (,) ...] }
            }
        }
        expect(m(1 2 3)).to.eql([1,2,3]);
    }

    it "should support withSyntax" {
        macro m {
            case {_ $x } => {
                return withSyntax($y = [makeValue(42, #{here})]) {
                    return #{
                        $x + $y
                    }
                }
            }
        }
        expect(m 100).to.be(142);
    }

    it "withSyntax should only modify its own scope" {
        macro test {
            case { _ $x } => {
                function foo() {
                    return #{ $x };
                }
                var x = #{ 12 };
                return withSyntax($x = x) {
                    return foo();
                }
            }
        }
        expect(test 42).to.be(42)
    }

    it "should support withSyntax with multiple patterns" {
        macro m {
            case {_ $x } => {
                return withSyntax($y = [makeValue(10, #{here})],
                                  $z = [makeValue(20, #{here})]) {
                    return #{$x + $y + $z}
                }
            }
        }
        expect(m 5).to.be(35);
    }

    it "should support withSyntax with repeaters" {
        macro m {
            case {_ $x } => {
                return withSyntax($y ... = [makeValue(10, #{here}),
                                            makePunc('+', #{here}),
                                            makeValue(20, #{here})],
                                  $z = [makeValue(30, #{here})]) {
                    return #{$x + $y ... + $z}
                }
            }
        }
        expect(m 5).to.be(65);
    }

    it "should support shorthand withSyntax form" {
        macro m {
            case {_ $x } => {
                return withSyntax($y = [makeValue(42, #{here})]) #{
                    $x + $y
                }
            }
        }
        expect(m 100).to.be(142);
    }

    it "should support let bound macros" {
        let m = macro {
            case {_ $x} => {
                return #{$x}
            }
        }

        expect(m 42).to.be(42);
    }

    it "should support let bound macros" {
        let function = macro {
            case {_ $x} => {
                return #{function foo() { return $x; } }
            }
        }

        expect((function 42)()).to.be(42);
    }

    it "should unwrap the context syntax array for makeDelim" {
        macro $delim {
            case { $$mac $val } => {
                var d = makeDelim('[]', #{$val}, #{$$mac});
                return [d];
            }
        }

        expect($delim 42).to.eql([42]);
    }

    it "should unwrap single element arrays in unwrapSyntax" {
        macro m {
            case {_ () } => {
                var num = unwrapSyntax(#{42})
                return [makeValue(num, #{here})];
            }
        }
        expect(m()).to.be(42);
    }

    it "should handle negative numbers in makeValue" {
        macro m {
            case {_ () } => {
                return [makeValue(-42, #{here})];
            }
        }
        expect(m()).to.be(-42);
    }

    it "should handle NaN in makeValue" {
        macro m {
            case {_ () } => {
                return [makeValue(0/0, #{here})];
            }
        }
        var n = m();
        expect(n).to.be.a('number');
        expect(n).not.to.equal(n);
    }

    it "should handle letstx" {
        let l = macro {
            case {_ $x } => {
                letstx $y = [makeValue(42, #{here})];
                return #{ $x + $y }
            }
        }
        expect(l 100).to.be(142);
    }

    it "should handle letstx with multiple patterns" {
        let l = macro {
            case {_ $x } => {
                letstx $y = [makeValue(42, #{here})], $z = [makeValue(100, #{here})];
                return #{ $x + $y + $z}
            }
        }
        expect(l 100).to.be(242);
    }

    it "should handle letstx with repeaters" {
        let l = macro {
            case {_ $x } => {
                letstx $y ... = [makeValue(10, #{here}),
                                            makePunc('+', #{here}),
                                            makeValue(20, #{here})],
                       $z = [makeValue(30, #{here})];
                return #{$x + $y ... + $z}
            }
        }
        expect(l 5).to.be(65);
    }

    it "should handle syntax quotes on the rhs of letstx" {
        let l = macro {
            case {_ $x } => {
                letstx $y = #{ $x + 1 };
                return #{ $y };
            }
        }
        expect(l 1).to.be(2);
    }

    it "should handle getExpr" {
        let m = macro {
            case {_ ($e ...) } => {
                var e = getExpr(#{$e ...});
                if (e.success && unwrapSyntax(e.result[0]) === 2) {
                    return #{true}
                }
                return #{false}
            }
        }
        expect(m (2 + 2)).to.be(true);
        expect(m (5 + 2)).to.be(false);
        expect(m ()).to.be(false);
        expect(m (function ())).to.be(false);

        (function() {
            // make sure the locally scoped macro `id` expands in the getExpr
            let id = macro { rule { $x } => { $x } }
            expect(m (id 2 + 2)).to.be(true);
        })();
    }

    it "should handle getId/getLit" {
        let m = macro {
            case {_ ($id ...) ($lit ...) } => {
                var i = getIdent(#{$id ...});
                var l = getLit(#{$lit ...});
                if (i.success && l.success) {
                    return #{"idlit"}
                } else if (i.success && !l.success) {
                    return #{"id"}
                } else if (l.success) {
                    return #{"lit"}
                } else {
                    return #{"other"}
                }
            }
        }
        expect (m (id foo) (100 200)).to.be("idlit")
        expect (m (id foo) (id 200)).to.be("id")
        expect (m (100 foo) (100 200)).to.be("lit")
        expect (m (100 foo) (id 200)).to.be("other")
    }

    it "should handle taking the lexical context from a delimiter" {
        let m = macro {
            case {_ $tok } => {
                letstx $foo = [makeIdent("foo", #{$tok})];
                return #{$foo}
            }
        }

        var foo = 100;
        expect(m ()).to.be(100);
    }

    it "should handle localExpand" {
        let m = macro {
            case {_ ($e ...) } => {
                var e = localExpand(#{$e ...});
                if (unwrapSyntax(e[0]) === 42) {
                    return #{true}
                }
                return #{false}
            }
        }
        let id = macro { rule { $x } => { $x } }
        expect(m (id 42)).to.be(true);
    }

    it "should handle localExpand with macros inside functions" {
        macro ex {
            case {_ { $body ... } } => {
                return localExpand(#{$body ...});
            }
        }

        var f = ex {
            function foo(x) {
                macro arg {
                    rule {} => { x }
                }
                return {
                    normal_x: x,
                    macro_x: arg
                };
            }
        }
        expect(f(42).normal_x).to.be(42);
        expect(f(42).macro_x).to.be(42);
    }

}
<|endoftext|>


<commit_before>module.exports = new (function (proc, psFind) {
    var self = this,
        _cm = null,
        _cmExecutable = "_cm.exe",
        env_vars_set = false,
        _onRead = null,
        _onError = null,
        _onExit = null,
        _debug = false,
        _options = null;

    this.setup = function (onRead, onError, onExit, options, debug) {
        _onRead = onRead;
        _onError = onError;
        _onExit = onExit;
        _options = options;

        if(debug != undefined && debug != null) {
            _debug = debug;
        }
    };

    this.start = function (options) {
        return new Promise(function (resolve, reject) {
            if (options && options.cmPath) {
                _cmExecutable = options.cmPath;
            }

            self.setEnvironmentVariables();
            self.kill();

            _cm = proc.spawn(_cmExecutable, ["/develop", "/nocoloring"]);

            _cm.stdout.on("data", function (data) {
                data = data.toString();

                if (_onRead)
                    _onRead(data);

                if (_isCompilerReady(data)) {
                    resolve(true);
                }
            });

            _cm.stderr.on("data", function (data) {
                data = data.toString();

                if (_onError)
                    _onError(data);
                else
                    throw new Error(data);
            });

            _cm.on("exit", function (code) {
                if (_onExit)
                    _onExit(code);
            });
        });
    };

    this.write = function (data) {
        var cmd = _makeCommand(data);

        if(_debug)
            console.log(data);

        _cm.stdin.write(cmd);
    };

    this.runFile = function (file) {
        file = file.replace(/\\/g, "");
        var cmd = "run(\"" + file + "\")";
        self.write(cmd);
    };

    this.compileFile = function (file) {
        file = file.replace(/\\/g, "");
        var cmd = "load(\"" + file + "\")";
        self.write(cmd);
    };

    this.kill = function () {
        self.setEnvironmentVariables();

        console.log("Killing pending processes");
        var code = proc.execSync("cm_pskill /name \"_cm.exe\" /beginsWith \"msdev\" /beginsWith \"link\" /titleBeginsWith \"Microsoft Visual\"");
        console.log("All processes killed");
        return code;
    };

    this.setEnvironmentVariables = function () {
        if (env_vars_set) {
            return;
        } else {
            env_vars_set = true;
        }

        var CM_ROOT = _options && _options.cmRoot || "C:\\CetDev\\version6.5",
            CM_HOME = CM_ROOT + "\\home",
            CM_WRITE = CM_ROOT + "\\write";

        process.env["CM_ARCH"] = "win64";
        process.env["CM_ENVFILE_EMACS"] = CM_WRITE + "\\_emacs.cmenv";
        process.env["CM_ENVFILE_OPERATOR"] = CM_WRITE + "\\_operator.cmenv";
        process.env["CM_HOME"] = CM_HOME;
        process.env["CM_LIBS"] = CM_WRITE + "\\data\\cm-libs\\win64";
        process.env["CM_ROOT"] = CM_ROOT;
        process.env["CM_UNIX_HOME"] = CM_HOME;
        process.env["CM_UNIX_WRITE"] = CM_WRITE;
        process.env["CM_VCVERSION"] = "10";
        process.env["CM_WRITE"] = CM_WRITE;
        process.env["PATH"] = process.env["PATH"] + ";" + CM_HOME + "\\bin\\;" + CM_HOME + "\\bin\\win64;";
    }

    function _makeCommand(data) {
        return data + "\x01";
    }

    function _isCompilerReady(data) {
        return data.match(/cm>$/g);
    }
})(require("child_process"), require("ps-node"));<commit_msg>Adding semi colon<commit_after>module.exports = new (function (proc, psFind) {
    var self = this,
        _cm = null,
        _cmExecutable = "_cm.exe",
        env_vars_set = false,
        _onRead = null,
        _onError = null,
        _onExit = null,
        _options = null;

    this.setup = function (onRead, onError, onExit, options) {
        _onRead = onRead;
        _onError = onError;
        _onExit = onExit;
        _options = options;
    };

    this.start = function (options) {
        return new Promise(function (resolve, reject) {
            if (options && options.cmPath) {
                _cmExecutable = options.cmPath;
            }

            self.setEnvironmentVariables();
            self.kill();

            _cm = proc.spawn(_cmExecutable, ["/develop", "/nocoloring"]);

            _cm.stdout.on("data", function (data) {
                data = data.toString();

                if (_onRead)
                    _onRead(data);

                if (_isCompilerReady(data)) {
                    resolve(true);
                }
            });

            _cm.stderr.on("data", function (data) {
                data = data.toString();

                if (_onError)
                    _onError(data);
                else
                    throw new Error(data);
            });

            _cm.on("exit", function (code) {
                if (_onExit)
                    _onExit(code);
            });
        });
    };

    this.write = function (data) {
        var cmd = _makeCommand(data);

        if(_options && _options.debug)
            console.log(data);

        _cm.stdin.write(cmd);
    };

    this.runFile = function (file) {
        file = file.replace(/\\/g, "");
        var cmd = "run(\"" + file + "\");";
        self.write(cmd);
    };

    this.compileFile = function (file) {
        file = file.replace(/\\/g, "");
        var cmd = "load(\"" + file + "\");";
        self.write(cmd);
    };

    this.kill = function () {
        self.setEnvironmentVariables();

        console.log("Killing pending processes");
        var code = proc.execSync("cm_pskill /name \"_cm.exe\" /beginsWith \"msdev\" /beginsWith \"link\" /titleBeginsWith \"Microsoft Visual\"");
        console.log("All processes killed");
        return code;
    };

    this.setEnvironmentVariables = function () {
        if (env_vars_set) {
            return;
        } else {
            env_vars_set = true;
        }

        var CM_ROOT = _options && _options.cmRoot || "C:\\CetDev\\version6.5",
            CM_HOME = CM_ROOT + "\\home",
            CM_WRITE = CM_ROOT + "\\write";

        process.env["CM_ARCH"] = "win64";
        process.env["CM_ENVFILE_EMACS"] = CM_WRITE + "\\_emacs.cmenv";
        process.env["CM_ENVFILE_OPERATOR"] = CM_WRITE + "\\_operator.cmenv";
        process.env["CM_HOME"] = CM_HOME;
        process.env["CM_LIBS"] = CM_WRITE + "\\data\\cm-libs\\win64";
        process.env["CM_ROOT"] = CM_ROOT;
        process.env["CM_UNIX_HOME"] = CM_HOME;
        process.env["CM_UNIX_WRITE"] = CM_WRITE;
        process.env["CM_VCVERSION"] = "10";
        process.env["CM_WRITE"] = CM_WRITE;
        process.env["PATH"] = process.env["PATH"] + ";" + CM_HOME + "\\bin\\;" + CM_HOME + "\\bin\\win64;";
    }

    function _makeCommand(data) {
        return data + "\x01";
    }

    function _isCompilerReady(data) {
        return data.match(/cm>$/g);
    }
})(require("child_process"), require("ps-node"));<|endoftext|>


<commit_before>var _ = require('lodash');
var async = require('async-chainable');
var traverse = require('traverse');

// Constants {{{
var FK_OBJECTID = 1; // 1:1 objectID mapping
var FK_OBJECTID_ARRAY = 2; // Array of objectIDs
var FK_SUBDOC = 3; // Sub-document embed
// }}}

var settings = {
	reset: true, // Reset all known refs on each call - if this is false the previously created refs will be remembered and can be used again
	connection: null,
	nuke: [], // Either a list of collections to nuke or 'true' to use the incomming scenario to calculate the collections

	called: 0, // How many times scenario has been called (if zero `nuke` gets fired)

	progress: { // Output data array (passed to callback on finish)
		created: {}, // Number of records created for each collection
		nuked: [], // Tables nuked during call
	},

	refs: {}, // Lookup list of known references

	knownFK: {}, // Cache of known foreign keys for a collection

	idVal: 0, // Incrementing ID value for fields that do not have a '_ref' (or whatever keys.ref is)
	exitTaskId: 0,

	// Define the keys mongoose-scenario uses to look up meta-data
	// NOTE: Changing these will not also alter omitFields - which will need to be updated seperately if you wish to override these keys
	keys: {
		ref: '_ref', // What key to use when looking up the reference
		after: '_after', // Define dependents
	},
	// Check whether all dependencies are met
	checkDependencies : true,

	omitFields: ['_ref', '_after'] // Fields to omit from creation process
};

/**
* Import a scenario file into a Mongo database
* A scenario must be complete - i.e. have no dangling references for it to suceed
* @param object model The scenario to create - expected format is a hash of collection names each containing a collection of records (e.g. `{users: [{name: 'user1'}, {name: 'user2'}] }`)
* @param object settings Optional Settings array to import
* @param finish function(err, data) Optional callback fired when scenario finishes creating records
*/
var scenarioImport = function(model, options, finish) {
	var asyncCreator = async(); // Task runner that actually creates all the Mongo records

	async()
		.then(function(next) { // Coherce args into scenario(<model>, [options], [callback]) {{{
			if (!model) throw new Error('No arguments passed to scenario()');
			if (_.isFunction(options)) { // Form: (model, callback)
				finish = options;
			} else if (options) { // Form: model(model, options)
				_.merge(settings, options);
			}
			if (!finish) finish = function() {};
			next();
		}) // }}}
		.then(function(next) { // Sanity checks {{{
			if (!settings.connection) throw new Error('Invalid connection to Mongoose');
			if (!_.isObject(model)) throw new Error('Invalid scenario invoke style - scenario(' + typeof model + ')');
			next();
		}) // }}}
		.then(function(next) { // Reset all state variables {{{
			settings.progress.created = {};
			if (settings.reset) settings.refs = {};
			next();
		}) /// }}}
		.then(function(next) { // Optionally Nuke existing models {{{
			if (!settings.nuke) return next();
			async()
				.set('models', _.isArray(settings.nuke) ? settings.nuke : _.keys(settings.connection.base.models))
				.forEach('models', function(next, model) {
					if (!settings.connection.base.models[model])
						return next('Model "' + model + '" is present in the Scenario schema but no model can be found matching that name, did you forget to load it?');
					settings.connection.base.models[model].find({}).remove(function(err) {
						if (err) next(err);
						settings.progress.nuked.push(model);
						next();
					});
				})
				.end(next);
		}) // }}}
		.forEach(model, function(next, rows, collection) { // Compute FKs for each model {{{
			if (settings.knownFK[collection]) return next(); // Already computed the FKs for this collection

			settings.knownFK[collection] = {};

			if (!settings.connection.base.models[collection]) throw new Error('Collection "' + collection + '" not found in Mongoose schema. Did you forget to load its model?');

			// Merge extracted keys into knownFKs storage
			settings.knownFK[collection] = extractFKs(settings.connection.base.models[collection].schema);

			next();
		}) // }}}
		.forEach(model, function(next, rows, collection) { // Process the Scenario profile {{{
			async()
				.forEach(rows, function(next, row) { // Split all incomming items into defered tasks {{{
					var rowFlattened = flatten(row);
					var id = row[settings.keys.ref] ? row[settings.keys.ref] : 'anon-' + settings.idVal++;
					var dependents = determineFKs(rowFlattened, settings.knownFK[collection]);

					asyncCreator.defer(dependents, id, function(next) {
						createRow(collection, id, rowFlattened, next);
					});

					next();
				}) // }}}
				.end(next);
		}) // }}}
		.then(function(next) { // Run all tasks {{{
			asyncCreator
				.await()
				.end(next);
		}) // }}}
		.end(function(err) {
			if (err) return finish(err);
			finish(null, settings.progress);
		});

	return scenarioImport;
};

/**
* Extract the FK relationship from a Mongo document
* @param object schema The schema object to examine (usually connection.base.models[model].schema
* @return object A dictionary of foreign keys for the schema
*/
function extractFKs(schema) {
	var FKs = {};

	_.forEach(schema.paths, function(path, id) {
		if (id == 'id' || id == '_id') {
			// Pass
		} else if (path.instance && path.instance == 'ObjectID') {
			FKs[id] = {type: FK_OBJECTID};
		} else if (path.caster && path.caster.instance == 'ObjectID') { // Array of ObjectIDs
			FKs[id] = {type: FK_OBJECTID_ARRAY};
		} else if (path.schema) {
			FKs[id] = {
				type: FK_SUBDOC,
				fks: extractFKs(path.schema),
			};
		}
	});

	return FKs;
}

/**
* Inject foreign keys into a row before it gets passed to Mongo for insert
* @param object row The row that will be inserted - values will be replaced inline
* @param object fks The foreign keys for the given row (extacted via extractFKs)
* @see extractFKs()
*/
function injectFKs(row, fks) {
	_.forEach(fks, function(fk, id) {
		if (row[id] === undefined) return; // Skip omitted FK refs

		switch (fk.type) {
			case FK_OBJECTID: // 1:1 relationship
				if (!settings.refs[row[id]])
					throw new Error('Attempting to use reference "' + row[id] + '" in field ' + id + ' before its been created!');
				row[id] = settings.refs[row[id]];
				break;
			case FK_OBJECTID_ARRAY: // 1:M array based relationship
				row[id] = _.map(row[id], function(fieldValueArr) { // Resolve each item in the array
					if (!settings.refs[fieldValueArr])
						throw new Error('Attempting to use reference "' + fieldValueArr + '" in 1:M field ' + id + ' before its been created!');
					return settings.refs[fieldValueArr];
				});
				break;
			case FK_SUBDOC: // Mongo subdocument
				_.forEach(row[id], function(subdocItem, subdocIndex) {
					row[id][subdocItem]
					injectFKs(subdocItem, fks[id].fks);
				});
				break;
		}
	});
}

/**
* Get an array of required foreign keys values so we can calculate the dependency tree
* @param object row The row that will be inserted
* @param object fks The foreign keys for the given row (extacted via extractFKs)
* @see extractFKs()
* @return array An array of required references
*/
function determineFKs(row, fks) {
	var refs = [];

	_.forEach(fks, function(fk, id) {
		if (row[id] === undefined) return; // Skip omitted FK refs

		switch (fk.type) {
			case FK_OBJECTID: // 1:1 relationship
				refs.push(row[id]);
				break;
			case FK_OBJECTID_ARRAY: // 1:M array based relationship
				_.forEach(row[id], function(v) {
					refs.push(v);
				});
				break;
			case FK_SUBDOC: // Mongo subdocument
				_.forEach(row[id], function(v) {
					determineFKs(v, fks[id].fks).forEach(function(dep) {
						refs.push(dep);
					});
				});
				break;
		}
	});

	return refs;
}

/**
* Take a nested object and return a flattened hash in Mongoose path notation
* e.g. {foo: {bar: 'baz'}} // Becomes {foo.bar: 'baz'}
* @param object obj The object to flatten
* @return object A flattened version of the object given
*/
function flatten(obj) {
	var flattenWorker = function(row, namespace, result) {
		return _.reduce(row, function(result, value, key) {
			var newKey;
			newKey = "" + namespace + (namespace ? '.' : '') + key;
			if (_.isPlainObject(value)) {
				if (_.size(value)) {
					flattenWorker(value, newKey, result);
				}
			} else {
				result[newKey] = value;
			}
			return result;
		}, result);
	};
	return flattenWorker(obj, '', {});
};

/**
* Create a single row in a collection
* @param string collection The collection where to create the row
* @param string id The ID of the row (if any)
* @param object row The (flattened) row contents to create
* @param function callback(err) Callback to chainable async function
*/
function createRow(collection, id, row, callback) {
	injectFKs(row, settings.knownFK[collection]);

  // build up list of all sub-document _ref's that we need to find in the newly saved document
  // this is to ensure we capture _id from inside nested array documents that do not exist at root level
	var refsMeta = [];
	traverse(row).forEach(function (value) {
		var path;
		if ('_ref' === this.key) {
			path = this.path.concat();
			path[path.length - 1] = '_id';
			refsMeta.push({
				ref: value,
				path: path
			});
		}
	});

	row = _.omit(row, settings.omitFields);

  // NOTE: MJM asks what does this do? looks like some project specific thing
	if (row['speakerQueues.motion']) {
		row['speakerQueues'] = {
			motion: row['speakerQueues.motion'],
		};
		delete row['speakerQueues.motion'];
		delete row['speakerQueues.general'];
	}
	settings.connection.base.models[collection].create(row, function(err, newItem) {
		if (err) return callback(err);

    // NOTE: MJM deleted if (collection == 'committees') block (left in by accident?)

		var newItemAsObject = newItem.toObject();
		for(var i = 0; i < refsMeta.length; i++) {
			if (traverse(newItemAsObject).has(refsMeta[i].path)) {
				settings.refs[refsMeta[i].ref] = traverse(newItemAsObject).get(refsMeta[i].path).toString();
			}
		}

		if (id) { // This unit has its own reference - add it to the stack
			settings.refs[id] = newItem._id.toString();
		}

		if (!settings.progress.created[collection])
			settings.progress.created[collection] = 0;
		settings.progress.created[collection]++;
		callback(null, newItem._id);
	});
};

function checkMerge(original, built) {
	var amended = false;

	_.forEach(original, function(v, k) {
		var pointer = built;
		k.split('.').forEach(function(pathBit, pathBitIndex) {
			if (!pointer[pathBit]) { // Mongo has dropped the field entirely
				console.log('PATH MISSING', pathBit, k.split('.').slice(0, pathBitIndex + 1).join('!'));
				if (_.isObject(v)) {
					pointer[pathBit] = v;
					console.log('CREATE', pathBit, v);
					if (pathBit == 'speakerQueues') {
						console.log('INJECT INTO SQ');
						pointer[pathBit] = {motion: [ {'title': 'POINTER TEST' } ] };
						console.log(pointer);
					}
				} else if (_.isArray(v)) {
					pointer[pathBit] = [];
					v.forEach(function(item) { pointer[pathBit].push(item) });
				} else {
					pointer[pathBit] = v;
				}
				amended = true;
			} else if (_.isArray(v) && pointer[pathBit].length != v.length) { // Its an array and Mongo has truncated it
				console.log('ARRAY LEN MISMATCH', k);
				pointer[pathBit] = v;
			} else { // Field is ok
				pointer = pointer[pathBit];
			}
		});
	});

	return amended;
};

var scenarioExport = function(options, finish) {
	var output = {};

	async()
		.then(function(next) { // Coherce args into scenario([options], [callback]) {{{
			if (!options) throw new Error('No arguments passed to scenario()');
			if (_.isFunction(options)) { // Form: (callback)
				finish = options;
			} else if (options) { // Form: model(model, options)
				_.merge(settings, options);
			}
			if (!finish) finish = function() {};
			next();
		}) // }}}
		.then(function(next) { // Sanity checks {{{
			if (!settings.connection) throw new Error('Invalid connection to Mongoose');
			next();
		}) // }}}
		.then('models', function(next) {
			next(null, _.keys(settings.connection.base.models));
		})
		.forEach('models', function(nextModel, model) {
			output[model] = [];
			async()
				.then('contents', function(next) {
					settings.connection.base.models[model].find(next);
				})
				.forEach('contents', function(next, row) {
					var rowOutput = {_id: row._id};

					if (row.__v != 0) rowOutput.__v = row.__v; // Only bother to export __v if its not zero

					_.forEach(row.toObject(), function(val, key) {
						if (key == '_id' || key == '__v') return; // Skip meta fields
						rowOutput[key] = row[key];
					});

					output[model].push(rowOutput);
					next();
				})
				.end(nextModel);
		})
		.end(function(err) {
			if (err) return finish(err);
			finish(null, output);
		});

	return scenarioExport;
};

var scenarioSet = function(options) {
	_.merge(settings, options);
};

module.exports = {
	import: scenarioImport,
	export: scenarioExport,
	set: scenarioSet,
};
<commit_msg>BUGFIX: Removed a few debugging artefacts<commit_after>var _ = require('lodash');
var async = require('async-chainable');
var traverse = require('traverse');

// Constants {{{
var FK_OBJECTID = 1; // 1:1 objectID mapping
var FK_OBJECTID_ARRAY = 2; // Array of objectIDs
var FK_SUBDOC = 3; // Sub-document embed
// }}}

var settings = {
	reset: true, // Reset all known refs on each call - if this is false the previously created refs will be remembered and can be used again
	connection: null,
	nuke: [], // Either a list of collections to nuke or 'true' to use the incomming scenario to calculate the collections

	called: 0, // How many times scenario has been called (if zero `nuke` gets fired)

	progress: { // Output data array (passed to callback on finish)
		created: {}, // Number of records created for each collection
		nuked: [], // Tables nuked during call
	},

	refs: {}, // Lookup list of known references

	knownFK: {}, // Cache of known foreign keys for a collection

	idVal: 0, // Incrementing ID value for fields that do not have a '_ref' (or whatever keys.ref is)
	exitTaskId: 0,

	// Define the keys mongoose-scenario uses to look up meta-data
	// NOTE: Changing these will not also alter omitFields - which will need to be updated seperately if you wish to override these keys
	keys: {
		ref: '_ref', // What key to use when looking up the reference
		after: '_after', // Define dependents
	},
	// Check whether all dependencies are met
	checkDependencies : true,

	omitFields: ['_ref', '_after'] // Fields to omit from creation process
};

/**
* Import a scenario file into a Mongo database
* A scenario must be complete - i.e. have no dangling references for it to suceed
* @param object model The scenario to create - expected format is a hash of collection names each containing a collection of records (e.g. `{users: [{name: 'user1'}, {name: 'user2'}] }`)
* @param object settings Optional Settings array to import
* @param finish function(err, data) Optional callback fired when scenario finishes creating records
*/
var scenarioImport = function(model, options, finish) {
	var asyncCreator = async(); // Task runner that actually creates all the Mongo records

	async()
		.then(function(next) { // Coherce args into scenario(<model>, [options], [callback]) {{{
			if (!model) throw new Error('No arguments passed to scenario()');
			if (_.isFunction(options)) { // Form: (model, callback)
				finish = options;
			} else if (options) { // Form: model(model, options)
				_.merge(settings, options);
			}
			if (!finish) finish = function() {};

			next();
		}) // }}}
		.then(function(next) { // Sanity checks {{{
			if (!settings.connection) throw new Error('Invalid connection to Mongoose');
			if (!_.isObject(model)) throw new Error('Invalid scenario invoke style - scenario(' + typeof model + ')');
			next();
		}) // }}}
		.then(function(next) { // Reset all state variables {{{
			settings.progress.created = {};
			if (settings.reset) settings.refs = {};
			next();
		}) /// }}}
		.then(function(next) { // Optionally Nuke existing models {{{
			if (!settings.nuke) return next();
			async()
				.set('models', _.isArray(settings.nuke) ? settings.nuke : _.keys(settings.connection.base.models))
				.forEach('models', function(next, model) {
					if (!settings.connection.base.models[model])
						return next('Model "' + model + '" is present in the Scenario schema but no model can be found matching that name, did you forget to load it?');
					settings.connection.base.models[model].find({}).remove(function(err) {
						if (err) next(err);
						settings.progress.nuked.push(model);
						next();
					});
				})
				.end(next);
		}) // }}}
		.forEach(model, function(next, rows, collection) { // Compute FKs for each model {{{
			if (settings.knownFK[collection]) return next(); // Already computed the FKs for this collection

			settings.knownFK[collection] = {};

			if (!settings.connection.base.models[collection]) throw new Error('Collection "' + collection + '" not found in Mongoose schema. Did you forget to load its model?');

			// Merge extracted keys into knownFKs storage
			settings.knownFK[collection] = extractFKs(settings.connection.base.models[collection].schema);

			next();
		}) // }}}
		.forEach(model, function(next, rows, collection) { // Process the Scenario profile {{{
			async()
				.forEach(rows, function(next, row) { // Split all incomming items into defered tasks {{{
					var rowFlattened = flatten(row);
					var id = row[settings.keys.ref] ? row[settings.keys.ref] : 'anon-' + settings.idVal++;
					var dependents = determineFKs(rowFlattened, settings.knownFK[collection]);

					asyncCreator.defer(dependents, id, function(next) {
						createRow(collection, id, rowFlattened, next);
					});

					next();
				}) // }}}
				.end(next);
		}) // }}}
		.then(function(next) { // Run all tasks {{{
			asyncCreator
				.await()
				.end(next);
		}) // }}}
		.end(function(err) {
			if (err) return finish(err);
			finish(null, settings.progress);
		});

	return scenarioImport;
};

/**
* Extract the FK relationship from a Mongo document
* @param object schema The schema object to examine (usually connection.base.models[model].schema
* @return object A dictionary of foreign keys for the schema
*/
function extractFKs(schema) {
	var FKs = {};

	_.forEach(schema.paths, function(path, id) {
		if (id == 'id' || id == '_id') {
			// Pass
		} else if (path.instance && path.instance == 'ObjectID') {
			FKs[id] = {type: FK_OBJECTID};
		} else if (path.caster && path.caster.instance == 'ObjectID') { // Array of ObjectIDs
			FKs[id] = {type: FK_OBJECTID_ARRAY};
		} else if (path.schema) {
			FKs[id] = {
				type: FK_SUBDOC,
				fks: extractFKs(path.schema),
			};
		}
	});

	return FKs;
}

/**
* Inject foreign keys into a row before it gets passed to Mongo for insert
* @param object row The row that will be inserted - values will be replaced inline
* @param object fks The foreign keys for the given row (extacted via extractFKs)
* @see extractFKs()
*/
function injectFKs(row, fks) {
	_.forEach(fks, function(fk, id) {
		if (row[id] === undefined) return; // Skip omitted FK refs

		switch (fk.type) {
			case FK_OBJECTID: // 1:1 relationship
				if (!settings.refs[row[id]])
					throw new Error('Attempting to use reference "' + row[id] + '" in field ' + id + ' before its been created!');
				row[id] = settings.refs[row[id]];
				break;
			case FK_OBJECTID_ARRAY: // 1:M array based relationship
				row[id] = _.map(row[id], function(fieldValueArr) { // Resolve each item in the array
					if (!settings.refs[fieldValueArr])
						throw new Error('Attempting to use reference "' + fieldValueArr + '" in 1:M field ' + id + ' before its been created!');
					return settings.refs[fieldValueArr];
				});
				break;
			case FK_SUBDOC: // Mongo subdocument
				_.forEach(row[id], function(subdocItem, subdocIndex) {
					row[id][subdocItem]
					injectFKs(subdocItem, fks[id].fks);
				});
				break;
		}
	});
}

/**
* Get an array of required foreign keys values so we can calculate the dependency tree
* @param object row The row that will be inserted
* @param object fks The foreign keys for the given row (extacted via extractFKs)
* @see extractFKs()
* @return array An array of required references
*/
function determineFKs(row, fks) {
	var refs = [];

	_.forEach(fks, function(fk, id) {
		if (row[id] === undefined) return; // Skip omitted FK refs

		switch (fk.type) {
			case FK_OBJECTID: // 1:1 relationship
				refs.push(row[id]);
				break;
			case FK_OBJECTID_ARRAY: // 1:M array based relationship
				_.forEach(row[id], function(v) {
					refs.push(v);
				});
				break;
			case FK_SUBDOC: // Mongo subdocument
				_.forEach(row[id], function(v) {
					determineFKs(v, fks[id].fks).forEach(function(dep) {
						refs.push(dep);
					});
				});
				break;
		}
	});

	return refs;
}

/**
* Take a nested object and return a flattened hash in Mongoose path notation
* e.g. {foo: {bar: 'baz'}} // Becomes {foo.bar: 'baz'}
* @param object obj The object to flatten
* @return object A flattened version of the object given
*/
function flatten(obj) {
	var flattenWorker = function(row, namespace, result) {
		return _.reduce(row, function(result, value, key) {
			var newKey;
			newKey = "" + namespace + (namespace ? '.' : '') + key;
			if (_.isPlainObject(value)) {
				if (_.size(value)) {
					flattenWorker(value, newKey, result);
				}
			} else {
				result[newKey] = value;
			}
			return result;
		}, result);
	};
	return flattenWorker(obj, '', {});
};

/**
* Create a single row in a collection
* @param string collection The collection where to create the row
* @param string id The ID of the row (if any)
* @param object row The (flattened) row contents to create
* @param function callback(err) Callback to chainable async function
*/
function createRow(collection, id, row, callback) {
	injectFKs(row, settings.knownFK[collection]);

	// build up list of all sub-document _ref's that we need to find in the newly saved document
	// this is to ensure we capture _id from inside nested array documents that do not exist at root level
	var refsMeta = [];
	traverse(row).forEach(function (value) {
		var path;
		if ('_ref' === this.key) {
			path = this.path.concat();
			path[path.length - 1] = '_id';
			refsMeta.push({
				ref: value,
				path: path
			});
		}
	});

	row = _.omit(row, settings.omitFields);

	settings.connection.base.models[collection].create(row, function(err, newItem) {
		if (err) return callback(err);

		var newItemAsObject = newItem.toObject();
		for(var i = 0; i < refsMeta.length; i++) {
			if (traverse(newItemAsObject).has(refsMeta[i].path)) {
				settings.refs[refsMeta[i].ref] = traverse(newItemAsObject).get(refsMeta[i].path).toString();
			}
		}

		if (id) { // This unit has its own reference - add it to the stack
			settings.refs[id] = newItem._id.toString();
		}

		if (!settings.progress.created[collection])
			settings.progress.created[collection] = 0;
		settings.progress.created[collection]++;
		callback(null, newItem._id);
	});
};

function checkMerge(original, built) {
	var amended = false;

	_.forEach(original, function(v, k) {
		var pointer = built;
		k.split('.').forEach(function(pathBit, pathBitIndex) {
			if (!pointer[pathBit]) { // Mongo has dropped the field entirely
				console.log('PATH MISSING', pathBit, k.split('.').slice(0, pathBitIndex + 1).join('!'));
				if (_.isObject(v)) {
					pointer[pathBit] = v;
				} else if (_.isArray(v)) {
					pointer[pathBit] = [];
					v.forEach(function(item) { pointer[pathBit].push(item) });
				} else {
					pointer[pathBit] = v;
				}
				amended = true;
			} else if (_.isArray(v) && pointer[pathBit].length != v.length) { // Its an array and Mongo has truncated it
				console.log('ARRAY LEN MISMATCH', k);
				pointer[pathBit] = v;
			} else { // Field is ok
				pointer = pointer[pathBit];
			}
		});
	});

	return amended;
};

var scenarioExport = function(options, finish) {
	var output = {};

	async()
		.then(function(next) { // Coherce args into scenario([options], [callback]) {{{
			if (!options) throw new Error('No arguments passed to scenario()');
			if (_.isFunction(options)) { // Form: (callback)
				finish = options;
			} else if (options) { // Form: model(model, options)
				_.merge(settings, options);
			}
			if (!finish) finish = function() {};
			next();
		}) // }}}
		.then(function(next) { // Sanity checks {{{
			if (!settings.connection) throw new Error('Invalid connection to Mongoose');
			next();
		}) // }}}
		.then('models', function(next) {
			next(null, _.keys(settings.connection.base.models));
		})
		.forEach('models', function(nextModel, model) {
			output[model] = [];
			async()
				.then('contents', function(next) {
					settings.connection.base.models[model].find(next);
				})
				.forEach('contents', function(next, row) {
					var rowOutput = {_id: row._id};

					if (row.__v != 0) rowOutput.__v = row.__v; // Only bother to export __v if its not zero

					_.forEach(row.toObject(), function(val, key) {
						if (key == '_id' || key == '__v') return; // Skip meta fields
						rowOutput[key] = row[key];
					});

					output[model].push(rowOutput);
					next();
				})
				.end(nextModel);
		})
		.end(function(err) {
			if (err) return finish(err);
			finish(null, output);
		});

	return scenarioExport;
};

var scenarioSet = function(options) {
	_.merge(settings, options);
};

module.exports = {
	import: scenarioImport,
	export: scenarioExport,
	set: scenarioSet,
};
<|endoftext|>


<commit_before>(function(window) {
	var TwitterWidgetsLoader = {
		src: '//platform.twitter.com/widgets.js',
		loading: false,
		listeners: [],
		interval: 50,

		load: function(callback) {
			var _this = this;

			if (callback) this.listeners.push(callback);

			if(window.twttr && window.twttr.widgets) {
				setTimeout(function() {
					_this.done();
				});
				return;
			}

			if(this.loading) {
				return;
			}

			this.loading = true;

			var script = document.createElement('script');
			script.type = 'text/javascript';
			script.src = this.src;
			document.body.appendChild(script);

			this.poll();
		},

		poll: function() {
			if(window.twttr && window.twttr.widgets) {
				return this.done();
			}

			var _this = this;

			setTimeout(function() {
				_this.poll();
			}, this.interval);
		},

		done: function() {
			while(this.listeners.length) {
				this.listeners.pop()(window.twttr);
			}
		}
	};

	if(typeof module !== 'undefined' && module.exports) {
		module.exports = TwitterWidgetsLoader;
	} else {
		window.TwitterWidgetsLoader = TwitterWidgetsLoader;
	}
}(window));
<commit_msg>Coding style<commit_after>(function(window) {
	var TwitterWidgetsLoader = {
		src: '//platform.twitter.com/widgets.js',
		loading: false,
		listeners: [],
		interval: 50,

		load: function(callback) {
			var _this = this;

			if(callback) {
				this.listeners.push(callback);
			}

			if(window.twttr && window.twttr.widgets) {
				setTimeout(function() {
					_this.done();
				});
				return;
			}

			if(this.loading) {
				return;
			}

			this.loading = true;

			var script = document.createElement('script');
			script.type = 'text/javascript';
			script.src = this.src;
			document.body.appendChild(script);

			this.poll();
		},

		poll: function() {
			if(window.twttr && window.twttr.widgets) {
				return this.done();
			}

			var _this = this;

			setTimeout(function() {
				_this.poll();
			}, this.interval);
		},

		done: function() {
			while(this.listeners.length) {
				this.listeners.pop()(window.twttr);
			}
		}
	};

	if(typeof module !== 'undefined' && module.exports) {
		module.exports = TwitterWidgetsLoader;
	} else {
		window.TwitterWidgetsLoader = TwitterWidgetsLoader;
	}
}(window));
<|endoftext|>


<commit_before>var core = require('resolve/lib/core.json')
var JSONParse = require('safe-json-parse')
var ansihtml = require('ansi-html-stream')
var spawn = require('child_process').spawn
var remove = require('remove-element')
var coffee = require('coffee-script')
var detective = require('detective')
var domify = require('domify')
var findup = require('findup')
var path = require('path')
var fs = require('fs')

exports.activate = activate
exports.deactivate = deactivate

var messages = {
    cantFind: "Hmm... Couldn't find any packages to install!"
  , oneAtATime: "Sorry, you can only run one installation at a time"
  , alreadyInstalled: "Hey, looks like everything has already been installed!"
}

var panel
var inner
var npm

function activate() {
  atom.workspaceView.command('npm-install:save', save({ dev: false }))
  atom.workspaceView.command('npm-install:save-dev', save({ dev: true }))
}

function deactivate() {
  npm.exit()
  inner.innerHTML = ''
  remove(panel)
  remove(inner)
}

function notice(message, className) {
  var overlay = document.createElement('div')

  overlay.setAttribute('class', 'overlay npm-install from-bottom')
  overlay.innerText = message

  if (className) overlay.classList.add(className)

  atom.workspaceView.append(overlay)

  setTimeout(function() {
    overlay.classList.add('fade-out')
  }, 4000)

  setTimeout(function() {
    remove(overlay)
  }, 4500)
}

function save(opts) {
  opts = opts || {}

  inner = inner || document.createElement('div')
  panel = panel || document.createElement('div')
  panel.setAttribute('class', 'panel-bottom tool-panel npm-install')
  panel.appendChild(inner)
  inner.setAttribute('class', 'terminal')

  return function() {
    var editor = atom.workspace.activePaneItem
    var view = atom.workspaceView

    var data = editor.getBuffer().cachedText
    var file = editor.getPath()
    var cwd = path.dirname(file)

    var dkey = opts.dev
      ? 'devDependencies'
      : 'dependencies'

    var flag = opts.dev
      ? '--save-dev'
      : '--save'

    try {
      var found = detective(path.extname(file) === '.coffee'
        ? coffee.compile(data)
        : data
      )
    } catch(e) {
      return notice(e.message, 'warning')
    }

    found = found.filter(function(module) {
      return core.indexOf(module) === -1
    }).map(function(module) {
      return module.split('/')[0]
    }).filter(function(module) {
      return module !== '.'
    })

    if (!found.length) return notice(messages.cantFind)
    if (!(cwd = findup.sync(cwd, 'package.json'))) return

    var pkgFile = path.join(cwd, 'package.json')
    var pkgData = fs.readFileSync(pkgFile, 'utf8')

    JSONParse(pkgData, function(err, pkg) {
      if (err) return console.error(err)

      var output = ansihtml()
      var deps = []
        .concat(Object.keys(pkg.dependencies || {}))
        .concat(Object.keys(pkg.devDependencies || {}))
        .concat(Object.keys(pkg.peerDependencies || {}))

      found = found.filter(function(module) {
        return deps.indexOf(module) === -1
      })

      if (!found.length) return notice(messages.alreadyInstalled, 'success')
      if (npm) return notice(messages.oneAtATime, 'warning')

      npm = spawn('npm', [
          'install'
        , '--color=always'
        , flag
      ].concat(found), {
          cwd: cwd
        , env: process.env
      })

      npm.stdout.pipe(output)
      npm.stderr.pipe(output)
      npm.once('exit', function(code) {
        npm = null
        if (code === 0) return setTimeout(remove.bind(null, panel), 1000)
        notice('Invalid exit code from npm: ' + code, 'warning')
      })

      inner.innerHTML = ''
      output.on('data', function(data) {
        inner.innerHTML += data
      })

      if (!panel.parentNode)
        view.appendToBottom(panel)
    })
  }
}
<commit_msg>Ignore more things<commit_after>var core = require('resolve/lib/core.json')
var JSONParse = require('safe-json-parse')
var ansihtml = require('ansi-html-stream')
var spawn = require('child_process').spawn
var remove = require('remove-element')
var coffee = require('coffee-script')
var detective = require('detective')
var domify = require('domify')
var findup = require('findup')
var path = require('path')
var fs = require('fs')

exports.activate = activate
exports.deactivate = deactivate

var messages = {
    cantFind: "Hmm... Couldn't find any packages to install!"
  , oneAtATime: "Sorry, you can only run one installation at a time"
  , alreadyInstalled: "Hey, looks like everything has already been installed!"
}

var panel
var inner
var npm

function activate() {
  atom.workspaceView.command('npm-install:save', save({ dev: false }))
  atom.workspaceView.command('npm-install:save-dev', save({ dev: true }))
}

function deactivate() {
  npm.exit()
  inner.innerHTML = ''
  remove(panel)
  remove(inner)
}

function notice(message, className) {
  var overlay = document.createElement('div')

  overlay.setAttribute('class', 'overlay npm-install from-bottom')
  overlay.innerText = message

  if (className) overlay.classList.add(className)

  atom.workspaceView.append(overlay)

  setTimeout(function() {
    overlay.classList.add('fade-out')
  }, 4000)

  setTimeout(function() {
    remove(overlay)
  }, 4500)
}

function save(opts) {
  opts = opts || {}

  inner = inner || document.createElement('div')
  panel = panel || document.createElement('div')
  panel.setAttribute('class', 'panel-bottom tool-panel npm-install')
  panel.appendChild(inner)
  inner.setAttribute('class', 'terminal')

  return function() {
    var editor = atom.workspace.activePaneItem
    var view = atom.workspaceView

    var data = editor.getBuffer().cachedText
    var file = editor.getPath()
    var cwd = path.dirname(file)

    var dkey = opts.dev
      ? 'devDependencies'
      : 'dependencies'

    var flag = opts.dev
      ? '--save-dev'
      : '--save'

    try {
      var found = detective(path.extname(file) === '.coffee'
        ? coffee.compile(data)
        : data
      )
    } catch(e) {
      return notice(e.message, 'warning')
    }

    found = found.filter(function(module) {
      return core.indexOf(module) === -1
    }).map(function(module) {
      return module.split('/')[0]
    }).filter(function(module) {
      return module !== '.'
          && module !== '..'
          && module !== 'atom'
    })

    if (!found.length) return notice(messages.cantFind)
    if (!(cwd = findup.sync(cwd, 'package.json'))) return

    var pkgFile = path.join(cwd, 'package.json')
    var pkgData = fs.readFileSync(pkgFile, 'utf8')

    JSONParse(pkgData, function(err, pkg) {
      if (err) return console.error(err)

      var output = ansihtml()
      var deps = []
        .concat(Object.keys(pkg.dependencies || {}))
        .concat(Object.keys(pkg.devDependencies || {}))
        .concat(Object.keys(pkg.peerDependencies || {}))

      found = found.filter(function(module) {
        return deps.indexOf(module) === -1
      })

      if (!found.length) return notice(messages.alreadyInstalled, 'success')
      if (npm) return notice(messages.oneAtATime, 'warning')

      npm = spawn('npm', [
          'install'
        , '--color=always'
        , flag
      ].concat(found), {
          cwd: cwd
        , env: process.env
      })

      npm.stdout.pipe(output)
      npm.stderr.pipe(output)
      npm.once('exit', function(code) {
        npm = null
        if (code === 0) return setTimeout(remove.bind(null, panel), 1000)
        notice('Invalid exit code from npm: ' + code, 'warning')
      })

      inner.innerHTML = ''
      output.on('data', function(data) {
        inner.innerHTML += data
      })

      if (!panel.parentNode)
        view.appendToBottom(panel)
    })
  }
}
<|endoftext|>