<commit_before>'use strict';
/**
 * @file Update an account from specified access_token
 *
 */

var async = require('async');
var restify = require('restify');
var rarity = require('rarity');

var Token = require('../models/token.js');

/**
 * This handler downloads data for the specified access_token and starts uploading them onto AnyFetch.
 *
 * @param {Object} req Request object from the client
 * @param {Object} res Response we want to return
 * @param {Function} next Callback to call once res has been populated.
 */
module.exports = function(updateAccount, queue, workers) {
  return function(req, res, next) {
    if(!req.params.access_token) {
      return next(new restify.MissingParameterError("Missing access_token parameter."));
    }
    if(!req.params.api_url) {
      return next(new restify.MissingParameterError("Missing api_url parameter."));
    }

    Token.findOne({anyfetchToken: req.params.access_token}, function(err, token) {
      if(err) {
        return next(err);
      }
      if(!token) {
        return next(new restify.InvalidArgumentError("Unknown token."));
      }
      if(token.isUpdating) {
        return next(new restify.TooManyRequests('Already processing'));
      }
      else {
        res.send(202);
      }
      next();

      async.waterfall([
        function updateToken(cb) {
          // Update token
          token.lastUpdate = new Date();
          token.isUpdating = true;

          token.save(rarity.slice(1, cb));
        },
        function callUpdateAccount(cb) {
          var queues = {};

          Object.keys(workers).forEach(function(name) {
            queues[name] = [];
          });

          updateAccount(token.data || {}, token.cursor, queues, function(err, newCursor, providerData) {
            cb(err, queues, newCursor, providerData);
          });
        },
        function updateToken(queues, newCursor, providerData, cb) {
          if(providerData) {
            token.data = providerData;
            token.markModified('data');
          }
          token.cursor = newCursor;
          token.isUpdating = false;

          token.save(rarity.carryAndSlice([queues], 2, cb));
        },
        function executeQueue(queues, cb) {
          Object.keys(workers).forEach(function(name) {
            console.log("User `" + token.accountName + "` is pushing " + queues[name].length + " tasks onto `" + name + "`");
            queues[name].forEach(function(task) {
              task._anyfetchToken = token.anyfetchToken;
              task._anyfetchApiUrl = req.params.api_url;

              var job = queue.create(name, task);
              job.on('failed', function(){
                console.log("Job " + job.id + " onto `" + name + "` have failed");
              });
              job.save();
            });
            console.log("User `" + token.accountName + "` have pushed " + queues[name].length + " tasks onto `" + name + "`");
          });
          cb(null);
        }
      ], function(err) {
        if(err) {
          console.log('ERR:', err);
        }
      });
    });
  };
};
<commit_msg>Remove useless comments<commit_after>'use strict';
/**
 * @file Update an account from specified access_token
 *
 */

var async = require('async');
var restify = require('restify');
var rarity = require('rarity');

var Token = require('../models/token.js');

/**
 * This handler downloads data for the specified access_token and starts uploading them onto AnyFetch.
 *
 * @param {Object} req Request object from the client
 * @param {Object} res Response we want to return
 * @param {Function} next Callback to call once res has been populated.
 */
module.exports = function(updateAccount, queue, workers) {
  return function(req, res, next) {
    if(!req.params.access_token) {
      return next(new restify.MissingParameterError("Missing access_token parameter."));
    }
    if(!req.params.api_url) {
      return next(new restify.MissingParameterError("Missing api_url parameter."));
    }

    Token.findOne({anyfetchToken: req.params.access_token}, function(err, token) {
      if(err) {
        return next(err);
      }
      if(!token) {
        return next(new restify.InvalidArgumentError("Unknown token."));
      }
      if(token.isUpdating) {
        return next(new restify.TooManyRequests('Already processing'));
      }
      else {
        res.send(202);
      }
      next();

      async.waterfall([
        function updateToken(cb) {
          // Update token
          token.lastUpdate = new Date();
          token.isUpdating = true;

          token.save(rarity.slice(1, cb));
        },
        function callUpdateAccount(cb) {
          var queues = {};

          Object.keys(workers).forEach(function(name) {
            queues[name] = [];
          });

          updateAccount(token.data || {}, token.cursor, queues, function(err, newCursor, providerData) {
            cb(err, queues, newCursor, providerData);
          });
        },
        function updateToken(queues, newCursor, providerData, cb) {
          if(providerData) {
            token.data = providerData;
            token.markModified('data');
          }
          token.cursor = newCursor;
          token.isUpdating = false;

          token.save(rarity.carryAndSlice([queues], 2, cb));
        },
        function executeQueue(queues, cb) {
          Object.keys(workers).forEach(function(name) {
            console.log("User `" + token.accountName + "` have pushed " + queues[name].length + " tasks onto `" + name + "`");
            queues[name].forEach(function(task) {
              task._anyfetchToken = token.anyfetchToken;
              task._anyfetchApiUrl = req.params.api_url;

              var job = queue.create(name, task);
              job.on('failed', function(){
                console.log("Job " + job.id + " onto `" + name + "` have failed");
              });
              job.save();
            });
          });
          cb(null);
        }
      ], function(err) {
        if(err) {
          console.log('ERR:', err);
        }
      });
    });
  };
};
<|endoftext|>


<commit_before>function wrap(/* wrapperFn, [argsToWrappedFn...,] thingToWrap, modul ({name: 'foo', methd: 'bar'}) */) {
	var last  = arguments.length - 1,
	    modul = arguments[ last ]
	    me    = arguments[ last - 1 ],
			fn 	  = arguments[0],
			args  = [ ]

  // Don't wrap profile functions
	if (me instanceof Function && me.isWrappedWithProfiler())
	  return me

	for (var i = 1; i < last; i++)
		args.push(arguments[i])

	args.push(modul)

	var you = doWrap(me, fn, args)

	iterateAndWrap(you.prototype, me.prototype, fn, args)

	// This needs to be uncommented for tap - I don't know why
  console.info('')

	return you
}

function doWrap(me, fn, args) {
  var buffer;

	if (me instanceof Function)
    if (me.name.search(/[A-Z]/) < 0 || me.name.search(/[A-Z]/) > 0) {
  	  buffer = wrapItem(me, fn, args)
    } else {
      buffer = me
    }
  else
    buffer = me

	iterateAndWrap(buffer, me, fn, args)

	return buffer
}

function iterateAndWrap(ctx, me, fn, args) {
  for (var p in me) {

  	if (p !== 'isWrappedWithProfiler')
  	  if (me[p] instanceof Function) {
    	  var last = args.pop()

        last.methd = p

        args.push(last)

    	  if (ctx instanceof Function && !ctx.isWrappedWithProfiler())
    	    ctx[p] = wrapItem(me[p], fn, args)
    	  else if (ctx instanceof Object && !me[p].isWrappedWithProfiler())
    	    ctx[p] = wrapItem(me[p], fn, args)
  		} else {
  		  ctx[p] = me[p]
  		}
	}
}

function wrapItem(i, fn, args) {
  args.unshift(i)

  return i instanceof Function ? fn.apply(null, args) : i
}

module.exports = wrap<commit_msg>Cleaned things up a bit<commit_after>var no = require('../../config.json').no

function wrap(/* wrapperFn, [argsToWrappedFn...,] thingToWrap, modul ({name: 'foo', methd: 'bar'}) */) {
	var last = arguments.length - 1,
	    me   = arguments[ last ],
			fn 	 = arguments[0],
			args = [ ]

  // Don't wrap profile functions
	if (me instanceof Function && me.isWrappedWithProfiler())
	  return me

	for (var i = 1; i < last; i++)
		args.push(arguments[i])

	var you = doWrap(me, fn, args)

	iterateAndWrap(you.prototype, me.prototype, fn, args)

	// This needs to be here for tap - I don't know why
  process.stdout.write('')

	return you
}

function doWrap(me, fn, args) {
  var buffer;

	if (me instanceof Function)
    if (me.name.search(/[A-Z]/) < 0 || me.name.search(/[A-Z]/) > 0)
  	  buffer = wrapItem(me, fn, args)
    else
      buffer = me
  else
    buffer = me

	iterateAndWrap(buffer, me, fn, args)

	return buffer
}

function iterateAndWrap(ctx, me, fn, args) {
  for (var p in me)
  	if (p !== 'isWrappedWithProfiler')
  	  if (me[p] instanceof Function) {
    	  if (ctx instanceof Function && !ctx.isWrappedWithProfiler())
    	    ctx[p] = wrapItem(me[p], fn, args)
    	  else if (ctx instanceof Object && !me[p].isWrappedWithProfiler())
    	    ctx[p] = wrapItem(me[p], fn, args)
  		} else {
  		  ctx[p] = me[p]
  		}
}

function wrapItem(i, fn, args) {
  args.unshift(i)

  return i instanceof Function ? fn.apply(null, args) : i
}

module.exports = wrap<|endoftext|>


<commit_before>/*!
 * Image Processor
 *
 * Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
 * Licensed under MIT
 */

const fs = require('fs');
const path = require('path');
const cv = require('opencv');
const assign = require('lodash.assign');
const template = require('lodash.template');
const fetchAll = require('./fetch-all');
const reader = require('./reader');
const readCoordsFromFile = require('./read-coords-from-file');

// template used in writing the file
/* eslint-disable */
const summaryContentsTmplStr = [
  "Rating:\n",
  "<% const range = Array.apply(null, {length: data.breakdownLength}).map(Number.call, Number) %>",
  "<% range.forEach(function(item) { %>",
  "<% let breakdown = data.breakdown[(item + 1)]; %>",
  "<% if (typeof breakdown === 'undefined') { breakdown = 'N/A'; } %>",
  "<%= (item + 1) %>. <%= breakdown %>\n",
  "<% }); %>\n",
  "Summary of Rating:\n",
  "<% const statisticsKeys = Object.keys(data.statistics); %>",
  "<% statisticsKeys.forEach(function(item) { %>",
  "<%= item %>=<%= data.statistics[item] %>\n",
  "<% }); %>",
].join('');
/* eslint-enable */
const summaryContentsTmpl = template(summaryContentsTmplStr, {
  variable: 'data',
});

