<commit_before>var isolines = require('turf-isolines'),
    grid = require('turf-grid'),
    destination = require('turf-destination'),
    point = require('turf-point'),
    distance = require('turf-distance'),
    extent = require('turf-extent'),
    featureCollection = require('turf-featurecollection'),
    polylineDecode = require('polyline').decode,
    OSRM = require('osrm');

module.exports = function (center, time, options, done) {
    if (!options) throw 'options is mandatory';
    if (!options.resolution) throw 'resolution is mandatory in options';
    if (!options.network) throw 'network is mandatory in options';
    if (!options.maxspeed) throw 'maxspeed is mandatory in options';
    var unit = options.unit || 'miles';
    if (options && options.draw) {
        this.draw = options.draw;
    } else {
        this.draw = function(destinations) {
            console.log(destinations);
            return isolines(destinations, 'eta', options.resolution, [time]);
        };
    }
    this.getIsochrone = function() {
        var osrm = options.network instanceof OSRM ? options.network : new OSRM(options.network);
        // compute bbox
        // bbox should go out 1.4 miles in each direction for each minute
        // this will account for a driver going a bit above the max safe speed
        var centerPt = point(center[0], center[1]);
        var spokes = featureCollection([]);
        var length = (time/3600) * options.maxspeed;
        spokes.features.push(destination(centerPt, length, 180, unit));
        spokes.features.push(destination(centerPt, length, 0, unit));
        spokes.features.push(destination(centerPt, length, 90, unit));
        spokes.features.push(destination(centerPt, length, -90, unit));
        var bbox = this.bbox = extent(spokes);
        var sizeCellGrid = this.sizeCellGrid = distance(point(bbox[0], bbox[1]), point(bbox[0], bbox[3]), unit) / options.resolution;

        //compute destination grid
        var targets = grid(bbox, options.resolution);
        targets.features = targets.features.filter(function(feat) {
            return distance(point(feat.geometry.coordinates[0], feat.geometry.coordinates[1]), centerPt, unit) <= length;
        });
        var destinations = featureCollection([]);

        var coord = targets.features.map(function(feat) {
            return [feat.geometry.coordinates[0], feat.geometry.coordinates[1]]
        });
        coord.push([center[0], center[1]]);
        console.log(coord);
        var sources = coord.length - 1;
        console.log(sources);
        osrm.table({
                coordinates: coord,
                sources: [sources]
            }, function(err, res) {
                if (err) {
                    console.log(err);
                    return done(err);
                }
                console.log(res.durations);
                if (res.durations &&
                    res.durations[0] && res.destinations &&
                    res.durations[0].length == res.destinations.length) {

                    res.durations[0].forEach(function(time, idx) {
                        var distanceMapped = distance(
                            point(coord[idx][1], coord[idx][0]),
                            point(res.destinations[idx][1], res.destinations[idx][0]),
                            unit
                        );
                        if (distanceMapped < sizeCellGrid) {
                            destinations.features.push({
                                type: 'Feature',
                                properties: {
                                    eta: time / 10
                                },
                                geometry: {
                                    type: 'Point',
                                    coordinates: [res.destinations[idx][1], res.destinations[idx][0]]
                                }
                            });
                        }
                        // specific for isoline algorithm: exclude some points from grid
                        else {
                            destinations.features.push({
                                type: 'Feature',
                                properties: {
                                    // this point cannot be routed => a penality 2 is applied to maxspeed
                                    eta: time + (distanceMapped - sizeCellGrid) / (options.maxspeed / 3600) * 2
                                },
                                geometry: {
                                    type: 'Point',
                                    coordinates: [coord[idx][1], coord[idx][0]]
                                }
                            });
                        }
                    });
                }
                var result = self.draw(destinations);
                return done(null, result);
            }
        );
    };
    var self = this;

    // in case module is called directly
    if (this.process && this.process.title == 'node')
        return getIsochrone();
}
<commit_msg>fix lon/lat convention<commit_after>var isolines = require('turf-isolines'),
    grid = require('turf-grid'),
    destination = require('turf-destination'),
    point = require('turf-point'),
    distance = require('turf-distance'),
    extent = require('turf-extent'),
    featureCollection = require('turf-featurecollection'),
    polylineDecode = require('polyline').decode,
    OSRM = require('osrm');

module.exports = function (center, time, options, done) {
    if (!options) throw 'options is mandatory';
    if (!options.resolution) throw 'resolution is mandatory in options';
    if (!options.network) throw 'network is mandatory in options';
    if (!options.maxspeed) throw 'maxspeed is mandatory in options';
    var unit = options.unit || 'miles';
    if (options && options.draw) {
        this.draw = options.draw;
    } else {
        this.draw = function(destinations) {
            console.log(destinations);
            return isolines(destinations, 'eta', options.resolution, [time]);
        };
    }
    this.getIsochrone = function() {
        var osrm = options.network instanceof OSRM ? options.network : new OSRM(options.network);
        // compute bbox
        // bbox should go out 1.4 miles in each direction for each minute
        // this will account for a driver going a bit above the max safe speed
        var centerPt = point(center[0], center[1]);
        var spokes = featureCollection([]);
        var length = (time/3600) * options.maxspeed;
        spokes.features.push(destination(centerPt, length, 180, unit));
        spokes.features.push(destination(centerPt, length, 0, unit));
        spokes.features.push(destination(centerPt, length, 90, unit));
        spokes.features.push(destination(centerPt, length, -90, unit));
        var bbox = this.bbox = extent(spokes);
        var sizeCellGrid = this.sizeCellGrid = distance(point(bbox[0], bbox[1]), point(bbox[0], bbox[3]), unit) / options.resolution;

        //compute destination grid
        var targets = grid(bbox, options.resolution);
        targets.features = targets.features.filter(function(feat) {
            return distance(point(feat.geometry.coordinates[0], feat.geometry.coordinates[1]), centerPt, unit) <= length;
        });
        var destinations = featureCollection([]);

        var coord = targets.features.map(function(feat) {
            return [feat.geometry.coordinates[0], feat.geometry.coordinates[1]]
        });
        coord.push([center[0], center[1]]);
        console.log(coord);
        var sources = coord.length - 1;
        console.log(sources);
        osrm.table({
                coordinates: coord,
                sources: [sources]
            }, function(err, res) {
                if (err) {
                    console.log(err);
                    return done(err);
                }
                console.log(res.durations);
                if (res.durations &&
                    res.durations[0] && res.destinations &&
                    res.durations[0].length == res.destinations.length) {

                    res.durations[0].forEach(function(time, idx) {
                        var distanceMapped = distance(
                            point(coord[idx][0], coord[idx][1]),
                            point(res.destinations[idx][0], res.destinations[idx][1]),
                            unit
                        );
                        if (distanceMapped < sizeCellGrid) {
                            destinations.features.push({
                                type: 'Feature',
                                properties: {
                                    eta: time / 10
                                },
                                geometry: {
                                    type: 'Point',
                                    coordinates: [res.destinations[idx][0], res.destinations[idx][1]]
                                }
                            });
                        }
                        // specific for isoline algorithm: exclude some points from grid
                        else {
                            destinations.features.push({
                                type: 'Feature',
                                properties: {
                                    // this point cannot be routed => a penality 2 is applied to maxspeed
                                    eta: time + (distanceMapped - sizeCellGrid) / (options.maxspeed / 3600) * 2
                                },
                                geometry: {
                                    type: 'Point',
                                    coordinates: [coord[idx][0], coord[idx][1]]
                                }
                            });
                        }
                    });
                }
                var result = self.draw(destinations);
                return done(null, result);
            }
        );
    };
    var self = this;

    // in case module is called directly
    if (this.process && this.process.title == 'node')
        return getIsochrone();
}
<|endoftext|>


<commit_before>const assert = require('assert');
const {send} = require('micro');
const fetch = require('node-fetch');

const protocols = {
  HTTP: 'http://',
  HTTPS: 'https://'
};

module.exports = async (req, res) => {
  let url = req.url.substr(1).split('?')[0];
  let requestScheme = protocols.HTTP;
  if (url === 'favicon.ico') return;
  if (url.startsWith(protocols.HTTP)) {
    url = url.substr(7);
    requestScheme = protocols.HTTP;
  } else if (url.startsWith(protocols.HTTPS)) {
    url = url.substr(8);
    requestScheme = protocols.HTTPS;
  }
  let json = req.url.endsWith('?json');
  try {
    assert(url !== '');
  } catch (err) {
    return send(res, 400, 'URL must be defined. Usage: https://up.now.sh/google.com');
  }
  let statusCode;
  let message;
  res.setHeader('Content-Type', 'application/json');
  try {
    await fetch(`${requestScheme}${url}`, {
      timeout: 5000
    });
    statusCode = 200;
    if (json) {
      message = {url: url, status: 'Up'};
    } else {
      res.setHeader('Content-Type', 'text/plain');
      message = `${url} is up.`;
    }
  } catch (err) {
    const {type, code} = err;
    if (type === 'system' && code === 'ENOTFOUND') {
      statusCode = 200;
      message = (json) ? ({url: url, status: 'Down'}) : (`${url} is not up.`);
    } else {
      statusCode = 400;
      message = (json) ? ({error: 'Something went wrong.'}) : (`Something went wrong.`);
    }
  }
  send(res, statusCode, message);
};
<commit_msg>Refactor 🔨✨<commit_after>const url = require('url');
const {send} = require('micro');
const fetch = require('node-fetch');

const errors = {
  protocol: 'Invalid protocol. Must be: http:// or https://',
  host: 'Host must be defined. Usage: https://up.now.sh/google.com'
};

module.exports = async (req, res) => {
  const reqUrl = url.parse(req.url);
  const json = reqUrl.query === 'json';

  const host = url.parse(reqUrl.pathname.substr(1));
  if (host.pathname === 'favicon.ico') return;
  if (host.href === '') return send(res, 400, errors.host);

  const protocol = host.protocol ? host.protocol : 'http:';
  if (!['http:', 'https:'].includes(protocol)) return send(res, 400, errors.protocol);

  const hostname = host.hostname ? host.hostname : url.parse(`${protocol}//${host.path}`).hostname;

  res.setHeader('Content-Type', 'text/plain');
  if (json) res.setHeader('Content-Type', 'application/json');

  let statusCode;
  let message;

  try {
    await fetch(`${protocol}//${hostname}`, {
      timeout: 5000
    });
    statusCode = 200;
    message = json ? {url: hostname, status: 'Up'} : `${hostname} is up.`;
  } catch (err) {
    const {type, code} = err;
    if (type === 'system' && code === 'ENOTFOUND') {
      statusCode = 200;
      message = (json) ? ({url: hostname, status: 'Down'}) : (`${hostname} is not up.`);
    } else {
      statusCode = 400;
      message = (json) ? ({error: 'Something went wrong.'}) : (`Something went wrong.`);
    }
  }
  send(res, statusCode, message);
};
<|endoftext|>


<commit_before>'use strict';
var repeatString = require('repeat-string');

module.exports = function (str, indent, count) {
	if (typeof str !== 'string' || typeof indent !== 'string') {
		throw new TypeError('`string` and `indent` should be strings');
	}

	indent = count > 1 ? repeatString(indent, count) : indent;

	return str.replace(/(?:^|\r\n|\n)(?=[^\s$])/g, '$&' + indent);
};
<commit_msg>simplify regex<commit_after>'use strict';
var repeatString = require('repeat-string');

