<commit_before>K2.Area = function(args) {
    if (arguments.length) {
        this.getready(args);
    }
};

K2.extend(K2.Area, K2.UIElement);

K2.Area.prototype.getready = function(args) {

    var valueName, i;

     // Call the constructor from the superclass.
    K2.Area.superclass.getready.call(this, args);

    // A Area has its starting point, height, width and color.
    this.values = { 'width'     : 0,
                    'height'    : 0,
                    'selected'  : [],
                    'xOffset'   : 0,
                    'yOffset'   : 0,
                    'doubletap'	: [],
                    'held'		: []
                    };

    this.defaultSlot = 'height';

    this.color = args.color || 'black';
    this.borderColor = args.borderColor || 'green';

    this.proximity = Math.floor(args.proximity) || 10;
    this.thickness = Math.floor(args.thickness) || this.proximity;
    // Can paint the borders
    this.borders = args.borders || {top: true, bottom: true, right: true, left: true};
    // Can drag the borders
    this.drag = args.drag || {top: true, bottom: true, right: true, left: true};
    // Move can be 'none', 'x', 'y', 'all'
    this.move = args.move || 'all';

    this.xMonotone = args.xMonotone || false;
    this.yMonotone = args.yMonotone || false;

    // TODO ROI

    var height = args.height || 0;
    var width = args.width || 0;

    this.values.width = width;
    this.values.height = height;

    var xOffset = args.left || 0;
    var yOffset = args.top || 0;

    this.values.xOffset = xOffset;
    this.values.yOffset = yOffset;

};

K2.Area.prototype.isInArea = function (x,y) {
    var xInside = false;
    var yInside = false;

    if (this.values.width > 0) {
        if ((x > this.values.xOffset) && (x < this.values.xOffset + this.values.width)) {
            xInside = true;
        }
    }
    else {
        if ((x < this.values.xOffset) && (x > this.values.xOffset + this.values.width)) {
            xInside = true;
        }
    }

    if (this.values.height > 0) {
        if ((y > this.values.yOffset) && (y < this.values.height + this.values.yOffset)) {
            yInside = true;
        }
    }
    else {
        if ((y < this.values.yOffset) && (y > this.values.height + this.values.yOffset)) {
            yInside = true;
        }
    }

    if (xInside && yInside) {
        return true;
    }
    else {
        return false;
    }

};

K2.Area.prototype.tap = K2.Area.prototype.dragstart = K2.Area.prototype.mousedown = function(x, y) {

    /*if (this.isInROI(x, y)) {*/

        var left_min_prox = this.values.xOffset - this.proximity;
        var left_max_prox = this.values.xOffset + this.proximity;
        var right_min_prox = this.values.xOffset + this.values.width - this.proximity;
        var right_max_prox = this.values.xOffset + this.values.width + this.proximity;
        var bottom_max_prox = this.values.height + this.values.yOffset + this.proximity;
        var bottom_min_prox = this.values.height + this.values.yOffset - this.proximity;
        var top_max_prox = this.values.yOffset + this.proximity;
        var top_min_prox = this.values.yOffset - this.proximity;

        // Test side proximity
        if ((x > left_min_prox) &&  x < (left_max_prox) && this.drag.left === true) {
            // We're next to the left side
            this.leftSide = true;
            console.log ("Left side click detected");
        }
        if ((x > right_min_prox) &&  x < (right_max_prox) && this.drag.right === true) {
            // We're next to the right side
            this.rightSide = true;
            console.log ("Right side click detected");
        }
        if ((y > bottom_min_prox) &&  y < (bottom_max_prox) && this.drag.bottom === true) {
            // We're next to the bottom side
            this.bottomSide = true;
            console.log ("Bottom side click detected");
        }
        if ((y > top_min_prox) &&  y < (top_max_prox) && this.drag.top === true) {
            // We're next to the top side
            this.topSide = true;
            console.log ("Top side click detected");
        }

        if (this.isInArea (x,y)) {
            console.log ("clicked inside!");
            this.inside = true;
            this.startPoint = [x,y];
        }
        else this.inside = false;
};

K2.Area.prototype.drag = K2.Area.prototype.mousemove = function(curr_x, curr_y) {

    var ret = [];
    var newWidth, newHeight;

    if (this.leftSide && this.borders.left) {

        newWidth = this.values.width - (curr_x - this.values.xOffset);
        var newX = curr_x;

        if ((this.xMonotone) && (newWidth < 0)) {
            newWidth = 0;
            newX = this.values.xOffset;
        }

        ret.push ({slot: 'width', value : newWidth});
        ret.push ({slot : 'xOffset', value : newX});
    }

    if (this.rightSide && this.borders.right && !this.leftSide) {
        newWidth = curr_x - this.values.xOffset;

        if ((this.xMonotone) && (newWidth < 0)) {
            newWidth = 0;
        }

        ret.push ({slot : 'width', value : newWidth});
    }

    if (this.bottomSide && this.borders.bottom) {

        newHeight = (this.values.height + (curr_y - (this.values.yOffset + this.values.height)));

        if ((this.yMonotone) && (newHeight < 0)) {
            newHeight = 0;
        }

        ret.push ({slot: 'height', value : newHeight});
    }

    if (this.topSide && this.borders.top && !this.bottomSide) {

        newHeight = this.values.height + (this.values.yOffset - curr_y);
        var newY = curr_y;

        if ((this.yMonotone) && (newHeight < 0)) {
            newHeight = 0;
            newY = this.values.yOffset;
        }

        ret.push ({slot : 'yOffset', value : newY});
        ret.push ({slot : 'height', value : newHeight});
    }

    if (ret.length > 0) {
        // return here, do not move
        return ret;
    }

    // Move the element
    if (this.inside) {
        if (this.move !== 'none') {

            var xDelta = curr_x - this.startPoint[0];
            var yDelta = curr_y - this.startPoint[1];
            this.startPoint = [curr_x, curr_y];

            if (this.move === 'all') {
                return ([{slot : 'xOffset', value : this.values.xOffset + xDelta}, {slot : 'yOffset', value : this.values.yOffset + yDelta}]);
            }
            else if (this.move === 'x') {
                return ({slot : 'xOffset', value : this.values.xOffset + xDelta});
            }
            else if (this.move === 'y') {
                return ({slot : 'yOffset', value : this.values.yOffset + yDelta});
            }
        }
    }

};

K2.Area.prototype.release = K2.Area.prototype.dragend = K2.Area.prototype.mouseup = function(x, y) {

    var ret;

    // Drag guards are reset to false
    this.leftSide = this.rightSide =  this.bottomSide = this.topSide = false;

    // Clicked in and out inside the object. the object is selected
    if (this.inside) {
        if (this.isInArea (x,y)) {
           ret = {slot : 'selected', value : [x, y]};
        }
    }
    this.inside = false;

    return ret;

};

K2.Area.prototype.hold = function(x, y) {
	if (this.isInArea(x, y)) {
		//Area is held
	    var ret = {'slot' : 'held', 'value' : [x, y]};
	    return ret;
   }
};

K2.Area.prototype.doubletap = function(x, y) {
	if (this.isInArea(x, y)) {
		return {'slot' : 'doubletap', 'value' : [x, y]};
	}
};

K2.Area.prototype.setValue = function(slot, value) {
    // Superclass
    K2.Area.superclass.setValue.call(this, slot, value);

};

K2.Area.prototype.refresh_CANVAS2D = function(engine) {

    if (this.isVisible === true) {

        engine.context.fillStyle = this.color;
        engine.context.strokeStyle = this.borderColor;
        engine.context.lineWidth = this.thickness;
        var halfThickness = Math.floor (this.thickness / 2);
        engine.context.fillRect (this.xOrigin + this.values.xOffset + halfThickness,
                                 this.values.yOffset + halfThickness,
                                 this.values.width - halfThickness * 2,
                                 this.values.height - halfThickness * 2);
        engine.context.strokeRect (this.xOrigin + this.values.xOffset,
                                 this.values.yOffset,
                                 this.values.width,
                                 this.values.height);
    }
};

K2.Area.prototype.getXCoord = function() {
    return this.values.xOrigin;
};

K2.Area.prototype.getYCoord = function() {
    return this.values.yOrigin;
};

K2.Area.prototype.getWidth = function() {
    return this.values.width;
};

K2.Area.prototype.getHeight = function() {
    return this.values.height;
};

K2.Area.prototype.setHeight = function(height) {
    this.values.height = height;
    if (typeof this.ROIHeight === 'undefined') {
        this.ROIHeight = height;
    }
};

K2.Area.prototype.setWidth = function(width) {
    this.values.width = width;
    if (typeof this.ROIWidth === 'undefined') {
        this.ROIWidth = width;
    }
};
<commit_msg>Added zero-thickness handling in area (= no borders)<commit_after>K2.Area = function(args) {
    if (arguments.length) {
        this.getready(args);
    }
};

K2.extend(K2.Area, K2.UIElement);

K2.Area.prototype.getready = function(args) {

    var valueName, i;

     // Call the constructor from the superclass.
    K2.Area.superclass.getready.call(this, args);

    // A Area has its starting point, height, width and color.
    this.values = { 'width'     : 0,
                    'height'    : 0,
                    'selected'  : [],
                    'xOffset'   : 0,
                    'yOffset'   : 0,
                    'doubletap'	: [],
                    'held'		: []
                    };

    this.defaultSlot = 'height';

    this.color = args.color || 'black';
    this.borderColor = args.borderColor || 'green';

    this.proximity = Math.floor(args.proximity) || 10;
    this.thickness = Math.floor(args.thickness) || this.proximity;

    if (args.thickness === 0) {
		this.thickness = 0;
    }

    // Can paint the borders
    this.borders = args.borders || {top: true, bottom: true, right: true, left: true};
    // Can drag the borders
    this.drag = args.drag || {top: true, bottom: true, right: true, left: true};
    // Move can be 'none', 'x', 'y', 'all'
    this.move = args.move || 'all';

    this.xMonotone = args.xMonotone || false;
    this.yMonotone = args.yMonotone || false;

    // TODO ROI

    var height = args.height || 0;
    var width = args.width || 0;

    this.values.width = width;
    this.values.height = height;

    var xOffset = args.left || 0;
    var yOffset = args.top || 0;

    this.values.xOffset = xOffset;
    this.values.yOffset = yOffset;

};

K2.Area.prototype.isInArea = function (x,y) {
    var xInside = false;
    var yInside = false;

    if (this.values.width > 0) {
        if ((x > this.values.xOffset) && (x < this.values.xOffset + this.values.width)) {
            xInside = true;
        }
    }
    else {
        if ((x < this.values.xOffset) && (x > this.values.xOffset + this.values.width)) {
            xInside = true;
        }
    }

    if (this.values.height > 0) {
        if ((y > this.values.yOffset) && (y < this.values.height + this.values.yOffset)) {
            yInside = true;
        }
    }
    else {
        if ((y < this.values.yOffset) && (y > this.values.height + this.values.yOffset)) {
            yInside = true;
        }
    }

    if (xInside && yInside) {
        return true;
    }
    else {
        return false;
    }

};