const imageProcessor = (imagesDirPath, outputPath, coordsDataFile, options = {}) => {
  const defaultOptions = {
    diameter: 16,
    extensions: ['jpg', 'png'],
    shapeThickness: 2,
    shapeColors: {
      blank: [0, 255, 0], // green
      crossed: [0, 255, 0], // green
      shaded: [0, 0, 255], // red
    },
  };

  // resolve the default options
  const resolvedOptions = assign({}, defaultOptions, options);

  return fetchAll(imagesDirPath, resolvedOptions.extensions)
    .then((images) => {
      // show log info
      console.log(`Reading images from the directory: ${imagesDirPath}`);
      console.log(`Saving processed files to: ${outputPath}`);

      // create an array of image promises
      const promises = images.map(imagePath => reader(imagePath));

      // process all the promises using the all method of Promise object
      return Promise.all(promises);
    })
    .then((images) => {
      // read the coordinates and re-resolve the casted images
      const retPromise = Promise.all([
        Promise.resolve(images),
        readCoordsFromFile(coordsDataFile, { delimiter: ' ' }),
      ]);

      return retPromise;
    })
    .then((values) => {
      const [images, coordsData] = values;

      images.forEach((image) => {
        const { cvImage, imagePath } = image;

        // show log info
        console.log(`Processing Image: ${imagePath}`);

        // convert to grayscale
        const grayImg = cvImage.copy();
        grayImg.convertGrayscale();

        // perform thresholding using Otsu
        const binaryImage = grayImg.threshold(0, 255, 'Binary', 'Otsu');

        // emulate morph_open since node-opencv doesn't support it
        const kernel = cv.imgproc.getStructuringElement(0, [5, 5]);
        binaryImage.erode(1, kernel);
        binaryImage.dilate(1, kernel);

        // initialize variables for the breakdown and statistics
        const shadeBreakdown = {};
        const statistics = {
          SA: 0,
          A: 0,
          SLA: 0,
          NAD: 0,
          SLD: 0,
          D: 0,
          SD: 0,
        };

        const statisticsKeys = Object.keys(statistics);

        coordsData.forEach((row, coordsIdx) => {
          row.forEach((coords, idx) => {
            const [x, y] = coords;
            let isShaded = false;
            let shapeColor = resolvedOptions.shapeColors.blank;

            // identify where the item resides in the choices
            const statKey = statisticsKeys[idx];

            const start = x - (resolvedOptions.diameter / 2);
            const end = y - (resolvedOptions.diameter / 2);

            // crop the image to the specific region
            const roi = binaryImage.crop(
              start,
              end,
              resolvedOptions.diameter,
              resolvedOptions.diameter);

            // opencv's mean function processes all 4 channels of the image
            // and we need only the first channel since we are processing binary images
            // and discard all the channels other than the first channel
            //
            // This to determine how much black pixels are present on the cropped area
            const [channel1, , , ] = roi.mean();

            // override the default rectangle color based on certain range of values
            if (channel1 <= 69) {
              shapeColor = resolvedOptions.shapeColors.crossed;
            } else if (channel1 > 69 && channel1 < 135) {
              shapeColor = resolvedOptions.shapeColors.shaded;

              isShaded = true;
            }

            // create the output folder if it does not exist
            if (!fs.existsSync(outputPath)) {
              fs.mkdirSync(outputPath);
            }

            // add one to the matched stat value and
            // store the value of shaded key and its index to the breakdown
            if (isShaded) {
              statistics[statKey] += 1;

              shadeBreakdown[(coordsIdx + 1)] = statKey;
            }

            // draw rectangle in the original image
            cvImage.rectangle(
              [start, end],
              [resolvedOptions.diameter, resolvedOptions.diameter],
              shapeColor,
              resolvedOptions.shapeThickness);
          });
        });

        const imageBasename = path.basename(imagePath);

        // write the manipulated image to the destination folder
        cvImage.save(`${outputPath}/${imageBasename}`);

        // assemble the contents that will be written to the file
        const fileContents = summaryContentsTmpl({
          breakdown: shadeBreakdown,
          breakdownLength: coordsData.length,
          statistics,
        });

        // save the statistics in a text file
        fs.writeFileSync(`${outputPath}/${imageBasename}.txt`, fileContents);
      });
    })
    ;
};

module.exports = imageProcessor;

<commit_msg>Extract cell processing logic to another function<commit_after>/*!
 * Image Processor
 *
 * Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
 * Licensed under MIT
 */

const fs = require('fs');
const path = require('path');
const cv = require('opencv');
const assign = require('lodash.assign');
const template = require('lodash.template');
const fetchAll = require('./fetch-all');
const reader = require('./reader');
const readCoordsFromFile = require('./read-coords-from-file');

// template used in writing the file
/* eslint-disable */
const summaryContentsTmplStr = [
  "Rating:\n",
  "<% const range = Array.apply(null, {length: data.breakdownLength}).map(Number.call, Number) %>",
  "<% range.forEach(function(item) { %>",
  "<% let breakdown = data.breakdown[(item + 1)]; %>",
  "<% if (typeof breakdown === 'undefined') { breakdown = 'N/A'; } %>",
  "<%= (item + 1) %>. <%= breakdown %>\n",
  "<% }); %>\n",
  "Summary of Rating:\n",
  "<% const statisticsKeys = Object.keys(data.statistics); %>",
  "<% statisticsKeys.forEach(function(item) { %>",
  "<%= item %>=<%= data.statistics[item] %>\n",
  "<% }); %>",
].join('');
/* eslint-enable */
const summaryContentsTmpl = template(summaryContentsTmplStr, {
  variable: 'data',
});

const processCell = (origImage, binaryImage, coords, diameter, shapeColors, shapeThickness) => {
  const [x, y] = coords;
  let isShaded = false;
  let shapeColor = shapeColors.blank;

  const start = x - (diameter / 2);
  const end = y - (diameter / 2);

  // crop the image to the specific region
  const roi = binaryImage.crop(start, end, diameter, diameter);

  // opencv's mean function processes all 4 channels of the image
  // and we need only the first channel since we are processing binary images
  // and discard all the channels other than the first channel
  //
  // This to determine how much black pixels are present on the cropped area
  const [channel1, , , ] = roi.mean();

  // override the default rectangle color based on certain range of values
  if (channel1 <= 69) {
    shapeColor = shapeColors.crossed;
  } else if (channel1 > 69 && channel1 < 135) {
    shapeColor = shapeColors.shaded;

    isShaded = true;
  }

  // draw rectangle in the original image
  origImage.rectangle([start, end], [diameter, diameter], shapeColor, shapeThickness);

  return isShaded;
};

const imageProcessor = (imagesDirPath, outputPath, coordsDataFile, options = {}) => {
  const defaultOptions = {
    diameter: 16,
    extensions: ['jpg', 'png'],
    shapeThickness: 2,
    shapeColors: {
      blank: [0, 255, 0], // green
      crossed: [0, 255, 0], // green
      shaded: [0, 0, 255], // red
    },
  };

  // resolve the default options
  const resolvedOptions = assign({}, defaultOptions, options);

  return fetchAll(imagesDirPath, resolvedOptions.extensions)
    .then((images) => {
      // show log info
      console.log(`Reading images from the directory: ${imagesDirPath}`);
      console.log(`Saving processed files to: ${outputPath}`);

      // create an array of image promises
      const promises = images.map(imagePath => reader(imagePath));

      // process all the promises using the all method of Promise object
      return Promise.all(promises);
    })
    .then((images) => {
      // read the coordinates and re-resolve the casted images
      const retPromise = Promise.all([
        Promise.resolve(images),
        readCoordsFromFile(coordsDataFile, { delimiter: ' ' }),
      ]);

      return retPromise;
    })
    .then((values) => {
      const [images, coordsData] = values;

      // create the output folder if it does not exist
      if (!fs.existsSync(outputPath)) {
        fs.mkdirSync(outputPath);
      }

      images.forEach((image) => {
        const { cvImage, imagePath } = image;

        // show log info
        console.log(`Processing Image: ${imagePath}`);

        // convert to grayscale
        const grayImg = cvImage.copy();
        grayImg.convertGrayscale();

        // perform thresholding using Otsu
        const binaryImage = grayImg.threshold(0, 255, 'Binary', 'Otsu');

        // emulate morph_open since node-opencv doesn't support it
        const kernel = cv.imgproc.getStructuringElement(0, [5, 5]);
        binaryImage.erode(1, kernel);
        binaryImage.dilate(1, kernel);

        // initialize variables for the breakdown and statistics
        const shadeBreakdown = {};
        const statistics = {
          SA: 0,
          A: 0,
          SLA: 0,
          NAD: 0,
          SLD: 0,
          D: 0,
          SD: 0,
        };

        const statisticsKeys = Object.keys(statistics);

        coordsData.forEach((row, coordsIdx) => {
          row.forEach((coords, idx) => {
            const isShaded = processCell(cvImage, binaryImage, coords, resolvedOptions.diameter,
              resolvedOptions.shapeColors, resolvedOptions.shapeThickness);

            // identify where the item resides in the choices
            const statKey = statisticsKeys[idx];

            // add one to the matched stat value and
            // store the value of shaded key and its index to the breakdown
            if (isShaded) {
              statistics[statKey] += 1;

              shadeBreakdown[(coordsIdx + 1)] = statKey;
            }
          });
        });

        const imageBasename = path.basename(imagePath);

        // write the manipulated image to the destination folder
        cvImage.save(`${outputPath}/${imageBasename}`);

        // assemble the contents that will be written to the file
        const fileContents = summaryContentsTmpl({
          breakdown: shadeBreakdown,
          breakdownLength: coordsData.length,
          statistics,
        });

        // save the statistics in a text file
        fs.writeFileSync(`${outputPath}/${imageBasename}.txt`, fileContents);
      });
    })
    ;
};

module.exports = imageProcessor;

<|endoftext|>


<commit_before>/**
 *
 * Project Euler Problem 3
 * =======================
 *
 * The prime factors of 13195 are 5, 7, 13 and 29.
 *
 * What is the largest prime factor of the number 600851475143?
 *
 * link to reference: https://www.mathsisfun.com/prime-factorization.html
 *
 */

var utils = require('../utils/reusables.js');

function prime(n) {
  return n;
}

utils.show_answer('03', prime(600851475143));
<commit_msg>Push poorly written test can down the road another ten years<commit_after>/**
 *
 * Project Euler Problem 3
 * =======================
 *
 * The prime factors of 13195 are 5, 7, 13 and 29.
 *
 * What is the largest prime factor of the number 600851475143?
 *
 * link to reference: https://www.mathsisfun.com/prime-factorization.html
 *
 */

var utils = require('../utils/reusables.js');

function is_prime(n) {
  return true
}

function prime(n) {
  return n;
}

utils.show_answer('03', prime(600851475143));
<|endoftext|>


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

const fs = require("fs");
const path = require("path");
const https = require("https");
const exec = require("child_process").exec;

const name = process.argv[2];
const repo = process.argv[3] || "kbrsh/moon-template";
const archive = {
	method: "GET",
	host: "api.github.com",
	path: `/repos/${repo}/tarball/master`,
	headers: {
		"User-Agent": "Node.js"
	}
};