module.exports = function (str, indent, count) {
	if (typeof str !== 'string' || typeof indent !== 'string') {
		throw new TypeError('`string` and `indent` should be strings');
	}

	indent = count > 1 ? repeatString(indent, count) : indent;

	return str.replace(/(?:^|\r?\n)(?=[\S$])/g, '$&' + indent);
};
<|endoftext|>


<commit_before>/**
 * © 2017 Liferay, Inc. <https://liferay.com>
 *
 * SPDX-License-Identifier: MIT
 */

'use strict';

const fs = require('fs');
const local = require('./utils/local');

const config = {
	env: {
		es6: true,
	},
	extends: ['eslint:recommended', require.resolve('eslint-config-prettier')],
	parserOptions: {
		ecmaVersion: 2017,
		sourceType: 'module',
	},
	plugins: [local('liferay'), 'no-for-of-loops', 'no-only-tests', 'notice'],
	rules: {
		'default-case': 'error',
		'liferay/no-it-should': 'error',
		'no-for-of-loops/no-for-of-loops': 'error',
		'no-only-tests/no-only-tests': 'error',
		'no-return-assign': ['error', 'always'],
		'no-unused-expressions': 'error',
		'no-unused-vars': ['error', {argsIgnorePattern: '^_'}],
		'object-shorthand': 'error',
		'prefer-const': 'error',
		'quote-props': ['error', 'as-needed'],
		'sort-keys': ['error', 'asc', {caseSensitive: false}],
	},
};

if (fs.existsSync('copyright.js')) {
	config.rules['notice/notice'] = [
		'error',
		{
			templateFile: 'copyright.js',
		},
	];
}

module.exports = config;
<commit_msg>feat: makes sorting keys follow natural order so 1 < 2 < 11<commit_after>/**
 * © 2017 Liferay, Inc. <https://liferay.com>
 *
 * SPDX-License-Identifier: MIT
 */

'use strict';

const fs = require('fs');
const local = require('./utils/local');

const config = {
	env: {
		es6: true,
	},
	extends: ['eslint:recommended', require.resolve('eslint-config-prettier')],
	parserOptions: {
		ecmaVersion: 2017,
		sourceType: 'module',
	},
	plugins: [local('liferay'), 'no-for-of-loops', 'no-only-tests', 'notice'],
	rules: {
		'default-case': 'error',
		'liferay/no-it-should': 'error',
		'no-for-of-loops/no-for-of-loops': 'error',
		'no-only-tests/no-only-tests': 'error',
		'no-return-assign': ['error', 'always'],
		'no-unused-expressions': 'error',
		'no-unused-vars': ['error', {argsIgnorePattern: '^_'}],
		'object-shorthand': 'error',
		'prefer-const': 'error',
		'quote-props': ['error', 'as-needed'],
		'sort-keys': ['error', 'asc', {caseSensitive: false, natural: true}],
	},
};

if (fs.existsSync('copyright.js')) {
	config.rules['notice/notice'] = [
		'error',
		{
			templateFile: 'copyright.js',
		},
	];
}

module.exports = config;
<|endoftext|>