K2.Area.prototype.tap = K2.Area.prototype.dragstart = K2.Area.prototype.mousedown = function(x, y) {

    /*if (this.isInROI(x, y)) {*/

        var left_min_prox = this.values.xOffset - this.proximity;
        var left_max_prox = this.values.xOffset + this.proximity;
        var right_min_prox = this.values.xOffset + this.values.width - this.proximity;
        var right_max_prox = this.values.xOffset + this.values.width + this.proximity;
        var bottom_max_prox = this.values.height + this.values.yOffset + this.proximity;
        var bottom_min_prox = this.values.height + this.values.yOffset - this.proximity;
        var top_max_prox = this.values.yOffset + this.proximity;
        var top_min_prox = this.values.yOffset - this.proximity;

        // Test side proximity
        if ((x > left_min_prox) &&  x < (left_max_prox) && this.drag.left === true) {
            // We're next to the left side
            this.leftSide = true;
            console.log ("Left side click detected");
        }
        if ((x > right_min_prox) &&  x < (right_max_prox) && this.drag.right === true) {
            // We're next to the right side
            this.rightSide = true;
            console.log ("Right side click detected");
        }
        if ((y > bottom_min_prox) &&  y < (bottom_max_prox) && this.drag.bottom === true) {
            // We're next to the bottom side
            this.bottomSide = true;
            console.log ("Bottom side click detected");
        }
        if ((y > top_min_prox) &&  y < (top_max_prox) && this.drag.top === true) {
            // We're next to the top side
            this.topSide = true;
            console.log ("Top side click detected");
        }

        if (this.isInArea (x,y)) {
            console.log ("clicked inside!");
            this.inside = true;
            this.startPoint = [x,y];
        }
        else this.inside = false;
};

K2.Area.prototype.drag = K2.Area.prototype.mousemove = function(curr_x, curr_y) {

    var ret = [];
    var newWidth, newHeight;

    if (this.leftSide && this.borders.left) {

        newWidth = this.values.width - (curr_x - this.values.xOffset);
        var newX = curr_x;

        if ((this.xMonotone) && (newWidth < 0)) {
            newWidth = 0;
            newX = this.values.xOffset;
        }

        ret.push ({slot: 'width', value : newWidth});
        ret.push ({slot : 'xOffset', value : newX});
    }

    if (this.rightSide && this.borders.right && !this.leftSide) {
        newWidth = curr_x - this.values.xOffset;

        if ((this.xMonotone) && (newWidth < 0)) {
            newWidth = 0;
        }

        ret.push ({slot : 'width', value : newWidth});
    }

    if (this.bottomSide && this.borders.bottom) {

        newHeight = (this.values.height + (curr_y - (this.values.yOffset + this.values.height)));

        if ((this.yMonotone) && (newHeight < 0)) {
            newHeight = 0;
        }

        ret.push ({slot: 'height', value : newHeight});
    }

    if (this.topSide && this.borders.top && !this.bottomSide) {

        newHeight = this.values.height + (this.values.yOffset - curr_y);
        var newY = curr_y;

        if ((this.yMonotone) && (newHeight < 0)) {
            newHeight = 0;
            newY = this.values.yOffset;
        }

        ret.push ({slot : 'yOffset', value : newY});
        ret.push ({slot : 'height', value : newHeight});
    }

    if (ret.length > 0) {
        // return here, do not move
        return ret;
    }

    // Move the element
    if (this.inside) {
        if (this.move !== 'none') {

            var xDelta = curr_x - this.startPoint[0];
            var yDelta = curr_y - this.startPoint[1];
            this.startPoint = [curr_x, curr_y];

            if (this.move === 'all') {
                return ([{slot : 'xOffset', value : this.values.xOffset + xDelta}, {slot : 'yOffset', value : this.values.yOffset + yDelta}]);
            }
            else if (this.move === 'x') {
                return ({slot : 'xOffset', value : this.values.xOffset + xDelta});
            }
            else if (this.move === 'y') {
                return ({slot : 'yOffset', value : this.values.yOffset + yDelta});
            }
        }
    }

};

K2.Area.prototype.release = K2.Area.prototype.dragend = K2.Area.prototype.mouseup = function(x, y) {

    var ret;

    // Drag guards are reset to false
    this.leftSide = this.rightSide =  this.bottomSide = this.topSide = false;

    // Clicked in and out inside the object. the object is selected
    if (this.inside) {
        if (this.isInArea (x,y)) {
           ret = {slot : 'selected', value : [x, y]};
        }
    }
    this.inside = false;

    return ret;

};

K2.Area.prototype.hold = function(x, y) {
	if (this.isInArea(x, y)) {
		//Area is held
	    var ret = {'slot' : 'held', 'value' : [x, y]};
	    return ret;
   }
};

K2.Area.prototype.doubletap = function(x, y) {
	if (this.isInArea(x, y)) {
		return {'slot' : 'doubletap', 'value' : [x, y]};
	}
};

K2.Area.prototype.setValue = function(slot, value) {
    // Superclass
    K2.Area.superclass.setValue.call(this, slot, value);

};

K2.Area.prototype.refresh_CANVAS2D = function(engine) {

    if (this.isVisible === true) {

        engine.context.fillStyle = this.color;
        engine.context.strokeStyle = this.borderColor;
        engine.context.lineWidth = this.thickness;
        var halfThickness = Math.floor (this.thickness / 2);
        engine.context.fillRect (this.xOrigin + this.values.xOffset + halfThickness,
                                 this.values.yOffset + halfThickness,
                                 this.values.width - halfThickness * 2,
                                 this.values.height - halfThickness * 2);
        if (this.thickness > 0) {
			engine.context.strokeRect (	this.xOrigin + this.values.xOffset,
										this.values.yOffset,
										this.values.width,
										this.values.height);
		}
    }
};

K2.Area.prototype.getXCoord = function() {
    return this.values.xOrigin;
};

K2.Area.prototype.getYCoord = function() {
    return this.values.yOrigin;
};

K2.Area.prototype.getWidth = function() {
    return this.values.width;
};

K2.Area.prototype.getHeight = function() {
    return this.values.height;
};

K2.Area.prototype.setHeight = function(height) {
    this.values.height = height;
    if (typeof this.ROIHeight === 'undefined') {
        this.ROIHeight = height;
    }
};

K2.Area.prototype.setWidth = function(width) {
    this.values.width = width;
    if (typeof this.ROIWidth === 'undefined') {
        this.ROIWidth = width;
    }
};
<|endoftext|>


<commit_before>
/**
 * A lot of this entry file is based off of node's src/node.js.
 */

var regenerator = require('regenerator');

// grab a reference to the entry point script, then clean up the env
var entryPoint = process.env.GNODE_ENTRY_POINT;
delete process.env.GNODE_ENTRY_POINT;

// load the custom `.js` ES6 Generator compiler
require('./index.js');

if (process._eval != null) {
  // User passed '-e' or '--eval' arguments to Node.
  evalScript('[eval]');
} else if (entryPoint) {
  // replace `process.argv[1]` with the expected path value,
  // and re-run Module.runMain()
  process.argv[1] = require('path').resolve(entryPoint);
  require('module').runMain();
} else {
  // run the REPL, or run from stdin

  // If -i or --interactive were passed, or stdin is a TTY.
  if (process._forceRepl || require('tty').isatty(0)) {
    // REPL
    var opts = {
      useGlobal: true,
      ignoreUndefined: false
    };
    if (parseInt(process.env.NODE_NO_READLINE, 10)) {
      opts.terminal = false;
    }
    if (parseInt(process.env.NODE_DISABLE_COLORS, 10)) {
      opts.useColors = false;
    }
    var repl = require('module').requireRepl().start(opts);
    repl.on('exit', function() {
      process.exit();
    });

  } else {
    // Read all of stdin - execute it.
    process.stdin.resume();
    process.stdin.setEncoding('utf8');

    var code = '';
    process.stdin.on('data', function(d) {
      code += d;
    });

    process.stdin.on('end', function() {
      process._eval = code;
      evalScript('[stdin]');
    });
  }
}

// copied directly from joyent/node's src/node.js
function evalScript (name) {
  var Module = require('module');
  var path = require('path');
  var cwd = process.cwd();

  var module = new Module(name);
  module.filename = path.join(cwd, name);
  module.paths = Module._nodeModulePaths(cwd);
  var script = process._eval;

  // compile JS via facebook/regenerator
  script = regenerator(script, {
    includeRuntime: true
  });

  if (!Module._contextLoad) {
    var body = script;
    script = 'global.__filename = ' + JSON.stringify(name) + ';\n' +
             'global.exports = exports;\n' +
             'global.module = module;\n' +
             'global.__dirname = __dirname;\n' +
             'global.require = require;\n' +
             'return require("vm").runInThisContext(' +
             JSON.stringify(body) + ', ' +
             JSON.stringify(name) + ', true);\n';
  }

  var result = module._compile(script, name + '-wrapper');
  if (process._print_eval) console.log(result);
}
<commit_msg>fallback: add proper REPL support<commit_after>
/**
 * A lot of this entry file is based off of node's src/node.js.
 */

var regenerator = require('regenerator');

// grab a reference to the entry point script, then clean up the env
var entryPoint = process.env.GNODE_ENTRY_POINT;
delete process.env.GNODE_ENTRY_POINT;

// load the custom `.js` ES6 Generator compiler
require('./index.js');

if (process._eval != null) {
  // User passed '-e' or '--eval' arguments to Node.
  evalScript('[eval]');
} else if (entryPoint) {
  // replace `process.argv[1]` with the expected path value,
  // and re-run Module.runMain()
  process.argv[1] = require('path').resolve(entryPoint);
  require('module').runMain();
} else {
  // run the REPL, or run from stdin

  // If -i or --interactive were passed, or stdin is a TTY.
  if (process._forceRepl || require('tty').isatty(0)) {
    // REPL
    var opts = {
      eval: gnodeEval,
      useGlobal: true,
      ignoreUndefined: false
    };
    if (parseInt(process.env.NODE_NO_READLINE, 10)) {
      opts.terminal = false;
    }
    if (parseInt(process.env.NODE_DISABLE_COLORS, 10)) {
      opts.useColors = false;
    }
    var repl = require('module').requireRepl().start(opts);
    repl.on('exit', function() {
      process.exit();
    });

  } else {
    // Read all of stdin - execute it.
    process.stdin.resume();
    process.stdin.setEncoding('utf8');

    var code = '';
    process.stdin.on('data', function(d) {
      code += d;
    });

    process.stdin.on('end', function() {
      process._eval = code;
      evalScript('[stdin]');
    });
  }
}

// custom eval() function for the REPL, that first compiles
var compileOpts = {
  includeRuntime: true
};
function gnodeEval (code, context, file, fn) {
  var err, result;
  try {
    // compile JS via facebook/regenerator
    code = regenerator(code, compileOpts);

    if (this.useGlobal) {
      result = vm.runInThisContext(code, file);
    } else {
      result = vm.runInContext(code, context, file);
    }
  } catch (e) {
    err = e;
  }

  // after the first regenerator() call, we can turn off the
  // `includeRuntime` option since it gets included in the global scope
  compileOpts.includeRuntime = false;

  fn(err, result);
}