const MoonNameRE = /{# MoonName #}/g;

const log = (type, message) => {
	console.log(`\x1b[34m${type}\x1b[0m ${message}`);
};

const download = (res) => {
	const archivePath = path.join(__dirname, "moon-template.tar.gz");
	const stream = fs.createWriteStream(archivePath);

	res.on("data", (chunk) => {
		stream.write(chunk);
	});

	res.on("end", () => {
		stream.end();
		log("download", "template");
		install(archivePath);
	});
};

const install = (archivePath) => {
	const targetPath = path.join(process.cwd(), name);
	exec(`mkdir ${targetPath}; tar -xzf ${archivePath} -C ${targetPath} --strip=1`, (err) => {
		if (err) throw err;

		log("install", "template");

		clean(archivePath, targetPath);
	});
};

const clean = (archivePath, targetPath) => {
	fs.unlink(archivePath, (err) => {
		if (err) throw err;

		log("clean", "template");

		create(targetPath, targetPath);
		log("success", `Generated project "${name}"`)
		console.log(`To start, run:
	cd ${name}
	npm install
	npm run dev`);
	});
};

const create = (currentPath, targetPath) => {
	const files = fs.readdirSync(currentPath);
	for (let i = 0; i < files.length; i++) {
		const file = files[i];
		const nextPath = path.join(currentPath, file);
		if (fs.statSync(nextPath).isDirectory()) {
			create(nextPath, targetPath);
		} else {
			fs.writeFileSync(nextPath, fs.readFileSync(nextPath).toString().replace(MoonNameRE, name));
			log("create", path.relative(targetPath, nextPath));
		}
	}
};

https.get(archive, (res) => {
	if (res.statusCode > 300 && res.statusCode < 400 && res.headers.location !== undefined) {
		https.get(res.headers.location, (redirectRes) => {
			download(redirectRes);
		});
	} else {
		download(res);
	}
});
<commit_msg>split up download instructions<commit_after>#!/usr/bin/env node

const fs = require("fs");
const path = require("path");
const https = require("https");
const exec = require("child_process").exec;

const name = process.argv[2];
const repo = process.argv[3] || "kbrsh/moon-template";
const archive = {
	method: "GET",
	host: "api.github.com",
	path: `/repos/${repo}/tarball/master`,
	headers: {
		"User-Agent": "Node.js"
	}
};

const MoonNameRE = /{# MoonName #}/g;

const log = (type, message) => {
	console.log(`\x1b[34m${type}\x1b[0m ${message}`);
};

const download = (res) => {
	const archivePath = path.join(__dirname, "moon-template.tar.gz");
	const stream = fs.createWriteStream(archivePath);

	res.on("data", (chunk) => {
		stream.write(chunk);
	});

	res.on("end", () => {
		stream.end();
		log("download", "template");
		install(archivePath);
	});
};

const install = (archivePath) => {
	const targetPath = path.join(process.cwd(), name);

	exec(`mkdir ${targetPath}`, (err) => {
		if (err) throw err;
	});

	exec(`tar -xzf ${archivePath} -C ${targetPath} --strip=1`, (err) => {
		if (err) throw err;

		log("install", "template");

		clean(archivePath, targetPath);
	});
};

const clean = (archivePath, targetPath) => {
	fs.unlink(archivePath, (err) => {
		if (err) throw err;

		log("clean", "template");

		create(targetPath, targetPath);
		log("success", `Generated project "${name}"`)
		console.log(`To start, run:
	cd ${name}
	npm install
	npm run dev`);
	});
};

const create = (currentPath, targetPath) => {
	const files = fs.readdirSync(currentPath);
	for (let i = 0; i < files.length; i++) {
		const file = files[i];
		const nextPath = path.join(currentPath, file);
		if (fs.statSync(nextPath).isDirectory()) {
			create(nextPath, targetPath);
		} else {
			fs.writeFileSync(nextPath, fs.readFileSync(nextPath).toString().replace(MoonNameRE, name));
			log("create", path.relative(targetPath, nextPath));
		}
	}
};

https.get(archive, (res) => {
	if (res.statusCode > 300 && res.statusCode < 400 && res.headers.location !== undefined) {
		https.get(res.headers.location, (redirectRes) => {
			download(redirectRes);
		});
	} else {
		download(res);
	}
});
<|endoftext|>


<commit_before>({
  appDir: '../src/',

  baseUrl: 'js',

  dir: '../dist/',

  optimize: 'none',

  pragmas: {
    asynchLoader: true
  },

  locale: 'en-us',

  packages: [
    {
      name: 'dojo',
      location: 'dojo-release-1.6.0-src/dojo',
      main: 'lib/main-browser',
      lib: '.'
    },
    {
      name: 'dijit',
      location: 'dojo-release-1.6.0-src/dijit',
      main: 'lib/main',
      lib: '.'
    }
  ],

  modules: [
    {
      name: 'app/_base'
    }
  ]
})<commit_msg>I have an idea: let's make sure the built version is actually optimized.<commit_after>({
  appDir: '../src/',

  baseUrl: 'js',

  dir: '../dist/',

  pragmas: {
    asynchLoader: true
  },

  locale: 'en-us',

  packages: [
    {
      name: 'dojo',
      location: 'dojo-release-1.6.0-src/dojo',
      main: 'lib/main-browser',
      lib: '.'
    },
    {
      name: 'dijit',
      location: 'dojo-release-1.6.0-src/dijit',
      main: 'lib/main',
      lib: '.'
    }
  ],

  modules: [
    {
      name: 'app/_base'
    }
  ]
})<|endoftext|>


<commit_before>(function(root, factory) {
    if (typeof define == 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports == 'object') {
        module.exports = factory(require('jquery'));
    } else {
        factory(root.$);
    }
}(this, function($) {
    var $keyValDiv = $('<div>').css('display', 'inline-block'),
        createLine = function(opt) {
            var indentation = opt.vtdOpt.indentation * opt.vtdOpt.indentationPadding,
                $line = $('<div>').css('white-space', 'nowrap'),
                $key = $keyValDiv
                    .clone()
                    .addClass('key')
                    .css('padding-left', indentation)
                    .text(opt.key + ':'),
                $val = $keyValDiv
                    .clone()
                    .text(opt.beginCollection ? opt.beginCollection : opt.endCollection ? opt.endCollection : opt.val);

            if (opt.beginCollection == '{' || opt.endCollection == '}') {
                $val.addClass('object');
            }
            else if (opt.beginCollection == '[' || opt.endCollection == ']') {
                $val.addClass('array');
            }

            if ($.type(opt.val) == 'boolean') {
                $val.addClass('boolean');
            }
            else if ($.type(opt.val) == 'string') {
                $val.addClass('string')
                    .text('"' + $val.text() + '"');
            }
            else if ($.isNumeric(opt.val)) {
                $val.addClass('number');
            }

            if (opt.key == null || $.type(opt.endCollection) == 'string') {
                $val.css('padding-left', indentation);
            }
            else {
                $line.append($key);
                $val.css('padding-left', opt.vtdOpt.keyValPadding);
            }

            $line.append($val);

            return $line;
        },
        processKeyVal = function($el, key, val, opt) {
            var isObject = $.isPlainObject(val);

            if (isObject || $.isArray(val)) {
                if (isObject) {
                    $el.append(createLine({key: key, vtdOpt: opt, beginCollection: '{'}));
                }
                else {
                    $el.append(createLine({key: key, vtdOpt: opt, beginCollection: '['}));

                    val = $.extend({}, val);
                }

                $el.varToDOM(
                    $.extend({}, opt, {
                        var: val,
                        indentation: opt.indentation + 1,
                        _timesIndented: opt._timesIndented + 1,
                        onComplete: function() {
                            $el.append(createLine({vtdOpt: opt, endCollection: isObject ? '}' : ']'}));
                        }
                    })
                );
            }
            else {
                $el.append(createLine({key: key, val: val, vtdOpt: opt}));
            }
        };

    $.fn.varToDOM = function(opt) {
        var $el = $(this);

        if (!$el.length) {
            throw new TypeError('Cannot run varToDOM on an empty jQuery object');
        }
        if (!$.isPlainObject(opt)) {
            throw new TypeError('varToDOM must be supplied an options object');
        }
        if (opt.var === undefined) {
            throw new TypeError('The varToDOM options object must have a var property');
        }
        if (opt.indentation !== undefined && !$.isNumeric(opt.indentation)) {
            throw new TypeError('The varToDOM indentation level must be numeric');
        }
        if (opt.indentationPadding !== undefined && !$.isNumeric(opt.indentationPadding)) {
            throw new TypeError('The varToDOM indentation padding must be numeric');
        }
        if (opt.keyValPadding !== undefined && !$.isNumeric(opt.keyValPadding)) {
            throw new TypeError('The varToDOM key / value padding must be numeric');
        }
        if (opt.onComplete !== undefined && !$.isFunction(opt.onComplete)) {
            throw new TypeError('varToDOM onComplete must be a function');
        }

        if (!$.isNumeric(opt.indentation)) {
            opt.indentation = 0;
        }
        if (!$.isNumeric(opt.indentationPadding)) {
            opt.indentationPadding = 20;
        }
        if (!$.isNumeric(opt.keyValPadding)) {
            opt.keyValPadding = 10;
        }
        if (!$.isNumeric(opt._timesIndented)) {
            opt._timesIndented = 0;
        }

        if ($.isPlainObject(opt.var) || $.isArray(opt.var)) {
            if (opt._timesIndented === 0) {
                processKeyVal($el, null, opt.var, opt);
            }
            else {
                $.each(opt.var, function(key, val) {
                    processKeyVal($el, key, val, opt);
                });
            }
        }
        else {
            $el.append(createLine({key: null, val: opt.var, vtdOpt: opt}));
        }

        if ($.isFunction(opt.onComplete)) {
            opt.onComplete();
        }
    };
}));<commit_msg>Don't call createLine from $.fn.varToDOM<commit_after>(function(root, factory) {
    if (typeof define == 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports == 'object') {
        module.exports = factory(require('jquery'));
    } else {
        factory(root.$);
    }
}(this, function($) {
    var $keyValDiv = $('<div>').css('display', 'inline-block'),
        createLine = function(opt) {
            var indentation = opt.vtdOpt.indentation * opt.vtdOpt.indentationPadding,
                $line = $('<div>').css('white-space', 'nowrap'),
                $key = $keyValDiv
                    .clone()
                    .addClass('key')
                    .css('padding-left', indentation)
                    .text(opt.key + ':'),
                $val = $keyValDiv
                    .clone()
                    .text(opt.beginCollection ? opt.beginCollection : opt.endCollection ? opt.endCollection : opt.val);

            if (opt.beginCollection == '{' || opt.endCollection == '}') {
                $val.addClass('object');
            }
            else if (opt.beginCollection == '[' || opt.endCollection == ']') {
                $val.addClass('array');
            }

            if ($.type(opt.val) == 'boolean') {
                $val.addClass('boolean');
            }
            else if ($.type(opt.val) == 'string') {
                $val.addClass('string')
                    .text('"' + $val.text() + '"');
            }
            else if ($.isNumeric(opt.val)) {
                $val.addClass('number');
            }

            if (opt.key == null || $.type(opt.endCollection) == 'string') {
                $val.css('padding-left', indentation);
            }
            else {
                $line.append($key);
                $val.css('padding-left', opt.vtdOpt.keyValPadding);
            }

            $line.append($val);

            return $line;
        },
        processKeyVal = function($el, key, val, opt) {
            var isObject = $.isPlainObject(val);

            if (isObject || $.isArray(val)) {
                if (isObject) {
                    $el.append(createLine({key: key, vtdOpt: opt, beginCollection: '{'}));
                }
                else {
                    $el.append(createLine({key: key, vtdOpt: opt, beginCollection: '['}));

                    val = $.extend({}, val);
                }

                $el.varToDOM(
                    $.extend({}, opt, {
                        var: val,
                        indentation: opt.indentation + 1,
                        _timesIndented: opt._timesIndented + 1,
                        onComplete: function() {
                            $el.append(createLine({vtdOpt: opt, endCollection: isObject ? '}' : ']'}));
                        }
                    })
                );
            }
            else {
                $el.append(createLine({key: key, val: val, vtdOpt: opt}));
            }
        };

    $.fn.varToDOM = function(opt) {
        var $el = $(this);

        if (!$el.length) {
            throw new TypeError('Cannot run varToDOM on an empty jQuery object');
        }
        if (!$.isPlainObject(opt)) {
            throw new TypeError('varToDOM must be supplied an options object');
        }
        if (opt.var === undefined) {
            throw new TypeError('The varToDOM options object must have a var property');
        }
        if (opt.indentation !== undefined && !$.isNumeric(opt.indentation)) {
            throw new TypeError('The varToDOM indentation level must be numeric');
        }
        if (opt.indentationPadding !== undefined && !$.isNumeric(opt.indentationPadding)) {
            throw new TypeError('The varToDOM indentation padding must be numeric');
        }
        if (opt.keyValPadding !== undefined && !$.isNumeric(opt.keyValPadding)) {
            throw new TypeError('The varToDOM key / value padding must be numeric');
        }
        if (opt.onComplete !== undefined && !$.isFunction(opt.onComplete)) {
            throw new TypeError('varToDOM onComplete must be a function');
        }

        if (!$.isNumeric(opt.indentation)) {
            opt.indentation = 0;
        }
        if (!$.isNumeric(opt.indentationPadding)) {
            opt.indentationPadding = 20;
        }
        if (!$.isNumeric(opt.keyValPadding)) {
            opt.keyValPadding = 10;
        }
        if (!$.isNumeric(opt._timesIndented)) {
            opt._timesIndented = 0;
        }

        if ($.isPlainObject(opt.var) || $.isArray(opt.var)) {
            if (opt._timesIndented === 0) {
                processKeyVal($el, null, opt.var, opt);
            }
            else {
                $.each(opt.var, function(key, val) {
                    processKeyVal($el, key, val, opt);
                });
            }
        }
        else {
            processKeyVal($el, null, opt.var, opt);
        }

        if ($.isFunction(opt.onComplete)) {
            opt.onComplete();
        }
    };
}));<|endoftext|>