<commit_before>(function (global) {
  'use strict';

  // Helper function to check if a node is visible in the viewport
  function isVisible (node) {
    return !!(node.offsetWidth || node.offsetHeight || node.getClientRects().length);
  }

  // Helper function to get all focusable children from a node
  function getFocusableChildren (node) {
    var focusableElements = ['a[href]', 'area[href]', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', 'iframe', 'object', 'embed', '[contenteditable]', '[tabindex]:not([value="-1"])'];

    return $$(focusableElements.join(','), node).filter(function (child) {
      return isVisible(child);
    });
  }

  // Helper function to get first node in context matching selector
  function $ (selector, context) {
    return (context || document).querySelector(selector);
  }

  // Helper function to get all nodes in context matching selector as an array
  function $$ (selector, context) {
    var nodes = (context || document).querySelectorAll(selector);
    return nodes.length ? Array.prototype.slice.call(nodes) : [];
  }

  // Helper function trapping the tab key inside a node
  function trapTabKey (node, event) {
    var focusableChildren = getFocusableChildren(node);
    var focusedItem = document.activeElement;
    var focusedItemIndex = focusableChildren.indexOf(focusedItem);

    if (event.shiftKey && focusedItemIndex === 0) {
      focusableChildren[focusableChildren.length - 1].focus();
      event.preventDefault();
    } else if (!event.shiftKey && focusedItemIndex === focusableChildren.length - 1) {
      focusableChildren[0].focus();
      event.preventDefault();
    }
  }

  // Helper function to bind listeners for a Modal instance
  function bindListeners (instance) {
    instance.$openers.forEach(function ($opener) {
      $opener.addEventListener('click', function (event) {
        event.stopPropagation();
        instance.show();
      });
    });

    instance.$closers.forEach(function ($closer) {
      $closer.addEventListener('click', function (event) {
        instance.hide();
      });
    });

    document.addEventListener('keydown', function (event) {
      if (instance.shown === false) return;

      if (event.which === 27) {
        event.preventDefault();
        instance.hide();
      }

      if (event.which === 9) {
        trapTabKey(instance.$modal, event);
      }
    });

    document.body.addEventListener('focus', function (event) {
      if (instance.shown && !instance.$modal.contains(event.target)) {
        setFocusToFirstItem(instance.$modal);
      }
    }, true);

    document.addEventListener('click', function (event) {
      if (instance.shown === false) return;
      instance.hide();
    });

    instance.$modal.addEventListener('click', function (event) {
      event.stopPropagation();
    });
  };

  // Helper function to focus first focusable item in node
  function setFocusToFirstItem (node) {
    var focusableChildren = getFocusableChildren(node);
    if (focusableChildren.length) focusableChildren[0].focus();
  }

  var focusedElementBeforeModal;

  /**
   * Modal constructor
   * @param {Node} node - Modal element
   * @param {Node} main - Main element of the page
   * @param {Node} overlay - Overlay element
   */
  var Modal = function (node, main, overlay) {
    this.$main = main || $('#main');
    this.$overlay = overlay || $('#modal-overlay');

    this.$modal = node;
    this.$closers = $$('[data-hide-modal]', this.$modal);
    this.$openers = $$('[data-show-modal="' + this.$modal.id + '"]');
    this.shown = false;

    bindListeners(this);
  };

  /**
   * Method to display the modal
   */
  Modal.prototype.show = function () {
    this.shown = true;

    this.$main.setAttribute('aria-hidden', 'true');
    this.$modal.setAttribute('aria-hidden', 'false');
    this.$overlay.style.display = 'block';
    this.$modal.style.display = 'block';

    focusedElementBeforeModal = document.activeElement;
    setFocusToFirstItem(this.$modal);
  };

  /**
   * Method to hide the modal
   */
  Modal.prototype.hide = function () {
    this.shown = false;

    this.$modal.setAttribute('aria-hidden', 'true');
    this.$main.setAttribute('aria-hidden', 'false');
    this.$overlay.style.display = 'none';
    this.$modal.style.display = 'none';

    focusedElementBeforeModal.focus();
  };

  global.Modal = Modal
}(window));
<commit_msg>Fixed a few linting errors<commit_after>(function (global) {
  'use strict';

  // Helper function to check if a node is visible in the viewport
  function isVisible (node) {
    return !!(node.offsetWidth || node.offsetHeight || node.getClientRects().length);
  }

  // Helper function to get all focusable children from a node
  function getFocusableChildren (node) {
    var focusableElements = ['a[href]', 'area[href]', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', 'iframe', 'object', 'embed', '[contenteditable]', '[tabindex]:not([value="-1"])'];

    return $$(focusableElements.join(','), node).filter(function (child) {
      return isVisible(child);
    });
  }

  // Helper function to get first node in context matching selector
  function $ (selector, context) {
    return (context || document).querySelector(selector);
  }

  // Helper function to get all nodes in context matching selector as an array
  function $$ (selector, context) {
    var nodes = (context || document).querySelectorAll(selector);
    return nodes.length ? Array.prototype.slice.call(nodes) : [];
  }

  // Helper function trapping the tab key inside a node
  function trapTabKey (node, event) {
    var focusableChildren = getFocusableChildren(node);
    var focusedItem = document.activeElement;
    var focusedItemIndex = focusableChildren.indexOf(focusedItem);

    if (event.shiftKey && focusedItemIndex === 0) {
      focusableChildren[focusableChildren.length - 1].focus();
      event.preventDefault();
    } else if (!event.shiftKey && focusedItemIndex === focusableChildren.length - 1) {
      focusableChildren[0].focus();
      event.preventDefault();
    }
  }

  // Helper function to bind listeners for a Modal instance
  function bindListeners (instance) {
    instance.$openers.forEach(function ($opener) {
      $opener.addEventListener('click', function (event) {
        event.stopPropagation();
        instance.show();
      });
    });

    instance.$closers.forEach(function ($closer) {
      $closer.addEventListener('click', function (event) {
        instance.hide();
      });
    });

    document.addEventListener('keydown', function (event) {
      if (instance.shown === false) return;

      if (event.which === 27) {
        event.preventDefault();
        instance.hide();
      }

      if (event.which === 9) {
        trapTabKey(instance.$modal, event);
      }
    });

    document.body.addEventListener('focus', function (event) {
      if (instance.shown && !instance.$modal.contains(event.target)) {
        setFocusToFirstItem(instance.$modal);
      }
    }, true);

    document.addEventListener('click', function (event) {
      if (instance.shown === false) return;
      instance.hide();
    });

    instance.$modal.addEventListener('click', function (event) {
      event.stopPropagation();
    });
  }

  // Helper function to focus first focusable item in node
  function setFocusToFirstItem (node) {
    var focusableChildren = getFocusableChildren(node);
    if (focusableChildren.length) focusableChildren[0].focus();
  }

  var focusedElementBeforeModal;

  /**
   * Modal constructor
   * @param {Node} node - Modal element
   * @param {Node} main - Main element of the page
   * @param {Node} overlay - Overlay element
   */
  var Modal = function (node, main, overlay) {
    this.$main = main || $('#main');
    this.$overlay = overlay || $('#modal-overlay');

    this.$modal = node;
    this.$closers = $$('[data-hide-modal]', this.$modal);
    this.$openers = $$('[data-show-modal="' + this.$modal.id + '"]');
    this.shown = false;

    bindListeners(this);
  };

  /**
   * Method to display the modal
   */
  Modal.prototype.show = function () {
    this.shown = true;

    this.$main.setAttribute('aria-hidden', 'true');
    this.$modal.setAttribute('aria-hidden', 'false');
    this.$overlay.style.display = 'block';
    this.$modal.style.display = 'block';

    focusedElementBeforeModal = document.activeElement;
    setFocusToFirstItem(this.$modal);
  };

  /**
   * Method to hide the modal
   */
  Modal.prototype.hide = function () {
    this.shown = false;

    this.$modal.setAttribute('aria-hidden', 'true');
    this.$main.setAttribute('aria-hidden', 'false');
    this.$overlay.style.display = 'none';
    this.$modal.style.display = 'none';

    focusedElementBeforeModal.focus();
  };

  global.Modal = Modal;
}(window));
<|endoftext|>


<commit_before>var VError, httpRequest, async, uri;
VError = require('verror');
httpRequest = require('request');
async = require('async');

exports.configUri = function (newUri) {
  'use strict';

  uri = newUri;
};

exports.session = function authSession() {
  'use strict';

  return function authSessionMiddleware(request, response, next) {
    var token;
    token = request.get('csrf-token');
    httpRequest({
      'url'     : uri + '/users/me',
      'headers' : {'csrf-token' : token},
      'json'    : true
    }, function (error, res, body) {
      next(error, body);
    });
  };
};

exports.can = function authCan(permission) {
  'use strict';

  return function authPermissionMiddleware(request, response, next) {
    var session;
    session = request.session;
    if (!session || session.profile.permissions.lastIndexOf(permission) === -1) {
      return response.status(403).end();
    }
    return next();
  };
};
<commit_msg>seting session variable<commit_after>var VError, httpRequest, async, uri;
VError = require('verror');
httpRequest = require('request');
async = require('async');

exports.configUri = function (newUri) {
  'use strict';

  uri = newUri;
};

exports.session = function authSession() {
  'use strict';

  return function authSessionMiddleware(request, response, next) {
    var token;
    token = request.get('csrf-token');
    httpRequest({
      'url'     : uri + '/users/me',
      'headers' : {'csrf-token' : token},
      'json'    : true
    }, function (error, res, body) {
      next(error, body);
      request.session = body;
    });
  };
};

exports.can = function authCan(permission) {
  'use strict';

  return function authPermissionMiddleware(request, response, next) {
    var session;
    session = request.session;
    if (!session || session.profile.permissions.lastIndexOf(permission) === -1) {
      return response.status(403).end();
    }
    return next();
  };
};
<|endoftext|>


<commit_before>var Freud = require('freud').Freud,
  fs = require('fs'),
  config = require('./config.json'),
  md = require('node-markdown').Markdown,
  jade = require('jade'),
  stylus = require('stylus'),
  coffee = require('coffee-script'),
  uncanny = {
    "uncanny": {
      "version": "0.0.6",
      "files": []
    }
  },
  ignore = config.ignore || [];

var freud = new Freud(config.source, config.target, {
  "monitorDot": config.watchDotFile,
  "monitorSquiggle": false
});

function _rebuildUncanny(callback) {
  fs.readdir(config.source, function (err, files) {
    if (err) { throw err; }

    files.forEach(function (filename) {
      fs.stat(config.source + filename, function (err, stats) {

        var fileObject = {
          "name": filename,
          "stats": stats
        };

        if (filename.match(/\./)) {
          var extension = filename.split('.').pop();
          uncanny.uncanny.files[extension] = uncanny.uncanny.files[extension] || [];
          uncanny.uncanny.files[extension].push(fileObject);
          console.log(uncanny.uncanny.files[extension][0]);
        } else {
          uncanny.uncanny.files['!'] = uncanny.uncanny.files['!'] || [];
          uncanny.uncanny.files['!'].push(fileObject);
        }

      });
    });
    callback();
  });
}

function _recompileJade() {
  fs.readdir(config.source, function (err, files) {
    if (err) { throw err; }

    files.forEach(function (filename) {
      if (filename.match(/\.jade$/) && -ignore.indexOf(filename)) {
        freud.recompile(filename);
      }
    });
  });
}

freud.listen('md', function (file) {
  file.name = file.name.replace(/\.md$/, (config.md || '.htm'));
  file.data = md(file.data);

  return file;
});

freud.listen('coffee', function (file) {
  file.name = file.name.replace(/\.coffee/, '.js');
  file.data = coffee.compile(file.data);

  return file;
});

freud.listen('jade', function (file) {
  file.name = file.name.replace(/\.jade/, (config.jade || '.html'));
  var fn = jade.compile(file.data, {
    "filename": config.target + file.name
  });
  file.data = fn(uncanny);

  return file;
});

freud.listen('styl', function (file) {
  file.name = file.name.replace(/\.styl/, '.css');
  stylus.render(file.data, function (err, css) {
    if (err) { throw err; }

    file.data = css;
  });

  return file;
});

freud.listen('*:before', function (file) {
  if (!-ignore.indexOf(file.name)) {
    file.write = false;
  }

  return file;
});

freud.go();

if (config.syncOnInit) {
  fs.readdir(config.source, function (err, files) {
    if (err) { throw err; }

    files.forEach(function (file) {
      freud.recompile(file);
    });

  });
}

freud.on('started', function () {
  _rebuildUncanny();
  process.title = config.title || 'uncanny.';
});

freud.on('compiled', function (filename) {
  if (!filename.match(/\.jade$/)) {
    _rebuildUncanny(function () {
      _recompileJade();
    });
  }
});<commit_msg>just run it<commit_after>var Freud = require('freud').Freud,
  fs = require('fs'),
  config = require('./config.json'),
  md = require('node-markdown').Markdown,
  jade = require('jade'),
  stylus = require('stylus'),
  coffee = require('coffee-script'),
  uncanny = {
    "uncanny": {
      "version": "0.0.6",
      "files": []
    }
  },
  ignore = config.ignore || [];

var freud = new Freud(config.source, config.target, {
  "monitorDot": config.watchDotFile,
  "monitorSquiggle": false
});

function _rebuildUncanny(callback) {
  fs.readdir(config.source, function (err, files) {
    if (err) { throw err; }

    files.forEach(function (filename) {
      fs.stat(config.source + filename, function (err, stats) {

        var fileObject = {
          "name": filename,
          "stats": stats
        };

        if (filename.match(/\./)) {
          var extension = filename.split('.').pop();
          uncanny.uncanny.files[extension] = uncanny.uncanny.files[extension] || [];
          uncanny.uncanny.files[extension].push(fileObject);
        } else {
          uncanny.uncanny.files['!'] = uncanny.uncanny.files['!'] || [];
          uncanny.uncanny.files['!'].push(fileObject);
        }

      });
    });
    callback();
  });
}

function _recompileJade() {
  fs.readdir(config.source, function (err, files) {
    if (err) { throw err; }

    files.forEach(function (filename) {
      if (filename.match(/\.jade$/) && -ignore.indexOf(filename)) {
        freud.recompile(filename);
      }
    });
  });
}

freud.listen('md', function (file) {
  file.name = file.name.replace(/\.md$/, (config.md || '.htm'));
  file.data = md(file.data);

  return file;
});

freud.listen('coffee', function (file) {
  file.name = file.name.replace(/\.coffee/, '.js');
  file.data = coffee.compile(file.data);

  return file;
});

freud.listen('jade', function (file) {
  file.name = file.name.replace(/\.jade/, (config.jade || '.html'));
  var fn = jade.compile(file.data, {
    "filename": config.target + file.name
  });
  file.data = fn(uncanny);

  return file;
});

freud.listen('styl', function (file) {
  file.name = file.name.replace(/\.styl/, '.css');
  stylus.render(file.data, function (err, css) {
    if (err) { throw err; }

    file.data = css;
  });

  return file;
});

freud.listen('*:before', function (file) {
  if (!-ignore.indexOf(file.name)) {
    file.write = false;
  }

  return file;
});

freud.go();

if (config.syncOnInit) {
  fs.readdir(config.source, function (err, files) {
    if (err) { throw err; }

    files.forEach(function (file) {
      freud.recompile(file);
    });

  });
}

freud.on('compiled', function (filename) {
  if (!filename.match(/\.jade$/)) {
    _rebuildUncanny(function () {
      _recompileJade();
    });
  }
});

_rebuildUncanny();
process.title = config.title || 'uncanny.';<|endoftext|>


<commit_before>'user strict';

var config = require('./config/config'),
  firebase = require('./services/firebase'),
   express = require('express'),
bodyParser = require('body-parser'),
   request = require("request"),
       app = express();

app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.get('/', function (req, res){
  res.send('Hello World!');
});

app.post('/new_message', function (req, res){
  //console.log(req.body);

  if (req.body.token == config.slack.webhookToken){
    var payload = {
      room:  req.body.channel_name,
      token: req.body.token,
      userId: req.body.user_id,
      message: req.body.text,
      username: req.body.user_name,
      timestamp: req.body.timestamp
    }

    if (payload.message == ''){
      return res.send('No message provided');
    }

    getUserProfile(payload,pushToFirebase);

    res.send('success');

  } else {

    res.send('Token is incorrect');
  }

});

var getUserProfile = function(payload, callback){
  request('https://slack.com/api/users.info?token=' + config.slack.apiToken + '&user=' + payload.userId + '&pretty=1',
    function(error,response,body){

      if (error){
        return console.log("Error" + error);
      }

      userInfo = JSON.parse(body).user;

      payload.color  = userInfo.color;
      payload.avatar = userInfo.profile.image_192;

      callback(payload,resizeMessageLength);
    })
}

var pushToFirebase = function(payload, callback){
  var roomRef = firebase.child(payload.room).push().set({
    color:     payload.color,
    avatar:    payload.avatar,
    message:   payload.message,
    username:  payload.username,
    timestamp: payload.timestamp
  })

  callback(payload.room);
}

var resizeMessageLength = function(room){
  var ref = firebase.child(room);
  ref.on('value', function(snapshot){
    console.log(snapshot.val());
    var length = Object.keys(snapshot.val()).length
    if (length > config.maxMessageLength){
      for (first in snapshot.val()) break;
      ref.child(first).remove();
    }
  }, function(errorObject){
    console.log("The read failed: " + errorObject.code);
  });
}

var server = app.listen(3002, function (){
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
})
<commit_msg>Checks tokens for any configured rooms<commit_after>'user strict';

var config = require('./config/config'),
  firebase = require('./services/firebase'),
   express = require('express'),
bodyParser = require('body-parser'),
   request = require("request"),
       app = express();

app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.get('/', function (req, res){
  res.send('Hello World!');
});

app.post('/new_message', function (req, res){
  //console.log(req.body);

  if (checkToken(req.body.token)){
    var payload = {
      room:  req.body.channel_name,
      token: req.body.token,
      userId: req.body.user_id,
      message: req.body.text,
      username: req.body.user_name,
      timestamp: req.body.timestamp
    }

    if (payload.message == ''){
      return res.send('No message provided');
    }

    getUserProfile(payload,pushToFirebase);

    res.send('success');

  } else {

    res.send('Token is incorrect');
  }

});

var checkToken = function(token){
  if (token == config.slack.webhookGeneralToken ||
      token == config.slack.webhookEngineeringToken ||
      token == config.slack.webhookRandomToken){
    return true;
  } else {
    return false;
  }
}

var getUserProfile = function(payload, callback){
  request('https://slack.com/api/users.info?token=' + config.slack.apiToken + '&user=' + payload.userId + '&pretty=1',
    function(error,response,body){

      if (error){
        return console.log("Error" + error);
      }

      userInfo = JSON.parse(body).user;

      payload.color  = userInfo.color;
      payload.avatar = userInfo.profile.image_192;

      callback(payload,resizeMessageLength);
    })
}

var pushToFirebase = function(payload, callback){
  var roomRef = firebase.child(payload.room).push().set({
    color:     payload.color,
    avatar:    payload.avatar,
    message:   payload.message,
    username:  payload.username,
    timestamp: payload.timestamp
  })

  callback(payload.room);
}

var resizeMessageLength = function(room){
  var ref = firebase.child(room);
  ref.on('value', function(snapshot){
    console.log(snapshot.val());
    var length = Object.keys(snapshot.val()).length
    if (length > config.maxMessageLength){
      for (first in snapshot.val()) break;
      ref.child(first).remove();
    }
  }, function(errorObject){
    console.log("The read failed: " + errorObject.code);
  });
}

var server = app.listen(3002, function (){
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
})
<|endoftext|>


<commit_before>'use strict';
const util = require('util');
const path = require('path');
const childProcess = require('child_process');

const TEN_MEGABYTES = 1000 * 1000 * 10;
const execFile = util.promisify(childProcess.execFile);

const windows = async () => {
	// Source: https://github.com/MarkTiedemann/fastlist
	const bin = path.join(__dirname, 'fastlist.exe');

	const {stdout} = await execFile(bin, {maxBuffer: TEN_MEGABYTES});

	return stdout
		.trim()
		.split('\r\n')
		.map(line => line.split('\t'))
		.map(([name, pid, ppid]) => ({
			name,
			pid: Number.parseInt(pid, 10),
			ppid: Number.parseInt(ppid, 10)
		}));
};

const nonWindowsMultipleCalls = async (options = {}) => {
	const flags = (options.all === false ? '' : 'a') + 'wwxo';
	const ret = {};

	await Promise.all(['comm', 'args', 'ppid', 'uid', '%cpu', '%mem'].map(async cmd => {
		const {stdout} = await execFile('ps', [flags, `pid,${cmd}`], {maxBuffer: TEN_MEGABYTES});

		for (let line of stdout.trim().split('\n').slice(1)) {
			line = line.trim();
			const [pid] = line.split(' ', 1);
			const val = line.slice(pid.length + 1).trim();

			if (ret[pid] === undefined) {
				ret[pid] = {};
			}

			ret[pid][cmd] = val;
		}
	}));

	// Filter out inconsistencies as there might be race
	// issues due to differences in `ps` between the spawns
	return Object.entries(ret)
		.filter(([, value]) => value.comm && value.args && value.ppid && value.uid && value['%cpu'] && value['%mem'])
		.map(([key, value]) => ({
			pid: Number.parseInt(key, 10),
			name: path.basename(value.comm),
			cmd: value.args,
			ppid: Number.parseInt(value.ppid, 10),
			uid: Number.parseInt(value.uid, 10),
			cpu: Number.parseFloat(value['%cpu']),
			memory: Number.parseFloat(value['%mem'])
		}));
};

const ERROR_MESSAGE_PARSING_FAILED = 'ps output parsing failed';

const psFields = 'pid,ppid,uid,%cpu,%mem,comm,args';

// TODO: Use named capture groups when targeting Node.js 10
const psOutputRegex = /^[ \t]*(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+\.\d+)[ \t]+(\d+\.\d+)[ \t]+/; // Groups: pid, ppid, uid, cpu, mem

const nonWindowsSingleCall = async (options = {}) => {
	const flags = options.all === false ? 'wwxo' : 'awwxo';

	// TODO: Use the promise version of `execFile` when https://github.com/nodejs/node/issues/28244 is fixed
	const [psPid, stdout] = await new Promise((resolve, reject) => {
		const child = childProcess.execFile('ps', [flags, psFields], {maxBuffer: TEN_MEGABYTES}, (error, stdout) => {
			if (error === null) {
				resolve([child.pid, stdout]);
			} else {
				reject(error);
			}
		});
	});

	const lines = stdout.trim().split('\n');
	lines.shift();

	let psIndex;
	let commPosition;
	let argsPosition;

	const processes = lines.map((line, i) => {
		const match = psOutputRegex.exec(line);
		if (match === null) {
			throw new Error(ERROR_MESSAGE_PARSING_FAILED);
		}

		const process = {
			pid: Number.parseInt(match[1], 10),
			ppid: Number.parseInt(match[2], 10),
			uid: Number.parseInt(match[3], 10),
			cpu: Number.parseFloat(match[4]),
			memory: Number.parseFloat(match[5]),
			name: undefined,
			cmd: undefined
		};
		if (process.pid === psPid) {
			psIndex = i;
			commPosition = line.indexOf('ps', match[0].length);
			argsPosition = line.indexOf('ps', commPosition + 2);
		}

		return process;
	});

	if (psIndex === undefined || commPosition === -1 || argsPosition === -1) {
		throw new Error(ERROR_MESSAGE_PARSING_FAILED);
	}

	const commLength = argsPosition - commPosition;
	for (const [i, line] of lines.entries()) {
		processes[i].name = line.slice(commPosition, commPosition + commLength).trim();
		processes[i].cmd = line.slice(argsPosition).trim();
	}

	processes.splice(psIndex, 1);
	return processes;
};

const nonWindows = async (options = {}) => {
	try {
		return await nonWindowsSingleCall(options);
	} catch (_) { // If the error is not a parsing error, it should manifest itself in multicall version too
		return nonWindowsMultipleCalls(options);
	}
};

module.exports = process.platform === 'win32' ? windows : nonWindows;
// TODO: remove this in the next major version
module.exports.default = module.exports;
<commit_msg>Don't show the console window on Windows<commit_after>'use strict';
const util = require('util');
const path = require('path');
const childProcess = require('child_process');

const TEN_MEGABYTES = 1000 * 1000 * 10;
const execFile = util.promisify(childProcess.execFile);

const windows = async () => {
	// Source: https://github.com/MarkTiedemann/fastlist
	const bin = path.join(__dirname, 'fastlist.exe');

	const {stdout} = await execFile(bin, {
		maxBuffer: TEN_MEGABYTES,
		windowsHide: true
	});

	return stdout
		.trim()
		.split('\r\n')
		.map(line => line.split('\t'))
		.map(([name, pid, ppid]) => ({
			name,
			pid: Number.parseInt(pid, 10),
			ppid: Number.parseInt(ppid, 10)
		}));
};

const nonWindowsMultipleCalls = async (options = {}) => {
	const flags = (options.all === false ? '' : 'a') + 'wwxo';
	const ret = {};

	await Promise.all(['comm', 'args', 'ppid', 'uid', '%cpu', '%mem'].map(async cmd => {
		const {stdout} = await execFile('ps', [flags, `pid,${cmd}`], {maxBuffer: TEN_MEGABYTES});

		for (let line of stdout.trim().split('\n').slice(1)) {
			line = line.trim();
			const [pid] = line.split(' ', 1);
			const val = line.slice(pid.length + 1).trim();

			if (ret[pid] === undefined) {
				ret[pid] = {};
			}

			ret[pid][cmd] = val;
		}
	}));

	// Filter out inconsistencies as there might be race
	// issues due to differences in `ps` between the spawns
	return Object.entries(ret)
		.filter(([, value]) => value.comm && value.args && value.ppid && value.uid && value['%cpu'] && value['%mem'])
		.map(([key, value]) => ({
			pid: Number.parseInt(key, 10),
			name: path.basename(value.comm),
			cmd: value.args,
			ppid: Number.parseInt(value.ppid, 10),
			uid: Number.parseInt(value.uid, 10),
			cpu: Number.parseFloat(value['%cpu']),
			memory: Number.parseFloat(value['%mem'])
		}));
};

const ERROR_MESSAGE_PARSING_FAILED = 'ps output parsing failed';

const psFields = 'pid,ppid,uid,%cpu,%mem,comm,args';

// TODO: Use named capture groups when targeting Node.js 10
const psOutputRegex = /^[ \t]*(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+\.\d+)[ \t]+(\d+\.\d+)[ \t]+/; // Groups: pid, ppid, uid, cpu, mem

const nonWindowsSingleCall = async (options = {}) => {
	const flags = options.all === false ? 'wwxo' : 'awwxo';

	// TODO: Use the promise version of `execFile` when https://github.com/nodejs/node/issues/28244 is fixed
	const [psPid, stdout] = await new Promise((resolve, reject) => {
		const child = childProcess.execFile('ps', [flags, psFields], {maxBuffer: TEN_MEGABYTES}, (error, stdout) => {
			if (error === null) {
				resolve([child.pid, stdout]);
			} else {
				reject(error);
			}
		});
	});

	const lines = stdout.trim().split('\n');
	lines.shift();

	let psIndex;
	let commPosition;
	let argsPosition;

	const processes = lines.map((line, i) => {
		const match = psOutputRegex.exec(line);
		if (match === null) {
			throw new Error(ERROR_MESSAGE_PARSING_FAILED);
		}

		const process = {
			pid: Number.parseInt(match[1], 10),
			ppid: Number.parseInt(match[2], 10),
			uid: Number.parseInt(match[3], 10),
			cpu: Number.parseFloat(match[4]),
			memory: Number.parseFloat(match[5]),
			name: undefined,
			cmd: undefined
		};
		if (process.pid === psPid) {
			psIndex = i;
			commPosition = line.indexOf('ps', match[0].length);
			argsPosition = line.indexOf('ps', commPosition + 2);
		}

		return process;
	});

	if (psIndex === undefined || commPosition === -1 || argsPosition === -1) {
		throw new Error(ERROR_MESSAGE_PARSING_FAILED);
	}

	const commLength = argsPosition - commPosition;
	for (const [i, line] of lines.entries()) {
		processes[i].name = line.slice(commPosition, commPosition + commLength).trim();
		processes[i].cmd = line.slice(argsPosition).trim();
	}

	processes.splice(psIndex, 1);
	return processes;
};

const nonWindows = async (options = {}) => {
	try {
		return await nonWindowsSingleCall(options);
	} catch (_) { // If the error is not a parsing error, it should manifest itself in multicall version too
		return nonWindowsMultipleCalls(options);
	}
};

module.exports = process.platform === 'win32' ? windows : nonWindows;
// TODO: remove this in the next major version
module.exports.default = module.exports;
<|endoftext|>


<commit_before>(function () {
  /*******************
   * define functions
   *******************/

  /**
   * お気に入りボタンの初期化をします
   */
  function initFavButton() {
    var infoTextElement = document.querySelector('#movieWrap .infoWrap .programInfo .infoText');

    // 再生中でないときは要素自体ないので、そのときは何もしない
    if (!infoTextElement) {
      return;
    }

    var buttonBlock = document.createElement('div');
    buttonBlock.classList.add('favButton');
    var button = document.createElement('button');

    var playingCard = findPlayingCard();
    var id = playingCard.getAttribute('id');

    button.innerText = isFavorited(id) ? '★お気に入り登録済' : '☆お気に入り登録';
    button.addEventListener('click', function () {
      if (isFavorited(id)) {
        button.innerText = '☆お気に入り登録';
        removeFavorite(id);
      } else {
        button.innerText = '★お気に入り登録済';
        addFavorite(id);
      }
    });

    buttonBlock.appendChild(button);
    infoTextElement.insertBefore(buttonBlock, infoTextElement.querySelector('.parsonarity'));
  }

  /**
   * 現在再生中の番組情報のDOMを取得します。（リストに表示されるカードみたいなやつ）
   * @returns {Node}
   */
  function findPlayingCard() {
    var list = Array.from(document.querySelectorAll('#movieList .listWrap ul.clr li'));
    return list.find(function (el) {
      return el.classList.contains('playing');
    });
  }

  /**
   * お気に入りタブの初期化をします
   */
  function createFavTab() {
    var categoryList = document.querySelector('#movieNav .categoryList');
    var favTab = document.createElement('ul');
    favTab.classList.add('favorite');
    favTab.innerHTML = '
お気に入り
';

    // お気に入りタブをクリックしたときにやること
    favTab.addEventListener('click', function () {
      // 前に選択中のタブによっては、全ての番組が表示されていないことがあるので、`ALL`をクリックして全て表示させておく
      categoryList.querySelector('.btnSort.all').click();

      categoryList.querySelector('.select').classList.remove('select');
      favTab.querySelector('li').classList.add('select');

      var list = Array.from(document.querySelectorAll('#movieList .listWrap ul.clr li'));
      list.forEach(function (el) {
        var id = el.getAttribute('id');
        if (isFavorited(id)) {
          el.classList.add('active');
        } else {
          el.classList.remove('active');
        }
      });
    });

    // お気に入りタブ以外をクリックしたときにやること
    categoryList.querySelectorAll('ul:not(.favorite)').forEach(function (el) {
      el.addEventListener('click', function () {
        favTab.querySelector('li').classList.remove('select');
      });
    });

    categoryList.appendChild(favTab);
  }

  /***********
   * favorite
   ***********/

  var favorites = [];
  var localStorageKey = 'onsen-ex_favorites';

  function restoreFavorites() {
    favorites = JSON.parse(localStorage.getItem(localStorageKey)) || [];
  }

  function saveFavorites() {
    localStorage.setItem(localStorageKey, JSON.stringify(favorites));
  }

  function addFavorite(id) {
    favorites.push(id);
    saveFavorites();
  }

  function removeFavorite(id) {
    favorites.some(function(v, i) {
      if (v == id) {
        favorites.splice(i, 1);
      }
    });
    saveFavorites();
  }

  function isFavorited(id) {
    return favorites.includes(id);
  }

  /**********
   * process
   **********/
  restoreFavorites();

  var infoWrapElement = document.querySelector('#movieWrap .infoWrap');
  var mutationObserver = new MutationObserver(initFavButton);
  mutationObserver.observe(infoWrapElement, {
    childList: true
  });

  createFavTab();
})();<commit_msg>localStorage 利用可能判定追加<commit_after>(function () {
  /*******************
   * define functions
   *******************/

  /**
   * お気に入りボタンの初期化をします
   */
  function initFavButton() {
    var infoTextElement = document.querySelector('#movieWrap .infoWrap .programInfo .infoText');

    // 再生中でないときは要素自体ないので、そのときは何もしない
    if (!infoTextElement) {
      return;
    }

    var buttonBlock = document.createElement('div');
    buttonBlock.classList.add('favButton');
    var button = document.createElement('button');

    var playingCard = findPlayingCard();
    var id = playingCard.getAttribute('id');

    button.innerText = isFavorited(id) ? '★お気に入り登録済' : '☆お気に入り登録';
    button.addEventListener('click', function () {
      if (isFavorited(id)) {
        button.innerText = '☆お気に入り登録';
        removeFavorite(id);
      } else {
        button.innerText = '★お気に入り登録済';
        addFavorite(id);
      }
    });

    buttonBlock.appendChild(button);
    infoTextElement.insertBefore(buttonBlock, infoTextElement.querySelector('.parsonarity'));
  }

  /**
   * 現在再生中の番組情報のDOMを取得します。（リストに表示されるカードみたいなやつ）
   * @returns {Node}
   */
  function findPlayingCard() {
    var list = Array.from(document.querySelectorAll('#movieList .listWrap ul.clr li'));
    return list.find(function (el) {
      return el.classList.contains('playing');
    });
  }

  /**
   * お気に入りタブの初期化をします
   */
  function createFavTab() {
    var categoryList = document.querySelector('#movieNav .categoryList');
    var favTab = document.createElement('ul');
    favTab.classList.add('favorite');
    favTab.innerHTML = '
お気に入り
';

    // お気に入りタブをクリックしたときにやること
    favTab.addEventListener('click', function () {
      // 前に選択中のタブによっては、全ての番組が表示されていないことがあるので、`ALL`をクリックして全て表示させておく
      categoryList.querySelector('.btnSort.all').click();

      categoryList.querySelector('.select').classList.remove('select');
      favTab.querySelector('li').classList.add('select');

      var list = Array.from(document.querySelectorAll('#movieList .listWrap ul.clr li'));
      list.forEach(function (el) {
        var id = el.getAttribute('id');
        if (isFavorited(id)) {
          el.classList.add('active');
        } else {
          el.classList.remove('active');
        }
      });
    });

    // お気に入りタブ以外をクリックしたときにやること
    categoryList.querySelectorAll('ul:not(.favorite)').forEach(function (el) {
      el.addEventListener('click', function () {
        favTab.querySelector('li').classList.remove('select');
      });
    });

    categoryList.appendChild(favTab);
  }

  /***********
   * favorite
   ***********/

  var favorites = [];
  var localStorageKey = 'onsen-ex_favorites';

  function restoreFavorites() {
    favorites = JSON.parse(localStorage.getItem(localStorageKey)) || [];
  }

  function saveFavorites() {
    localStorage.setItem(localStorageKey, JSON.stringify(favorites));
  }

  function addFavorite(id) {
    favorites.push(id);
    saveFavorites();
  }

  function removeFavorite(id) {
    favorites.some(function(v, i) {
      if (v == id) {
        favorites.splice(i, 1);
      }
    });
    saveFavorites();
  }

  function isFavorited(id) {
    return favorites.includes(id);
  }

  /**********
   * process
   **********/
  // localStorage が使えること前提の機能なので、チェックして使えなければ初期化しない
  if(!('localStorage' in window) || (window.localStorage === null)) {
    console.warn('onsen-ex: localStorage が利用不可のため初期化できませんでした。');
    return;
  }

  restoreFavorites();

  var infoWrapElement = document.querySelector('#movieWrap .infoWrap');
  var mutationObserver = new MutationObserver(initFavButton);
  mutationObserver.observe(infoWrapElement, {
    childList: true
  });

  createFavTab();
})();<|endoftext|>


<commit_before>var prussdrv = require('prussdrv'),
	fs = require('fs');

function slots(callback) {
	fs.readdir('/sys/devices', function(err, files) {
		if (err) {
			return callback(err);
		}

		var bone_capemgr;
		files.forEach(function(f) {
			if (f.slice(0, 'bone_capemgr.'.length) === 'bone_capemgr.') {
				bone_capemgr = f;
				return false;
			}
		});

		if (bone_capemgr === undefined) {
			return callback(new Error('Can not find /sys/devices/bone_capemgr.*/slots'));
		}

		callback(null, '/sys/devices/' + bone_capemgr + '/slots');
	});
}

function ensureLoaded(fragment, callback) {

	slots(function(err, slots) {
		if (err) {
			return callback(err);
		}

		fs.readFile(slots, function(err, data) {
			if (err) {
				return callback(err);
			}

			var found = false;
			data.toString().split('\n').forEach(function(line) {
				if (line.search(fragment) != -1) {
					found = true;
					return false;
				}
			});

			if (!found) {
				fs.writeFile(slots, fragment, callback);
			} else {
				callback(null);
			}
		});
	});
}

function init(callback) {
	ensureLoaded('BB-BONE-PRU-01', function(err) {
		if (err) {
			return callback(err);
		}

		ensureLoaded('BB-ADC', function(err) {
			if (err) {
				return callback(err);
			}

			setTimeout(function() {
				try {
					callback(null, Capture());
				} catch(err) {
					return callback(err);
				}

			}, 500);  // FIXME: do we need this delay??
		});
	});
}

function Capture() {

	prussdrv.init();

	var capture = {
		OFF: {
			FLAG        : 0x0008,
			TIMER       : 0x0004,
			EMA_POW     : 0x001c,
			VALUES      : 0x0020,
			ENC0_PIN    : 0x0040,
			ENC1_PIN    : 0x0041,
			ENC0_THRESH : 0x0044,
			ENC1_THRESH : 0x0084,
			ENC0_VALUES : 0x0048,
			ENC1_VALUES : 0x0088,
			ENC0_TICKS  : 0x0054,
			ENC1_TICKS  : 0x0094,
			ENC0_SPEED  : 0x0058,
			ENC1_SPEED  : 0x0098,
			ENC0_DELAY  : 0x0060,
			ENC1_DELAY  : 0x00a0,
			SCOPE_ADDR  : 0x000c,
			SCOPE_OFFSET: 0x0010,
			SCOPE_SIZE  : 0x0014,
			DEBUG       : 0x0018
		}
	};

	[
		0x1965beef,  // eye
		0,           // timer
		0,           // flags
		0,           // scope.addr
		0,           // scope.offset
		0,           // scope.length
		0,           // reserved
		0,           // ema_pow
		0,           // ain_ema[8]
		0,           //
		0,           //
		0,           //
		0,           //
		0,           //
		0,           //
		0,           //
		0x0000ffff,  // enc

		0,           // threshold
		0,           // raw
		0,           // min
		0,           // max
		0,           // ticks
		0,           // speed
		0,           // acc
		0,           // delay
		0,           // uptick_time
		0,           // downtick_time
		0,           // reserved[6]
		0,           //
		0,           //
		0,           //
		0,           //
		0,           //

		0,           // threshold
		0,           // raw
		0,           // min
		0,           // max
		0,           // ticks
		0,           // speed
		0,           // acc
		0,           // delay
		0,           // uptick_time
		0,           // downtick_time
		0,           // reserved[6]
		0,           //
		0,           //
		0,           //
		0,           //
		0            //
	].forEach(function(value, index) {
		prussdrv.setDataRAMInt(index, value);
	});

	function setWord(offset, value) {
		if (offset % 4 !== 0) {
			throw new Error('offset must be multiple of 4 (word-aligned)');
		}

		offset /= 4;
		prussdrv.setDataRAMInt(offset, value);
	}

	function getWord(offset) {
		if (offset % 4 !== 0) {
			throw new Error('offset must be multiple of 4 (word-aligned)');
		}

		offset /= 4;
		return prussdrv.getDataRAMInt(offset);
	}

	capture.start = function() {
		prussdrv.execute(__dirname + '/firmware/firmware.bin');
	};

	capture.stop = function() {
		setWord(capture.OFF.FLAG, 1);  // exit flag
	};

	capture.close = function() {
		prussdrv.close();
	};

	capture.timer = function() {
		return getWord(capture.OFF.TIMER);
	};

	capture.ema_pow = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.EMA_POW);

		} else {

			if (value < 0 || value > 31) {
				throw new Error('value out of range (expected 0..31)');
			}

			setWord(capture.OFF.EMA_POW, value);
			return capture;
		}
	};

	capture.values = function() {
		return [
			getWord(capture.OFF.VALUES +  0),
			getWord(capture.OFF.VALUES +  4),
			getWord(capture.OFF.VALUES +  8),
			getWord(capture.OFF.VALUES + 12),
			getWord(capture.OFF.VALUES + 16),
			getWord(capture.OFF.VALUES + 20),
			getWord(capture.OFF.VALUES + 24),
			getWord(capture.OFF.VALUES + 28)
		];
	};

	capture.encoder0Pin = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.ENC0_PIN) & 0xff;
		} else {
			var packed = getWord(capture.OFF.ENC0_PIN) & 0xffffff00 + value & 0xff;
			setWord(capture.OFF.ENC0_PIN, packed);
			return capture;
		}
	};

	capture.encoder1Pin = function(value) {

		if (value === undefined) {
			return (getWord(capture.OFF.ENC0_PIN) >> 8) & 0xff;
		} else {
			var packed = getWord(capture.OFF.ENC0_PIN) & 0xffff00ff + ((value & 0xff) << 8);
			setWord(capture.OFF.ENC0_PIN, packed);
			return capture;
		}
	};

	capture.encoder0Threshold = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.ENC0_THRESH);
		} else {
			setWord(capture.OFF.ENC0_THRESH);
			return capture;
		}
	};

	capture.encoder1Threshold = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.ENC1_THRESH);
		} else {
			setWord(capture.OFF.ENC1_THRESH);
			return capture;
		}
	};

	capture.encoder0Values = function() {
		return [
			getWord(capture.OFF.ENC0_VALUES +  0),
			getWord(capture.OFF.ENC0_VALUES +  4),
			getWord(capture.OFF.ENC0_VALUES +  8),
			getWord(capture.OFF.ENC0_VALUES + 12),
			getWord(capture.OFF.ENC0_VALUES + 16)
		];
	};

	capture.encoder1Values = function() {
		return [
			getWord(capture.OFF.ENC1_VALUES +  0),
			getWord(capture.OFF.ENC1_VALUES +  4),
			getWord(capture.OFF.ENC1_VALUES +  8),
			getWord(capture.OFF.ENC1_VALUES + 12),
			getWord(capture.OFF.ENC1_VALUES + 16)
		];
	};

	capture.encoder0Delay = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.ENC0_DELAY);

		} else {
			setWord(capture.OFF.ENC0_DELAY, value);
		}
	};

	capture.encoder1Delay = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.ENC1_DELAY);

		} else {
			setWord(capture.OFF.ENC1_DELAY, value);
		}
	};

	capture.encoder0Ticks = function() {
		return getWord(capture.OFF.ENC0_TICKS);
	};

	capture.encoder1Ticks = function() {
		return getWord(capture.OFF.ENC1_TICKS);
	};

	capture.encoder0Speed = function() {
		return getWord(capture.OFF.ENC0_SPEED);
	};

	capture.encoder1Speed = function() {
		return getWord(capture.OFF.ENC1_SPEED);
	};

	return capture;
}

