<commit_before>function is_quote(c) {
  return c == '"' || c == "'";
}

function last(array) {
  return array[array.length - 1];
}

export default function parse(input) {
  let c = '';
  let temp = '';
  let name = '';
  let stack = [];
  let result = {
    textures: []
  };
  let w = '';
  let words = [];
  let i = 0;
  while ((c = input[i++]) !== undefined) {
    if (c == '"' || c == "'") {
      if (last(stack) == c) {
        stack.pop();
      } else {
        stack.push(c);
      }
    }
    if (c == '{' && !is_quote(last(stack)))  {
      if (!stack.length) {
        name = temp;
        temp = '';
      } else {
        temp += c;
      }
      stack.push(c);
    }
    else if (c == '}' && !is_quote(last(stack)))  {
      stack.pop();
      if (!stack.length) {
        let key = name.trim();
        let value = temp.trim();
        if (key.length) {
          if (key.startsWith('texture')) {
            result.textures.push({
              name: key,
              value: value
            });
          } else {
            result[key] = value;
          }
        }
        name = temp = '';
      } else {
        temp += c;
      }
    }
    else {
      if (/\s/.test(c) && w.length) {
        words.push(w);
        w = '';
        let need_break =
          (words[words.length - 3] == '#define') ||
          (words[words.length - 2] == '#ifdef') ||
          (words[words.length - 1] == '#else') ||
          (words[words.length - 1] == '#endif');

        if (need_break) {
          temp = temp + '\n';
        }
      } else {
        w += c;
      }
      temp += c;
    }
  }

  if (result.fragment === undefined) {
    return {
      fragment: input,
      textures: []
    }
  }

  return result;
}
<commit_msg>Fix reading shaders from CSS variables.<commit_after>function is_quote(c) {
  return c == '"' || c == "'";
}

function last(array) {
  return array[array.length - 1];
}