<commit_before>(function (tree) {

tree.Media = function (value, features) {
    var el = new(tree.Element)('&', null, 0),
        selectors = [new(tree.Selector)([el])];

    this.features = new(tree.Value)(features);
    this.ruleset = new(tree.Ruleset)(selectors, value);
    this.ruleset.allowImports = true;
};
tree.Media.prototype = {
    toCSS: function (ctx, env) {
        var features = this.features.toCSS(env);

        this.ruleset.root = (ctx.length === 0 || ctx[0].multiMedia);
        return '@media ' + features + (env.compress ? '{' : ' {\n  ') +
               this.ruleset.toCSS(ctx, env).trim().replace(/\n/g, '\n  ') +
                           (env.compress ? '}': '\n}\n');
    },
    eval: function (env) {
        if (!env.mediaBlocks) {
          env.mediaBlocks = [];
          env.mediaPath = [];
        }

        env.mediaBlocks.push(this);
        env.mediaPath.push(this);

        this.features = this.features.eval(env);
        env.frames.unshift(this);
        this.ruleset = this.ruleset.eval(env);
        env.frames.shift();

        env.mediaPath.pop();

        if (env.mediaPath.length === 0) {
          return this.evalTop(env);
        } else {
          return this.evalNested(env);
        }
    },
    variable: function (name) { return tree.Ruleset.prototype.variable.call(this.ruleset, name) },
    find: function () { return tree.Ruleset.prototype.find.apply(this.ruleset, arguments) },
    rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.ruleset) },

    evalTop: function (env) {
      var result = this;

      // Render all dependent Media blocks.
      if (env.mediaBlocks.length > 1) {
        var el = new(tree.Element)('&', null, 0);
        var selectors = [new(tree.Selector)([el])];
        result = new(tree.Ruleset)(selectors, env.mediaBlocks);
        result.multiMedia = true;
      }

      delete env.mediaBlocks;
      delete env.mediaPath;

      return result;
    },
    evalNested: function (env) {
      var i, value,
          path = env.mediaPath.concat([this]);

      // Extract the media-query conditions separated with `,` (OR).
      for (i = 0; i < path.length; i++) {
        value = path[i].features instanceof tree.Value ?
                  path[i].features.value : path[i].features;
        path[i] = Array.isArray(value) ? value : [value];
      }

      // Trace all permutations to generate the resulting media-query.
      //
      // (a, b and c) with nested (d, e) ->
      //    a and d
      //    a and e
      //    b and c and d
      //    b and c and e
      this.features = new(tree.Value)(this.permute(path).map(function (path) {
        path = path.map(function (fragment) {
          return fragment.toCSS ? fragment : new(tree.Anonymous)(fragment);
        });

        for(i = path.length - 1; i > 0; i--) {
          path.splice(i, 0, new(tree.Anonymous)("and"));
        }

        return new(tree.Expression)(path);
      }));

      // Fake a tree-node that doesn't output anything.
      return new(tree.Ruleset)([], []);
    },
    permute: function (arr) {
      if (arr.length == 0) {
        return [];
      } else if (arr.length == 1) {
        return arr[0];
      } else {
        var result = [];
        var rest = this.permute(arr.slice(1));
        for (var i = 0; i < rest.length; i++) {
          for (var j = 0; j < arr[0].length; j++) {
            result.push([arr[0][j]].concat(rest[i]));
          }
        }
        return result;
      }
    }
};

})(require('../tree'));
<commit_msg>adjusted indent-whitespace to 4 spaces<commit_after>(function (tree) {

tree.Media = function (value, features) {
    var el = new(tree.Element)('&', null, 0),
        selectors = [new(tree.Selector)([el])];

    this.features = new(tree.Value)(features);
    this.ruleset = new(tree.Ruleset)(selectors, value);
    this.ruleset.allowImports = true;
};
tree.Media.prototype = {
    toCSS: function (ctx, env) {
        var features = this.features.toCSS(env);

        this.ruleset.root = (ctx.length === 0 || ctx[0].multiMedia);
        return '@media ' + features + (env.compress ? '{' : ' {\n  ') +
               this.ruleset.toCSS(ctx, env).trim().replace(/\n/g, '\n  ') +
                           (env.compress ? '}': '\n}\n');
    },
    eval: function (env) {
        if (!env.mediaBlocks) {
            env.mediaBlocks = [];
            env.mediaPath = [];
        }

        env.mediaBlocks.push(this);
        env.mediaPath.push(this);

        this.features = this.features.eval(env);
        env.frames.unshift(this);
        this.ruleset = this.ruleset.eval(env);
        env.frames.shift();

        env.mediaPath.pop();

        if (env.mediaPath.length === 0) {
            return this.evalTop(env);
        } else {
            return this.evalNested(env);
        }
    },
    variable: function (name) { return tree.Ruleset.prototype.variable.call(this.ruleset, name) },
    find: function () { return tree.Ruleset.prototype.find.apply(this.ruleset, arguments) },
    rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.ruleset) },

    evalTop: function (env) {
        var result = this;

        // Render all dependent Media blocks.
        if (env.mediaBlocks.length > 1) {
            var el = new(tree.Element)('&', null, 0);
            var selectors = [new(tree.Selector)([el])];
            result = new(tree.Ruleset)(selectors, env.mediaBlocks);
            result.multiMedia = true;
        }

        delete env.mediaBlocks;
        delete env.mediaPath;

        return result;
    },
    evalNested: function (env) {
        var i, value,
            path = env.mediaPath.concat([this]);

        // Extract the media-query conditions separated with `,` (OR).
        for (i = 0; i < path.length; i++) {
            value = path[i].features instanceof tree.Value ?
                        path[i].features.value : path[i].features;
            path[i] = Array.isArray(value) ? value : [value];
        }

        // Trace all permutations to generate the resulting media-query.
        //
        // (a, b and c) with nested (d, e) ->
        //    a and d
        //    a and e
        //    b and c and d
        //    b and c and e
        this.features = new(tree.Value)(this.permute(path).map(function (path) {
            path = path.map(function (fragment) {
                return fragment.toCSS ? fragment : new(tree.Anonymous)(fragment);
            });

            for(i = path.length - 1; i > 0; i--) {
                path.splice(i, 0, new(tree.Anonymous)("and"));
            }

            return new(tree.Expression)(path);
        }));

        // Fake a tree-node that doesn't output anything.
        return new(tree.Ruleset)([], []);
    },
    permute: function (arr) {
      if (arr.length == 0) {
          return [];
      } else if (arr.length == 1) {
          return arr[0];
      } else {
          var result = [];
          var rest = this.permute(arr.slice(1));
          for (var i = 0; i < rest.length; i++) {
              for (var j = 0; j < arr[0].length; j++) {
                  result.push([arr[0][j]].concat(rest[i]));
              }
          }
          return result;
      }
    }
};

})(require('../tree'));
<|endoftext|>


<commit_before>'use strict';

var events = require('events');

var express = require('express');
var mocks = require('node-mocks-http');

var createMiddleware = require('hops-middleware');