module.exports = init;
<commit_msg>fixed eyecatcher<commit_after>var prussdrv = require('prussdrv'),
	fs = require('fs');

function slots(callback) {
	fs.readdir('/sys/devices', function(err, files) {
		if (err) {
			return callback(err);
		}

		var bone_capemgr;
		files.forEach(function(f) {
			if (f.slice(0, 'bone_capemgr.'.length) === 'bone_capemgr.') {
				bone_capemgr = f;
				return false;
			}
		});

		if (bone_capemgr === undefined) {
			return callback(new Error('Can not find /sys/devices/bone_capemgr.*/slots'));
		}

		callback(null, '/sys/devices/' + bone_capemgr + '/slots');
	});
}

function ensureLoaded(fragment, callback) {

	slots(function(err, slots) {
		if (err) {
			return callback(err);
		}

		fs.readFile(slots, function(err, data) {
			if (err) {
				return callback(err);
			}

			var found = false;
			data.toString().split('\n').forEach(function(line) {
				if (line.search(fragment) != -1) {
					found = true;
					return false;
				}
			});

			if (!found) {
				fs.writeFile(slots, fragment, callback);
			} else {
				callback(null);
			}
		});
	});
}

function init(callback) {
	ensureLoaded('BB-BONE-PRU-01', function(err) {
		if (err) {
			return callback(err);
		}

		ensureLoaded('BB-ADC', function(err) {
			if (err) {
				return callback(err);
			}

			setTimeout(function() {
				try {
					callback(null, Capture());
				} catch(err) {
					return callback(err);
				}

			}, 500);  // FIXME: do we need this delay??
		});
	});
}