// copied (almost) directly from joyent/node's src/node.js
function evalScript (name) {
  var Module = require('module');
  var path = require('path');
  var cwd = process.cwd();

  var module = new Module(name);
  module.filename = path.join(cwd, name);
  module.paths = Module._nodeModulePaths(cwd);
  var script = process._eval;

  // compile JS via facebook/regenerator
  script = regenerator(script, {
    includeRuntime: true
  });

  if (!Module._contextLoad) {
    var body = script;
    script = 'global.__filename = ' + JSON.stringify(name) + ';\n' +
             'global.exports = exports;\n' +
             'global.module = module;\n' +
             'global.__dirname = __dirname;\n' +
             'global.require = require;\n' +
             'return require("vm").runInThisContext(' +
             JSON.stringify(body) + ', ' +
             JSON.stringify(name) + ', true);\n';
  }

  var result = module._compile(script, name + '-wrapper');
  if (process._print_eval) console.log(result);
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var config = require('../config'),
	chalk = require('chalk'),
	path = require('path'),
	mongoose = require('mongoose');

// Load the mongoose models
module.exports.loadModels = function() {
	// Globbing model files
	config.files.server.models.forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});
};

// Initialize Mongoose
module.exports.connect = function(cb) {
	var _this = this;

	var db = mongoose.connect(config.db, function (err) {
		// Log Error
		if (err) {
			console.error(chalk.red('Could not connect to MongoDB!'));
			console.log(err);
		} else {
			// Load modules
			_this.loadModels();

			// Call callback FN
			if (cb) cb(db);
		}
	});
};

module.exports.disconnect = function() {
  mongoose.disconnect();
  console.info(chalk.yellow('Disconnected from MongoDB.'));
};
<commit_msg>Properly track DB disconnect<commit_after>'use strict';

/**
 * Module dependencies.
 */
var config = require('../config'),
	chalk = require('chalk'),
	path = require('path'),
	mongoose = require('mongoose');

// Load the mongoose models
module.exports.loadModels = function() {
	// Globbing model files
	config.files.server.models.forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});
};

// Initialize Mongoose
module.exports.connect = function(cb) {
	var _this = this;

	var db = mongoose.connect(config.db, function (err) {
		// Log Error
		if (err) {
			console.error(chalk.red('Could not connect to MongoDB!'));
			console.log(err);
		} else {
			// Load modules
			_this.loadModels();

			// Call callback FN
			if (cb) cb(db);
		}
	});
};

module.exports.disconnect = function(cb) {
  mongoose.disconnect(function(err) {
  	console.info(chalk.yellow('Disconnected from MongoDB.'));
  	cb(err);
  });
};
<|endoftext|>


<commit_before>/*
 * grunt-autoindex
 * https://github.com/Matt/grunt-autoindex
 *
 * Copyright (c) 2013 mattdesl
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');
var walk = require('fs-walk');
var path = require('path');
var DEFAULT_BANNER = "/** Auto-generated index file, created on <%= grunt.template.today('yyyy-mm-dd') %> */"

var buildIndex = function(grunt, outFile, src, dependencies, banner, opts, fileIgnores, requireIgnores) {
	grunt.log.writeln("Writing "+outFile);

	fileIgnores = fileIgnores || [];
	requireIgnores = requireIgnores || [];

	var text = banner.trim() + "\n";

	text += "module.exports = {\n";

	var UMD_DEPS = dependencies;

	var baseOutName = path.basename(outFile, '.js');

	//TODO: support deep source folder.

	var reqs = [{comment: 'core classes'}];
	walk.walkSync(src, function(basedir, filename, stat) {
		if (stat.isDirectory())
			return;
		if ( filename === "index.js" )
			return;

		if (path.extname(filename) in require.extensions) {
			var fullname = path.join(basedir, filename);

			if (fullname === outFile || fileIgnores.indexOf(fullname) !== -1)
				return;

			var reqName = fullname.split(path.sep);
			reqName.shift(); //remove src folder

			//re-join paths.. maybe better way of doing this in node
			var reqPath = './' + path.join.apply(this, reqName);
			var className = path.basename(reqPath, path.extname(reqPath));
			if (requireIgnores.indexOf(className) === -1)
				reqs.push({name: className, path: reqPath});
		}
	});

	for (var i=0; i<UMD_DEPS.length; i++) {
		var depModule = UMD_DEPS[i];

		var dep = require(depModule);
		var standalone = null;
		var ignores = [];
		opts = opts || {};

		if (depModule in opts) {
			//if null is specified for this module
			if (!opts[depModule])
				continue;

			standalone = opts[depModule].standalone;
			ignores = opts[depModule].ignores || [];
		}

		reqs.push({comment:depModule+' dependencies'});

		if (standalone) {
			reqs.push({path: depModule, name: standalone});
		} else {
			//Not a standalone module, so export everything inside it..
			//except for any ignores
			for (var k in dep) {
				if (dep.hasOwnProperty(k) && ignores.indexOf(k) === -1) {
					reqs.push({path: depModule, name: k, prop: k });
				}
			}
		}
	}

	var longest = 0;
	for (var i=0; i<reqs.length; i++) {
		if (reqs[i].comment) continue;
		longest = Math.max(longest, reqs[i].name.length);
	}

	for (var i=0; i<reqs.length; i++) {
		if (reqs[i].comment) {
			if (i!==0)
				text += '\n';
			text += '    //'+reqs[i].comment+'\n';
			continue;
		}
		var className = reqs[i].name;
		var reqPath = reqs[i].path;
		var tab = Array( Math.max(4, 4 + longest-className.length) ).join(' ');

		text += "    '" + className + "':"+tab+"require('"+reqPath+"')";
		if (reqs[i].prop)
			text += '.'+reqs[i].prop;

		if (i !== reqs.length-1)
			text += ',\n';
		else
			text += '\n';
	}
	text += "};";

	var file = grunt.template.process(outFile);
	fs.writeFileSync(file, text);
};

module.exports = function(grunt) {

	// Please see the Grunt documentation for more information regarding task
	// creation: http://gruntjs.com/creating-tasks

	grunt.registerMultiTask('autoindex', 'Writes an index.js file, ideal for Browserify.', function() {
		// Merge task-specific and/or target-specific options with these defaults.
		var options = this.options({
			banner: grunt.template.process(DEFAULT_BANNER),
			requires: {}
		});

		//Get the output index.js file
		var file = this.data.dest;
		//the source folder to look through
		var srcFolder = this.data.src;

		var deps = options.dependencies || Object.keys( grunt.file.readJSON('package.json').dependencies );
		buildIndex(grunt, file, srcFolder, deps, options.banner,
					options.modules, options.file_ignores, options.require_ignores);

	});

};
<commit_msg>updating task<commit_after>/*
 * grunt-autoindex
 * https://github.com/Matt/grunt-autoindex
 *
 * Copyright (c) 2013 mattdesl
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');
var walk = require('fs-walk');
var path = require('path');
var DEFAULT_BANNER = "/** Auto-generated index file, created on <%= grunt.template.today('yyyy-mm-dd') %> */"

var buildIndex = function(grunt, outFile, src, dependencies, banner, opts, fileIgnores, requireIgnores) {
	grunt.log.writeln("Writing "+outFile);

	fileIgnores = fileIgnores || [];
	requireIgnores = requireIgnores || [];

	var text = banner.trim() + "\n";

	text += "module.exports = {\n";

	var UMD_DEPS = dependencies;

	var baseOutName = path.basename(outFile, '.js');

	//TODO: support deep source folder.

	var reqs = [{comment: 'core classes'}];
	walk.walkSync(src, function(basedir, filename, stat) {
		if (stat.isDirectory())
			return;
		if ( filename === "index.js" )
			return;

		if (path.extname(filename) in require.extensions) {
			var fullname = path.join(basedir, filename);

			if (fullname === outFile || fileIgnores.indexOf(fullname) !== -1)
				return;

			var reqName = fullname.split(path.sep);
			reqName.shift(); //remove src folder

			//re-join paths.. maybe better way of doing this in node
			var reqPath = './' + path.join.apply(this, reqName);
			var className = path.basename(reqPath, path.extname(reqPath));
			if (requireIgnores.indexOf(className) === -1)
				reqs.push({name: className, path: reqPath});
		}
	});

	for (var i=0; i<UMD_DEPS.length; i++) {
		var depModule = UMD_DEPS[i];

		var dep = require(depModule);
		var standalone = null;
		var ignores = [];
		opts = opts || {};

		if (depModule in opts) {
			//if null is specified for this module
			if (!opts[depModule])
				continue;

			standalone = opts[depModule].standalone;
			ignores = opts[depModule].ignores || [];
		}

		reqs.push({comment:depModule+' dependencies'});

		if (standalone) {
			reqs.push({path: depModule, name: standalone});
		} else {
			//Not a standalone module, so export everything inside it..
			//except for any ignores
			for (var k in dep) {
				if (dep.hasOwnProperty(k) && ignores.indexOf(k) === -1) {
					reqs.push({path: depModule, name: k, prop: k });
				}
			}
		}
	}

	var longest = 0;
	for (var i=0; i<reqs.length; i++) {
		if (reqs[i].comment) continue;
		longest = Math.max(longest, reqs[i].name.length);
	}

	for (var i=0; i<reqs.length; i++) {
		if (reqs[i].comment) {
			if (i!==0)
				text += '\n';
			text += '    //'+reqs[i].comment+'\n';
			continue;
		}
		var className = reqs[i].name;
		var reqPath = reqs[i].path;
		var tab = Array( Math.max(4, 4 + longest-className.length) ).join(' ');

		text += "    '" + className + "':"+tab+"require('"+reqPath+"')";
		if (reqs[i].prop)
			text += '.'+reqs[i].prop;

		if (i !== reqs.length-1)
			text += ',\n';
		else
			text += '\n';
	}
	text += "};";

	var file = grunt.template.process(outFile);
	fs.writeFileSync(file, text);
};

module.exports = function(grunt) {

	// Please see the Grunt documentation for more information regarding task
	// creation: http://gruntjs.com/creating-tasks

	grunt.registerMultiTask('autoindex', 'Writes an index.js file, ideal for Browserify.', function() {
		// Merge task-specific and/or target-specific options with these defaults.
		var options = this.options({
			banner: grunt.template.process(DEFAULT_BANNER),
			requires: {}
		});

		//Get the output index.js file
		var file = this.data.dest;
		//the source folder to look through
		var srcFolder = this.data.src;

		var deps = options.dependencies || Object.keys( grunt.file.readJSON('package.json').dependencies );
		buildIndex(grunt, file, srcFolder, deps, options.banner,
					options.modules, options.file_ignores, options.require_ignores);

	});

};
<|endoftext|>