module.exports = function createRenderer (options) {
  var hopsConfig = options.hopsConfig || {};
  var router = new express.Router();

  if (hopsConfig.bootstrapServer) {
    hopsConfig.bootstrapServer(router, hopsConfig);
  }

  router.use(createMiddleware(
    options.webpackConfig,
    options.watchOptions
  ));

  return function (location) {
    return new Promise(function (resolve, reject) {
      var req = mocks.createRequest({
        url: location
      });
      var res = mocks.createResponse({
        eventEmitter: events.EventEmitter,
        request: req
      });
      res.on('finish', function () {
        if (res.statusCode !== 200) {
          reject(new Error('invalid status code: ' + res.statusCode));
        } else {
          resolve(res._getData());
        }
      });
      router.handle(req, res, function (error) {
        if (error) { reject(error); } else { resolve(); }
      });
    });
  };
};
<commit_msg>feat(renderer): add support for an options hash<commit_after>'use strict';

var events = require('events');

var express = require('express');
var mocks = require('node-mocks-http');

var createMiddleware = require('hops-middleware');

module.exports = function createRenderer (options) {
  var hopsConfig = options.hopsConfig || {};
  var router = new express.Router();

  if (hopsConfig.bootstrapServer) {
    hopsConfig.bootstrapServer(router, hopsConfig);
  }

  router.use(createMiddleware(
    options.webpackConfig,
    options.watchOptions
  ));

  return function (options) {
    if (typeof options === 'string') {
      options = { url: options };
    }
    return new Promise(function (resolve, reject) {
      var req = mocks.createRequest(options);
      var res = mocks.createResponse({
        eventEmitter: events.EventEmitter,
        request: req
      });
      res.on('finish', function () {
        if (res.statusCode !== 200) {
          reject(new Error('invalid status code: ' + res.statusCode));
        } else {
          resolve(res._getData());
        }
      });
      router.handle(req, res, function (error) {
        if (error) { reject(error); } else { resolve(); }
      });
    });
  };
};
<|endoftext|>


<commit_before>/**
 * 文字类型的按钮
 * @class BI.Button
 * @extends BI.BasicButton
 *
 * @cfg {JSON} options 配置属性
 * @cfg {'common'/'success'/'warning'/'ignore'} [options.level='common'] 按钮类型，用不同颜色强调不同的场景
 */
BI.Button = BI.inherit(BI.BasicButton, {

    _const: {
        iconWidth: 18
    },

    _defaultConfig: function (props) {
        var conf = BI.Button.superclass._defaultConfig.apply(this, arguments);
        return BI.extend(conf, {
            baseCls: (conf.baseCls || "") + " bi-button" + ((BI.isIE() && BI.isIE9Below()) ? " hack" : ""),
            minWidth: (props.block === true || props.clear === true) ? 0 : 80,
            height: 24,
            shadow: props.clear !== true,
            isShadowShowingOnSelected: true,
            readonly: true,
            iconCls: "",
            level: "common",
            block: false, // 是否块状显示，即不显示边框，没有最小宽度的限制
            clear: false, // 是否去掉边框和背景
            ghost: false, // 是否幽灵显示, 即正常状态无背景
            textAlign: "center",
            whiteSpace: "nowrap",
            textWidth: null,
            textHeight: null,
            hgap: props.clear ? 0 : 10,
            vgap: 0,
            tgap: 0,
            bgap: 0,
            lgap: 0,
            rgap: 0
        });
    },

    render: function () {
        var o = this.options, self = this;

        // 由于button默认情况下有个边框，所以要主动算行高
        var lineHeight, textHeight = o.textHeight;
        if (BI.isNumber(o.height)) {
            if (o.clear || o.block) {
                lineHeight = o.height;
            } else {
                lineHeight = o.height - 2;
            }
        }
        if (!textHeight) {
            if (o.whiteSpace === "nowrap") {
                textHeight = lineHeight;
            }
        }
        if (BI.isKey(o.iconCls)) {
            this.icon = BI.createWidget({
                type: "bi.icon_label",
                cls: o.iconCls,
                width: this._const.iconWidth,
                height: lineHeight,
                lineHeight: lineHeight,
                iconWidth: o.iconWidth,
                iconHeight: o.iconHeight
            });
            this.text = BI.createWidget({
                type: "bi.label",
                text: o.text,
                textWidth: BI.isNotNull(o.textWidth) ? o.textWidth - this._const.iconWidth : null,
                textHeight: textHeight,
                height: lineHeight,
                value: o.value
            });
            BI.createWidget({
                type: "bi.center_adapt",
                element: this,
                hgap: o.hgap,
                vgap: o.vgap,
                items: [{
                    type: "bi.horizontal",
                    columnSize: ["", "fill"],
                    items: [this.icon, this.text]
                }]
            });
        } else {
            this.text = BI.createWidget({
                type: "bi.label",
                height: lineHeight,
                textAlign: o.textAlign,
                whiteSpace: o.whiteSpace,
                textWidth: o.textWidth,
                textHeight: textHeight,
                hgap: o.hgap,
                vgap: o.vgap,
                tgap: o.tgap,
                bgap: o.bgap,
                lgap: o.lgap,
                rgap: o.rgap,
                element: this,
                text: o.text,
                value: o.value
            });
        }
        if (o.block === true) {
            this.element.addClass("block");
        }
        if (o.clear === true) {
            this.element.addClass("clear");
        }
        if (o.ghost === true) {
            this.element.addClass("ghost");
        }
        if (o.minWidth > 0) {
            this.element.css({"min-width": o.minWidth / BI.pixRatio + BI.pixUnit});
        }
    },

    doClick: function () {
        BI.Button.superclass.doClick.apply(this, arguments);
        if (this.isValid()) {
            this.fireEvent(BI.Button.EVENT_CHANGE, this);
        }
    },

    setText: function (text) {
        BI.Button.superclass.setText.apply(this, arguments);
        this.text.setText(text);
    },

    setValue: function (text) {
        BI.Button.superclass.setValue.apply(this, arguments);
        if (!this.isReadOnly()) {
            this.text.setValue(text);
        }
    },

    doRedMark: function () {
        this.text.doRedMark.apply(this.text, arguments);
    },

    unRedMark: function () {
        this.text.unRedMark.apply(this.text, arguments);
    },

    doHighLight: function () {
        this.text.doHighLight.apply(this.text, arguments);
    },

    unHighLight: function () {
        this.text.unHighLight.apply(this.text, arguments);
    }
});
BI.shortcut("bi.button", BI.Button);
BI.Button.EVENT_CHANGE = "EVENT_CHANGE";
<commit_msg>Pull request #2349: 无JIRA任务 bugfix<commit_after>/**
 * 文字类型的按钮
 * @class BI.Button
 * @extends BI.BasicButton
 *
 * @cfg {JSON} options 配置属性
 * @cfg {'common'/'success'/'warning'/'ignore'} [options.level='common'] 按钮类型，用不同颜色强调不同的场景
 */
BI.Button = BI.inherit(BI.BasicButton, {

    _const: {
        iconWidth: 18
    },

    _defaultConfig: function (props) {
        var conf = BI.Button.superclass._defaultConfig.apply(this, arguments);
        return BI.extend(conf, {
            baseCls: (conf.baseCls || "") + " bi-button" + ((BI.isIE() && BI.isIE9Below()) ? " hack" : ""),
            minWidth: (props.block === true || props.clear === true) ? 0 : 80,
            height: 24,
            shadow: props.clear !== true,
            isShadowShowingOnSelected: true,
            readonly: true,
            iconCls: "",
            level: "common",
            block: false, // 是否块状显示，即不显示边框，没有最小宽度的限制
            clear: false, // 是否去掉边框和背景
            ghost: false, // 是否幽灵显示, 即正常状态无背景
            textAlign: "center",
            whiteSpace: "nowrap",
            textWidth: null,
            textHeight: null,
            hgap: props.clear ? 0 : 10,
            vgap: 0,
            tgap: 0,
            bgap: 0,
            lgap: 0,
            rgap: 0
        });
    },

    render: function () {
        var o = this.options, self = this;

        // 由于button默认情况下有个边框，所以要主动算行高
        var lineHeight, textHeight = o.textHeight;
        if (BI.isNumber(o.height)) {
            if (o.clear || o.block) {
                lineHeight = o.height;
            } else {
                lineHeight = o.height - 2;
            }
        }
        if (!textHeight) {
            if (o.whiteSpace === "nowrap") {
                textHeight = lineHeight;
            }
        }
        if (BI.isKey(o.iconCls)) {
            this.icon = BI.createWidget({
                type: "bi.icon_label",
                cls: o.iconCls,
                width: this._const.iconWidth,
                height: lineHeight,
                lineHeight: lineHeight,
                iconWidth: o.iconWidth,
                iconHeight: o.iconHeight
            });
            this.text = BI.createWidget({
                type: "bi.label",
                text: o.text,
                textWidth: BI.isNotNull(o.textWidth) ? o.textWidth - this._const.iconWidth : null,
                textHeight: textHeight,
                height: lineHeight,
                value: o.value
            });
            BI.createWidget({
                type: "bi.center_adapt",
                element: this,
                hgap: o.hgap,
                vgap: o.vgap,
                items: [{
                    type: "bi.horizontal",
                    columnSize: ["", "fill"],
                    items: [this.icon, this.text]
                }]
            });
        } else {
            this.text = BI.createWidget({
                type: "bi.label",
                height: o.height,
                textAlign: o.textAlign,
                whiteSpace: o.whiteSpace,
                textWidth: o.textWidth,
                textHeight: textHeight,
                hgap: o.hgap,
                vgap: o.vgap,
                tgap: o.tgap,
                bgap: o.bgap,
                lgap: o.lgap,
                rgap: o.rgap,
                element: this,
                text: o.text,
                value: o.value
            });
        }
        if (o.block === true) {
            this.element.addClass("block");
        }
        if (o.clear === true) {
            this.element.addClass("clear");
        }
        if (o.ghost === true) {
            this.element.addClass("ghost");
        }
        if (o.minWidth > 0) {
            this.element.css({"min-width": o.minWidth / BI.pixRatio + BI.pixUnit});
        }
    },

    doClick: function () {
        BI.Button.superclass.doClick.apply(this, arguments);
        if (this.isValid()) {
            this.fireEvent(BI.Button.EVENT_CHANGE, this);
        }
    },

    setText: function (text) {
        BI.Button.superclass.setText.apply(this, arguments);
        this.text.setText(text);
    },

    setValue: function (text) {
        BI.Button.superclass.setValue.apply(this, arguments);
        if (!this.isReadOnly()) {
            this.text.setValue(text);
        }
    },

    doRedMark: function () {
        this.text.doRedMark.apply(this.text, arguments);
    },

    unRedMark: function () {
        this.text.unRedMark.apply(this.text, arguments);
    },

    doHighLight: function () {
        this.text.doHighLight.apply(this.text, arguments);
    },

    unHighLight: function () {
        this.text.unHighLight.apply(this.text, arguments);
    }
});
BI.shortcut("bi.button", BI.Button);
BI.Button.EVENT_CHANGE = "EVENT_CHANGE";
<|endoftext|>