function Capture() {

	prussdrv.init();

	var capture = {
		OFF: {
			FLAG        : 0x0008,
			TIMER       : 0x0004,
			EMA_POW     : 0x001c,
			VALUES      : 0x0020,
			ENC0_PIN    : 0x0040,
			ENC1_PIN    : 0x0041,
			ENC0_THRESH : 0x0044,
			ENC1_THRESH : 0x0084,
			ENC0_VALUES : 0x0048,
			ENC1_VALUES : 0x0088,
			ENC0_TICKS  : 0x0054,
			ENC1_TICKS  : 0x0094,
			ENC0_SPEED  : 0x0058,
			ENC1_SPEED  : 0x0098,
			ENC0_DELAY  : 0x0060,
			ENC1_DELAY  : 0x00a0,
			SCOPE_ADDR  : 0x000c,
			SCOPE_OFFSET: 0x0010,
			SCOPE_SIZE  : 0x0014,
			DEBUG       : 0x0018
		}
	};

	[
		0xbeef1965,  // eye
		0,           // timer
		0,           // flags
		0,           // scope.addr
		0,           // scope.offset
		0,           // scope.length
		0,           // reserved
		0,           // ema_pow
		0,           // ain_ema[8]
		0,           //
		0,           //
		0,           //
		0,           //
		0,           //
		0,           //
		0,           //
		0x0000ffff,  // enc

		0,           // threshold
		0,           // raw
		0,           // min
		0,           // max
		0,           // ticks
		0,           // speed
		0,           // acc
		0,           // delay
		0,           // uptick_time
		0,           // downtick_time
		0,           // reserved[6]
		0,           //
		0,           //
		0,           //
		0,           //
		0,           //

		0,           // threshold
		0,           // raw
		0,           // min
		0,           // max
		0,           // ticks
		0,           // speed
		0,           // acc
		0,           // delay
		0,           // uptick_time
		0,           // downtick_time
		0,           // reserved[6]
		0,           //
		0,           //
		0,           //
		0,           //
		0            //
	].forEach(function(value, index) {
		prussdrv.setDataRAMInt(index, value);
	});

	function setWord(offset, value) {
		if (offset % 4 !== 0) {
			throw new Error('offset must be multiple of 4 (word-aligned)');
		}

		offset /= 4;
		prussdrv.setDataRAMInt(offset, value);
	}

	function getWord(offset) {
		if (offset % 4 !== 0) {
			throw new Error('offset must be multiple of 4 (word-aligned)');
		}

		offset /= 4;
		return prussdrv.getDataRAMInt(offset);
	}

	capture.start = function() {
		prussdrv.execute(__dirname + '/firmware/firmware.bin');
	};

	capture.stop = function() {
		setWord(capture.OFF.FLAG, 1);  // exit flag
	};

	capture.close = function() {
		prussdrv.close();
	};

	capture.timer = function() {
		return getWord(capture.OFF.TIMER);
	};

	capture.ema_pow = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.EMA_POW);

		} else {

			if (value < 0 || value > 31) {
				throw new Error('value out of range (expected 0..31)');
			}

			setWord(capture.OFF.EMA_POW, value);
			return capture;
		}
	};

	capture.values = function() {
		return [
			getWord(capture.OFF.VALUES +  0),
			getWord(capture.OFF.VALUES +  4),
			getWord(capture.OFF.VALUES +  8),
			getWord(capture.OFF.VALUES + 12),
			getWord(capture.OFF.VALUES + 16),
			getWord(capture.OFF.VALUES + 20),
			getWord(capture.OFF.VALUES + 24),
			getWord(capture.OFF.VALUES + 28)
		];
	};

	capture.encoder0Pin = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.ENC0_PIN) & 0xff;
		} else {
			var packed = getWord(capture.OFF.ENC0_PIN) & 0xffffff00 + value & 0xff;
			setWord(capture.OFF.ENC0_PIN, packed);
			return capture;
		}
	};

	capture.encoder1Pin = function(value) {

		if (value === undefined) {
			return (getWord(capture.OFF.ENC0_PIN) >> 8) & 0xff;
		} else {
			var packed = getWord(capture.OFF.ENC0_PIN) & 0xffff00ff + ((value & 0xff) << 8);
			setWord(capture.OFF.ENC0_PIN, packed);
			return capture;
		}
	};

	capture.encoder0Threshold = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.ENC0_THRESH);
		} else {
			setWord(capture.OFF.ENC0_THRESH);
			return capture;
		}
	};

	capture.encoder1Threshold = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.ENC1_THRESH);
		} else {
			setWord(capture.OFF.ENC1_THRESH);
			return capture;
		}
	};

	capture.encoder0Values = function() {
		return [
			getWord(capture.OFF.ENC0_VALUES +  0),
			getWord(capture.OFF.ENC0_VALUES +  4),
			getWord(capture.OFF.ENC0_VALUES +  8),
			getWord(capture.OFF.ENC0_VALUES + 12),
			getWord(capture.OFF.ENC0_VALUES + 16)
		];
	};

	capture.encoder1Values = function() {
		return [
			getWord(capture.OFF.ENC1_VALUES +  0),
			getWord(capture.OFF.ENC1_VALUES +  4),
			getWord(capture.OFF.ENC1_VALUES +  8),
			getWord(capture.OFF.ENC1_VALUES + 12),
			getWord(capture.OFF.ENC1_VALUES + 16)
		];
	};

	capture.encoder0Delay = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.ENC0_DELAY);

		} else {
			setWord(capture.OFF.ENC0_DELAY, value);
		}
	};

	capture.encoder1Delay = function(value) {

		if (value === undefined) {
			return getWord(capture.OFF.ENC1_DELAY);

		} else {
			setWord(capture.OFF.ENC1_DELAY, value);
		}
	};

	capture.encoder0Ticks = function() {
		return getWord(capture.OFF.ENC0_TICKS);
	};

	capture.encoder1Ticks = function() {
		return getWord(capture.OFF.ENC1_TICKS);
	};

	capture.encoder0Speed = function() {
		return getWord(capture.OFF.ENC0_SPEED);
	};

	capture.encoder1Speed = function() {
		return getWord(capture.OFF.ENC1_SPEED);
	};

	return capture;
}