<commit_before>function view_memory(addr, memory) {
    addr = addr & 0xFFF0;
    var pad = '00';
    var str = addr.toString(16) + ':';
    for (var i = addr; i < addr + 0x10; i++) {
        if ((i & 0x1) == 0) {
            str += ' ';
        }
        var val = memory[i] || 0;

        val = val.toString(16);
        str += pad.substring(val.length) + val;
    }

    return str;
}
<commit_msg>view_tile debug function<commit_after>function view_memory(addr, memory) {
    addr = addr & 0xFFF0;
    var pad = '00';
    var str = addr.toString(16) + ':';
    for (var i = addr; i < addr + 0x10; i++) {
        if ((i & 0x1) == 0) {
            str += ' ';
        }
        var val = memory[i] || 0;

        val = val.toString(16);
        str += pad.substring(val.length) + val;
    }

    return str;
}

function view_tile(screen, index) {
    var tileData = screen.readTileData(index, 0b11100011);

    var pixelData = new Array(8 * 8)
    for (var line = 0; line < 8; line++) {
        var b1 = tileData.shift();
        var b2 = tileData.shift();

        for (var pixel = 0; pixel < 8; pixel++) {
            var mask = (1 << (7-pixel));
            var colorValue = ((b1 & mask) >> (7-pixel)) + ((b2 & mask) >> (7-pixel))*2;
            pixelData[line * 8 + pixel] = colorValue;
        }
    }

    var i = 0;
    while (pixelData.length) {
        console.log(i++ + ' ' + pixelData.splice(0, 8).join(''));
    }
}
<|endoftext|>


<commit_before>'use strict';

// ---------------------------------------------------------------------------

const ftx = require ('./ftx.js');

module.exports = class ftxus extends ftx {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ftxus',
            'name': 'FTX US',
            'countries': [ 'US' ],
            'certified': false,
            'hostname': 'ftx.us',
            'has': {
                'CORS': undefined,
                'spot': true,
                'margin': undefined, // Has but not fully implemented
                'swap': false,
                'future': false,
                'option': undefined,
                'fetchFundingHistory': false,
                'fetchFundingRate': false,
                'fetchFundingRateHistory': false,
                'fetchFundingRates': false,
                'fetchIndexOHLCV': false,
                'fetchMarkOHLCV': false,
                'fetchOpenInterestHistory': false,
                'fetchPremiumIndexOHLCV': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/141506670-12f6115f-f425-4cd8-b892-b51d157ca01f.jpg',
                'www': 'https://ftx.us/',
                'docs': 'https://docs.ftx.us/',
                'fees': 'https://help.ftx.us/hc/en-us/articles/360043579273-Fees',
            },
        });
    }
};
<commit_msg>updated ftxus fees. fixes:#15219<commit_after>'use strict';

// ---------------------------------------------------------------------------

const ftx = require ('./ftx.js');

module.exports = class ftxus extends ftx {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ftxus',
            'name': 'FTX US',
            'countries': [ 'US' ],
            'certified': false,
            'hostname': 'ftx.us',
            'has': {
                'CORS': undefined,
                'spot': true,
                'margin': undefined, // Has but not fully implemented
                'swap': false,
                'future': false,
                'option': undefined,
                'fetchFundingHistory': false,
                'fetchFundingRate': false,
                'fetchFundingRateHistory': false,
                'fetchFundingRates': false,
                'fetchIndexOHLCV': false,
                'fetchMarkOHLCV': false,
                'fetchOpenInterestHistory': false,
                'fetchPremiumIndexOHLCV': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/141506670-12f6115f-f425-4cd8-b892-b51d157ca01f.jpg',
                'www': 'https://ftx.us/',
                'docs': 'https://docs.ftx.us/',
                'fees': 'https://help.ftx.us/hc/en-us/articles/360043579273-Fees',
            },
            'fees': {
                'trading': {
                    'tierBased': true,
                    'percentage': true,
                    'maker': this.parseNumber ('0.001'),
                    'taker': this.parseNumber ('0.002'),
                    'tiers': {
                        'taker': [
                            [ this.parseNumber ('0'), this.parseNumber ('0.002') ],
                            [ this.parseNumber ('100000'), this.parseNumber ('0.0018') ],
                            [ this.parseNumber ('1000000'), this.parseNumber ('0.0015') ],
                            [ this.parseNumber ('5000000'), this.parseNumber ('0.001') ],
                            [ this.parseNumber ('10000000'), this.parseNumber ('0.0008') ],
                            [ this.parseNumber ('15000000'), this.parseNumber ('0.0006') ],
                        ],
                        'maker': [
                            [ this.parseNumber ('0'), this.parseNumber ('0.001') ],
                            [ this.parseNumber ('100000'), this.parseNumber ('0.0006') ],
                            [ this.parseNumber ('1000000'), this.parseNumber ('0.0005') ],
                            [ this.parseNumber ('5000000'), this.parseNumber ('0.0004') ],
                            [ this.parseNumber ('10000000'), this.parseNumber ('0.0002') ],
                            [ this.parseNumber ('15000000'), this.parseNumber ('0.0') ],
                        ],
                    },
                },
                'funding': {
                    'withdraw': {},
                },
            },
        });
    }
};
<|endoftext|>


<commit_before>/**
 * Created by Johannes on 02.12.2014.
 */

function initializeChart(root) {

    var margin = {top: 350, right: 480, bottom: 350, left: 480},
        radius = Math.min(margin.top, margin.right, margin.bottom, margin.left) - 10;

    var hue = d3.scale.category10();

    var luminance = d3.scale.sqrt()
        .domain([0, 1e7])
        .clamp(true)
        .range([90, 20]);

    var svg = d3.select("#content").append("svg")
        .attr("width", margin.left + margin.right)
        .attr("height", margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var partition = d3.layout.partition()
        .sort(function (a, b) {
            return d3.ascending(a.size, b.size);
        })
        .size([2 * Math.PI, radius]);

    var arc = d3.svg.arc()
        .startAngle(function (d) {
            return d.x;
        })
        .endAngle(function (d) {
            return d.x + d.dx - .01 / (d.depth + .5);
        })
        .innerRadius(function (d) {
            return radius / 3 * d.depth;
        })
        .outerRadius(function (d) {
            return radius / 3 * (d.depth + 1) - 1;
        });

    console.log(root)
    // Compute the initial layout on the entire tree to sum sizes.
    // Also compute the full name and fill color for each node,
    // and stash the children so they can be restored as we descend.
    partition
        .value(function (d) {
            return d.size;
        })
        .nodes(root)
        .forEach(function (d) {
            d._children = d.children;
            d.fill = fill(d);
        });

    // Now redefine the value function to use the previously-computed sum.
    partition
        .children(function (d, depth) {
            return depth < 2 ? d._children : null;
        })
        .value(function (d) {
            return d.size;
        });

    var center = svg.append("circle")
        .attr("r", radius / 3)
        .on("click", zoomOut);

    center.append("title")
        .text("zoom out");

    var path = svg.selectAll("path")
        .data(partition.nodes(root).slice(1))
        .enter().append("path")
        .attr("d", arc)
        .style("fill", function (d) {
            return d.fill;
        })
        .each(function (d) {
            this._current = updateArc(d);
        })
        .on("click", zoomIn)

    path.append("title")
        .text(function(d){
            return d.name + ": "+ getReadableFileSizeString(d.size);
        });

    function zoomIn(p) {
        if (p.depth > 1) p = p.parent;
        if (!p.children) return;
        zoom(p, p);
    }

    function zoomOut(p) {
        if (!p.parent) return;
        zoom(p.parent, p);
    }

    // Zoom to the specified new root.
    function zoom(root, p) {
        if (document.documentElement.__transition__) return;

        // Rescale outside angles to match the new layout.
        var enterArc,
            exitArc,
            outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);

        function insideArc(d) {
            return p.key > d.key
                ? {depth: d.depth - 1, x: 0, dx: 0} : p.key < d.key
                ? {depth: d.depth - 1, x: 2 * Math.PI, dx: 0}
                : {depth: 0, x: 0, dx: 2 * Math.PI};
        }

        function outsideArc(d) {
            return {depth: d.depth + 1, x: outsideAngle(d.x), dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)};
        }

        center.datum(root);

        // When zooming in, arcs enter from the outside and exit to the inside.
        // Entering outside arcs start from the old layout.
        if (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);

        path = path.data(partition.nodes(root).slice(1), function (d) {
            return d.key;
        });

        // When zooming out, arcs enter from the inside and exit to the outside.
        // Exiting outside arcs transition to the new layout.
        if (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);

        d3.transition().duration(d3.event.altKey ? 7500 : 750).each(function () {
            path.exit().transition()
                .style("fill-opacity", function (d) {
                    return d.depth === 1 + (root === p) ? 1 : 0;
                })
                .attrTween("d", function (d) {
                    return arcTween.call(this, exitArc(d));
                })
                .remove();

            path.enter().append("path")
                .style("fill-opacity", function (d) {
                    return d.depth === 2 - (root === p) ? 1 : 0;
                })
                .style("fill", function (d) {
                    return d.fill;
                })
                .on("click", zoomIn)
                .each(function (d) {
                    this._current = enterArc(d);
                });

            path.append("title")
                .text(function(d){
                    return d.name + ": "+ getReadableFileSizeString(d.size);
                });

            path.transition()
                .style("fill-opacity", 1)
                .attrTween("d", function (d) {
                    return arcTween.call(this, updateArc(d));
                });
        });
    }

    function key(d) {
        var k = [], p = d;
        while (p.depth) k.push(p.name), p = p.parent;
        return k.reverse().join(".");
    }

    function fill(d) {
        var p = d;
        while (p.depth > 1) p = p.parent;
        var c = d3.lab(hue(p.name));
        c.l = luminance(d.size);
        return c;
    }

    function arcTween(b) {
        var i = d3.interpolate(this._current, b);
        this._current = i(0);
        return function (t) {
            return arc(i(t));
        };
    }

    function updateArc(d) {
        return {depth: d.depth, x: d.x, dx: d.dx};
    }

    d3.select(self.frameElement).style("height", margin.top + margin.bottom + "px");

    function update(){
        partition
            .nodes(root)
            .forEach(function (d) {
                d._children = d.__children;
                d.fill = fill(d);
            });

        path = path.data(partition.nodes(root).slice(1), function (d) {
            return d.key;
        });

        path.attr("d", arc)
            .style("fill", function (d) {
                return d.fill;
            })
            .each(function (d) {
                this._current = updateArc(d);
            });

        path.enter().append("path")
            .attr("d", arc)
            .style("fill", function (d) {
                return d.fill;
            })
            .each(function (d) {
                this._current = updateArc(d);
            })
            .on("click", zoomIn);

        path.exit().remove();

        console.log(root)
    }
    return update;
}<commit_msg>fixed overlay, colors<commit_after>/**
 * Created by Johannes on 02.12.2014.
 */