<commit_before>const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  })

  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})
<commit_msg>Do not open devtools by default<commit_after>const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  })

  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Uncomment next line to open the DevTools.
  // win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})
<|endoftext|>


<commit_before>"use strict";

var getEffProp = function (name) {
  return function (node) {
    return function () {
      return node[name];
    };
  };
};

exports.nodeTypeIndex = function (node) {
  return node.nodeType;
};

exports.nodeName = function (node) {
  return node.nodeName;
};

exports.baseURI = getEffProp("baseURI");

exports.ownerDocument = getEffProp("ownerDocument");

exports.parentNode = getEffProp("parentNode");

exports.parentElement = getEffProp("parentElement");

exports.hasChildNodes = function (node) {
  return function () {
    return node.hasChildNodes();
  };
};

exports.childNodes = getEffProp("childNodes");

exports.firstChild = getEffProp("firstChild");

exports.lastChild = getEffProp("lastChild");

exports.previousSibling = getEffProp("previousSibling");

exports.nextSibling = getEffProp("nextSibling");

exports.nodeValue = getEffProp("nodeValue");

exports.setNodeValue = function (value) {
  return function (node) {
    return function () {
      node.nodeValue = value;
      return {};
    };
  };
};

exports.textContent = getEffProp("textContent");

exports.setTextContent = function (value) {
  return function (node) {
    return function () {
      node.textContent = value;
      return {};
    };
  };
};

exports.normalize = function (node) {
  return function () {
    node.normalize();
    return {};
  };
};

exports.clone = function (node) {
  return function () {
    return node.clone(false);
  };
};

exports.deepClone = function (node) {
  return function () {
    return node.clone(false);
  };
};

exports.isEqualNode = function (node1) {
  return function (node2) {
    return function () {
      return node1.isEqualNode(node2);
    };
  };
};

exports.compareDocumentPositionBits = function (node1) {
  return function (node2) {
    return function () {
      return node1.compareDocumentPosition(node2);
    };
  };
};

exports.contains = function (node1) {
  return function (node2) {
    return function () {
      return node1.contains(node2);
    };
  };
};

exports.lookupPrefix = function (prefix) {
  return function (node) {
    return function () {
      return node.lookupPrefix(prefix);
    };
  };
};

exports.lookupNamespaceURI = function (ns) {
  return function (node) {
    return function () {
      return node.lookupNamespaceURI(ns);
    };
  };
};

exports.isDefaultNamespace = function (ns) {
  return function (node) {
    return function () {
      return node.isDefaultNamespace(ns);
    };
  };
};

exports.insertBefore = function (node1) {
  return function (node2) {
    return function (parent) {
      return function () {
        return parent.insertBefore(node1, node2);
      };
    };
  };
};

exports.appendChild = function (node) {
  return function (parent) {
    return function () {
      return parent.appendChild(node);
    };
  };
};

exports.replaceChild = function (oldChild) {
  return function (newChild) {
    return function (parent) {
      return function () {
        return parent.replaceChild(oldChild, newChild);
      };
    };
  };
};

exports.removeChild = function (node) {
  return function (parent) {
    return function () {
      return parent.removeChild(node);
    };
  };
};
<commit_msg>Rename replaceChild arguments to reflect function logic<commit_after>"use strict";

var getEffProp = function (name) {
  return function (node) {
    return function () {
      return node[name];
    };
  };
};

exports.nodeTypeIndex = function (node) {
  return node.nodeType;
};

exports.nodeName = function (node) {
  return node.nodeName;
};

exports.baseURI = getEffProp("baseURI");

exports.ownerDocument = getEffProp("ownerDocument");

exports.parentNode = getEffProp("parentNode");

exports.parentElement = getEffProp("parentElement");

exports.hasChildNodes = function (node) {
  return function () {
    return node.hasChildNodes();
  };
};

exports.childNodes = getEffProp("childNodes");

exports.firstChild = getEffProp("firstChild");

exports.lastChild = getEffProp("lastChild");

exports.previousSibling = getEffProp("previousSibling");

exports.nextSibling = getEffProp("nextSibling");

exports.nodeValue = getEffProp("nodeValue");

exports.setNodeValue = function (value) {
  return function (node) {
    return function () {
      node.nodeValue = value;
      return {};
    };
  };
};

exports.textContent = getEffProp("textContent");

exports.setTextContent = function (value) {
  return function (node) {
    return function () {
      node.textContent = value;
      return {};
    };
  };
};

exports.normalize = function (node) {
  return function () {
    node.normalize();
    return {};
  };
};

exports.clone = function (node) {
  return function () {
    return node.clone(false);
  };
};

exports.deepClone = function (node) {
  return function () {
    return node.clone(false);
  };
};

exports.isEqualNode = function (node1) {
  return function (node2) {
    return function () {
      return node1.isEqualNode(node2);
    };
  };
};

exports.compareDocumentPositionBits = function (node1) {
  return function (node2) {
    return function () {
      return node1.compareDocumentPosition(node2);
    };
  };
};

exports.contains = function (node1) {
  return function (node2) {
    return function () {
      return node1.contains(node2);
    };
  };
};

exports.lookupPrefix = function (prefix) {
  return function (node) {
    return function () {
      return node.lookupPrefix(prefix);
    };
  };
};

exports.lookupNamespaceURI = function (ns) {
  return function (node) {
    return function () {
      return node.lookupNamespaceURI(ns);
    };
  };
};

exports.isDefaultNamespace = function (ns) {
  return function (node) {
    return function () {
      return node.isDefaultNamespace(ns);
    };
  };
};

exports.insertBefore = function (node1) {
  return function (node2) {
    return function (parent) {
      return function () {
        return parent.insertBefore(node1, node2);
      };
    };
  };
};

exports.appendChild = function (node) {
  return function (parent) {
    return function () {
      return parent.appendChild(node);
    };
  };
};

exports.replaceChild = function (newChild) {
  return function (oldChild) {
    return function (parent) {
      return function () {
        return parent.replaceChild(newChild, oldChild);
      };
    };
  };
};

exports.removeChild = function (node) {
  return function (parent) {
    return function () {
      return parent.removeChild(node);
    };
  };
};
<|endoftext|>


<commit_before>
'use strict';

var path = require('path');
var core = require('thehelp-core');
core.env.merge(path.join(__dirname, '../../env.json'));
core.logs.setupConsole();

var fs = require('fs');
var cluster = require('cluster');

var logShim = require('thehelp-log-shim');
var logger = logShim('end-to-end:server');
var express = require('express');
var morgan = require('morgan');

var thCluster = require('../../src/server');
var gracefulExpress = new thCluster.GracefulExpress();

var app = express();

app.use(morgan('combined', {
  stream: {
    write: function(text) {
      logger.info(text.replace(/\n$/, ''));
    }
  }
}));

var worker = cluster.isMaster ? 'n/a' : cluster.worker.id;
app.use(function(req, res, next) {
  res.header('X-Worker', worker);
  next();
});

app.use(gracefulExpress.middleware);

app.get('/', function(req, res) {
  res.send('success');
});

app.get('/delay', function(req, res) {
  setTimeout(function() {
    res.send('OK\n');
  }, 2000);
});

app.get('/longDelay', function(req, res) {
  setTimeout(function() {
    res.send('OK\n');
  }, 4000);
});

app.get('/writeHeadAndDelay', function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  setTimeout(function() {
    res.end('OK\n');
  }, 2000);
});

app.get('/delayWriteHead', function(req, res) {
  setTimeout(function() {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('OK\n');
  }, 2000);
});

app.get('/delayWrite', function(req, res) {
  setTimeout(function() {
    res.write('first bit');
    res.end('second bit\n');
  }, 2000);
});

app.get('/error', function() {
  fs.readFile('something', function(err, result) {
    logger.info(result.toString());
  });
});

app.get('/errorSync', function() {
  //just to get jshint to shut up:
  /*global x */
  x.blah();
});

app.get('/hang', function() {
  //nuthin!
});

app.use(function(req, res) {
  res.status(404);
  res.send('could not find that!');
});

app.use(function(err, req, res, next) {
  /*jshint unused: false */
  logger.error(req.url + ': ' + core.breadcrumbs.toString(err));
  var message = err.text || ('error! ' + err.stack);

  res.type('txt');
  res.status(err.statusCode || 500);
  res.send(message);
});

module.exports = {
  gracefulExpress: gracefulExpress,
  app: app,
  start: function() {
    var server = gracefulExpress.listen(app, 3000, function() {
      logger.warn('Worker listening on port 3000');
    });
    module.exports.server = server;
  }
};
<commit_msg>end_to_end_server: don't need to expose server<commit_after>
'use strict';

var path = require('path');
var core = require('thehelp-core');
core.env.merge(path.join(__dirname, '../../env.json'));
core.logs.setupConsole();

var fs = require('fs');
var cluster = require('cluster');

var logShim = require('thehelp-log-shim');
var logger = logShim('end-to-end:server');
var express = require('express');
var morgan = require('morgan');

var thCluster = require('../../src/server');
var gracefulExpress = new thCluster.GracefulExpress();

var app = express();

app.use(morgan('combined', {
  stream: {
    write: function(text) {
      logger.info(text.replace(/\n$/, ''));
    }
  }
}));

var worker = cluster.isMaster ? 'n/a' : cluster.worker.id;
app.use(function(req, res, next) {
  res.header('X-Worker', worker);
  next();
});

app.use(gracefulExpress.middleware);

app.get('/', function(req, res) {
  res.send('success');
});

app.get('/delay', function(req, res) {
  setTimeout(function() {
    res.send('OK\n');
  }, 2000);
});

app.get('/longDelay', function(req, res) {
  setTimeout(function() {
    res.send('OK\n');
  }, 4000);
});

app.get('/writeHeadAndDelay', function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  setTimeout(function() {
    res.end('OK\n');
  }, 2000);
});

app.get('/delayWriteHead', function(req, res) {
  setTimeout(function() {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('OK\n');
  }, 2000);
});

app.get('/delayWrite', function(req, res) {
  setTimeout(function() {
    res.write('first bit');
    res.end('second bit\n');
  }, 2000);
});

app.get('/error', function() {
  fs.readFile('something', function(err, result) {
    logger.info(result.toString());
  });
});

app.get('/errorSync', function() {
  //just to get jshint to shut up:
  /*global x */
  x.blah();
});

app.get('/hang', function() {
  //nuthin!
});

app.use(function(req, res) {
  res.status(404);
  res.send('could not find that!');
});

app.use(function(err, req, res, next) {
  /*jshint unused: false */
  logger.error(req.url + ': ' + core.breadcrumbs.toString(err));
  var message = err.text || ('error! ' + err.stack);

  res.type('txt');
  res.status(err.statusCode || 500);
  res.send(message);
});