module.exports = init;
<|endoftext|>


<commit_before>/**
 * Format date time string as Chinese format
 * @param {string} dateTimeString
 * @param {string} format
 * @return {string}
 */

const dateFormat = require('dateformat');

module.exports = (dateTimeString, format) => {
  let formatResult = dateFormat(dateTimeString, format);
  const d = new Date(dateTimeString);
  const n = d.getDay();
  const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const weekDaysZhou = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  formatResult = formatResult.replace('ww', weekDays[n]);
  formatResult = formatResult.replace('zz', weekDaysZhou[n]);
  return formatResult;
};
<commit_msg>should convert - to / otherwise it will not work<commit_after>/**
 * Format date time string as Chinese format
 * @param {string} dateTimeString
 * @param {string} format
 * @return {string}
 */

const dateFormat = require('dateformat');

module.exports = (dateTimeString, format) => {
  let formatResult = dateFormat(dateTimeString.replace('-', '/'), format);
  const d = new Date(dateTimeString);
  const n = d.getDay();
  const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const weekDaysZhou = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  formatResult = formatResult.replace('ww', weekDays[n]);
  formatResult = formatResult.replace('zz', weekDaysZhou[n]);
  return formatResult;
};
<|endoftext|>


<commit_before>"use strict";

/**
 * Module dependencies.
 */