function initializeChart(root) {

    var margin = {top: 350, right: 480, bottom: 350, left: 480},
        radius = Math.min(margin.top, margin.right, margin.bottom, margin.left) - 10;

    var hue = d3.scale.category10();

    var luminance = d3.scale.sqrt()
        .domain([0, 1e7])
        .clamp(true)
        .range([90, 20]);

    var svg = d3.select("#content").append("svg")
        .attr("width", margin.left + margin.right)
        .attr("height", margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var partition = d3.layout.partition()
        .sort(function (a, b) {
            return d3.ascending(a.size, b.size);
        })
        .size([2 * Math.PI, radius]);

    var arc = d3.svg.arc()
        .startAngle(function (d) {
            return d.x;
        })
        .endAngle(function (d) {
            return d.x + d.dx - .01 / (d.depth + .5);
        })
        .innerRadius(function (d) {
            return radius / 3 * d.depth;
        })
        .outerRadius(function (d) {
            return radius / 3 * (d.depth + 1) - 1;
        });

    console.log(root)
    // Compute the initial layout on the entire tree to sum sizes.
    // Also compute the full name and fill color for each node,
    // and stash the children so they can be restored as we descend.
    partition
        .value(function (d) {
            return d.size;
        })
        .nodes(root)
        .forEach(function (d) {
            d._children = d.children;
            d.fill = fill(d);
        });

    // Now redefine the value function to use the previously-computed sum.
    partition
        .children(function (d, depth) {
            return depth < 2 ? d._children : null;
        })
        .value(function (d) {
            return d.size;
        });

    var center = svg.append("circle")
        .attr("r", radius / 3)
        .on("click", zoomOut);

    center.append("title")
        .text("zoom out");

    var path = svg.selectAll("path")
        .data(partition.nodes(root).slice(1))
        .enter().append("path")
        .attr("d", arc)
        .style("fill", function (d) {
            return d.fill;
        })
        .each(function (d) {
            this._current = updateArc(d);
        })
        .on("click", zoomIn)

    path.append("title")
        .text(function(d){
            return d.name + ": "+ getReadableFileSizeString(d.size);
        });

    function zoomIn(p) {
        if (p.depth > 1) p = p.parent;
        if (!p.children) return;
        zoom(p, p);
    }

    function zoomOut(p) {
        if (!p.parent) return;
        zoom(p.parent, p);
    }

    // Zoom to the specified new root.
    function zoom(root, p) {
        if (document.documentElement.__transition__) return;

        // Rescale outside angles to match the new layout.
        var enterArc,
            exitArc,
            outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);

        function insideArc(d) {
            return p.key > d.key
                ? {depth: d.depth - 1, x: 0, dx: 0} : p.key < d.key
                ? {depth: d.depth - 1, x: 2 * Math.PI, dx: 0}
                : {depth: 0, x: 0, dx: 2 * Math.PI};
        }

        function outsideArc(d) {
            return {depth: d.depth + 1, x: outsideAngle(d.x), dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)};
        }

        center.datum(root);

        // When zooming in, arcs enter from the outside and exit to the inside.
        // Entering outside arcs start from the old layout.
        if (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);

        path = path.data(partition.nodes(root).slice(1), function (d) {
            return d.key;
        });

        // When zooming out, arcs enter from the inside and exit to the outside.
        // Exiting outside arcs transition to the new layout.
        if (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);

        d3.transition().duration(d3.event.altKey ? 7500 : 750).each(function () {
            path.exit().transition()
                .style("fill-opacity", function (d) {
                    return d.depth === 1 + (root === p) ? 1 : 0;
                })
                .attrTween("d", function (d) {
                    return arcTween.call(this, exitArc(d));
                })
                .remove();

            path.enter().append("path")
                .style("fill-opacity", function (d) {
                    return d.depth === 2 - (root === p) ? 1 : 0;
                })
                .style("fill", function (d) {
                    return d.fill;
                })
                .on("click", zoomIn)
                .each(function (d) {
                    this._current = enterArc(d);
                });

            path.append("title")
                .text(function(d){
                    return d.name + ": "+ getReadableFileSizeString(d.size);
                });

            path.transition()
                .style("fill-opacity", 1)
                .attrTween("d", function (d) {
                    return arcTween.call(this, updateArc(d));
                });
        });
    }

    function fill(d) {
        var p = d;
        while (p.depth > 1) p = p.parent;
        var c = d3.lab(hue(p.name));
        c.l = luminance(d.size);
        return c;
    }

    function arcTween(b) {
        var i = d3.interpolate(this._current, b);
        this._current = i(0);
        return function (t) {
            return arc(i(t));
        };
    }

    function updateArc(d) {
        return {depth: d.depth, x: d.x, dx: d.dx};
    }

    d3.select(self.frameElement).style("height", margin.top + margin.bottom + "px");

    function update(){
        partition
            .nodes(root)
            .forEach(function (d) {
                d._children = d.__children;
            });
        partition.children(function (d) {   //make sure to update all children in the next step
                return d._children;
            });
        partition.nodes(root)
            .forEach(function (d) {
                d.fill = fill(d)
            });
        partition.children(function (d, depth) {
                return depth < 2 ? d._children : null;  //reset to only show two inner circles
            });

        path = path.data(partition.nodes(root).slice(1), function (d) {
            return d.key;
        });

        path.enter().append("path")
            .attr("d", arc)
            .on("click", zoomIn);

        path.attr("d", arc)
            .style("fill", function (d) {
                return d.fill;
            })
            .each(function (d) {
                this._current = updateArc(d);
            });

        path.append("title")
            .text(function(d){
                return d.name + ": "+ getReadableFileSizeString(d.size);
            });

        path.exit().remove();
    }
    return update;
}<|endoftext|>


<commit_before>const path = require('path')
const webpack = require('webpack')
const cssnano = require('cssnano')
const settings = require('./settings')
const styleLoader = require('./style-loader')
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')

const isProduction = process.env.NODE_ENV === 'production'
const env = isProduction ? 'build' : 'dev'
const assetsPath = curPath => path.posix.join(settings[env].assets.subDir, curPath)
const resolve = dir => path.join(__dirname, '..', dir)
const publicPath = dir => settings[env].publicPath + dir
const assetConfig = (filename, hash) => ({
  filepath: require.resolve(filename),
  outputPath: 'js',
  publicPath: publicPath('js'),
  includeSourcemap: false,
  hash: hash || false
})

let loaderRules = [
  {
    test: /\.(js|jsx)$/,
    loader: 'babel-loader',
    include: [resolve('src'), resolve('test')]
  }, {
    test: /\.css$/,
    use: styleLoader()
  }, {
    test: /\.less$/,
    use: styleLoader('less-loader')
  }, {
    test: /\.(scss|sass)$/,
    use: styleLoader('sass-loader')
  }, {
    test: /\.(stylus|styl)$/,
    use: styleLoader('stylus-loader')
  }, {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    query: {
      limit: 8192,
      name: assetsPath('images/[name].[hash:7].[ext]')
    }
  }, {
    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
    loader: 'url-loader',
    query: {
      limit: 8192,
      name: assetsPath('fonts/[name].[hash:7].[ext]')
    }
  }
]

if (!isProduction && settings.dev.lint) {
  loaderRules = [{
    test: /\.(js|jsx)$/,
    loader: 'eslint-loader',
    enforce: 'pre',
    include: [resolve('src'), resolve('test')],
    options: {
      formatter: require('eslint-friendly-formatter')
    }
  }].concat(loaderRules)
}

module.exports = {
  entry: {
    app: './src/core/main.js',
    vendor: [
      // core
      'react',
      'redux',
      'react-dom',
      'react-redux',
      'redux-thunk',
      'react-router',
      'redux-actions',
      'redux-persist',
      'react-router-dom',
      'react-transition-group/CSSTransitionGroup',
      // plugins
      'qs',
      'md5',
      'nprogress',
      'antd/lib/button',
      'antd/lib/checkbox',
      'antd/lib/col',
      'antd/lib/date-picker',
      'antd/lib/form',
      'antd/lib/icon',
      'antd/lib/input',
      'antd/lib/message',
      'antd/lib/modal',
      'antd/lib/notification',
      'antd/lib/radio',
      'antd/lib/row',
      'antd/lib/select',
      'antd/lib/slider',
      'antd/lib/spin',
      'antd/lib/table',
      'antd/lib/tree',
      'antd/lib/tree-select',
      'antd/lib/popconfirm'
    ]
  },
  output: {
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json'],
    modules: [
      resolve('src'),
      resolve('node_modules')
    ],
    alias: {
      // 自定义路径别名
      ASSET: resolve('src/assets'),
      COMPONENT: resolve('src/components'),
      CONSTANT: resolve('src/constants'),
      CORE: resolve('src/core'),
      STORE: resolve('src/store'),
      GLOBAL: resolve('src/globals'),
      IMAGE: resolve('src/assets/images'),
      LAYOUT: resolve('src/layouts'),
      MIDDLEWARE: resolve('src/middleware'),
      REDUCER: resolve('src/reducers'),
      STYLE: resolve('src/assets/styles'),
      UTIL: resolve('src/utils'),
      VIEW: resolve('src/views')
    }
  },
  module: {
    rules: loaderRules
  },
  plugins: [
    new AddAssetHtmlPlugin([
      assetConfig('../shim/es5-shim.min.js'),
      assetConfig('../shim/es6-shim.min.js'),
      assetConfig('../shim/fetch.min.js')
    ]),
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: [
          cssnano({
            autoprefixer: {
              add: true,
              remove: true,
              browsers: ['last 2 versions']
            },
            discardComments: {
              removeAll: true
            },
            discardUnused: false,
            mergeIdents: false,
            reduceIdents: false,
            safe: true,
            sourcemap: true
          })
        ]
      }
    })
  ]
}
<commit_msg>update base webpack config<commit_after>const path = require('path')
const webpack = require('webpack')
const cssnano = require('cssnano')
const settings = require('./settings')
const styleLoader = require('./style-loader')
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')

const isProduction = process.env.NODE_ENV === 'production'
const env = isProduction ? 'build' : 'dev'
const assetsPath = curPath => path.posix.join(settings[env].assets.subDir, curPath)
const resolve = dir => path.join(__dirname, '..', dir)
const publicPath = dir => settings[env].publicPath + dir
const assetConfig = (filename, hash) => ({
  filepath: require.resolve(filename),
  outputPath: 'js',
  publicPath: publicPath('js'),
  includeSourcemap: false,
  hash: hash || false
})

let loaderRules = [
  {
    test: /\.(js|jsx)$/,
    loader: 'babel-loader',
    include: [resolve('src'), resolve('test')]
  }, {
    test: /\.css$/,
    use: styleLoader()
  }, {
    test: /\.less$/,
    use: styleLoader('less-loader')
  }, {
    test: /\.(scss|sass)$/,
    use: styleLoader('sass-loader')
  }, {
    test: /\.(stylus|styl)$/,
    use: styleLoader('stylus-loader')
  }, {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    query: {
      limit: 8192,
      name: assetsPath('images/[name].[hash:7].[ext]')
    }
  }, {
    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
    loader: 'url-loader',
    query: {
      limit: 8192,
      name: assetsPath('fonts/[name].[hash:7].[ext]')
    }
  }
]

if (settings[env].lint) {
  loaderRules = [{
    test: /\.(js|jsx)$/,
    loader: 'eslint-loader',
    enforce: 'pre',
    include: [resolve('src'), resolve('test')],
    options: {
      formatter: require('eslint-friendly-formatter')
    }
  }].concat(loaderRules)
}