module.exports = {
  gracefulExpress: gracefulExpress,
  app: app,
  start: function() {
    gracefulExpress.listen(app, 3000, function() {
      logger.warn('Worker listening on port 3000');
    });
  }
};
<|endoftext|>


<commit_before>const gulp = require('gulp');
const del = require('del');
const paths = require('vinyl-paths');
const rev = require('gulp-rev');
const through = require('through2');
const concat = require('gulp-concat-util');
const concatCss = require('gulp-concat-css');
const rename = require('gulp-rename');
const cleanCSS = require('gulp-clean-css');
const { addToManifest } = require('./revision');

gulp.task('clean-bundle', () => gulp.src('./www/js/bundle*').pipe(paths(del)));

gulp.task('bundle-js', () =>
    gulp
        .src([
            './node_modules/blockly/blockly_compressed.js',
            './node_modules/blockly/blocks_compressed.js',
            './node_modules/blockly/javascript_compressed.js',
            './node_modules/blockly/msg/messages.js',
        ])
        .pipe(concat('bundle.js'))
        .pipe(rev())
        .pipe(through.obj(addToManifest))
        .pipe(gulp.dest('www/js/'))
);

gulp.task('bundle-css', () =>
    gulp
        .src(['node_modules/{bootstrap/dist/css/bootstrap.min,jquery-ui-css/jquery-ui.min}.css'])
        .pipe(concatCss('bundle.css'))
        .pipe(rev())
        .pipe(through.obj(addToManifest))
        .pipe(gulp.dest('www/css'))
);
<commit_msg>Remove bootstrap css from bundling<commit_after>const gulp = require('gulp');
const del = require('del');
const paths = require('vinyl-paths');
const rev = require('gulp-rev');
const through = require('through2');
const concat = require('gulp-concat-util');
const concatCss = require('gulp-concat-css');
const rename = require('gulp-rename');
const cleanCSS = require('gulp-clean-css');
const { addToManifest } = require('./revision');

gulp.task('clean-bundle', () => gulp.src('./www/js/bundle*').pipe(paths(del)));

gulp.task('bundle-js', () =>
    gulp
        .src([
            './node_modules/blockly/blockly_compressed.js',
            './node_modules/blockly/blocks_compressed.js',
            './node_modules/blockly/javascript_compressed.js',
            './node_modules/blockly/msg/messages.js',
        ])
        .pipe(concat('bundle.js'))
        .pipe(rev())
        .pipe(through.obj(addToManifest))
        .pipe(gulp.dest('www/js/'))
);

gulp.task('bundle-css', () =>
    gulp
        .src(['node_modules/jquery-ui-css/jquery-ui.min.css'])
        .pipe(concatCss('bundle.css'))
        .pipe(rev())
        .pipe(through.obj(addToManifest))
        .pipe(gulp.dest('www/css'))
);
<|endoftext|>


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

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

const { readdirSync, readFileSync } = require('fs');

if (process.argv.length < 3) {
    console.error('Missing measure timings storage path argument');
    process.exit(1);
}

const performanceMeasuresStoragePath = process.argv[2].trimRight('/') + '/';
const files = readdirSync(performanceMeasuresStoragePath);
const performanceMeasures = {};

if (files.length === 0) {
    console.log('No logs found!');
    process.exit(0);
}

// Aggregate data
for (const file of files) {
    const performanceMeasure = JSON.parse(readFileSync(performanceMeasuresStoragePath + file));

    performanceMeasures[performanceMeasure.name] = performanceMeasures[performanceMeasure.name] ?? {
        duration: [],
        scripting: [],
        styling: [],
        blocking: [],
        longTasks: [],
        database: [],
        networking: [],
    };
    performanceMeasures[performanceMeasure.name].duration.push(performanceMeasure.duration);
    performanceMeasures[performanceMeasure.name].scripting.push(performanceMeasure.scripting);
    performanceMeasures[performanceMeasure.name].styling.push(performanceMeasure.styling);
    performanceMeasures[performanceMeasure.name].blocking.push(performanceMeasure.blocking);
    performanceMeasures[performanceMeasure.name].longTasks.push(performanceMeasure.longTasks);
    performanceMeasures[performanceMeasure.name].database.push(performanceMeasure.database);
    performanceMeasures[performanceMeasure.name].networking.push(performanceMeasure.networking);
}

// Calculate averages
for (const [name, { duration, scripting, styling, blocking, longTasks, database, networking }] of Object.entries(performanceMeasures)) {
    const totalRuns = duration.length;
    const averageDuration = Math.round(duration.reduce((total, duration) => total + duration) / totalRuns);
    const averageScripting = Math.round(scripting.reduce((total, scripting) => total + scripting) / totalRuns);
    const averageStyling = Math.round(styling.reduce((total, styling) => total + styling) / totalRuns);
    const averageBlocking = Math.round(blocking.reduce((total, blocking) => total + blocking) / totalRuns);
    const averageLongTasks = Math.round(longTasks.reduce((total, longTasks) => total + longTasks) / totalRuns);
    const averageDatabase = Math.round(database.reduce((total, database) => total + database) / totalRuns);
    const averageNetworking = Math.round(networking.reduce((total, networking) => total + networking) / totalRuns);

    performanceMeasures[name] = {
        'Total duration': `${averageDuration}ms`,
        'Scripting': `${averageScripting}ms`,
        'Styling': `${averageStyling}ms`,
        'Blocking': `${averageBlocking}ms`,
        '# Network requests': averageNetworking,
        '# DB Queries': averageDatabase,
        '# Long Tasks': averageLongTasks,
        '# runs': totalRuns,
    };
}

// Display data
console.table(performanceMeasures);
<commit_msg>MOBILE-3833 performance: Sort tests in summary<commit_after>#!/usr/bin/env node

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

const { readdirSync, readFileSync } = require('fs');

if (process.argv.length < 3) {
    console.error('Missing measure timings storage path argument');
    process.exit(1);
}

const performanceMeasuresStoragePath = process.argv[2].trimRight('/') + '/';
const files = readdirSync(performanceMeasuresStoragePath);
const performanceMeasures = {};

if (files.length === 0) {
    console.log('No logs found!');
    process.exit(0);
}

// Aggregate data
for (const file of files) {
    const performanceMeasure = JSON.parse(readFileSync(performanceMeasuresStoragePath + file));

    performanceMeasures[performanceMeasure.name] = performanceMeasures[performanceMeasure.name] ?? {
        duration: [],
        scripting: [],
        styling: [],
        blocking: [],
        longTasks: [],
        database: [],
        networking: [],
    };
    performanceMeasures[performanceMeasure.name].duration.push(performanceMeasure.duration);
    performanceMeasures[performanceMeasure.name].scripting.push(performanceMeasure.scripting);
    performanceMeasures[performanceMeasure.name].styling.push(performanceMeasure.styling);
    performanceMeasures[performanceMeasure.name].blocking.push(performanceMeasure.blocking);
    performanceMeasures[performanceMeasure.name].longTasks.push(performanceMeasure.longTasks);
    performanceMeasures[performanceMeasure.name].database.push(performanceMeasure.database);
    performanceMeasures[performanceMeasure.name].networking.push(performanceMeasure.networking);
}

// Calculate averages
for (const [name, { duration, scripting, styling, blocking, longTasks, database, networking }] of Object.entries(performanceMeasures)) {
    const totalRuns = duration.length;
    const averageDuration = Math.round(duration.reduce((total, duration) => total + duration) / totalRuns);
    const averageScripting = Math.round(scripting.reduce((total, scripting) => total + scripting) / totalRuns);
    const averageStyling = Math.round(styling.reduce((total, styling) => total + styling) / totalRuns);
    const averageBlocking = Math.round(blocking.reduce((total, blocking) => total + blocking) / totalRuns);
    const averageLongTasks = Math.round(longTasks.reduce((total, longTasks) => total + longTasks) / totalRuns);
    const averageDatabase = Math.round(database.reduce((total, database) => total + database) / totalRuns);
    const averageNetworking = Math.round(networking.reduce((total, networking) => total + networking) / totalRuns);

    performanceMeasures[name] = {
        'Total duration': `${averageDuration}ms`,
        'Scripting': `${averageScripting}ms`,
        'Styling': `${averageStyling}ms`,
        'Blocking': `${averageBlocking}ms`,
        '# Network requests': averageNetworking,
        '# DB Queries': averageDatabase,
        '# Long Tasks': averageLongTasks,
        '# runs': totalRuns,
    };
}

// Sort tests
const tests = Object.keys(performanceMeasures).sort();
const sortedPerformanceMeasures = {};

for (const test of tests) {
    sortedPerformanceMeasures[test] = performanceMeasures[test];
}

// Display data
console.table(sortedPerformanceMeasures);
<|endoftext|>


<commit_before>(() => {
  const value = decodeURIComponent(
    location.search.replace('?input=', '').replace(/\++/g, '%20')
  );

  if (/^https?:\/\//.test(value)) {
    location = value;
    return;
  }

  document.title = `${value} - My Homepage`;

  const input = document.getElementsByTagName('input')[0];
  input.value = value;

  const form = document.getElementsByTagName('form')[0];
  form.onclick = ({ target: { nodeName, value } }) => {
    if (nodeName === 'BUTTON' && input.value) {
      location = value.replace('%s', encodeURIComponent(input.value));
    }
  };

  document.title = `${value} - My Homepage`;

  navigator.serviceWorker.register('/sw.js');
})()
<commit_msg>Fix page title<commit_after>(() => {
  const value = decodeURIComponent(
    location.search.replace('?input=', '').replace(/\++/g, '%20')
  );

  if (/^https?:\/\//.test(value)) {
    location = value;
    return;
  }

  const input = document.querySelector('input');
  input.value = value;

  const form = document.querySelector('form');
  form.onclick = ({ target: { nodeName, value } }) => {
    if (nodeName === 'BUTTON' && input.value) {
      location = value.replace('%s', encodeURIComponent(input.value));
    }
  };

  document.title = (value ? `${value} - ` : '') + 'My Homepage';

  navigator.serviceWorker.register('/sw.js');
})()
<|endoftext|>


<commit_before>/* global module */

var debug = true,
  src     = 'app/',
  dest    = 'dist/',
  test    = 'test/',
  lib     = 'lib/';