var fs = require("fs")
var path = require("path")

var clone = require("clone")
var resolve = require("resolve")
var postcss = require("postcss")
var helpers = require("postcss-message-helpers")

/**
 * Expose the plugin.
 */
module.exports = AtImport

/**
 * Inline `@import`ed files
 *
 * @param {Object} options
 */
function AtImport(options) {
  options = options || {}
  options.path = (
    // convert string to an array of a single element
    typeof options.path === "string" ?
    [options.path] :
    (options.path || []) // fallback to empty array
  )

  return function(styles) {
    // auto add from option if possible
    if (!options.from && styles && styles.childs && styles.childs[0] && styles.childs[0].source && styles.childs[0].source.file) {
      options.from = styles.childs[0].source.file
    }

    // if from available, prepend from directory in the path array
    addInputToPath(options)

    // if we got nothing for the path, just use cwd
    if (options.path.length === 0) {
      options.path.push(process.cwd())
    }

    var importedFiles = {}
    if (options.from) {
      importedFiles[options.from] = {
        "": true
      }
    }
    var ignoredAtRules = []

    parseStyles(styles, options, insertRules, importedFiles, ignoredAtRules)
    addIgnoredAtRulesOnTop(styles, ignoredAtRules)

    if (typeof options.onImport === "function") {
      options.onImport(Object.keys(importedFiles))
    }
  }
}

/**
 * lookup for @import rules
 *
 * @param {Object} styles
 * @param {Object} options
 */
function parseStyles(styles, options, cb, importedFiles, ignoredAtRules, media) {
  styles.eachAtRule(function checkAtRule(atRule) {
    if (atRule.name !== "import") {
      return
    }

    helpers.try(function transformAtImport() {
      readAtImport(atRule, options, cb, importedFiles, ignoredAtRules, media)
    }, atRule.source)
  })
}

/**
 * put back at the top ignored url (absolute url)
 *
 * @param {Object} styles
 * @param {Array} ignoredAtRules
 */
function addIgnoredAtRulesOnTop(styles, ignoredAtRules) {
  var i = ignoredAtRules.length
  if (i) {
    var first = styles.first

    while (i--) {
      var ignoredAtRule = ignoredAtRules[i][0]
      ignoredAtRule.params = ignoredAtRules[i][1].fullUri + (ignoredAtRules[i][1].media ? " " + ignoredAtRules[i][1].media : "")
      ignoredAtRule.before = "\n"
      ignoredAtRule.after = ""

      // don't use prepend() to avoid weird behavior of normalize()
      styles.childs.unshift(ignoredAtRule)
    }

    first.before = "\n\n" + first.before
  }
}

/**
 * parse @import rules & inline appropriate rules
 *
 * @param {Object} atRule  postcss atRule
 * @param {Object} options
 */