export default function parse(input) {
  let c = '';
  let temp = '';
  let name = '';
  let stack = [];
  let result = {
    textures: []
  };
  let w = '';
  let words = [];
  let i = 0;
  while ((c = input[i++]) !== undefined) {
    if (c == '"' || c == "'") {
      if (last(stack) == c) {
        stack.pop();
      } else {
        stack.push(c);
      }
    }
    if (c == '{' && !is_quote(last(stack)))  {
      if (!stack.length) {
        name = temp;
        temp = '';
      } else {
        temp += c;
      }
      stack.push(c);
    }
    else if (c == '}' && !is_quote(last(stack)))  {
      stack.pop();
      if (!stack.length) {
        let key = name.trim()
        let value = temp.trim().replace(/^\(+|\)+$/g, '');
        if (key.length) {
          if (key.startsWith('texture')) {
            result.textures.push({
              name: key,
              value: value
            });
          } else {
            result[key] = value;
          }
        }
        name = temp = '';
      } else {
        temp += c;
      }
    }
    else {
      if (/\s/.test(c) && w.length) {
        words.push(w);
        w = '';
        let need_break =
          (words[words.length - 3] == '#define') ||
          (words[words.length - 2] == '#ifdef') ||
          (words[words.length - 1] == '#else') ||
          (words[words.length - 1] == '#endif');

        if (need_break) {
          temp = temp + '\n';
        }
      } else {
        w += c;
      }
      temp += c;
    }
  }

  if (result.fragment === undefined) {
    return {
      fragment: input,
      textures: []
    }
  }

  return result;
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Parses and serializes HTTP headers, used as parameters, i.e. namespaced
 */

const titleize = require('underscore.string/titleize');
const { chain, mapKeys } = require('lodash');

const NAMESPACE = require('../../utilities').CONSTANTS.NAMESPACE;
const HEADERS_NAMESPACE = `x-${NAMESPACE.toLowerCase()}-`;
// Headers that provide application data, not just HTTP protocol semantics
// Must all be lowercase
const PARAM_HEADERS = [
];

/**
 * Returns a request's or response's HTTP headers
 * Only returns the namespaced ones, e.g. X-MYNAMESPACE-HEADER, and remove their namespace
 * Also returns the headers that provide application data, not just HTTP protocol semantics, according to a whitelist.
 *
 * @param {req|res} reqOrRes - HTTP request or response object
 * @returns {object} appHeaders
 */
const parse = function (reqOrRes) {
  const headers = getHeaders(reqOrRes);
  const appHeaders = getAppHeaders(headers);

  return appHeaders;
};

// Returns request or response headers
// Note that node.js automatically converts header names to lowercase
const getHeaders = function (reqOrRes) {
  // Is a response
  if (reqOrRes.getHeaders) {
    return reqOrRes.getHeaders();
  // Is a request
  } else {
    return reqOrRes.headers || {};
  }
};
const getHeader = function (reqOrRes, headerName) {
  return getHeaders(reqOrRes)[headerName.toLowerCase()];
};

// Filters headers with only the headers whose name starts with X-NAMESPACE-
const getAppHeaders = function (headers) {
  const appHeaderRegex = new RegExp(`^${HEADERS_NAMESPACE}`);
  return chain(headers)
    .pickBy((_, headerName) => appHeaderRegex.test(headerName) || PARAM_HEADERS.includes(headerName))
    .mapKeys((_, headerName) => headerName.replace(appHeaderRegex, ''))
    .value();
};

/**
 * Take a plain object of parameters, and transforms it in an object that can be set as headers to a HTTP request or response
 * Namespaces headers names, e.g. X-Mynamespace-Header, unless part of a whitelist
 *
 * @param {object} appHeaders
 * @returns {object} headers
 */
const serialize = function (headers) {
  return mapKeys(headers, (_, headerName) => {
    if (!PARAM_HEADERS.includes(headerName.toLowerCase())) {
      headerName = `${HEADERS_NAMESPACE}${headerName}`;
    }
    // Make sure case is X-Mynamespace-Header
    return titleize(headerName);
  });
};

module.exports = {
  httpAppHeaders: {
    parse,
    serialize,
  },
  httpHeaders: {
    get: getHeader,
    getAll: getHeaders,
  },
};<commit_msg>Fix line width<commit_after>'use strict';

/**
 * Parses and serializes HTTP headers, used as parameters, i.e. namespaced
 */

const titleize = require('underscore.string/titleize');
const { chain, mapKeys } = require('lodash');

const NAMESPACE = require('../../utilities').CONSTANTS.NAMESPACE;
const HEADERS_NAMESPACE = `x-${NAMESPACE.toLowerCase()}-`;
// Headers that provide application data, not just HTTP protocol semantics
// Must all be lowercase
const PARAM_HEADERS = [
];

/**
 * Returns a request's or response's HTTP headers
 * Only returns the namespaced ones, e.g. X-MYNAMESPACE-HEADER,
 * and remove their namespace
 * Also returns the headers that provide application data,
 * not just HTTP protocol semantics, according to a whitelist.
 *
 * @param {req|res} reqOrRes - HTTP request or response object
 * @returns {object} appHeaders
 */
const parse = function (reqOrRes) {
  const headers = getHeaders(reqOrRes);
  const appHeaders = getAppHeaders(headers);

  return appHeaders;
};

// Returns request or response headers
// Note that node.js automatically converts header names to lowercase
const getHeaders = function (reqOrRes) {
  // Is a response
  if (reqOrRes.getHeaders) {
    return reqOrRes.getHeaders();
  // Is a request
  } else {
    return reqOrRes.headers || {};
  }
};
const getHeader = function (reqOrRes, headerName) {
  return getHeaders(reqOrRes)[headerName.toLowerCase()];
};

// Filters headers with only the headers whose name starts with X-NAMESPACE-
const getAppHeaders = function (headers) {
  const appHeaderRegex = new RegExp(`^${HEADERS_NAMESPACE}`);
  return chain(headers)
    .pickBy((_, headerName) => appHeaderRegex.test(headerName) ||
      PARAM_HEADERS.includes(headerName))
    .mapKeys((_, headerName) => headerName.replace(appHeaderRegex, ''))
    .value();
};

/**
 * Take a plain object of parameters, and transforms it in an object that
 * can be set as headers to a HTTP request or response
 * Namespaces headers names, e.g. X-Mynamespace-Header,
 * unless part of a whitelist
 *
 * @param {object} appHeaders
 * @returns {object} headers
 */
const serialize = function (headers) {
  return mapKeys(headers, (_, headerName) => {
    if (!PARAM_HEADERS.includes(headerName.toLowerCase())) {
      headerName = `${HEADERS_NAMESPACE}${headerName}`;
    }
    // Make sure case is X-Mynamespace-Header
    return titleize(headerName);
  });
};

module.exports = {
  httpAppHeaders: {
    parse,
    serialize,
  },
  httpHeaders: {
    get: getHeader,
    getAll: getHeaders,
  },
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Parses and serializes HTTP headers, used as parameters, i.e. namespaced
 */

const { titleize, dasherize } = require('underscore.string');
const { mapKeys } = require('lodash');
const parsePreferHeader = require('parse-prefer-header');

const { EngineError } = require('../../error');

/**
 * Returns a request's or response's HTTP headers
 * Only returns the namespaced ones, e.g. X-MYNAMESPACE-HEADER,
 * and remove their namespace
 * Also returns the headers that provide application data,
 * not just HTTP protocol semantics, according to a whitelist.
 *
 * @param {req|res} reqOrRes - HTTP request or response object
 * @param {string} projectName - MYNAMESPACE
 * @returns {object} appHeaders
 */
const parse = function (reqOrRes, projectName) {
  const headers = getHeaders(reqOrRes);
  const nonAppHeaders = getNonAppHeaders(headers, projectName);
  const appHeaders = getAppHeaders(headers, projectName);

  return { nonAppHeaders, appHeaders };
};

// Returns request or response headers
// Note that node.js automatically converts header names to lowercase
const getHeaders = function (reqOrRes) {
  // Is a response
  if (reqOrRes.getHeaders) {
    return reqOrRes.getHeaders();
  // Is a request
  } else {
    return reqOrRes.headers || {};
  }
};

// Filters headers with only the headers whose name starts with X-NAMESPACE-
const getAppHeaders = function (headers, projectName) {
  const headersNamespace = `x-${dasherize(projectName)}-`;
  // We don't need to RegExp-escape since `headersNamespace` only contains
  // ASCII letters, numbers and dashes
  const appHeaderRegex = new RegExp(`^${headersNamespace}`);
  return Object.entries(headers)
    .filter(([name]) => appHeaderRegex.test(name))
    .map(([name, value]) => {
      const shortName = name.replace(appHeaderRegex, '');
      return { [shortName]: value };
    })
    .reduce((memo, obj) => Object.assign(memo, obj), {});
};

// Inverse
const getNonAppHeaders = function (headers, projectName) {
  const headersNamespace = `x-${dasherize(projectName)}-`;
  const appHeaderRegex = new RegExp(`^${headersNamespace}`);
  return Object.entries(headers)
    .filter(([name]) => !appHeaderRegex.test(name))
    .map(([name, value]) => ({ [name]: value }))
    .reduce((memo, obj) => Object.assign(memo, obj), {});
};

// Parses Prefer HTTP header
const parsePrefer = function ({ headers: { prefer } }) {
  if (!prefer) { return {}; }

  try {
    return parsePreferHeader(prefer);
  } catch (error) {
    const message = `HTTP 'Prefer' header value syntax error: ${prefer}`;
    throw new EngineError(message, { reason: 'INPUT_VALIDATION' });
  }
};

// Set HTTP header, ready to be sent with response
const send = function ({ specific: { res }, headers = {} }) {
  for (const [name, value] of Object.entries(headers)) {
    res.setHeader(name, value);
  }
};

module.exports = {
  httpHeaders: {
    parse,
    parsePrefer,
    send,
  },
};
<commit_msg>Remove dead code<commit_after>'use strict';

/**
 * Parses and serializes HTTP headers, used as parameters, i.e. namespaced
 */

const { dasherize } = require('underscore.string');
const parsePreferHeader = require('parse-prefer-header');

const { EngineError } = require('../../error');

/**
 * Returns a request's or response's HTTP headers
 * Only returns the namespaced ones, e.g. X-MYNAMESPACE-HEADER,
 * and remove their namespace
 * Also returns the headers that provide application data,
 * not just HTTP protocol semantics, according to a whitelist.
 *
 * @param {req|res} reqOrRes - HTTP request or response object
 * @param {string} projectName - MYNAMESPACE
 * @returns {object} appHeaders
 */
const parse = function (reqOrRes, projectName) {
  const headers = getHeaders(reqOrRes);
  const nonAppHeaders = getNonAppHeaders(headers, projectName);
  const appHeaders = getAppHeaders(headers, projectName);

  return { nonAppHeaders, appHeaders };
};

// Returns request or response headers
// Note that node.js automatically converts header names to lowercase
const getHeaders = function (reqOrRes) {
  // Is a response
  if (reqOrRes.getHeaders) {
    return reqOrRes.getHeaders();
  // Is a request
  } else {
    return reqOrRes.headers || {};
  }
};

// Filters headers with only the headers whose name starts with X-NAMESPACE-
const getAppHeaders = function (headers, projectName) {
  const headersNamespace = `x-${dasherize(projectName)}-`;
  // We don't need to RegExp-escape since `headersNamespace` only contains
  // ASCII letters, numbers and dashes
  const appHeaderRegex = new RegExp(`^${headersNamespace}`);
  return Object.entries(headers)
    .filter(([name]) => appHeaderRegex.test(name))
    .map(([name, value]) => {
      const shortName = name.replace(appHeaderRegex, '');
      return { [shortName]: value };
    })
    .reduce((memo, obj) => Object.assign(memo, obj), {});
};

// Inverse
const getNonAppHeaders = function (headers, projectName) {
  const headersNamespace = `x-${dasherize(projectName)}-`;
  const appHeaderRegex = new RegExp(`^${headersNamespace}`);
  return Object.entries(headers)
    .filter(([name]) => !appHeaderRegex.test(name))
    .map(([name, value]) => ({ [name]: value }))
    .reduce((memo, obj) => Object.assign(memo, obj), {});
};

// Parses Prefer HTTP header
const parsePrefer = function ({ headers: { prefer } }) {
  if (!prefer) { return {}; }

  try {
    return parsePreferHeader(prefer);
  } catch (error) {
    const message = `HTTP 'Prefer' header value syntax error: ${prefer}`;
    throw new EngineError(message, { reason: 'INPUT_VALIDATION' });
  }
};

// Set HTTP header, ready to be sent with response
const send = function ({ specific: { res }, headers = {} }) {
  for (const [name, value] of Object.entries(headers)) {
    res.setHeader(name, value);
  }
};

module.exports = {
  httpHeaders: {
    parse,
    parsePrefer,
    send,
  },
};
<|endoftext|>


<commit_before>define([
    'jquery',
    '../logging',
    '../../lib/chosen.jquery'
], function($) {
    var log = logging.getLogger('breadcrumbs');

    var init = function($el, opts) {
        // wrap elements in a DIV that will be shifted around
        var $content = $el.children()
                .wrapAll('

').parent();

        // set fixed width on content
        var width = $content.children().toArray().reduce(function(acc, el) {
            return acc + $(el).outerWidth(true);
        }, 0);
        $content.width(width);

        // shift ctrl
        var $ctrl = $('shift')
                .prependTo($el);

        var shifted = false,
            shifting = false,
            difference = 0;
        var shifter = function(toggle) {
            return function() {
                var margin;
                if (toggle) {
                    margin = shifted ? 0 : difference;
                    $content.animate({"margin-left": margin}, function() {
                        $ctrl.toggleClass('shift-right shift-left');
                        shifted = !shifted;
                    });
                } else {
                    margin = shifted ? difference : 0;
                    $content.css({"margin-left": margin});
                }
            };
        };

        var maybeshift = function() {
            // account for other stuff on the same line (100px)
            difference = $el.innerWidth() - $content.width() - 100;

            if (difference < 0) {
                // we should be shifting
                if (!shifting) {
                    shifting = true;
                    $el.addClass('shifting');
                    $ctrl.removeClass('shift-right');
                    $ctrl.addClass('shift-left');
                    $ctrl.on('click.breadcrumbs', shifter(true));
                    $ctrl.click();
                } else {
                    // a shifter that keeps state
                    shifter(false)();
                }
            } else {
                // we should not be shifting
                if (shifting) {
                    $content.animate({"margin-left": 0}, function() {
                        shifted = false;
                        shifting = false;
                        $el.removeClass('shifting');
                        $ctrl.removeClass('shift-left shift-right');
                        $ctrl.off('.breadcrumbs');
                    });
                }
            }
        };
        maybeshift();
        $(window).on('resize.breadcrumbs', maybeshift);
    };

    var pattern = {
        markup_trigger: 'nav.breadcrumbs',
        init: init
    };
    return pattern;
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>update breadcrumbs<commit_after>define([
    'jquery',
    '../logging',
    '../registry',
    '../../lib/chosen.jquery'
], function($, logging, registry) {
    var log = logging.getLogger('breadcrumbs');

    var _ = {
        name: "breadcrumbs",
        trigger: 'nav.breadcrumbs',
        init: function($el, opts) {
            if ($el.length > 1) {
                return $el.map(function() {
                    return _.init($(this), opts);
                });
            }

            // wrap elements in a DIV that will be shifted around
            var $content = $el.children()
                    .wrapAll('

').parent();

            // set fixed width on content
            var width = $content.children().toArray().reduce(function(acc, el) {
                return acc + $(el).outerWidth(true);
            }, 0);
            $content.width(width);

            // shift ctrl
            var $ctrl = $('shift')
                    .prependTo($el);

            var shifted = false,
                shifting = false,
                difference = 0;
            var shifter = function(toggle) {
                return function() {
                    var margin;
                    if (toggle) {
                        margin = shifted ? 0 : difference;
                        $content.animate({"margin-left": margin}, function() {
                            $ctrl.toggleClass('shift-right shift-left');
                            shifted = !shifted;
                        });
                    } else {
                        margin = shifted ? difference : 0;
                        $content.css({"margin-left": margin});
                    }
                };
            };

            var maybeshift = function() {
                // account for other stuff on the same line (100px)
                difference = $el.innerWidth() - $content.width() - 100;

                if (difference < 0) {
                    // we should be shifting
                    if (!shifting) {
                        shifting = true;
                        $el.addClass('shifting');
                        $ctrl.removeClass('shift-right');
                        $ctrl.addClass('shift-left');
                        $ctrl.on('click.breadcrumbs', shifter(true));
                        $ctrl.click();
                    } else {
                        // a shifter that keeps state
                        shifter(false)();
                    }
                } else {
                    // we should not be shifting
                    if (shifting) {
                        $content.animate({"margin-left": 0}, function() {
                            shifted = false;
                            shifting = false;
                            $el.removeClass('shifting');
                            $ctrl.removeClass('shift-left shift-right');
                            $ctrl.off('.breadcrumbs');
                        });
                    }
                }
            };
            maybeshift();
            $(window).on('resize.breadcrumbs', maybeshift);

            return $el;
        },
        destroy: function($el) {
            $el.off('.breadcrumbs');
        }
    };
    return registry.register(_);
});

};

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>


<commit_before>/**
 * @fileoverview Run the bootstrap service
 */

var port = 3020;
var system = require('system');
var page = require('webpage').create();
var server = require('./server').create(port);
var util = require('./util');
var module = system.args[1];
var config = system.args[2];

if (!module) {
    console.log('Missing module def');
    phantom.exit();
}

if (!config) {
    console.log('Missing config def');
    phantom.exit();
}

var url = 'http://localhost:' + port + '/' + module + '.html?config=' + config;
console.log('Bootstrapper: requesting url', url);

page.open(url, function(status) {
    console.log('got status: ' + status);

    if (status !== 'success') {
        console.log('No bs page for this module', module);
        phantom.exit();
    }

    // TODO(rrp): Generalize this bit
    // Wait for fyre-comment-stream el? (need to ensure 100% loaded somehow)
    util.waitFor(function() {
        return page.evaluate(function() {
            return document.getElementsByClassName('fyre-comment-stream').length > 0;
        });
    }, function() {
        var html = page.evaluate(function() {
            return document.getElementById('bs').innerHTML;
        });

        phantom.exit();
    });
});
<commit_msg>Settimeout for 3500ms once page ready to let it catch up with stream a bit<commit_after>/**
 * @fileoverview Run the bootstrap service
 */

var port = 3020;
var system = require('system');
var page = require('webpage').create();
var server = require('./server').create(port);
var util = require('./util');
var module = system.args[1];
var config = system.args[2];

if (!module) {
    console.log('Missing module def');
    phantom.exit();
}

if (!config) {
    console.log('Missing config def');
    phantom.exit();
}

var url = 'http://localhost:' + port + '/' + module + '.html?config=' + config;
console.log('Bootstrapper: requesting url', url);

page.open(url, function(status) {
    console.log('got status: ' + status);

    if (status !== 'success') {
        console.log('No bs page for this module', module);
        phantom.exit();
    }

    // TODO(rrp): Generalize this bit
    // Wait for fyre-comment-stream el? (need to ensure 100% loaded somehow)
    util.waitFor(function() {
        return page.evaluate(function() {
            return document.getElementsByClassName('fyre-comment-stream').length > 0;
        });
    }, function() {

        // So we wait (by default) for 3000ms for the page to catch up.
        // This allows one or two stream requests to make their way in.
        var html = page.evaluate(function() {
            setTimeout(function() {
                return document.getElementById('bs').innerHTML;
            }, 3500);
        });
        phantom.exit();
    });
});
<|endoftext|>


<commit_before>var net  = require('net');
var fs = require('fs');

function rinfo(tcpstream, data) {
    this.address = tcpstream.remoteAddress;
    this.port = tcpstream.remotePort;
    this.family = tcpstream.address().family;
    this.size = data.length;
}

exports.start = function(config, callback) {
  var server = net.createServer(function(stream) {
      stream.setEncoding('ascii');

      var buffer = '';
      stream.on('data', function(data) {
          buffer += data;
          var offset = buffer.lastIndexOf("\n");
          if (offset > -1) {
             var packet = buffer.slice(0, offset + 1);
             buffer = buffer.slice(offset + 1);
             callback(packet, new rinfo(stream, packet));
          }
      });
  });

  server.on('listening', (e) => {
    config.socket && config.socket_mod && fs.chmod(config.socket, config.socket_mod);
  });

  process.on('exit', (e) => {
      config.socket && fs.unlinkSync(config.socket);
  })

  server.listen(config.socket || config.port || 8125, config.address || undefined);
  this.server = server;
  return true;
};
<commit_msg>Do not use lambda expression.<commit_after>var net  = require('net');
var fs = require('fs');

function rinfo(tcpstream, data) {
    this.address = tcpstream.remoteAddress;
    this.port = tcpstream.remotePort;
    this.family = tcpstream.address().family;
    this.size = data.length;
}

exports.start = function(config, callback) {
  var server = net.createServer(function(stream) {
      stream.setEncoding('ascii');

      var buffer = '';
      stream.on('data', function(data) {
          buffer += data;
          var offset = buffer.lastIndexOf("\n");
          if (offset > -1) {
             var packet = buffer.slice(0, offset + 1);
             buffer = buffer.slice(offset + 1);
             callback(packet, new rinfo(stream, packet));
          }
      });
  });

  server.on('listening', function() {
    config.socket && config.socket_mod && fs.chmod(config.socket, config.socket_mod);
  });

  process.on('exit', function() {
      config.socket && fs.unlinkSync(config.socket);
  });

  server.listen(config.socket || config.port || 8125, config.address || undefined);
  this.server = server;
  return true;
};
<|endoftext|>


<commit_before>var AutoLoader = require("auto-loader");
var camel = require("to-camel-case");

module.exports = Loader;

/**
 * Loads in various files and modules
 * @parm {object} BigGulp - the main BigGulp app object
 * @constructor
 */
function Loader(BigGulp) {
	var self = this;

	if(!(this instanceof Loader))
		return new Loader(BigGulp);

	/** @private */
	self._BigGulp = BigGulp;
	self._moduleList = {};
	self._modules = {};
	self._appPath = this._BigGulp._packageInfo._BigGulp.config.absolutePath;
}

/**
 * Initializes all the tasks and registers them with Gulp
 * @private
 */
Loader.prototype._initTasks = function() {
	var BigGulp = this._BigGulp,
		BaseTask = this._BigGulp._core.BaseTask;

	_.forEach(this._BigGulp.tasks, function(task, taskName) {
		task = _.merge(new BaseTask(), task);
		task.init(BigGulp, task, taskName);
	});
};

/**
 * Performs a basic load
 * @param {object} moduleList
 */
Loader.prototype.load = function(moduleList) {
	this._moduleList = moduleList;

	var Loader = this;

	_.forEach(this._moduleList, function(result, namespace) {
		if(_.isObject(result) && _.size(result) > 0) {
			Loader._BigGulp[camel(namespace)] = {};

			_.forEach(result, function(result, moduleName) {
				if(result === true) {
					Loader._BigGulp[camel(namespace)][camel(moduleName)] = require(Loader._appPath + namespace + "/" + moduleName);
				}
			});

		} else if(result === true) {
			Loader._BigGulp[namespace] = AutoLoader.load(Loader._appPath + namespace);
		}
	});

	this._initTasks();

	return this._BigGulp;
};<commit_msg>Updated path slashes to account for possible mistakes from developers<commit_after>var AutoLoader = require("auto-loader");
var camel = require("to-camel-case");

module.exports = Loader;

/**
 * Loads in various files and modules
 * @parm {object} BigGulp - the main BigGulp app object
 * @constructor
 */
function Loader(BigGulp) {
	var self = this;

	if(!(this instanceof Loader))
		return new Loader(BigGulp);

	/** @private */
	self._BigGulp = BigGulp;
	self._moduleList = {};
	self._modules = {};
	self._appPath = this._BigGulp._packageInfo._BigGulp.config.absolutePath;
}

/**
 * Initializes all the tasks and registers them with Gulp
 * @private
 */
Loader.prototype._initTasks = function() {
	var BigGulp = this._BigGulp,
		BaseTask = this._BigGulp._core.BaseTask;

	_.forEach(this._BigGulp.tasks, function(task, taskName) {
		task = _.merge(new BaseTask(), task);
		task.init(BigGulp, task, taskName);
	});
};

/**
 * Performs a basic load
 * @param {object} moduleList
 */
Loader.prototype.load = function(moduleList) {
	this._moduleList = moduleList;

	var Loader = this;

	_.forEach(this._moduleList, function(result, namespace) {
		if(_.isObject(result) && _.size(result) > 0) {
			Loader._BigGulp[camel(namespace)] = {};

			_.forEach(result, function(result, moduleName) {
				if(result === true) {
					Loader._BigGulp[camel(namespace)][camel(moduleName)] = require(Loader._appPath + "/" + namespace + "/" + moduleName);
				}
			});

		} else if(result === true) {
			Loader._BigGulp[namespace] = AutoLoader.load(Loader._appPath + "/" + namespace);
		}
	});

	this._initTasks();

	return this._BigGulp;
};<|endoftext|>


<commit_before>export const SECTIONS = [
  {
    name: "Opinions",
    imageLink: null,
    description: `The Opinions section of the Spectator focuses on analyzing and dissecting important, complex,
    and relevant issues happening in our Stuyvesant community and in the world beyond.
    In each issue, a number of writers across all grades give their opinions on subjects ranging from politics to economics and from technology to culture.
    The Opinions section often includes Point-Counter-Points and spreads that reflect a diverse set of beliefs and perspectives,
    and use their stances to uncover a deeper understanding of the subject at hand.
    The overarching goal is to create engaging, substantive, and relevant content to provide a closer look at the world.`,
    quotes: [
      {
        text: `Joining the Spectator Opinions Department has been the best decision I have made freshman year here at Stuyvesant.
        Throughout the half of a year on the department, I’ve had the opportunity to share many of my opinions that I only told my close friends
        or family to a wider audience. With writing drafts and coming up with arguments, I’ve also seen myself grow as a writer, allowing me to support my
        arguments more effectively. As teenagers, it’s easy to feel like our voices do not matter as much as adults,
        but this department has allowed for many students’ voices to be recognized, and I find that very special.`,
        source: "Angela Wong",
      },
    ],
    link:
      null,
  },
  {
    name: "Arts and Entertainment",
    imageLink: null,
    description: `We here at Arts and Entertainment department of the Spectator and we are the zestiest department in the world.  We get to write about cool stuff like music, movies, books, plays, basically anything, that makes Stuy students less soulless!!
We love everything artsy and cultural (especially like... Beyonce). We also cover major entertainment events like StuySquad, SOS, and SING! So what are you waiting for?
Apply for the Spectator Arts and Entertainment department now!!!`,
    quotes: [
      {
        text: `Being part of Arts and Entertainment is the best choice I ever made in my life. It is just so fun to write about things that we as human beings already enjoy. Like, it couldn't be more enjoyable than that. (Except eating Häagen-Dazs while listening to Beyonce)`,
        source: "Anonymous",
      },
    ],
    link:
      null,
  },
  {
    name: "Features",
    imageLink: null,
    description: `The best way to describe Features in one word is STORYTELLING.
    This is our main, essential craft. We write profiles telling the stories of interesting people
    or communities at Stuyvesant, provide more information and delve deeper into issues that News has covered,
    uncover information about specific issues at Stuy, and more. We're a very fun, creative department,
    but we also deal with hardcore investigative journalism that can actually affect change and shock people!
    If you love writing stories, digging around, and writing some hard-hitting articles, then the Features Department is the place for you.`,
    quotes: [
      {
        text: `Joining Features as a second term freshman was undeniably my best decision of that year.
        A few articles and meetings later, Features became engraved in my vocabulary.
        Where else can you interview the most wholesome people of Stuy and write a holistic article about them?
        Where I found amazing and unique editors, talented and quirky writers, Whole Foods cupcakes, and endless opportunities,
        I hope you do too. Join Features!`,
        source: "Amy Huang",
      },
    ],
    link:
      null,
  },
  {
    name: "Humor",
    imageLink: null,
    description: `Do you want to lowkey rant about your life and roast everything?
        Would you like to have a personality glow up?
        Do you want to join a low commitment and fun Spec department?
        Join Spec Humor!
        We write funny and satirical pieces for The Spec and unlike other departments, everything we publish is libel and slander which means that you'll be in control of what everyone says!`,
    quotes: [],
    link: "https://docs.google.com/forms/d/e/1FAIpQLSebWEsyBO4o4-yD35cIKiI90ce6vB1VdKsnZjJ1-bjedPo6MA/viewform",
  },
  {
    name: "Sports",
    imageLink: null,
    description: `Were you following March Madness? Are you hype for the start of the MLB season? Do you know who LeBron James is?
If you answered yes (or no!) to any of those questions, the Spectator Sports department is the place for you!! We cover Stuy sports as well as non-Stuy sports topics such as whether NCAA athletes should be paid and steroid use in the MLB. `,
    quotes: [
      {
        text: "Ray hates Spec.",
        source: "Ray Jones",
      },
    ],
    link:
      null,
  },
  {
    name: "News",
    imageLink: null,
    description: `Do you want to be a part of the best department of The Spectator? Do you want to get tight with the administration? Do you want to see your name and your articles on the front page? Do you want to find out about the coolest news at Stuy before anyone else? Do you want to report on that cool news? If so, join the Spectator News Department!!! `,
    quotes: [],
    link:
      null,
  },
  {
    name: "Copy",
    imageLink: null,
    description: `The Copy department makes sure The Spectator is free of all grammatical errors!
    Being a part of this department means honing your grammar skills and meeting other grammar nerds. We send out articles to edit roughly every two weeks,
    and only expect members to edit one or two articles per issue.
    We are a low-commitment department and don’t have many meetings, so balancing this department and other extracurriculars won’t be a problem.`,
    quotes: [
      {
        text: `Being a part of Spec Copy is incredibly satisfying! I've always been a grammar nerd,
        so being able to use that to my advantage to help out The Spectator is absolutely a win-win situation.
        I love that it also means getting to see the various pieces before the final issue is released.
        We have some really talented writers, and being able to polish their work and contribute to such a great publication is a privilege.`,
        source: "Tasfia Bashar",
      },
    ],
    link:
      null,
  },
  {
    name: "Web",
    imageLink: null,
    description: `The Web department is responsible for designing and updating The Spectator's website, www.stuyspec.com.
    Web teaches how to develop and maintain a server using Ruby on Rails, a website using Javascript and React, and other tools using modern languages like Go.
    These real-world skills are a great resume builder and provide invaluable experience in working together as a team.
    This is the perfect department for both computer programming enthusiasts and novices who want to help The Spectator continue to storm the frontier of online journalism.`,
    quotes: [
      {
        text: `Having the privilege of being a part of the Web Department was
        the highlight of my year—not only did I learn more about different
         technologies in web development and the newest frontiers of programming,
        but I also became friends with an amazing group of people!`,
        source: "Jerry Ye",
      },
    ],
    link:
      null,
  },
  {
    name: "Layout",
    imageLink: null,
    description: `A good publication should interest readers before they even pick it up and read it;
    the Layout department does just that! We are the last department that works with the newspaper and are responsible for formatting all of the articles,
    photos, art, etc. We make sure that the paper is aesthetically appealing and easy to read.
    After all, no one wants to read ugly and confusing blocks of text. With creativity and a certain magic called the InDesign,
    we present to you what you know as the Spectator. \n\nAs a staff member, you will be taught how to use InDesign and asked to critique
    the formatting of each issue as it is released.`,
    quotes: [],
    link:
      null,
  },
  {
    name: "Photo",
    imageLink: null,
    description: `Photo is dedicated to providing interesting and dynamic photographs to support the articles in the Spectator.
    Typical assignments include portraits of students and teachers, photos at school events – including sports games – and shots of fun things around the city as well.
    Photography is not just support for articles though, it is journalism in its own right.
    Photo department members regularly contribute to or spearhead photo essay projects.\n\n
    The Spectator Photo department only hosts a few meetings each term, so the most work is coordinated via email.
    Photo assignments are completed on the photographer’s own schedule, so long as they are in by department deadlines.
    This department is a good fit for anyone interested in photography, whether you’re just starting out,
    or you’re an expert looking for a place to practice and refine your skills.`,
    quotes: [
      {
        text: `Being a part of Spec Photo is such a fun and rewarding experience!
        Photography is a great creative outlet and seeing your photos get published makes it so much more cool.
        Taking assignments and going to events, meetings, and clubs that you’ve never even heard of before to take photos lets you
        interact with the Stuyvesant community in a personal and unique way, you never know who you might meet.
        If there’s any way to contribute to the Spectator, I wholeheartedly say the best way is through Photo!`,
        source: "Elena Sapelyuk",
      },
    ],
    link:
      null,
  },
  {
    name: "Business",
    imageLink: null,
    description: `The Business Department is the beating heart of The Spectator --
    as an independent student-run newspaper, The Spectator is able to publish thousands of copies every issue because
    of companies that place advertisements and agree to sponsorships. In order to continue this process, SpecBiz members have the responsibility
    in contacting various businesses and acquiring advertisements and sponsorships for the newspaper.
    Members are exposed to real life situations by learning proper etiquette, dealing with money, and communicating with adults in the real world.`,
    quotes: [
      {
        text: `SpecBiz opened up my passion for business and taught me valuable life assets that no other department or club in high school could provide me.
        My confidence built as I began contacting more businesses and became much more comfortable in talking to adults on the phone in a professional manner,
        meeting with business managers throughout the city, and properly formatting emails. Joining this department was a life-changer,
        and even to those who don’t have much interest in money,
        I highly encourage you to join this heartwarming family who will teach you the things that you need beyond college.`,
        source: "Stacey Xue",
      },
      {
        text: `I used to be this shy kid, afraid of talking to strangers or in front of large audiences.
        But after joining SpecBiz and networking with representatives from various types of companies,
        securing deals here and there, I’ve become the most extrovert kind of guy you can ever meet!`,
        source: "Alexander Radu",
      },
    ],
    link:
      null,
  },
  {
    name: "Art",
    imageLink: null,
    description: `It is often difficult to read through dense blocks of text without something to rest your eyes on.
    In the Art Department, we strive to embellish the newspaper with our unique illustrations, each perfectly suited for its article.
    In a school where artistic abilities are not seen as priority, you can easily find your niche as an artist for the Spectator,
    where your art will be displayed for all of its readers to admire. The limits of your creativity have no bounds;
    you can flaunt your skills in thematic spreads, comics, or Caption Contest illustrations! We encourage the use of all media!`,
    quotes: [
      {
        text: `Spectator Art has allowed me to learn about and deeply analyze current issues, vital concepts both timeless and immediate,
        as well as relearn how my mind functions in converting a written idea into an artistic manifestation. Being able to support a
        writer’s message and visually enhance the Spectator has been a rewarding experience.`,
        source: "Yume Igarashi",
      },
      {
        text: `Spectator Art simultaneously drives my passion to create art and provides me with a platform to share my art with a large,
        supportive audience. Honestly, I don’t think I would’ve drawn much in high school at all if it wasn’t for Spec Art.`,
        source: "Sammi Chen`",
      },
    ],
    link:
      null,
  },
  {
    name: "Science",
    imageLink: null,
    description: `The Spectator’s very own Science Department is one of the newer members on the list,
    created in 2019 as an offshoot of the Opinions department. Science writers are curious, ambitious,
    forward-looking, and always open to new ideas -- the cornerstones of progress. We cover a diverse
    range of topics, including recent experimental breakthroughs, high-profile scientific efforts,
    and disruptive new theories or technologies so the next time Elon Musk launches a sports car into space,
    we’ll be the ones covering it.`,
    quotes: [],
    link:
      null,
  },
];
<commit_msg>Update application links<commit_after>export const SECTIONS = [
  {
    name: "Opinions",
    imageLink: null,
    description: `The Opinions section of the Spectator focuses on analyzing and dissecting important, complex,
    and relevant issues happening in our Stuyvesant community and in the world beyond.
    In each issue, a number of writers across all grades give their opinions on subjects ranging from politics to economics and from technology to culture.
    The Opinions section often includes Point-Counter-Points and spreads that reflect a diverse set of beliefs and perspectives,
    and use their stances to uncover a deeper understanding of the subject at hand.
    The overarching goal is to create engaging, substantive, and relevant content to provide a closer look at the world.`,
    quotes: [
      {
        text: `Joining the Spectator Opinions Department has been the best decision I have made freshman year here at Stuyvesant.
        Throughout the half of a year on the department, I’ve had the opportunity to share many of my opinions that I only told my close friends
        or family to a wider audience. With writing drafts and coming up with arguments, I’ve also seen myself grow as a writer, allowing me to support my
        arguments more effectively. As teenagers, it’s easy to feel like our voices do not matter as much as adults,
        but this department has allowed for many students’ voices to be recognized, and I find that very special.`,
        source: "Angela Wong",
      },
    ],
    link:
      "https://docs.google.com/document/d/11nTdoyrcTnRmLaEpuAIo7W7q5OZ64xYpKEXZQaFTXy0/edit?usp=sharing",
  },
  {
    name: "Arts and Entertainment",
    imageLink: null,
    description: `We here at Arts and Entertainment department of the Spectator and we are the zestiest department in the world.  We get to write about cool stuff like music, movies, books, plays, basically anything, that makes Stuy students less soulless!!
We love everything artsy and cultural (especially like... Beyonce). We also cover major entertainment events like StuySquad, SOS, and SING! So what are you waiting for?
Apply for the Spectator Arts and Entertainment department now!!!`,
    quotes: [
      {
        text: `Being part of Arts and Entertainment is the best choice I ever made in my life. It is just so fun to write about things that we as human beings already enjoy. Like, it couldn't be more enjoyable than that. (Except eating Häagen-Dazs while listening to Beyonce)`,
        source: "Anonymous",
      },
    ],
    link:
      "https://docs.google.com/document/d/1jv51dLglBhw2KyMBc-3ZXaqC4K-ChuZZq7M4hLzJ0Q0/edit?usp=sharing",
  },
  {
    name: "Features",
    imageLink: null,
    description: `The best way to describe Features in one word is STORYTELLING.
    This is our main, essential craft. We write profiles telling the stories of interesting people
    or communities at Stuyvesant, provide more information and delve deeper into issues that News has covered,
    uncover information about specific issues at Stuy, and more. We're a very fun, creative department,
    but we also deal with hardcore investigative journalism that can actually affect change and shock people!
    If you love writing stories, digging around, and writing some hard-hitting articles, then the Features Department is the place for you.`,
    quotes: [
      {
        text: `Joining Features as a second term freshman was undeniably my best decision of that year.
        A few articles and meetings later, Features became engraved in my vocabulary.
        Where else can you interview the most wholesome people of Stuy and write a holistic article about them?
        Where I found amazing and unique editors, talented and quirky writers, Whole Foods cupcakes, and endless opportunities,
        I hope you do too. Join Features!`,
        source: "Amy Huang",
      },
    ],
    link:
      "https://forms.gle/GkWCCScPmPih8f7PA",
  },
  {
    name: "Humor",
    imageLink: null,
    description: `Do you want to lowkey rant about your life and roast everything?
        Would you like to have a personality glow up?
        Do you want to join a low commitment and fun Spec department?
        Join Spec Humor!
        We write funny and satirical pieces for The Spec and unlike other departments, everything we publish is libel and slander which means that you'll be in control of what everyone says!`,
    quotes: [],
    link: "https://forms.gle/5j7V1vPJTHdsF2jCA",
  },
  {
    name: "Sports",
    imageLink: null,
    description: `Were you following March Madness? Are you hype for the start of the MLB season? Do you know who LeBron James is?
If you answered yes (or no!) to any of those questions, the Spectator Sports department is the place for you!! We cover Stuy sports as well as non-Stuy sports topics such as whether NCAA athletes should be paid and steroid use in the MLB. `,
    quotes: [
      {
        text: "Ray hates Spec.",
        source: "Ray Jones",
      },
    ],
    link:
      "https://forms.gle/E6woBgfX493fMjDQ7",
  },
  {
    name: "News",
    imageLink: null,
    description: `Do you want to be a part of the best department of The Spectator? Do you want to get tight with the administration? Do you want to see your name and your articles on the front page? Do you want to find out about the coolest news at Stuy before anyone else? Do you want to report on that cool news? If so, join the Spectator News Department!!! `,
    quotes: [],
    link:
      "https://forms.gle/DDmutuu7BuV4nU5A6",
  },
  {
    name: "Copy",
    imageLink: null,
    description: `The Copy department makes sure The Spectator is free of all grammatical errors!
    Being a part of this department means honing your grammar skills and meeting other grammar nerds. We send out articles to edit roughly every two weeks,
    and only expect members to edit one or two articles per issue.
    We are a low-commitment department and don’t have many meetings, so balancing this department and other extracurriculars won’t be a problem.`,
    quotes: [
      {
        text: `Being a part of Spec Copy is incredibly satisfying! I've always been a grammar nerd,
        so being able to use that to my advantage to help out The Spectator is absolutely a win-win situation.
        I love that it also means getting to see the various pieces before the final issue is released.
        We have some really talented writers, and being able to polish their work and contribute to such a great publication is a privilege.`,
        source: "Tasfia Bashar",
      },
    ],
    link:
      "https://docs.google.com/forms/d/e/1FAIpQLSdCUEfCIfhoeTLy7M-_u0LJc53bL1PAJeRGRfsTh9CaHde9og/viewform?usp=sf_link",
  },
  {
    name: "Web",
    imageLink: null,
    description: `The Web department is responsible for designing and updating The Spectator's website, www.stuyspec.com.
    Web teaches how to develop and maintain a server using Ruby on Rails, a website using Javascript and React, and other tools using modern languages like Go.
    These real-world skills are a great resume builder and provide invaluable experience in working together as a team.
    This is the perfect department for both computer programming enthusiasts and novices who want to help The Spectator continue to storm the frontier of online journalism.`,
    quotes: [
      {
        text: `Having the privilege of being a part of the Web Department was
        the highlight of my year—not only did I learn more about different
         technologies in web development and the newest frontiers of programming,
        but I also became friends with an amazing group of people!`,
        source: "Jerry Ye",
      },
    ],
    link:
      "https://forms.gle/km8AhjzxDDEhEQbF8",
  },
  {
    name: "Layout",
    imageLink: null,
    description: `A good publication should interest readers before they even pick it up and read it;
    the Layout department does just that! We are the last department that works with the newspaper and are responsible for formatting all of the articles,
    photos, art, etc. We make sure that the paper is aesthetically appealing and easy to read.
    After all, no one wants to read ugly and confusing blocks of text. With creativity and a certain magic called the InDesign,
    we present to you what you know as the Spectator. \n\nAs a staff member, you will be taught how to use InDesign and asked to critique
    the formatting of each issue as it is released.`,
    quotes: [],
    link:
      "https://docs.google.com/forms/d/e/1FAIpQLSefYzXDztPdc1IX4eWbvyr4chaagRgzNyFzboGFJjFjFvMRAA/viewform",
  },
  {
    name: "Photo",
    imageLink: null,
    description: `Photo is dedicated to providing interesting and dynamic photographs to support the articles in the Spectator.
    Typical assignments include portraits of students and teachers, photos at school events – including sports games – and shots of fun things around the city as well.
    Photography is not just support for articles though, it is journalism in its own right.
    Photo department members regularly contribute to or spearhead photo essay projects.\n\n
    The Spectator Photo department only hosts a few meetings each term, so the most work is coordinated via email.
    Photo assignments are completed on the photographer’s own schedule, so long as they are in by department deadlines.
    This department is a good fit for anyone interested in photography, whether you’re just starting out,
    or you’re an expert looking for a place to practice and refine your skills.`,
    quotes: [
      {
        text: `Being a part of Spec Photo is such a fun and rewarding experience!
        Photography is a great creative outlet and seeing your photos get published makes it so much more cool.
        Taking assignments and going to events, meetings, and clubs that you’ve never even heard of before to take photos lets you
        interact with the Stuyvesant community in a personal and unique way, you never know who you might meet.
        If there’s any way to contribute to the Spectator, I wholeheartedly say the best way is through Photo!`,
        source: "Elena Sapelyuk",
      },
    ],
    link:
      "https://forms.gle/1ynxXcPGA6uC3z269",
  },
  {
    name: "Business",
    imageLink: null,
    description: `The Business Department is the beating heart of The Spectator --
    as an independent student-run newspaper, The Spectator is able to publish thousands of copies every issue because
    of companies that place advertisements and agree to sponsorships. In order to continue this process, SpecBiz members have the responsibility
    in contacting various businesses and acquiring advertisements and sponsorships for the newspaper.
    Members are exposed to real life situations by learning proper etiquette, dealing with money, and communicating with adults in the real world.`,
    quotes: [
      {
        text: `SpecBiz opened up my passion for business and taught me valuable life assets that no other department or club in high school could provide me.
        My confidence built as I began contacting more businesses and became much more comfortable in talking to adults on the phone in a professional manner,
        meeting with business managers throughout the city, and properly formatting emails. Joining this department was a life-changer,
        and even to those who don’t have much interest in money,
        I highly encourage you to join this heartwarming family who will teach you the things that you need beyond college.`,
        source: "Stacey Xue",
      },
      {
        text: `I used to be this shy kid, afraid of talking to strangers or in front of large audiences.
        But after joining SpecBiz and networking with representatives from various types of companies,
        securing deals here and there, I’ve become the most extrovert kind of guy you can ever meet!`,
        source: "Alexander Radu",
      },
    ],
    link:
      "https://forms.gle/8wQYdAqRQLScocrk8",
  },
  {
    name: "Art",
    imageLink: null,
    description: `It is often difficult to read through dense blocks of text without something to rest your eyes on.
    In the Art Department, we strive to embellish the newspaper with our unique illustrations, each perfectly suited for its article.
    In a school where artistic abilities are not seen as priority, you can easily find your niche as an artist for the Spectator,
    where your art will be displayed for all of its readers to admire. The limits of your creativity have no bounds;
    you can flaunt your skills in thematic spreads, comics, or Caption Contest illustrations! We encourage the use of all media!`,
    quotes: [
      {
        text: `Spectator Art has allowed me to learn about and deeply analyze current issues, vital concepts both timeless and immediate,
        as well as relearn how my mind functions in converting a written idea into an artistic manifestation. Being able to support a
        writer’s message and visually enhance the Spectator has been a rewarding experience.`,
        source: "Yume Igarashi",
      },
      {
        text: `Spectator Art simultaneously drives my passion to create art and provides me with a platform to share my art with a large,
        supportive audience. Honestly, I don’t think I would’ve drawn much in high school at all if it wasn’t for Spec Art.`,
        source: "Sammi Chen`",
      },
    ],
    link:
      "https://docs.google.com/forms/d/e/1FAIpQLScQM9mYdYvwvS_uYYValtdm5LGhKCNl5qmItlwQUeI4WuPvoQ/viewform?usp=sf_link",
  },
  {
    name: "Science",
    imageLink: null,
    description: `The Spectator’s very own Science Department is one of the newer members on the list,
    created in 2019 as an offshoot of the Opinions department. Science writers are curious, ambitious,
    forward-looking, and always open to new ideas -- the cornerstones of progress. We cover a diverse
    range of topics, including recent experimental breakthroughs, high-profile scientific efforts,
    and disruptive new theories or technologies so the next time Elon Musk launches a sports car into space,
    we’ll be the ones covering it.`,
    quotes: [],
    link:
      "https://docs.google.com/document/d/1vLVgwRFf9C9oDRVMFRAhKcLE-6YZPTcWv0KW-4tro4M/edit?usp=sharing",
  },
];
<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var Rope = require('./Rope');
var GameObjectFactory = require('../GameObjectFactory');

/**
 * Creates a new Rope Game Object and adds it to the Scene.
 *
 * Note: This method will only be available if the Rope Game Object and WebGL support have been built into Phaser.
 *
 * @method Phaser.GameObjects.GameObjectFactory#mesh
 * @webglOnly
 * @since 3.23.0
 *
 * @param {number} x - The horizontal position of this Game Object in the world.
 * @param {number} y - The vertical position of this Game Object in the world.
 * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager.
 * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with.
 * @param {Phaser.Types.Math.Vector2Like[]} [points] - An array containing the vertices data for this Rope. If none is provided a simple quad is created. See `setPoints` to set this post-creation.
 * @param {boolean} [horizontal=true] - Should the vertices of this Rope be aligned horizontally (`true`), or vertically (`false`)?
 * @param {number[]} [colors] - An optional array containing the color data for this Rope. You should provide one color value per pair of vertices.
 * @param {number[]} [alphas] - An optional array containing the alpha data for this Rope. You should provide one alpha value per pair of vertices.
 *
 * @return {Phaser.GameObjects.Rope} The Game Object that was created.
 */
if (typeof WEBGL_RENDERER)
{
    GameObjectFactory.register('rope', function (x, y, texture, frame, points, horizontal, colors, alphas)
    {
        return this.displayList.add(new Rope(this.scene, x, y, texture, frame, points, horizontal, colors, alphas));
    });
}

//  When registering a factory function 'this' refers to the GameObjectFactory context.
//
//  There are several properties available to use:
//
//  this.scene - a reference to the Scene that owns the GameObjectFactory
//  this.displayList - a reference to the Display List the Scene owns
//  this.updateList - a reference to the Update List the Scene owns
<commit_msg>Push to the updateList too<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var Rope = require('./Rope');
var GameObjectFactory = require('../GameObjectFactory');

/**
 * Creates a new Rope Game Object and adds it to the Scene.
 *
 * Note: This method will only be available if the Rope Game Object and WebGL support have been built into Phaser.
 *
 * @method Phaser.GameObjects.GameObjectFactory#mesh
 * @webglOnly
 * @since 3.23.0
 *
 * @param {number} x - The horizontal position of this Game Object in the world.
 * @param {number} y - The vertical position of this Game Object in the world.
 * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager.
 * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with.
 * @param {Phaser.Types.Math.Vector2Like[]} [points] - An array containing the vertices data for this Rope. If none is provided a simple quad is created. See `setPoints` to set this post-creation.
 * @param {boolean} [horizontal=true] - Should the vertices of this Rope be aligned horizontally (`true`), or vertically (`false`)?
 * @param {number[]} [colors] - An optional array containing the color data for this Rope. You should provide one color value per pair of vertices.
 * @param {number[]} [alphas] - An optional array containing the alpha data for this Rope. You should provide one alpha value per pair of vertices.
 *
 * @return {Phaser.GameObjects.Rope} The Game Object that was created.
 */
if (typeof WEBGL_RENDERER)
{
    GameObjectFactory.register('rope', function (x, y, texture, frame, points, horizontal, colors, alphas)
    {
        var rope = new Rope(this.scene, x, y, texture, frame, points, horizontal, colors, alphas);

        this.displayList.add(rope);

        return this.updateList.add(rope);
    });
}

//  When registering a factory function 'this' refers to the GameObjectFactory context.
//
//  There are several properties available to use:
//
//  this.scene - a reference to the Scene that owns the GameObjectFactory
//  this.displayList - a reference to the Display List the Scene owns
//  this.updateList - a reference to the Update List the Scene owns
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { Link, browserHistory } from 'react-router';
import _ from 'lodash';
import { fetchHousehold, deleteHousehold, resetCurrentHousehold } from '../actions/householdActions';
import { fetchPersons } from '../actions/personActions';
import { fetchVehicles } from '../actions/vehicleActions';
import HouseholdHeader from '../components/HouseholdHeader';
import { getGenderDisplay } from '../utils/personHelper'

class HouseholdsShow extends React.Component {
  componentWillMount() {
    const householdId = this.props.params.id;
    // Fetch a household with the given id
    this.props.fetchHousehold(householdId);
    // Fetch persons for the current household
    this.props.fetchPersons(householdId);
    // Fetch vehicles for the current household
    this.props.fetchVehicles(householdId);
  }

  componentWillUnmount() {
    // Reset the current household to prevent flash of content when loading new household
    this.props.resetCurrentHousehold();
  }

  onDeleteClick() {
    // Delete the household
    this.props.deleteHousehold(this.props.params.id).then(() => {
      // Redirect to household index
      browserHistory.push('/');
    });
  }

  renderPersons() {
    const { persons } = this.props;

    return persons.map((person) => {
      return (

{person.first_name} {person.last_name}

{person.email}

{person.age} year old {getGenderDisplay(person.gender)}

      );
    });
  }

  renderVehicles() {
    const { vehicles, persons } = this.props;

    return vehicles.map((vehicle) => {
      // Get the person assigned to this vehicle
      const person = _.find(persons, {id: vehicle.person});

      if (person) {
        return (

{vehicle.year} {vehicle.make} {vehicle.model}

{person.first_name} {person.last_name}

License Plate: {vehicle.license_plate}

        )
      }
    })
  }

  renderCompleteAction() {
    const { household } = this.props;

    if (household) {
      return (

      )
    }
  }

  render() {
    const { household, persons, vehicles } = this.props;

    // Show loading if data hasn't loaded yet
    if (!household) {
      return
Loading...

    }

    return (

        <HouseholdHeader household={household}/>

People

            {this.renderPersons()}

New Person

                <Link to={`/households/${household.id}/persons/new`}
                      className="btn btn-primary">Add</Link>

Vehicles

            {this.renderVehicles()}

New Vehicle

                <Link to={`/households/${household.id}/vehicles/new`}
                      className="btn btn-primary">Add</Link>

          <button className="btn btn-danger" role="button" onClick={this.onDeleteClick.bind(this)}>
            Delete Household
          </button>

    );
  }
}

function mapStateToProps(state) {
  return {
    household: state.households.all[state.households.currentId],
    // Filter persons by the current household
    persons: _.filter(_.values(state.persons.all), {'household': state.persons.filter.householdId}),
    // Filter vehicles by current household
    vehicles: _.filter(_.values(state.vehicles.all), {'household': state.vehicles.filter.householdId})
  };
}

export default connect(
  mapStateToProps,
  { fetchHousehold, deleteHousehold, fetchPersons, fetchVehicles, resetCurrentHousehold })
(HouseholdsShow);
<commit_msg>Removed unused code<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { Link, browserHistory } from 'react-router';
import _ from 'lodash';
import { fetchHousehold, deleteHousehold, resetCurrentHousehold } from '../actions/householdActions';
import { fetchPersons } from '../actions/personActions';
import { fetchVehicles } from '../actions/vehicleActions';
import HouseholdHeader from '../components/HouseholdHeader';
import { getGenderDisplay } from '../utils/personHelper'

class HouseholdsShow extends React.Component {
  componentWillMount() {
    const householdId = this.props.params.id;
    // Fetch a household with the given id
    this.props.fetchHousehold(householdId);
    // Fetch persons for the current household
    this.props.fetchPersons(householdId);
    // Fetch vehicles for the current household
    this.props.fetchVehicles(householdId);
  }

  componentWillUnmount() {
    // Reset the current household to prevent flash of content when loading new household
    this.props.resetCurrentHousehold();
  }

  onDeleteClick() {
    // Delete the household
    this.props.deleteHousehold(this.props.params.id).then(() => {
      // Redirect to household index
      browserHistory.push('/');
    });
  }

  renderPersons() {
    const { persons } = this.props;

    return persons.map((person) => {
      return (

{person.first_name} {person.last_name}

{person.email}

{person.age} year old {getGenderDisplay(person.gender)}

      );
    });
  }

  renderVehicles() {
    const { vehicles, persons } = this.props;

    return vehicles.map((vehicle) => {
      // Get the person assigned to this vehicle
      const person = _.find(persons, {id: vehicle.person});

      if (person) {
        return (

{vehicle.year} {vehicle.make} {vehicle.model}

{person.first_name} {person.last_name}

License Plate: {vehicle.license_plate}

        )
      }
    })
  }

  render() {
    const { household } = this.props;

    // Show loading if data hasn't loaded yet
    if (!household) {
      return
Loading...

    }

    return (

        <HouseholdHeader household={household}/>

People

            {this.renderPersons()}

New Person

                <Link to={`/households/${household.id}/persons/new`}
                      className="btn btn-primary">Add</Link>

Vehicles

            {this.renderVehicles()}

New Vehicle

                <Link to={`/households/${household.id}/vehicles/new`}
                      className="btn btn-primary">Add</Link>

          <button className="btn btn-danger" role="button" onClick={this.onDeleteClick.bind(this)}>
            Delete Household
          </button>

    );
  }
}

function mapStateToProps(state) {
  return {
    household: state.households.all[state.households.currentId],
    // Filter persons by the current household
    persons: _.filter(_.values(state.persons.all), {'household': state.persons.filter.householdId}),
    // Filter vehicles by current household
    vehicles: _.filter(_.values(state.vehicles.all), {'household': state.vehicles.filter.householdId})
  };
}

export default connect(
  mapStateToProps,
  { fetchHousehold, deleteHousehold, fetchPersons, fetchVehicles, resetCurrentHousehold })
(HouseholdsShow);
<|endoftext|>


<commit_before>function modifyZillowMap() {
  var longitude1 = null;
  var latitude1 = null;
  var longitude2 = null;
  var latitude2 = null;
  var state = null;

  var lastUrl = "";
  var lastHomePrice = 0;

  function monitorUrlChange() {
    // url changes when the long / lat region changes, so monitor url to know when
    // region being looked at changes

    if(window.location.pathname != lastUrl) {
      lastUrl = window.location.pathname;

      // find lat lng region
      var urlParts = lastUrl.split(/_rect/g)[0].split(/\//g);
      var latLongString = urlParts[urlParts.length - 1];
      var latLongParts = latLongString.split(/,/g);

      latitude1 = latLongParts[0];
      longitude1 = latLongParts[1];
      latitude2 = latLongParts[2];
      longitude2 = latLongParts[3];

      // find state from search term
      urlParts = lastUrl.split(/_rid/g)[0].split(/\//g);
      var searchTerm = urlParts[urlParts.length - 2];
      urlParts = searchTerm.split(/-/g);
      var state = urlParts[urlParts.length - 1];

      if(!latitude1 || latitude1 == "") {
        reloadMap();
      }
      else {
        localStorage.setItem("coords", JSON.stringify({
            "x_min": longitude2,
            "x_max": longitude1,
            "y_min": latitude2,
            "y_max": latitude1
        }));
        console.log(state);
        console.log(longitude1);
        console.log(latitude1);
        console.log(longitude2);
        console.log(latitude2);
      }
    }
  }

  function monitorHomeInFocusPrice() {
    var homePrice = $(".estimates .main-row span").text();

    if(homePrice && homePrice.length > 0) {
      homePrice = homePrice.replace(/\$|,/g,"");
      homePrice = Math.round(parseFloat(homePrice));

      if(homePrice != lastHomePrice) {
        lastHomePrice = homePrice;

        var adviceElement = $("#adviceForHome");
        var adviceElementIsNew = false;

        if(adviceElement.length == 0) {
          adviceElement = $("
");
          adviceElementIsNew = true;
        }
        else {
          adviceElement.empty();
        }

        adviceElement.append($("
Zillow Personal Advisor
"));
        adviceElement.append($("Advice for home based on your financials:
"));
        adviceElement.append($("
Loading advice...

"));
        adviceElement.append($("
Description
"));

        if(adviceElementIsNew) {
          $("#home-value-wrapper").append(adviceElement);
        }

        recommendationForPrice(homePrice, function(recommendation) {
          var recommendationMessage = "";
          if(recommendation.message) {
            recommendationMessage = recommendation.message;
          }
          else {
            recommendationMessage = "Based on your current liquid assets, we recommend a " + recommendation.percentage + "% down payment, which will result in an average " + recommendation.interestRate.toFixed(2) + "% interest rate and a $" + recommendation.monthlyPayment.toFixed(2) + " monthly payment.";
          }

          adviceElement.find("#personal-advisor-advice-message").empty().text(recommendationMessage);
        });
      }
    }
  }

  setInterval(monitorUrlChange, 100);
  setInterval(monitorHomeInFocusPrice, 100);
}
<commit_msg>minor fix<commit_after>function modifyZillowMap() {
  var longitude1 = null;
  var latitude1 = null;
  var longitude2 = null;
  var latitude2 = null;
  var state = null;

  var lastUrl = "";
  var lastHomePrice = 0;

  function monitorUrlChange() {
    // url changes when the long / lat region changes, so monitor url to know when
    // region being looked at changes

    if(window.location.pathname != lastUrl) {
      lastUrl = window.location.pathname;

      // find lat lng region
      var urlParts = lastUrl.split(/_rect/g)[0].split(/\//g);
      var latLongString = urlParts[urlParts.length - 1];
      var latLongParts = latLongString.split(/,/g);

      latitude1 = latLongParts[0];
      longitude1 = latLongParts[1];
      latitude2 = latLongParts[2];
      longitude2 = latLongParts[3];

      // find state from search term
      urlParts = lastUrl.split(/_rid/g)[0].split(/\//g);
      var searchTerm = urlParts[urlParts.length - 2];
      urlParts = searchTerm.split(/-/g);
      var state = urlParts[urlParts.length - 1];

      if(!latitude1 || latitude1 == "") {
        reloadMap();
      }
      else {
        localStorage.setItem("coords", JSON.stringify({
            "x_min": longitude2,
            "x_max": longitude1,
            "y_min": latitude2,
            "y_max": latitude1
        }));
        console.log(state);
        console.log(longitude1);
        console.log(latitude1);
        console.log(longitude2);
        console.log(latitude2);
      }
    }
  }

  function monitorHomeInFocusPrice() {
    var homePrice = $(".estimates .main-row span").text();

    if(homePrice && homePrice.length > 0) {
      homePrice = homePrice.replace(/\$|,/g,"");
      homePrice = Math.round(parseFloat(homePrice));

      if(homePrice != lastHomePrice) {
        lastHomePrice = homePrice;

        var adviceElement = $("#adviceForHome");
        var adviceElementIsNew = false;

        if(adviceElement.length == 0) {
          adviceElement = $("
");
          adviceElementIsNew = true;
        }
        else {
          adviceElement.empty();
        }

        adviceElement.append($("
Zillow Personal Advisor
"));
        adviceElement.append($("Advice for home based on your financials:
"));
        adviceElement.append($("
Loading advice...

"));
        adviceElement.append($("
Description
"));

        if(adviceElementIsNew) {
          $("#home-value-wrapper").append(adviceElement);
        }

        recommendationForPrice(homePrice, function(recommendation) {
          var recommendationMessage = "";
          if(recommendation.message) {
            recommendationMessage = recommendation.message;
          }
          else {
            recommendationMessage = "Based on your current liquid assets, we recommend a " + recommendation.percentage + "% down payment, which will result in an average " + recommendation.interestRate.toFixed(2) + "% interest rate and a $" + recommendation.monthlyPayment.toFixed(2) + " monthly payment.";
          }

          adviceElement.find("#personal-advisor-advice-message").empty().html(recommendationMessage);
        });
      }
    }
  }

  setInterval(monitorUrlChange, 100);
  setInterval(monitorHomeInFocusPrice, 100);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs=require('fs');
var path=require('path');
var crypto=require('crypto');

var config;
var samples={
    allSamples:[],
    topSamples:[]
};

var testCaseGenerators=[];

var fileCount=0;

process.on('message',messageHandler);

var messageTypes={
    'init':init,
    'trim':trim,
    'updateTestCase':updateTestCase,
    'samplesLow':generateNewTestCase
};

function messageHandler(message){
    if(messageTypes.hasOwnProperty(message.type)){
       messageTypes[message.type](message.data);
    }
    else{
       console.log('No message type: '+message.type);
    }
}

/*
    List files from inputDirectory and sort by size.
*/
function init(conf){
    var inputDirectory="";
    if(config===undefined){
       config=conf;
       inputDirectory=config.inputDirectory;
    }
    else{
       inputDirectory=config.outputDirectory;
    }
    if(!config.testCaseGenerators){
       console.log('No test case generators specified.');
       process.exit();
    }

    if(Array.isArray(config.testCaseGenerators)){
        config.testCaseGenerators.forEach(function(generator){
            testCaseGenerators.push(require(generator));
        });
    }
    else{
        testCaseGenerators.push(require(config.testCaseGenerators));
    }

    testCaseGenerators.forEach(function(generator){
        if(generator.hasOwnProperty('init'))
            generator.init(config);
    });

    var allSamples=fs.readdirSync(inputDirectory).map(function(fileName){
    if(!fs.statSync(path.resolve(inputDirectory,fileName)).isDirectory()){
       return path.resolve(inputDirectory,fileName);
    }else{
       return undefined;
    }
    });

    allSamples=allSamples.filter(function(file){
       if(file){
         return file;
       }else{
         return false;
       }
    });

    allSamples.sort(function(a,b){
       if(config.reverse)
         return fs.statSync(path.resolve(inputDirectory,b)).size-fs.statSync(path.resolve(inputDirectory,a)).size;
       else
         return fs.statSync(path.resolve(inputDirectory,a)).size-fs.statSync(path.resolve(inputDirectory,b)).size;
    });

    process.send({type:'initReady',data:{files:allSamples}});
}

function trim(){
    console.log('TRIMMING');
    if(config.filterInputFolder===true){
       console.log("Enabling brutal removing.");
       config.deleteFiles=true;
    }

    samples.allSamples.sort(function(a,b){
       return ((a.exec_time)/a.testCaseBlocks-(b.exec_time)/b.testCaseBlocks);
    });

    var allSamples=[];
    for(var x=0; x<samples.allSamples.length; x++){
       allSamples.push(samples.allSamples[x].file);
    }

    samples={
       allSamples:[],
       topSamples:[]
    };

    process.send({type:'initReady',data:{files:allSamples}});
}

/*
    updateTestCase-message handler
*/
function updateTestCase(message){
    if(message.action=='remove')
       removeTestCase(message.data);
    else if(message.action=='save')
       saveNewSample(message.data);
    if(!message.data.noNew)
       generateNewTestCase();
    else{
       sendNewTestCase(undefined);
    }
}

function generateNewTestCase(){
    var generator=ra(testCaseGenerators);
    generator.generateTestCase(getSampleSet,newTestCase);
}

/*
    Save new sample to outputDirectory
*/
function saveNewSample(data){
    //newBlocks:newBlocks,testCaseBlocks:testCaseBlocks

    var fileContent=fs.readFileSync(data.file);
    var original=path.resolve(data.file);
    var fileName=crypto.createHash('sha1').update(fileContent).digest('hex');
    var fullName=path.resolve(config.outputDirectory,path.basename(fileName)+path.extname(data.file));
    if(!fs.existsSync(fullName))
       fs.writeFileSync(fullName,fileContent);
    var fileStats={
         file:fullName,
         newBlocks:data.newBlocks,
         testCaseBlocks:data.testCaseBlocks,
         exec_time:data.exec_time,
         size:fileContent.length
       };
    samples.allSamples.push(fileStats);
    var cloneStat=Object.assign({},fileStats);
       cloneStat.weight=200;
    samples.topSamples.push(cloneStat);
    console.log('['+(new Date().getTime())+']File: '+fullName+' newblocks:'+data.newBlocks+' corpussize: '+samples.allSamples.length+' totalblocks: '+data.totalBlocks);
    if( original != fullName){
       removeTestCase(data);
    }
}

/*
    Remove sample from lists
*/
function removeTestCase(data){

    var file=path.resolve(data.file);
    var inInputDir=(path.resolve(file).indexOf(config.inputDirectory)!=-1);
    var inOutputDir=(path.resolve(file).indexOf(config.outputDirectory)!=-1);
    if((!inInputDir || config.deleteFiles) && fs.existsSync(file)){
       if(inInputDir||inOutputDir){
         for(var x=0; x<samples.allSamples.length; x++){
          if(samples.allSamples[x].file==file){
              samples.allSamples.splice(x,1);
          }
         }
         for(var y=0; y<samples.topSamples.length; y++){
          if(samples.topSamples[y].file==file){
              samples.topSamples.splice(y,1);
          }
         }
       }
       fs.unlink(file);
    }
}

function rint(max){
    return Math.floor(Math.random()*max);
}

function ra(arr){
    return arr[rint(arr.length)];
}

/*
    Select sample for surku and call surku to generate new test case.
*/
function getSampleSet(count){
    if(!count || count<1){
        if(samples.allSamples.length>1000)
            count=1000;
        else
            count=samples.allSamples.length;
    }

    if(samples.topSamples.length===0 && samples.allSamples.length===0){
        console.log('No samples in input queue.');
        process.exit();
    }

    var sampleSet=[];
    while(count--){
        if(samples.topSamples.length>0 && rint(3)){
            var index=rint(samples.topSamples.length);
            var sample=samples.topSamples.splice(index,1)[0];
            var newWeight=sample.weight-1;
            if(newWeight>0)
                samples.topSamples.push({file:sample.file,weight:newWeight});
            sampleSet.push(sample.file);
        }
        else if(samples.allSamples.length>0){
           sampleSet.push(ra(samples.allSamples).file);
        }
        else{
           console.log('No samples.');
        }
    }
    return sampleSet;
}

function newTestCase(file){
    if(!file || file.data.length===0){
        setTimeout(generateNewTestCase,10);
    }
    else if(file.type=="data"){
        var prefix=""+new Date().getTime()+Math.random().split('.')[1];
        var fileName=config.tempDirectory+'/samples/'+prefix+fileCount+path;
        fs.writeFile(fileName,file.data,function(){
         sendNewTestCase(fileName);
        });
    }
    else if(file.type=="file"){
        sendNewTestCase(file.data);
    }
}

function sendNewTestCase(fileName){
    process.send({
         type:'newTestCase',
         data:{
          file:fileName,
          corpusSize:samples.allSamples.length
         }
    });
}

process.on('disconnect',function(e){
    console.log("testcasegen.js error:"+e);
    process.exit();
});
<commit_msg>Add trim modes for total blocks, exec_time and combined<commit_after>#!/usr/bin/env node

var fs=require('fs');
var path=require('path');
var crypto=require('crypto');

var config;
var samples={
    allSamples:[],
    topSamples:[]
};

var testCaseGenerators=[];

var fileCount=0;

process.on('message',messageHandler);

var messageTypes={
    'init':init,
    'trim':trim,
    'updateTestCase':updateTestCase,
    'samplesLow':generateNewTestCase
};

function messageHandler(message){
    if(messageTypes.hasOwnProperty(message.type)){
       messageTypes[message.type](message.data);
    }
    else{
       console.log('No message type: '+message.type);
    }
}

/*
    List files from inputDirectory and sort by size.
*/
function init(conf){
    var inputDirectory="";
    if(config===undefined){
       config=conf;
       inputDirectory=config.inputDirectory;
    }
    else{
       inputDirectory=config.outputDirectory;
    }
    if(!config.testCaseGenerators){
       console.log('No test case generators specified.');
       process.exit();
    }

    if(Array.isArray(config.testCaseGenerators)){
        config.testCaseGenerators.forEach(function(generator){
            testCaseGenerators.push(require(generator));
        });
    }
    else{
        testCaseGenerators.push(require(config.testCaseGenerators));
    }

    testCaseGenerators.forEach(function(generator){
        if(generator.hasOwnProperty('init'))
            generator.init(config);
    });

    var allSamples=fs.readdirSync(inputDirectory).map(function(fileName){
    if(!fs.statSync(path.resolve(inputDirectory,fileName)).isDirectory()){
       return path.resolve(inputDirectory,fileName);
    }else{
       return undefined;
    }
    });

    allSamples=allSamples.filter(function(file){
       if(file){
         return file;
       }else{
         return false;
       }
    });

    allSamples.sort(function(a,b){
       if(config.reverse)
         return fs.statSync(path.resolve(inputDirectory,b)).size-fs.statSync(path.resolve(inputDirectory,a)).size;
       else
         return fs.statSync(path.resolve(inputDirectory,a)).size-fs.statSync(path.resolve(inputDirectory,b)).size;
    });

    process.send({type:'initReady',data:{files:allSamples}});
}

function filterSamples(samples){
  var mode=rint(3);

  if(mode===0){
    console.log('Block mode.');
    samples.allSamples.sort(function(a,b){
        return a.testCaseBlocks-b.testCaseBlocks;
    });
  }
  else if(mode===1){
    console.log('Exec time mode.');
    samples.allSamples.sort(function(a,b){
        return a.exec_time-b.exec_time;
    });
  }
  else{
    console.log('Combined mode.');
    samples.allSamples.sort(function(a,b){
        return ((a.exec_time)/a.testCaseBlocks-(b.exec_time)/b.testCaseBlocks);
    });
  }
}

function trim(){
    console.log('TRIMMING');
    if(config.filterInputFolder===true){
       console.log("Enabling brutal removing.");
       config.deleteFiles=true;
    }

    filterSamples(samples);

    var allSamples=[];
    for(var x=0; x<samples.allSamples.length; x++){
       allSamples.push(samples.allSamples[x].file);
    }

    samples={
       allSamples:[],
       topSamples:[]
    };

    process.send({type:'initReady',data:{trim:true, files:allSamples}});
}

/*
    updateTestCase-message handler
*/
function updateTestCase(message){
    if(message.action=='remove')
       removeTestCase(message.data);
    else if(message.action=='save')
       saveNewSample(message.data);
    if(!message.data.noNew)
       generateNewTestCase();
    else{
       sendNewTestCase(undefined);
    }
}

function generateNewTestCase(){
    var generator=ra(testCaseGenerators);
    generator.generateTestCase(getSampleSet,newTestCase);
}

/*
    Save new sample to outputDirectory
*/
function saveNewSample(data){
    //newBlocks:newBlocks,testCaseBlocks:testCaseBlocks

    var fileContent=fs.readFileSync(data.file);
    var original=path.resolve(data.file);
    var fileName=crypto.createHash('sha1').update(fileContent).digest('hex');
    var fullName=path.resolve(config.outputDirectory,path.basename(fileName)+path.extname(data.file));
    if(!fs.existsSync(fullName))
       fs.writeFileSync(fullName,fileContent);
    var fileStats={
         file:fullName,
         newBlocks:data.newBlocks,
         testCaseBlocks:data.testCaseBlocks,
         exec_time:data.exec_time,
         size:fileContent.length
       };
    samples.allSamples.push(fileStats);
    var cloneStat=Object.assign({},fileStats);
       cloneStat.weight=200;
    samples.topSamples.push(cloneStat);
    console.log('['+(new Date().getTime())+']File: '+fullName+' newblocks:'+data.newBlocks+' corpussize: '+samples.allSamples.length+' totalblocks: '+data.totalBlocks);
    if( original != fullName){
       removeTestCase(data);
    }
}

/*
    Remove sample from lists
*/
function removeTestCase(data){

    var file=path.resolve(data.file);
    var inInputDir=(path.resolve(file).indexOf(config.inputDirectory)!=-1);
    var inOutputDir=(path.resolve(file).indexOf(config.outputDirectory)!=-1);
    if((!inInputDir || config.deleteFiles) && fs.existsSync(file)){
       if(inInputDir||inOutputDir){
         for(var x=0; x<samples.allSamples.length; x++){
          if(samples.allSamples[x].file==file){
              samples.allSamples.splice(x,1);
          }
         }
         for(var y=0; y<samples.topSamples.length; y++){
          if(samples.topSamples[y].file==file){
              samples.topSamples.splice(y,1);
          }
         }
       }
       fs.unlink(file);
    }
}

function rint(max){
    return Math.floor(Math.random()*max);
}

function ra(arr){
    return arr[rint(arr.length)];
}

/*
    Select sample for surku and call surku to generate new test case.
*/
function getSampleSet(count){
    if(!count || count<1){
        if(samples.allSamples.length>1000)
            count=1000;
        else
            count=samples.allSamples.length;
    }

    if(samples.topSamples.length===0 && samples.allSamples.length===0){
        console.log('No samples in input queue.');
        process.exit();
    }

    var sampleSet=[];
    while(count--){
        if(samples.topSamples.length>0 && rint(3)){
            var index=rint(samples.topSamples.length);
            var sample=samples.topSamples.splice(index,1)[0];
            var newWeight=sample.weight-1;
            if(newWeight>0)
                samples.topSamples.push({file:sample.file,weight:newWeight});
            sampleSet.push(sample.file);
        }
        else if(samples.allSamples.length>0){
           sampleSet.push(ra(samples.allSamples).file);
        }
        else{
           console.log('No samples.');
        }
    }
    return sampleSet;
}

function newTestCase(file){
    if(!file || file.data.length===0){
        setTimeout(generateNewTestCase,10);
    }
    else if(file.type=="data"){
        var prefix=""+new Date().getTime()+Math.random().split('.')[1];
        var fileName=config.tempDirectory+'/samples/'+prefix+fileCount+path;
        fs.writeFile(fileName,file.data,function(){
         sendNewTestCase(fileName);
        });
    }
    else if(file.type=="file"){
        sendNewTestCase(file.data);
    }
}

function sendNewTestCase(fileName){
    process.send({
         type:'newTestCase',
         data:{
          file:fileName,
          corpusSize:samples.allSamples.length
         }
    });
}

process.on('disconnect',function(e){
    console.log("testcasegen.js error:"+e);
    process.exit();
});
<|endoftext|>


<commit_before>var http = require('http');
var emitter = require('events').EventEmitter;

var options = { host : 'isbn.net.in',
                path : '/' }

function error(code, desc)
{
    this['code'] = code;
    this['desc'] = desc;
}

function Book(data)
{
    // A simple bean to hold the required data
    this.vendor = data[0];
    this.price  = data[1].price;
    this.url    = data[1].url;
}

function Books(books)
{
    // A collection for holding a set of books
    this.books = books;

    /* To enable simple look up add the vendors as attributes to the class
       ex : var b = getBooks();
            // This will print the details of the book set by the vendor
            console.log(b.flipkart);
    */
    for(var i = 0; i < books.length; i++)
        this[books[i].vendor] = books[i];
}

Books.prototype.count    = function() { return this.books.length; };
Books.prototype.cheapest = function() {
    // returns the cheapest deal from the set of books
    var book;
    for(var i = 0; i < this.books.length; i++)
    {
        if(book == null) book = this.books[i];
        else
        {
            if(book.price > this.books[i].price)
                book = this.books[i];
        }
    }
    return book;
}

Books.prototype.vendors = function() {
    // returns a set of vendors
    var vendors = new Array(this.books.length);

    for(var i = 0; i < vendors.length; i++ )
        vendors[i] = this.books[i].vendor;

    return vendors;
}

function parse(data)
{
    // parses the data which is in json format and creates a list of
    // books
    try
    {
        var json = JSON.parse(data.toString());
        var books = new Array(json.length);
        for(var i = 0; i < json.length; i++)
        {
            books[i] = new Book(json[i]);
        }
        this.emit('success', new Books(books));
    }
    catch(e)
    {
        console.log(e);
        this.emit('error', e);
    }
}

function lookup(isbn)
{
    // makes an http request to isbn.net.in and triggers
    // the appropriate events
    var $ = this;
    options.path = '/' + isbn + '.json';
    http.get( options, function(res)
    {
      var data;
      if(res.statusCode != 200)
      {
        if(res.statusCode == 404)
          $.emit('error',
                      new error(res.statusCode, "Invalid isbn : " + isbn));
        else
           $.emit('error',
                      new error(res.statusCode,
                         "Failed fetching the isbn. Http Error"));
        return;
      }
      res.on('data', function(response) {
             if(data == null)
                 data = response;
             else
                 data += response;
     });
      res.on('end', function() { $.__parse(data); });
    }).on('error', function(e) { $.emit('error', new error(-1, e)); });
}

lookup.prototype = new emitter;
lookup.prototype.on = function(str, cb) {
       this.addListener(str, cb);
       return this;
 };
lookup.prototype.__parse = parse;

function search(isbn)
{

    var cls = new lookup(isbn);
    return cls;
}

var isbn = { lookup : search };

module.exports = isbn;

<commit_msg>Code cleanup<commit_after>var http = require('http');
var emitter = require('events').EventEmitter;

var options = { host : 'isbn.net.in',
                path : '/' }

function error(code, desc)
{
    this['code'] = code;
    this['desc'] = desc;
}

function Book(data)
{
    // A simple bean to hold the required data
    this.vendor = data[0];
    this.price  = data[1].price;
    this.url    = data[1].url;
}

function Books(books)
{
    // A collection for holding a set of books
    this.books = books;

    /* To enable simple look up add the vendors as attributes to the class
       ex : var b = getBooks();
            // This will print the details of the book set by the vendor
            console.log(b.flipkart);
    */
    for(var i = 0; i < books.length; i++)
        this[books[i].vendor] = books[i];
}

Books.prototype.count    = function() { return this.books.length; };
Books.prototype.cheapest = function() {
    // returns the cheapest deal from the set of books
    var book;
    for(var i = 0; i < this.books.length; i++)
    {
        if(book == null) book = this.books[i];
        else
        {
            if(book.price > this.books[i].price)
                book = this.books[i];
        }
    }
    return book;
}

Books.prototype.vendors = function() {
    // returns a set of vendors
    var vendors = new Array(this.books.length);

    for(var i = 0; i < vendors.length; i++ )
        vendors[i] = this.books[i].vendor;

    return vendors;
}

function parse(data)
{
    // parses the data which is in json format and creates a list of
    // books
    try
    {
        var json = JSON.parse(data.toString());
        var books = new Array(json.length);
        for(var i = 0; i < json.length; i++)
        {
            books[i] = new Book(json[i]);
        }
        this.emit('success', new Books(books));
    }
    catch(e)
    {
        console.log(e);
        this.emit('error', e);
    }
}

function lookup(isbn)
{
    // makes an http request to isbn.net.in and triggers
    // the appropriate events
    var $ = this;
    options.path = '/' + isbn + '.json';
    http.get( options, function(res)
    {
      var data;
      if(res.statusCode != 200)
      {
        if(res.statusCode == 404)
          $.emit('error',
                      new error(res.statusCode, "Invalid isbn : " + isbn));
        else
           $.emit('error',
                      new error(res.statusCode,
                         "Failed fetching the isbn. Http Error"));
        return;
      }
      res.on('data', function(response) {
             if(data == null)
                 data = response;
             else
                 data += response;
     });
      res.on('end', function() { $.__parse(data); });
    }).on('error', function(e) { $.emit('error', new error(-1, e)); });
}

lookup.prototype = new emitter;
lookup.prototype.on = function(str, cb) {
       this.addListener(str, cb);
       return this;
 };
lookup.prototype.__parse = parse;

function search(isbn)
{
    var cls = new lookup(isbn);
    return cls;
}

var isbn = { lookup : search };

module.exports = isbn;

<|endoftext|>