module.exports = {
  entry: {
    app: './src/core/main.js',
    vendor: [
      // core
      'react',
      'redux',
      'react-dom',
      'react-redux',
      'redux-thunk',
      'react-router',
      'redux-actions',
      'redux-persist',
      'react-router-dom',
      'react-transition-group/CSSTransitionGroup',
      // plugins
      'qs',
      'md5',
      'nprogress',
      'antd/lib/button',
      'antd/lib/checkbox',
      'antd/lib/col',
      'antd/lib/date-picker',
      'antd/lib/form',
      'antd/lib/icon',
      'antd/lib/input',
      'antd/lib/message',
      'antd/lib/modal',
      'antd/lib/notification',
      'antd/lib/radio',
      'antd/lib/row',
      'antd/lib/select',
      'antd/lib/slider',
      'antd/lib/spin',
      'antd/lib/table',
      'antd/lib/tree',
      'antd/lib/tree-select',
      'antd/lib/popconfirm'
    ]
  },
  output: {
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json'],
    modules: [
      resolve('src'),
      resolve('node_modules')
    ],
    alias: {
      // 自定义路径别名
      ASSET: resolve('src/assets'),
      COMPONENT: resolve('src/components'),
      CONSTANT: resolve('src/constants'),
      CORE: resolve('src/core'),
      STORE: resolve('src/store'),
      GLOBAL: resolve('src/globals'),
      IMAGE: resolve('src/assets/images'),
      LAYOUT: resolve('src/layouts'),
      MIDDLEWARE: resolve('src/middleware'),
      REDUCER: resolve('src/reducers'),
      STYLE: resolve('src/assets/styles'),
      UTIL: resolve('src/utils'),
      VIEW: resolve('src/views')
    }
  },
  module: {
    rules: loaderRules
  },
  plugins: [
    new AddAssetHtmlPlugin([
      assetConfig('../shim/es5-shim.min.js'),
      assetConfig('../shim/es6-shim.min.js'),
      assetConfig('../shim/fetch.min.js')
    ]),
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: [
          cssnano({
            autoprefixer: {
              add: true,
              remove: true,
              browsers: ['last 2 versions']
            },
            discardComments: {
              removeAll: true
            },
            discardUnused: false,
            mergeIdents: false,
            reduceIdents: false,
            safe: true,
            sourcemap: true
          })
        ]
      }
    })
  ]
}
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc directive for Simulation Extraction View Animation
 * @name flowsimUiApp.directive:fgextraction
 * @description
 * # fgextraction
 */
angular.module('flowsimUiApp')
    .directive('fgExtraction', function() {
        return {
            replace: true,
            restrict: 'EA',
            scope: {
                ctx: '='
            },
            link: function postLink(scope, element, attrs) {
            	var animationDuration = parseInt(attrs.animationDuration) || 500;

            	scope.protocols = null;
            	scope.keys = null;
                scope.init = function() {

                    var container = d3.select(element[0])
                        .append('div')
                        .attr('class', 'ext-container');
                    var firstRow = container.append('div').attr('class', 'ext-row');
                    var secondRow = container.append('div').attr('class', 'ext-row');
                    var packetHolderCell = firstRow.append('div').attr('class', 'ext-left');
                    scope.arrowsCell = secondRow.append('div').attr('class', 'ext-left');
                    var contextKeyCell = secondRow.append('div').attr('class', 'ext-right');
                    //Packet Section
                    var packetWrapper = packetHolderCell
                        .append('div')
                        .attr('id', 'packetIndicator')

                    .attr('class', 'rnn-holder ctx-key-context')
                        .text('Decoder');

                    scope.pack = packetWrapper.append('div')
                        .attr('class', 'rnn-stack');
                    scope.pack.append('div')
                        .attr('id', 'left-box')
                        .attr('class', 'rnn-item ext-pack-header ext-pack-left')
                        .text('\u00A0\u00A0\u00A0');
                    scope.protocols = scope.pack.selectAll('#rnn-item')
                        .data(scope.ctx.packet.protocols)
                        .enter()
                        .append('div')
                        .attr('id','rnn-item')
                        .attr('class', 'rnn-item ext-pack-header');

                    scope.pack.append('div')
                        .attr('class', 'rnn-item ext-pack-header ext-pack-right')
                        .attr('id', 'right-box')
                        .text('\u00A0\u00A0\u00A0');
                    scope.protocols.append('div')
                        .attr('class', 'rnn-item rnn-title')
                        .text(function(d) {
                            return d.name;
                        });
                    //END - Packet Section

                    //Context Key Section
                    var ctxRoot = contextKeyCell.append('div');
                    ctxRoot.append('div').attr('class', 'ctx-key-context').text('Context');
                    var ctxHeader = ctxRoot.append('div').attr('class', 'ctx-key-header');
                    ctxHeader.append('div').attr('style', 'padding-left:10px').text('Key');
                    scope.keyWrapper = ctxHeader.append('div');
                    scope.addKey();
                };
                scope.addKey = function() {

                    var keys = scope.keyWrapper.selectAll('#ext-ctx-key-keys')
                        .data(scope.ctx.key)
                        .enter()
                        .insert('div', ':first-child')
                        .attr('id', 'ext-ctx-key-keys')
                        .attr('class', function(d, i) {
                            var cls = i % 2 ? 'ctx-key-color-prim' : 'ctx-key-color-sec';
                            return 'ctx-key-keys ' + cls;
                        })
                        .attr('style', 'opacity: 0');

                    keys.append('div').selectAll('#ext-ctx-key-td')
                        .data(function(d) {
                            return d.attrs;
                        })
                        .enter()
                        .append('div')
                        .attr('id','ext-ctx-key-td')
                        .attr('class', 'ctx-key-td')
                        .text(function(d) {
                            return d.name + ' : ' + d.value;
                        });
                    keys.append('div').attr('class', 'ctx-key-name').text(function(d) {
                        return d.name;
                    });
                    keys.transition().delay(animationDuration)
                        .duration(animationDuration).
                    attr('style', 'opacity: 1');
                };

                //END - Context Key Section
                //connect

                scope.addConnect = function() {
                    var keys = scope.keyWrapper.selectAll('#ext-ctx-key-keys');
                    var le = keys[0].length - 1;
                    var data = [];

                    for (var i = 0, len = le; i < len; i++) {
                    	var kdiv = keys[0][le - i - 1];
                    	var height = kdiv.offsetTop - kdiv.parentNode.parentNode.parentNode.offsetTop + 22;
                      var width = scope.protocols[0][i].parentNode.clientWidth - scope.protocols[0][i].offsetLeft + scope.protocols[0][i].offsetParent.offsetLeft - (scope.protocols[0][i].clientWidth / 2) + 6;
                        var dim = {
                            h: height,
                            w: width
                        };
                        data.push(dim);
                    }

                    scope.arrowsCell.selectAll('.ext-connect').remove();
                    scope.arrowsCell.selectAll('.ext-connect')
                        .data(data)
                        .enter()
                        .append('div')
                        .attr('class', 'ext-connect')
                        .attr('style', function(d) {
                            var style = 'width:' + d.w + 'px ; height:' + d.h + 'px';
                            return style;
                        });
                };

                //end connect
                scope.$watch('ctx', function(newData) {

                    if (!_.isUndefined(newData) && newData !== null) {
                        if (newData.key.length === 1) {
                            scope.init();
                        } else if (newData.key.length > 1) {
                            if(newData.key.length === 2){
                                scope.pack.select('#left-box')
                                    .transition()
                                    .attr('style', 'background-position:left bottom');
                            }

                            scope.protocols.filter(function(d, i) {
                                    return i === newData.key.length - 2; //select only prot by index (-2 due to initial size of array is 1)
                                })
                                .transition().delay(animationDuration)
                                .duration(animationDuration)
                                .attr('style', 'background-position:left bottom');
                            if(newData.key.length === scope.protocols[0].length +1 ){
                                scope.pack.select('#right-box')
                                    .transition().delay(animationDuration * 2)
                                    .duration(animationDuration )
                                    .attr('style', 'background-position:left bottom');
                            }
                            scope.addKey();
                            scope.addConnect();
                        }

                    }else{
                    	d3.select('.ext-container').remove();
                    }

                }, true);

            }
        };
    });
<commit_msg>Fixed witdhs of packets in extraction view.<commit_after>'use strict';

/**
 * @ngdoc directive for Simulation Extraction View Animation
 * @name flowsimUiApp.directive:fgextraction
 * @description
 * # fgextraction
 */