function readAtImport(atRule, options, cb, importedFiles, ignoredAtRules, media) {
  // parse-import module parse entire line
  // @todo extract what can be interesting from this one
  var parsedAtImport = parseImport(atRule.params, atRule.source)

  // adjust media according to current scope
  media = parsedAtImport.media ? (media ? media + " and " : "") + parsedAtImport.media : (media ? media : null)

  // just update protocol base uri (protocol://url) or protocol-relative (//url) if media needed
  if (parsedAtImport.uri.match(/^(?:[a-z]+:)?\/\//i)) {
    parsedAtImport.media = media
    ignoredAtRules.push([atRule, parsedAtImport])
    atRule.removeSelf()
    return
  }

  addInputToPath(options)
  var resolvedFilename = resolveFilename(parsedAtImport.uri, options.path, atRule.source)

  if (importedFiles[resolvedFilename] && importedFiles[resolvedFilename][media]) {
    atRule.removeSelf()
    return
  }
  if (!importedFiles[resolvedFilename]) {
    importedFiles[resolvedFilename] = {}
  }
  importedFiles[resolvedFilename][media] = true

  readImportedContent(atRule, parsedAtImport, clone(options), resolvedFilename, cb, importedFiles, ignoredAtRules)
}

/**
 * insert imported content at the right place
 *
 * @param {Object} atRule
 * @param {Object} parsedAtImport
 * @param {Object} options
 * @param {String} resolvedFilename
 * @param {Function} cb
 */
function readImportedContent(atRule, parsedAtImport, options, resolvedFilename, cb, importedFiles, ignoredAtRules) {
  // add directory containing the @imported file in the paths
  // to allow local import from this file
  var dirname = path.dirname(resolvedFilename)
  if (options.path.indexOf(dirname) === -1) {
    options.path = options.path.slice()
    options.path.unshift(dirname)
  }

  options.from = resolvedFilename
  var fileContent = readFile(resolvedFilename, options.encoding, options.transform || function(value) { return value })

  if (fileContent.trim() === "") {
    console.warn(helpers.message(resolvedFilename + " is empty", atRule.source))
    atRule.removeSelf()
    return
  }

  var newStyles = postcss.parse(fileContent, options)

  // recursion: import @import from imported file
  parseStyles(newStyles, options, cb, importedFiles, ignoredAtRules, parsedAtImport.media)

  cb(atRule, parsedAtImport, newStyles, resolvedFilename)
}

/**
 * insert new imported rules at the right place
 *
 * @param {Object} atRule
 * @param {Object} parsedAtImport
 * @param {Object} newStyles
 */
function insertRules(atRule, parsedAtImport, newStyles) {
  // wrap rules if the @import have a media query
  if (parsedAtImport.media && parsedAtImport.media.length) {
    // wrap new rules with media (media query)
    var wrapper = postcss.atRule({
      name: "media",
      params: parsedAtImport.media
    })
    wrapper.append(newStyles)
    newStyles = wrapper

    // better output
    newStyles.before = atRule.before
    if (newStyles.childs && newStyles.childs.length) {
      newStyles.childs[0].before = newStyles.childs[0].before || "\n"
    }
    newStyles.after = atRule.after || "\n"
  }
  else if (newStyles.childs && newStyles.childs.length) {
    newStyles.childs[0].before = atRule.before
  }

  atRule.parent.insertBefore(atRule, newStyles)
  atRule.removeSelf()
}

/**
 * parse @import parameter
 */
function parseImport(str, source) {
  var regex = /((?:url\s?\()?(?:'|")?([^)'"]+)(?:'|")?\)?)(?:(?:\s)(.*))?/gi
  var matches = regex.exec(str)
  if (matches === null) {
    throw new Error("Unable to find uri in '" + str + "'", source)
  }

  return {
    fullUri: matches[1],
    uri: matches[2],
    media: matches[3] ? matches[3] : null
  }
}

/**
 * Check if a file exists
 *
 * @param {String} name
 */
function resolveFilename(name, paths, source) {
  var root = paths[paths.length - 1]
  var dir = source && source.file ? path.dirname(path.resolve(root, source.file)) : root

  try {
    var resolveOpts = {
      basedir: dir,
      moduleDirectory: ["node_modules"].concat(paths),
      extensions: [".css"],
      packageFilter: function processPackage(pkg) {
        pkg.main = pkg.style || "index.css"
        return pkg
      }
    }
    var file
    try {
      file = resolve.sync(name, resolveOpts)
    }
    catch (e) {
      // fix to try relative files on windows with "./"
      // if it's look like it doesn't start with a relative path already
      if (name.match(/^\.\.?/)) {throw e}
      file = resolve.sync("." + path.sep + name, resolveOpts)
    }

    return path.normalize(file)
  }
  catch (e) {
    throw new Error(
      "Failed to find '" + name + "'" +
      "\n    in [ " +
      "\n        " + paths.join(",\n        ") +
      "\n    ]",
      source
    )
  }
}

/**
 * Read the contents of a file
 *
 * @param {String} file
 */
function readFile(file, encoding, transform) {
  return transform(fs.readFileSync(file, encoding || "utf8"), file)
}

/**
 * add `from` dirname to `path` if not already present
 *
 * @param {Object} options
 */
function addInputToPath(options) {
  if (options.from) {
    var fromDir = path.dirname(options.from)
    if (options.path.indexOf(fromDir) === -1) {
      options.path.unshift(fromDir)
    }
  }
}
<commit_msg>resolve want / not path.sep<commit_after>"use strict";

/**
 * Module dependencies.
 */
var fs = require("fs")
var path = require("path")

var clone = require("clone")
var resolve = require("resolve")
var postcss = require("postcss")
var helpers = require("postcss-message-helpers")

/**
 * Expose the plugin.
 */
module.exports = AtImport

/**
 * Inline `@import`ed files
 *
 * @param {Object} options
 */
function AtImport(options) {
  options = options || {}
  options.path = (
    // convert string to an array of a single element
    typeof options.path === "string" ?
    [options.path] :
    (options.path || []) // fallback to empty array
  )

  return function(styles) {
    // auto add from option if possible
    if (!options.from && styles && styles.childs && styles.childs[0] && styles.childs[0].source && styles.childs[0].source.file) {
      options.from = styles.childs[0].source.file
    }

    // if from available, prepend from directory in the path array
    addInputToPath(options)

    // if we got nothing for the path, just use cwd
    if (options.path.length === 0) {
      options.path.push(process.cwd())
    }

    var importedFiles = {}
    if (options.from) {
      importedFiles[options.from] = {
        "": true
      }
    }
    var ignoredAtRules = []

    parseStyles(styles, options, insertRules, importedFiles, ignoredAtRules)
    addIgnoredAtRulesOnTop(styles, ignoredAtRules)

    if (typeof options.onImport === "function") {
      options.onImport(Object.keys(importedFiles))
    }
  }
}

/**
 * lookup for @import rules
 *
 * @param {Object} styles
 * @param {Object} options
 */
function parseStyles(styles, options, cb, importedFiles, ignoredAtRules, media) {
  styles.eachAtRule(function checkAtRule(atRule) {
    if (atRule.name !== "import") {
      return
    }

    helpers.try(function transformAtImport() {
      readAtImport(atRule, options, cb, importedFiles, ignoredAtRules, media)
    }, atRule.source)
  })
}

/**
 * put back at the top ignored url (absolute url)
 *
 * @param {Object} styles
 * @param {Array} ignoredAtRules
 */
function addIgnoredAtRulesOnTop(styles, ignoredAtRules) {
  var i = ignoredAtRules.length
  if (i) {
    var first = styles.first

    while (i--) {
      var ignoredAtRule = ignoredAtRules[i][0]
      ignoredAtRule.params = ignoredAtRules[i][1].fullUri + (ignoredAtRules[i][1].media ? " " + ignoredAtRules[i][1].media : "")
      ignoredAtRule.before = "\n"
      ignoredAtRule.after = ""

      // don't use prepend() to avoid weird behavior of normalize()
      styles.childs.unshift(ignoredAtRule)
    }

    first.before = "\n\n" + first.before
  }
}

/**
 * parse @import rules & inline appropriate rules
 *
 * @param {Object} atRule  postcss atRule
 * @param {Object} options
 */
function readAtImport(atRule, options, cb, importedFiles, ignoredAtRules, media) {
  // parse-import module parse entire line
  // @todo extract what can be interesting from this one
  var parsedAtImport = parseImport(atRule.params, atRule.source)

  // adjust media according to current scope
  media = parsedAtImport.media ? (media ? media + " and " : "") + parsedAtImport.media : (media ? media : null)

  // just update protocol base uri (protocol://url) or protocol-relative (//url) if media needed
  if (parsedAtImport.uri.match(/^(?:[a-z]+:)?\/\//i)) {
    parsedAtImport.media = media
    ignoredAtRules.push([atRule, parsedAtImport])
    atRule.removeSelf()
    return
  }

  addInputToPath(options)
  var resolvedFilename = resolveFilename(parsedAtImport.uri, options.path, atRule.source)

  if (importedFiles[resolvedFilename] && importedFiles[resolvedFilename][media]) {
    atRule.removeSelf()
    return
  }
  if (!importedFiles[resolvedFilename]) {
    importedFiles[resolvedFilename] = {}
  }
  importedFiles[resolvedFilename][media] = true

  readImportedContent(atRule, parsedAtImport, clone(options), resolvedFilename, cb, importedFiles, ignoredAtRules)
}

/**
 * insert imported content at the right place
 *
 * @param {Object} atRule
 * @param {Object} parsedAtImport
 * @param {Object} options
 * @param {String} resolvedFilename
 * @param {Function} cb
 */
function readImportedContent(atRule, parsedAtImport, options, resolvedFilename, cb, importedFiles, ignoredAtRules) {
  // add directory containing the @imported file in the paths
  // to allow local import from this file
  var dirname = path.dirname(resolvedFilename)
  if (options.path.indexOf(dirname) === -1) {
    options.path = options.path.slice()
    options.path.unshift(dirname)
  }

  options.from = resolvedFilename
  var fileContent = readFile(resolvedFilename, options.encoding, options.transform || function(value) { return value })

  if (fileContent.trim() === "") {
    console.warn(helpers.message(resolvedFilename + " is empty", atRule.source))
    atRule.removeSelf()
    return
  }

  var newStyles = postcss.parse(fileContent, options)

  // recursion: import @import from imported file
  parseStyles(newStyles, options, cb, importedFiles, ignoredAtRules, parsedAtImport.media)

  cb(atRule, parsedAtImport, newStyles, resolvedFilename)
}

/**
 * insert new imported rules at the right place
 *
 * @param {Object} atRule
 * @param {Object} parsedAtImport
 * @param {Object} newStyles
 */
function insertRules(atRule, parsedAtImport, newStyles) {
  // wrap rules if the @import have a media query
  if (parsedAtImport.media && parsedAtImport.media.length) {
    // wrap new rules with media (media query)
    var wrapper = postcss.atRule({
      name: "media",
      params: parsedAtImport.media
    })
    wrapper.append(newStyles)
    newStyles = wrapper

    // better output
    newStyles.before = atRule.before
    if (newStyles.childs && newStyles.childs.length) {
      newStyles.childs[0].before = newStyles.childs[0].before || "\n"
    }
    newStyles.after = atRule.after || "\n"
  }
  else if (newStyles.childs && newStyles.childs.length) {
    newStyles.childs[0].before = atRule.before
  }

  atRule.parent.insertBefore(atRule, newStyles)
  atRule.removeSelf()
}

/**
 * parse @import parameter
 */
function parseImport(str, source) {
  var regex = /((?:url\s?\()?(?:'|")?([^)'"]+)(?:'|")?\)?)(?:(?:\s)(.*))?/gi
  var matches = regex.exec(str)
  if (matches === null) {
    throw new Error("Unable to find uri in '" + str + "'", source)
  }

  return {
    fullUri: matches[1],
    uri: matches[2],
    media: matches[3] ? matches[3] : null
  }
}

/**
 * Check if a file exists
 *
 * @param {String} name
 */
function resolveFilename(name, paths, source) {
  var root = paths[paths.length - 1]
  var dir = source && source.file ? path.dirname(path.resolve(root, source.file)) : root

  try {
    var resolveOpts = {
      basedir: dir,
      moduleDirectory: ["node_modules"].concat(paths),
      extensions: [".css"],
      packageFilter: function processPackage(pkg) {
        pkg.main = pkg.style || "index.css"
        return pkg
      }
    }
    var file
    try {
      file = resolve.sync(name, resolveOpts)
    }
    catch (e) {
      // fix to try relative files on windows with "./"
      // if it's look like it doesn't start with a relative path already
      if (name.match(/^\.\.?/)) {throw e}
      file = resolve.sync("./" + name, resolveOpts)
    }

    return path.normalize(file)
  }
  catch (e) {
    throw new Error(
      "Failed to find '" + name + "'" +
      "\n    in [ " +
      "\n        " + paths.join(",\n        ") +
      "\n    ]",
      source
    )
  }
}

/**
 * Read the contents of a file
 *
 * @param {String} file
 */
function readFile(file, encoding, transform) {
  return transform(fs.readFileSync(file, encoding || "utf8"), file)
}

/**
 * add `from` dirname to `path` if not already present
 *
 * @param {Object} options
 */
function addInputToPath(options) {
  if (options.from) {
    var fromDir = path.dirname(options.from)
    if (options.path.indexOf(fromDir) === -1) {
      options.path.unshift(fromDir)
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var del = require('del');
var esformatter = require('gulp-esformatter');
var file = require('gulp-file');
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var metaljs = require('metaljs');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');

function auiTasks(options) {
	options = normalizeOptions(options);

	metaljs(options);

	gulp.task('clean', function(done) {
		del('build', done);
	});

	gulp.task('build', function(done) {
		runSequence('clean', ['build:globals', 'css'], done);
	});

	gulp.task('css', function() {
		return gulp.src('src/**/*.scss')
			.pipe(file('bootstrap.scss', '@import "bootstrap";'))
			.pipe(sass({
				includePaths: ['bower_components/bootstrap-sass/assets/stylesheets'],
			}).on('error', sass.logError))
			.pipe(gulp.dest('build'));
	});

	gulp.task('format', function() {
	  var gulpOpts = {
	    base: process.cwd()
	  };
	  return gulp.src(options.formatGlobs, gulpOpts)
	    .pipe(esformatter({
				indent: {
					value: '	'
				}
			}))
	    .pipe(gulp.dest(process.cwd()));
	});

	gulp.task('lint', function() {
	  return gulp.src(options.lintGlobs)
	    .pipe(jshint())
	    .pipe(jshint.reporter(require('jshint-stylish')));
	});
}

function normalizeOptions(options) {
	var codeGlobs = ['src/**/*.js', '!src/**/*.soy.js', 'test/**/*.js', 'gulpfile.js'];

	options.buildDest = options.buildDest || 'build/globals';
	options.soyGeneratedDest = options.soyGeneratedDest || 'build';

	options.formatGlobs = options.formatGlobs || codeGlobs;
	options.lintGlobs = options.lintGlobs || codeGlobs;
	return options;
}

module.exports = auiTasks;
<commit_msg>Changes global variable name to be "aui"<commit_after>'use strict';

var del = require('del');
var esformatter = require('gulp-esformatter');
var file = require('gulp-file');
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var metaljs = require('metaljs');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');

function auiTasks(options) {
	options = normalizeOptions(options);

	metaljs(options);

	gulp.task('clean', function(done) {
		del('build', done);
	});

	gulp.task('build', function(done) {
		runSequence('clean', ['build:globals', 'css'], done);
	});

	gulp.task('css', function() {
		return gulp.src('src/**/*.scss')
			.pipe(file('bootstrap.scss', '@import "bootstrap";'))
			.pipe(sass({
				includePaths: ['bower_components/bootstrap-sass/assets/stylesheets'],
			}).on('error', sass.logError))
			.pipe(gulp.dest('build'));
	});

	gulp.task('format', function() {
	  var gulpOpts = {
	    base: process.cwd()
	  };
	  return gulp.src(options.formatGlobs, gulpOpts)
	    .pipe(esformatter({
				indent: {
					value: '	'
				}
			}))
	    .pipe(gulp.dest(process.cwd()));
	});

	gulp.task('lint', function() {
	  return gulp.src(options.lintGlobs)
	    .pipe(jshint())
	    .pipe(jshint.reporter(require('jshint-stylish')));
	});
}

function normalizeOptions(options) {
	var codeGlobs = ['src/**/*.js', '!src/**/*.soy.js', 'test/**/*.js', 'gulpfile.js'];

	options.buildDest = options.buildDest || 'build/globals';
	options.globalName = options.globalName || 'aui';
	options.soyGeneratedDest = options.soyGeneratedDest || 'build';

	options.formatGlobs = options.formatGlobs || codeGlobs;
	options.lintGlobs = options.lintGlobs || codeGlobs;
	return options;
}

module.exports = auiTasks;
<|endoftext|>


<commit_before>/** @jsx dom */
import dom from 'magic-virtual-element';

const propTypes = {
	class: {
		type: 'string'
	},
	collapsed: {
		type: 'boolean'
	},
	items: {
		type: 'array'
	},
	multiple: {
		type: 'boolean'
	}
};

function initialState() {
	return {
		active: []
	};
}

function afterMount({props}, el, setState) {
	const {items, multiple} = props;
	let active = [];

	items.forEach((el, i) => {
		if (!el.active) {
			return;
		}

		if (!multiple) {
			active = [i];
			return;
		}

		active.push(i);
	});

	setState({active});
}

function render({props, state}, setState) {
	const {items, multiple} = props;
	const {active} = state;

	function setActive(i) {
		const index = active.indexOf(i);

		if (!multiple) {
			if (index !== -1) {
				setState({active: []});
				return;
			}

			setState({active: [i]});
			return;
		}

		if (index !== -1) {
			active.splice(index, 1);
			setState({active});
			return;
		}

		active.push(i);
		setState({active});
	}

	function getElements() {
		return items.map((el, i) => {
			return (

 -1}]}>

 setActive(i)}>
						{el.heading}

						{el.content}

			);
		});
	}

	return (

			{getElements()}

	);
}

export default {afterMount, initialState, propTypes, render};
<commit_msg>Remove unnecessary block statement<commit_after>/** @jsx dom */
import dom from 'magic-virtual-element';

const propTypes = {
	class: {
		type: 'string'
	},
	collapsed: {
		type: 'boolean'
	},
	items: {
		type: 'array'
	},
	multiple: {
		type: 'boolean'
	}
};

function initialState() {
	return {
		active: []
	};
}

function afterMount({props}, el, setState) {
	const {items, multiple} = props;
	let active = [];

	items.forEach((el, i) => {
		if (!el.active) {
			return;
		}

		if (!multiple) {
			active = [i];
			return;
		}

		active.push(i);
	});

	setState({active});
}

function render({props, state}, setState) {
	const {items, multiple} = props;
	const {active} = state;

	function setActive(i) {
		const index = active.indexOf(i);

		if (!multiple) {
			if (index !== -1) {
				setState({active: []});
				return;
			}

			setState({active: [i]});
			return;
		}

		if (index !== -1) {
			active.splice(index, 1);
			setState({active});
			return;
		}

		active.push(i);
		setState({active});
	}

	function getElements() {
		return items.map((el, i) => (

 -1}]}>

 setActive(i)}>
					{el.heading}

					{el.content}

		));
	}

	return (

			{getElements()}

	);
}

export default {afterMount, initialState, propTypes, render};
<|endoftext|>