module.exports = {
  debug: debug,
  src:   src,
  dest:  dest,
  lib:   lib,

  browserSync: {
    proxy:  'b3.dev',
    notify: true,
    files:  [
      '**/*.php',
      dest + '**',
      '!' + dest + '**/*.map', // Exclude sourcemaps
      '!' + test + '**/*'  // Exclude PHPUnit tests
    ]
  },

  jasmine: {
    runner: 'test/jasmine/config/test-init.js',
    specs:  'test/jasmine/specs/**/*.spec.js',
    browserSync: {
      notify:    true,
      port:      3002,
      server:    '.',
      startPath: '/test/jasmine/SpecRunner.html',
      files:     [
        dest + '**',
        '!' + dest + '**/*.map', // Exclude sourcemaps
        test + 'jasmine/**'
      ]
    }
  },

  scripts: {
    src:  [
      src + 'scripts/**/*.js',
      '!' + src + 'scripts/templates/**/*'
    ],
    dest: dest + 'scripts/'
  },

  dust: {
    src:  src + 'templates/**/*.{html,dust}',
    dest: src + 'scripts/templates/'
  },

  less: {
    src:    src + 'styles/less/style.less',
    dest:   dest + 'styles/',
    concat: 'style.css'
  },

  images: {
    src:  src + 'images/**/*',
    dest: dest + 'images/'
  },

  fonts: {
    src:  [
      src + 'fonts/**/*.{eot,svg,ttf,woff}',
      lib + 'fonts/**/*.{eot,svg,ttf,woff}'
    ],
    dest: dest + 'fonts/'
  },

  phpunit: {
    src: 'test/phpunit/**/test*.php'
  },

  coverage: {
    instrument: {
      pattern: ['**/*.spec.js'],
      debugDirectory: 'debug'
    },
    report: {
      outFile: 'test/jasmine/coverage.html'
    }
  },

  jshint: {
    src: [
      src + 'scripts/**/*.js',
      '!' + src + 'scripts/templates/**/*'
    ],
    reporter: 'jshint-stylish'
  },

  autoprefixer: {
    browsers: [
      'last 2 version',
      'ie >= 9',
      'ie_mob >= 10',
      'ff >= 30',
      'chrome >= 34',
      'safari >= 7',
      'opera >= 23',
      'ios >= 7',
      'android >= 4.4',
      'bb >= 10'
    ]
  },
};
<commit_msg>Place compiled templates directly in the destination dir<commit_after>/* global module */

var debug = true,
  src     = 'app/',
  dest    = 'dist/',
  test    = 'test/',
  lib     = 'lib/';

module.exports = {
  debug: debug,
  src:   src,
  dest:  dest,
  lib:   lib,

  browserSync: {
    proxy:  'b3.dev',
    notify: true,
    files:  [
      '**/*.php',
      dest + '**',
      '!' + dest + '**/*.map', // Exclude sourcemaps
      '!' + test + '**/*'  // Exclude PHPUnit tests
    ]
  },

  jasmine: {
    runner: 'test/jasmine/config/test-init.js',
    specs:  'test/jasmine/specs/**/*.spec.js',
    browserSync: {
      notify:    true,
      port:      3002,
      server:    '.',
      startPath: '/test/jasmine/SpecRunner.html',
      files:     [
        dest + '**',
        '!' + dest + '**/*.map', // Exclude sourcemaps
        test + 'jasmine/**'
      ]
    }
  },

  scripts: {
    src:  [
      src + 'scripts/**/*.js',
      '!' + src + 'scripts/templates/**/*'
    ],
    dest: dest + 'scripts/'
  },

  dust: {
    src:  src + 'templates/**/*.{html,dust}',
    dest: dest + 'scripts/templates/'
  },

  less: {
    src:    src + 'styles/less/style.less',
    dest:   dest + 'styles/',
    concat: 'style.css'
  },

  images: {
    src:  src + 'images/**/*',
    dest: dest + 'images/'
  },

  fonts: {
    src:  [
      src + 'fonts/**/*.{eot,svg,ttf,woff}',
      lib + 'fonts/**/*.{eot,svg,ttf,woff}'
    ],
    dest: dest + 'fonts/'
  },

  phpunit: {
    src: 'test/phpunit/**/test*.php'
  },

  coverage: {
    instrument: {
      pattern: ['**/*.spec.js'],
      debugDirectory: 'debug'
    },
    report: {
      outFile: 'test/jasmine/coverage.html'
    }
  },

  jshint: {
    src: [
      src + 'scripts/**/*.js',
      '!' + src + 'scripts/templates/**/*'
    ],
    reporter: 'jshint-stylish'
  },

  autoprefixer: {
    browsers: [
      'last 2 version',
      'ie >= 9',
      'ie_mob >= 10',
      'ff >= 30',
      'chrome >= 34',
      'safari >= 7',
      'opera >= 23',
      'ios >= 7',
      'android >= 4.4',
      'bb >= 10'
    ]
  },
};
<|endoftext|>


<commit_before>
const $urlInput = $('.url-input');
const $displayUrls = $('.display-urls');

$(document).ready(() => {
  getAllUrls();
});

let getAllUrls = () => {
  $.getJSON('api/URLs', (data) => {
    putUrlsOnPage(data.URLs);
  });

};

let putUrlsOnPage = (urls) => {
  // let arr = Object.entries(urls);
  //
  // console.log(pizzas);

  // Object.keys(urls).map((key, value) => {
  //   console.log(key, value);
  // });
};
<commit_msg>Urls now correctly rendering on page.<commit_after>const $urlInput = $('.url-input');
const $displayUrls = $('.display-urls');

$(document).ready(() => {
  getAllUrls();
});

let getAllUrls = () => {
  $.getJSON('api/URLs', (data) => {
    putUrlsOnPage(data.URLs);
  });
};

let putUrlsOnPage = (urls) => {
  $.each(urls, (key,value) => {
     $displayUrls.append(
      `<div>
        ${key} is short for ${value}
      </div>`);
  });

};
<|endoftext|>


<commit_before>import { Kleros } from 'kleros-api'
import {
  requestDisputes,
  failureDisputes,
  receiveDisputes,
  requestCaseData,
  receiveCaseData
} from './actions'
import { getWeb3 } from '../../helpers/getWeb3'

export const errorAfterFiveSeconds = () => {
  return dispatch => {
    setTimeout(() => {
      // This function is able to dispatch other action creators
      dispatch(failureDisputes(true))
    }, 5000)
  }
}

export const getDisputes = () => async dispatch => {
  dispatch(requestDisputes(true))

  try {
    let web3 = await getWeb3()

    const provider = web3.currentProvider

    let KlerosInstance = new Kleros(provider, process.env.REACT_APP_STORE_PROVIDER)

    let court = KlerosInstance.court

    const disputes = await court.getDisputesForUser()
    await dispatch(receiveDisputes(disputes))
    await dispatch(requestDisputes(false))
  } catch (e) {
    // FIXME display a user-friendly error
    throw e
  }
}

export const submitDisputeResolution = (values) => async dispatch => {
  try {
    // TODO submit decision to contract //
  } catch (e) {
    // FIXME display a user-friendly error //
    throw e
  }
}

export const getDisputeById = (disputeId) => async dispatch => {
  dispatch(requestCaseData(true))

  try {
    let web3 = await getWeb3()

    const provider = web3.currentProvider

    let KlerosInstance = new Kleros(provider, process.env.REACT_APP_STORE_PROVIDER)

    // TODO use KlerosPOC
    let court = KlerosInstance.court
    // FIXME use a variable input for user to set their court contract
    const disputeData = await court.getDisputeByHash(disputeId)

    // use same reducer as fetch disputes
    await dispatch(receiveCaseData(disputeData))
    await dispatch(requestCaseData(false))
  } catch (e) {
    // FIXME display a user-friendly error
    throw e
  }
}
<commit_msg>pass contract address<commit_after>import { Kleros } from 'kleros-api'
import {
  requestDisputes,
  failureDisputes,
  receiveDisputes,
  requestCaseData,
  receiveCaseData
} from './actions'
import { getWeb3 } from '../../helpers/getWeb3'

export const errorAfterFiveSeconds = () => {
  return dispatch => {
    setTimeout(() => {
      // This function is able to dispatch other action creators
      dispatch(failureDisputes(true))
    }, 5000)
  }
}

export const getDisputes = () => async dispatch => {
  dispatch(requestDisputes(true))

  try {
    let web3 = await getWeb3()

    const provider = web3.currentProvider

    let KlerosInstance = new Kleros(provider, process.env.REACT_APP_STORE_PROVIDER)

    let court = KlerosInstance.court

    const disputes = await court.getDisputesForUser(process.env.REACT_APP_ARBITRATOR_ADDRESS)
    await dispatch(receiveDisputes(disputes))
    await dispatch(requestDisputes(false))
  } catch (e) {
    // FIXME display a user-friendly error
    throw e
  }
}

export const submitDisputeResolution = (values) => async dispatch => {
  try {
    // TODO submit decision to contract //
  } catch (e) {
    // FIXME display a user-friendly error //
    throw e
  }
}

export const getDisputeById = (disputeId) => async dispatch => {
  dispatch(requestCaseData(true))

  try {
    let web3 = await getWeb3()

    const provider = web3.currentProvider

    let KlerosInstance = new Kleros(provider, process.env.REACT_APP_STORE_PROVIDER)

    // TODO use KlerosPOC
    let court = KlerosInstance.court
    // FIXME use a variable input for user to set their court contract
    const disputeData = await court.getDisputeByHash(disputeId)

    // use same reducer as fetch disputes
    await dispatch(receiveCaseData(disputeData))
    await dispatch(requestCaseData(false))
  } catch (e) {
    // FIXME display a user-friendly error
    throw e
  }
}
<|endoftext|>


<commit_before>const { generateRandom } = require('../../server/simulation/drone');

describe('generateRandom()', () => {

  const sampleArguments = {coords: {lat: 1, long: 1}, distance: 1000 };

  test('returns an object', () => {
    expect(
      typeof generateRandom(sampleArguments)
    ).toBe('object');
  });

  test('returns an object with an id', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('id');
  });

  test('returns an object with a model', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('model');
  });

  test('returns an object with an icon property', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('icon');
  });

  test('returns an object with coords', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('coords');
  });

  test('returns an object with a rating attribute', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('icon');
  });

  test('returns an object with a missions_completed_7_days attribute', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('missions_completed_7_days');

  });
});
<commit_msg>fixed typo in rating test<commit_after>const { generateRandom } = require('../../server/simulation/drone');

describe('generateRandom()', () => {

  const sampleArguments = {coords: {lat: 1, long: 1}, distance: 1000 };

  test('returns an object', () => {
    expect(
      typeof generateRandom(sampleArguments)
    ).toBe('object');
  });

  test('returns an object with an id', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('id');
  });

  test('returns an object with a model', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('model');
  });

  test('returns an object with an icon property', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('icon');
  });

  test('returns an object with coords', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('coords');
  });

  test('returns an object with a rating attribute', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('rating');
  });

  test('returns an object with a missions_completed_7_days attribute', () => {
    expect(
      generateRandom(sampleArguments)
    ).toHaveProperty('missions_completed_7_days');

  });
});
<|endoftext|>