angular.module('flowsimUiApp')
    .directive('fgExtraction', function() {
        return {
            replace: true,
            restrict: 'EA',
            scope: {
                ctx: '='
            },
            link: function postLink(scope, element, attrs) {
            	var animationDuration = parseInt(attrs.animationDuration) || 500;

            	scope.protocols = null;
            	scope.keys = null;
                scope.init = function() {

                    var container = d3.select(element[0])
                        .append('div')
                        .attr('class', 'ext-container');
                    var firstRow = container.append('div').attr('class', 'ext-row');
                    var secondRow = container.append('div').attr('class', 'ext-row');
                    var packetHolderCell = firstRow.append('div').attr('class', 'ext-left');
                    scope.arrowsCell = secondRow.append('div').attr('class', 'ext-left');
                    var contextKeyCell = secondRow.append('div').attr('class', 'ext-right');
                    //Packet Section
                    var packetWrapper = packetHolderCell
                        .append('div')
                        .attr('id', 'packetIndicator')
                        .attr('style', 'width:450px;')

                    .attr('class', 'rnn-holder ctx-key-context')
                        .text('Decoder');

                    scope.pack = packetWrapper.append('div')
                        .attr('class', 'rnn-stack');
                    scope.pack.append('div')
                        .attr('id', 'left-box')
                        .attr('class', 'rnn-item ext-pack-header ext-pack-left')
                        .text('\u00A0\u00A0\u00A0');
                    scope.protocols = scope.pack.selectAll('#rnn-item')
                        .data(scope.ctx.packet.protocols)
                        .enter()
                        .append('div')
                        .attr('style',function (d){
                            return 'width:' + d.bytes*100.0/scope.ctx.packet.bytes + '%';
                        })
                        .attr('id','rnn-item')
                        .attr('class', 'rnn-item ext-pack-header');

                    scope.pack.append('div')
                        .attr('class', 'rnn-item ext-pack-header ext-pack-right')
                        .attr('id', 'right-box')
                        .text('\u00A0\u00A0\u00A0');
                    scope.protocols.append('div')
                        .attr('class', 'rnn-item rnn-title')
                        .attr('style','width:450px')
                        .text(function(d) {
                            return d.name;
                        });
                    //END - Packet Section

                    //Context Key Section
                    var ctxRoot = contextKeyCell.append('div');
                    ctxRoot.append('div').attr('class', 'ctx-key-context').text('Context');
                    var ctxHeader = ctxRoot.append('div').attr('class', 'ctx-key-header');
                    ctxHeader.append('div').attr('style', 'padding-left:10px').text('Key');
                    scope.keyWrapper = ctxHeader.append('div');
                    scope.addKey();
                };
                scope.addKey = function() {

                    var keys = scope.keyWrapper.selectAll('#ext-ctx-key-keys')
                        .data(scope.ctx.key)
                        .enter()
                        .insert('div', ':first-child')
                        .attr('id', 'ext-ctx-key-keys')
                        .attr('class', function(d, i) {
                            var cls = i % 2 ? 'ctx-key-color-prim' : 'ctx-key-color-sec';
                            return 'ctx-key-keys ' + cls;
                        })
                        .attr('style', 'opacity: 0');

                    keys.append('div').selectAll('#ext-ctx-key-td')
                        .data(function(d) {
                            return d.attrs;
                        })
                        .enter()
                        .append('div')
                        .attr('id','ext-ctx-key-td')
                        .attr('class', 'ctx-key-td')
                        .text(function(d) {
                            return d.name + ' : ' + d.value;
                        });
                    keys.append('div').attr('class', 'ctx-key-name').text(function(d) {
                        return d.name;
                    });
                    keys.transition().delay(animationDuration)
                        .duration(animationDuration).
                    attr('style', 'opacity: 1');
                };

                //END - Context Key Section
                //connect

                scope.addConnect = function() {
                    var keys = scope.keyWrapper.selectAll('#ext-ctx-key-keys');
                    var le = keys[0].length - 1;
                    var data = [];

                    for (var i = 0, len = le; i < len; i++) {
                    	var kdiv = keys[0][le - i - 1];
                    	var height = kdiv.offsetTop - kdiv.parentNode.parentNode.parentNode.offsetTop + 22;
                      var width = scope.protocols[0][i].parentNode.clientWidth - scope.protocols[0][i].offsetLeft + scope.protocols[0][i].offsetParent.offsetLeft - (scope.protocols[0][i].clientWidth / 2) + 6;
                        var dim = {
                            h: height,
                            w: width
                        };
                        data.push(dim);
                    }

                    scope.arrowsCell.selectAll('.ext-connect').remove();
                    scope.arrowsCell.selectAll('.ext-connect')
                        .data(data)
                        .enter()
                        .append('div')
                        .attr('class', 'ext-connect')
                        .attr('style', function(d) {
                            var style = 'width:' + d.w + 'px ; height:' + d.h + 'px';
                            return style;
                        });
                };

                //end connect
                scope.$watch('ctx', function(newData) {

                    if (!_.isUndefined(newData) && newData !== null) {
                        if (newData.key.length === 1) {
                            scope.init();
                        } else if (newData.key.length > 1) {
                            if(newData.key.length === 2){
                                scope.pack.select('#left-box')
                                    .transition()
                                    .attr('style', function(){
                                        return 'width:'+this.style.width + '%;background-position:left bottom;';
                                    });
                            }

                            scope.protocols.filter(function(d, i) {
                                    return i === newData.key.length - 2; //select only prot by index (-2 due to initial size of array is 1)
                                })
                                .transition().delay(animationDuration)
                                .duration(animationDuration)
                                .attr('style', function(){
                                    return 'width:'+this.style.width + '%;background-position:left bottom;';
                                });
                            if(newData.key.length === scope.protocols[0].length +1 ){
                                scope.pack.select('#right-box')
                                    .transition().delay(animationDuration * 2)
                                    .duration(animationDuration )
                                    .attr('style', function(){
                                        return 'width:'+this.style.width + '%;background-position:left bottom;';
                                    });
                            }
                            scope.addKey();
                            scope.addConnect();
                        }

                    }else{
                    	d3.select('.ext-container').remove();
                    }

                }, true);

            }
        };
    });
<|endoftext|>


<commit_before>// ==UserScript==
// @name         ViperGirls Images
// @namespace    https://nindogo.tumblr.com/
// @version      20200402
// @description  Link to the actual image in vipergirls.
// @require         https://gist.githubusercontent.com/raw/2625891/waitForKeyElements.js
//                  The previous require is from a script of Brock Adams (Thanks to him!)
// @author       nindogo
// @match        http://vipergirls.to/*
// @match        https://vipergirls.to/*
// @grant           GM_xmlhttpRequest
// @connect         turboimagehost.com
// @connect         imagebam.com
// @connect         imx.to
// @downloadURL     https://github.com/nindogo/test_repo/raw/master/vipergirlsImages.user.js
// ==/UserScript==

// imx.to
waitForKeyElements('a>img[src^="https://imx.to/u/t/"', process_imx_to);
waitForKeyElements('a>img[src^="http://imx.to/u/t/"', process_imx_to);
waitForKeyElements('a>img[src^="https://imx.to/upload/small/"', process_imxto_2);
waitForKeyElements('a>img[src^="http://imx.to/upload/small/"', process_imxto_2);

// TurboImageHost
waitForKeyElements('a[href^="https://www.turboimagehost.com/"', process_turboimage);
waitForKeyElements('a[href^="http://www.turboimagehost.com/"', process_turboimage);

// ImageBam
waitForKeyElements('a[href^="http://www.imagebam.com/image/"', process_imagebam);

// AcidImg
waitForKeyElements('a[href^="https://acidimg.cc/"', process_acidimg);

// PimpAndHost
waitForKeyElements('a[href^="https://pimpandhost.com/image/"', process_pimpandhost);

// PixHost
waitForKeyElements('a[href^="https://pixhost.to/show/"', process_pixhost);

function process_imx_to(jNode){
    jNode[0].parentNode.href = jNode[0].src.replace('/t/', '/i/');
}

function process_imxto_2(jNode){
//     console.log(jNode[0].src)
/*     console.log(jNode[0].parentNode.href) */
    var site_url = jNode[0].src
    GM_xmlhttpRequest({
        method: 'GET',
        url: site_url,
        context: jNode,
        onload: function(response){
            response.context[0].parentNode.href = response.finalUrl.replace('/t/', '/i/')
        }
    })
}

function process_turboimage(jNode){
    var img_page = jNode[0].childNodes[0].src;
    var site_url = jNode[0].href;
    var re_link = '<meta property="og:image" content="(.*?)"'

    GM_xmlhttpRequest({
        method: 'GET',
        url: site_url,
        context: jNode,
        onload: function(response){
//             var this_page = response.responseText;
//             var img_url = this_page.match(re_link)[1]
//             response.context[0].href = img_url
            response.context[0].href = response.responseText.match(re_link)[1]
        }
    })
}

function process_imagebam(jNode){
    var img_page = jNode[0].childNodes[0].src;
    var site_url = jNode[0].href;
    var re_link = '<meta property="og:image" content="(.*?)"'

    GM_xmlhttpRequest({
        method: 'GET',
        url: site_url,
        context: jNode,
        onload: function(response){
//             var this_page = response.responseText;
//             var img_url = this_page.match(re_link)[1]
//             response.context[0].href = img_url
            response.context[0].href = response.responseText.match(re_link)[1]
        }
    })
}

function process_acidimg(jNode) {
//     console.log(jNode[0])
    jNode[0].href = jNode[0].childNodes[0].src.replace('/upload/small/', '/upload/big/')
//     console.log(jNode[0].childNodes)

}

function process_pimpandhost(jNode) {
    function replace_url(match, p1, offset, string){
        return string.replace('_s.', '_l.')
    }

    var replacer = jNode[0].childNodes[0].src.replace(/http.*?\/pimpandhost\.com\/.*?\/[0-9]+?(_s\.).../, replace_url)
    if (replacer) {
        jNode[0].href = replacer
    }
}

function process_pixhost(jNode) {
    function replace_url(match, p1, p2, offset, string) {
        return p1 + 'img' + p2
    }
    var img_url = jNode[0].childNodes[0].src.replace('/thumbs/', '/images/').match(/http.*?t[0-9]*?\.pixhost\.to.*/)
    jNode[0].href = img_url.input.replace(/(http.*?)t([0-9]*?\.pixhost.to.*)/, replace_url)
}
<commit_msg>Added imgbox<commit_after>// ==UserScript==
// @name            ViperGirls Images
// @namespace       https://nindogo.tumblr.com/
// @version         20200403
// @description     Link to the actual image in vipergirls.
// @require         https://gist.githubusercontent.com/raw/2625891/waitForKeyElements.js
//                  The previous require is from a script of Brock Adams (Thanks to him!)
// @author          nindogo
// @match           http://vipergirls.to/*
// @match           https://vipergirls.to/*
// @grant           GM_xmlhttpRequest
// @connect         turboimagehost.com
// @connect         imagebam.com
// @connect         imx.to
// @downloadURL     https://github.com/nindogo/test_repo/raw/master/vipergirlsImages.user.js
// ==/UserScript==

// imx.to
waitForKeyElements('a>img[src^="https://imx.to/u/t/"', process_imx_to);
waitForKeyElements('a>img[src^="http://imx.to/u/t/"', process_imx_to);
waitForKeyElements('a>img[src^="https://imx.to/upload/small/"', process_imxto_2);
waitForKeyElements('a>img[src^="http://imx.to/upload/small/"', process_imxto_2);

// TurboImageHost
waitForKeyElements('a[href^="https://www.turboimagehost.com/"', process_turboimage);
waitForKeyElements('a[href^="http://www.turboimagehost.com/"', process_turboimage);

// ImageBam
waitForKeyElements('a[href^="https://www.imagebam.com/image/"', process_imagebam);
waitForKeyElements('a[href^="http://www.imagebam.com/image/"', process_imagebam);

// AcidImg
waitForKeyElements('a[href^="https://acidimg.cc/"', process_acidimg);
waitForKeyElements('a[href^="http://acidimg.cc/"', process_acidimg);

// PimpAndHost
waitForKeyElements('a[href^="https://pimpandhost.com/image/"', process_pimpandhost);
waitForKeyElements('a[href^="http://pimpandhost.com/image/"', process_pimpandhost);

// PixHost
waitForKeyElements('a[href^="https://pixhost.to/show/"', process_pixhost);
waitForKeyElements('a[href^="http://pixhost.to/show/"', process_pixhost);

// ImgBox
waitForKeyElements('a[href^="https://imgbox.com/"', process_imgbox);
waitForKeyElements('a[href^="http://imgbox.com/"', process_imgbox);

function process_imx_to(jNode){
    jNode[0].parentNode.href = jNode[0].src.replace('/t/', '/i/');
}

function process_imxto_2(jNode){
//     console.log(jNode[0].src)
/*     console.log(jNode[0].parentNode.href) */
    var site_url = jNode[0].src
    GM_xmlhttpRequest({
        method: 'GET',
        url: site_url,
        context: jNode,
        onload: function(response){
            response.context[0].parentNode.href = response.finalUrl.replace('/t/', '/i/')
        }
    })
}

function process_turboimage(jNode){
    var img_page = jNode[0].childNodes[0].src;
    var site_url = jNode[0].href;
    var re_link = '<meta property="og:image" content="(.*?)"'

    GM_xmlhttpRequest({
        method: 'GET',
        url: site_url,
        context: jNode,
        onload: function(response){
//             var this_page = response.responseText;
//             var img_url = this_page.match(re_link)[1]
//             response.context[0].href = img_url
            response.context[0].href = response.responseText.match(re_link)[1]
        }
    })
}

function process_imagebam(jNode){
    var img_page = jNode[0].childNodes[0].src;
    var site_url = jNode[0].href;
    var re_link = '<meta property="og:image" content="(.*?)"'

    GM_xmlhttpRequest({
        method: 'GET',
        url: site_url,
        context: jNode,
        onload: function(response){
//             var this_page = response.responseText;
//             var img_url = this_page.match(re_link)[1]
//             response.context[0].href = img_url
            response.context[0].href = response.responseText.match(re_link)[1]
        }
    })
}

function process_acidimg(jNode) {
//     console.log(jNode[0])
    jNode[0].href = jNode[0].childNodes[0].src.replace('/upload/small/', '/upload/big/')
//     console.log(jNode[0].childNodes)

}

function process_pimpandhost(jNode) {
    function replace_url(match, p1, offset, string){
        return string.replace('_s.', '_l.')
    }

    var replacer = jNode[0].childNodes[0].src.replace(/http.*?\/pimpandhost\.com\/.*?\/[0-9]+?(_s\.).../, replace_url)
    if (replacer) {
        jNode[0].href = replacer
    }
}

function process_pixhost(jNode) {
    function replace_url(match, p1, p2, offset, string) {
        return p1 + 'img' + p2
    }
    var img_url = jNode[0].childNodes[0].src.replace('/thumbs/', '/images/').match(/http.*?t[0-9]*?\.pixhost\.to.*/)
    jNode[0].href = img_url.input.replace(/(http.*?)t([0-9]*?\.pixhost.to.*)/, replace_url)
}

function process_imgbox(jNode) {
    jNode[0].href = jNode[0].childNodes[0].src.replace('_t.', '_o.').replace('/thumbs', '/images');
}
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const OfflinePlugin = require('offline-plugin');

/**
 * Webpack Constants
 */
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(commonConfig.metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: false
});

module.exports = webpackMerge(commonConfig, {

  /**
   * Switch loaders to debug mode.
   *
   * See: http://webpack.github.io/docs/configuration.html#debug
   */
  debug: false,

  /**
   * Developer tool to enhance debugging
   *
   * See: http://webpack.github.io/docs/configuration.html#devtool
   * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
   */
  devtool: 'source-map',

  /**
   * Options affecting the output of the compilation.
   *
   * See: http://webpack.github.io/docs/configuration.html#output
   */
  output: {

    /**
     * The output directory as absolute path (required).
     *
     * See: http://webpack.github.io/docs/configuration.html#output-path
     */
    path: helpers.root('dist'),

    /**
     * Specifies the name of each output file on disk.
     * IMPORTANT: You must not specify an absolute path here!
     *
     * See: http://webpack.github.io/docs/configuration.html#output-filename
     */
    filename: 'assets/[name].[chunkhash].bundle.js',

    /**
     * The filename of the SourceMaps for the JavaScript files.
     * They are inside the output.path directory.
     *
     * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
     */
    sourceMapFilename: 'assets/[name].[chunkhash].bundle.map',

    /**
     * The filename of non-entry chunks as relative path
     * inside the output.path directory.
     *
     * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
     */
    chunkFilename: 'assets/[id].[chunkhash].chunk.js'

  },

  /**
   * Add additional plugins to the compiler.
   *
   * See: http://webpack.github.io/docs/configuration.html#plugins
   */
  plugins: [

    /**
     * Plugin: WebpackMd5Hash
     * Description: Plugin to replace a standard webpack chunkhash with md5.
     *
     * See: https://www.npmjs.com/package/webpack-md5-hash
     */
    new WebpackMd5Hash(),

    /**
     * Plugin: DedupePlugin
     * Description: Prevents the inclusion of duplicate code into your bundle
     * and instead applies a copy of the function at runtime.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
     * See: https://github.com/webpack/docs/wiki/optimization#deduplication
     */
    new DedupePlugin(),

    /**
     * Plugin: DefinePlugin
     * Description: Define free variables.
     * Useful for having development builds with debug logging or adding global constants.
     *
     * Environment helpers
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
     */
    // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
    new DefinePlugin({
      'ENV': JSON.stringify(METADATA.ENV),
      'HMR': METADATA.HMR,
      'process.env': {
        'ENV': JSON.stringify(METADATA.ENV),
        'NODE_ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
      }
    }),

    /**
     * Plugin: UglifyJsPlugin
     * Description: Minimize all JavaScript output of chunks.
     * Loaders are switched into minimizing mode.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
     */
    // NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
    new UglifyJsPlugin({
      // beautify: true, //debug
      // mangle: false, //debug
      // dead_code: false, //debug
      // unused: false, //debug
      // deadCode: false, //debug
      // compress: {
      //   screw_ie8: true,
      //   keep_fnames: true,
      //   drop_debugger: false,
      //   dead_code: false,
      //   unused: false
      // }, // debug
      // comments: true, //debug

      beautify: false, //prod
      mangle: { screw_ie8 : true }, //prod
      compress: { screw_ie8: true }, //prod
      comments: false //prod
    }),

    /**
     * Plugin: NormalModuleReplacementPlugin
     * Description: Replace resources that matches resourceRegExp with newResource
     *
     * See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
     */

    new NormalModuleReplacementPlugin(
      /angular2-hmr/,
      helpers.root('config/modules/angular2-hmr-prod.js')
    ),

    new OfflinePlugin()

  ],

  /**
   * Static analysis linter for TypeScript advanced options configuration
   * Description: An extensible linter for the TypeScript language.
   *
   * See: https://github.com/wbuchwalter/tslint-loader
   */
  tslint: {
    emitErrors: true,
    failOnHint: true,
    resourcePath: 'src'
  },

  /**
   * Html loader advanced options
   *
   * See: https://github.com/webpack/html-loader#advanced-options
   */
  // TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
  htmlLoader: {
    minimize: true,
    removeAttributeQuotes: false,
    caseSensitive: true,
    customAttrSurround: [
      [/#/, /(?:)/],
      [/\*/, /(?:)/],
      [/\[?\(?/, /(?:)/]
    ],
    customAttrAssign: [/\)?\]?=/]
  },

  /*
   * Include polyfills or mocks for various node stuff
   * Description: Node configuration
   *
   * See: https://webpack.github.io/docs/configuration.html#node
   */
  node: {
    global: 'window',
    crypto: 'empty',
    process: false,
    module: false,
    clearImmediate: false,
    setImmediate: false
  }

});
<commit_msg>fix: fixes service worker cache<commit_after>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const OfflinePlugin = require('offline-plugin');

/**
 * Webpack Constants
 */
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(commonConfig.metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: false
});

module.exports = webpackMerge(commonConfig, {

  /**
   * Switch loaders to debug mode.
   *
   * See: http://webpack.github.io/docs/configuration.html#debug
   */
  debug: false,

  /**
   * Developer tool to enhance debugging
   *
   * See: http://webpack.github.io/docs/configuration.html#devtool
   * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
   */
  devtool: 'source-map',

  /**
   * Options affecting the output of the compilation.
   *
   * See: http://webpack.github.io/docs/configuration.html#output
   */
  output: {

    /**
     * The output directory as absolute path (required).
     *
     * See: http://webpack.github.io/docs/configuration.html#output-path
     */
    path: helpers.root('dist'),

    /**
     * Specifies the name of each output file on disk.
     * IMPORTANT: You must not specify an absolute path here!
     *
     * See: http://webpack.github.io/docs/configuration.html#output-filename
     */
    filename: 'assets/[name].[chunkhash].bundle.js',

    /**
     * The filename of the SourceMaps for the JavaScript files.
     * They are inside the output.path directory.
     *
     * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
     */
    sourceMapFilename: 'assets/[name].[chunkhash].bundle.map',

    /**
     * The filename of non-entry chunks as relative path
     * inside the output.path directory.
     *
     * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
     */
    chunkFilename: 'assets/[id].[chunkhash].chunk.js'

  },

  /**
   * Add additional plugins to the compiler.
   *
   * See: http://webpack.github.io/docs/configuration.html#plugins
   */
  plugins: [

    /**
     * Plugin: WebpackMd5Hash
     * Description: Plugin to replace a standard webpack chunkhash with md5.
     *
     * See: https://www.npmjs.com/package/webpack-md5-hash
     */
    new WebpackMd5Hash(),

    /**
     * Plugin: DedupePlugin
     * Description: Prevents the inclusion of duplicate code into your bundle
     * and instead applies a copy of the function at runtime.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
     * See: https://github.com/webpack/docs/wiki/optimization#deduplication
     */
    new DedupePlugin(),

    /**
     * Plugin: DefinePlugin
     * Description: Define free variables.
     * Useful for having development builds with debug logging or adding global constants.
     *
     * Environment helpers
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
     */
    // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
    new DefinePlugin({
      'ENV': JSON.stringify(METADATA.ENV),
      'HMR': METADATA.HMR,
      'process.env': {
        'ENV': JSON.stringify(METADATA.ENV),
        'NODE_ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
      }
    }),

    /**
     * Plugin: UglifyJsPlugin
     * Description: Minimize all JavaScript output of chunks.
     * Loaders are switched into minimizing mode.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
     */
    // NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
    new UglifyJsPlugin({
      // beautify: true, //debug
      // mangle: false, //debug
      // dead_code: false, //debug
      // unused: false, //debug
      // deadCode: false, //debug
      // compress: {
      //   screw_ie8: true,
      //   keep_fnames: true,
      //   drop_debugger: false,
      //   dead_code: false,
      //   unused: false
      // }, // debug
      // comments: true, //debug

      beautify: false, //prod
      mangle: { screw_ie8 : true }, //prod
      compress: { screw_ie8: true }, //prod
      comments: false //prod
    }),

    /**
     * Plugin: NormalModuleReplacementPlugin
     * Description: Replace resources that matches resourceRegExp with newResource
     *
     * See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
     */

    new NormalModuleReplacementPlugin(
      /angular2-hmr/,
      helpers.root('config/modules/angular2-hmr-prod.js')
    ),

    new OfflinePlugin({
      updateStrategy: 'all',
      version: 'v2'
    })

  ],

  /**
   * Static analysis linter for TypeScript advanced options configuration
   * Description: An extensible linter for the TypeScript language.
   *
   * See: https://github.com/wbuchwalter/tslint-loader
   */
  tslint: {
    emitErrors: true,
    failOnHint: true,
    resourcePath: 'src'
  },

  /**
   * Html loader advanced options
   *
   * See: https://github.com/webpack/html-loader#advanced-options
   */
  // TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
  htmlLoader: {
    minimize: true,
    removeAttributeQuotes: false,
    caseSensitive: true,
    customAttrSurround: [
      [/#/, /(?:)/],
      [/\*/, /(?:)/],
      [/\[?\(?/, /(?:)/]
    ],
    customAttrAssign: [/\)?\]?=/]
  },

  /*
   * Include polyfills or mocks for various node stuff
   * Description: Node configuration
   *
   * See: https://webpack.github.io/docs/configuration.html#node
   */
  node: {
    global: 'window',
    crypto: 'empty',
    process: false,
    module: false,
    clearImmediate: false,
    setImmediate: false
  }

});
<|endoftext|>