<commit_before>/**
 * gulp-tannwestlake
 * @param Gulp gulp
 */
module.exports = (function(gulp) {

    // Include our dependencies, starting with style stuff
    var sass        = require('gulp-sass'),
        autoprefix  = require('gulp-autoprefixer'),
        minify      = require('gulp-minify-css'),
        rename      = require('gulp-rename'),

        // Scripts
        uglify      = require('gulp-uglify'),
        strip       = require('gulp-strip-debug'),
        concat      = require('gulp-concat'),

        // Images
        png         = require('imagemin-optipng'),
        jpg         = require('imagemin-jpegtran'),
        gif         = require('imagemin-gifsicle'),
        cache       = require('gulp-cache'),

        // Other
        util        = require('gulp-util'),
        del         = require('del'),
        bust        = require('gulp-buster'),
        notify      = require('gulp-notify'),
        notifier    = require('node-notifier'),
        merge       = require('merge-stream')
        sequence    = require('run-sequence');

    // Store default settings for all tasks
    var settings = {

        // Deploy task settings
        deploy: {
            files: ['**/*'],
            destination: '_deploy'
        },

        // Style task settings
        styles: {
            autoprefix: {
                browsers: "last 15 versions"
            },
            public: 'public/styles',
            src: 'assets/styles/**/*.scss',
            cache: 'public/cache',
            sass: {
                sourceComments: 'normal'
            }
        },

        // Script task settings
        scripts: {
            src: 'assets/js/**/*.js',
            filename: 'main.min.js',
            public: 'public/js',
            cache: 'public/cache'
        },

        // Images task settings
        images: {
            src: 'assets/img/**/*',
            public: 'public/img'
        },

        // Clean task settings
        clean: {
            paths: [
                'public/styles',
                'public/js',
                'public/img'
            ],
        },

        // Default task settings
        default: {
            notify: {message: 'Tasks complete'},
            watch: true,
            clean: true
        },

        // Watch task settings
        watch: {
            tasks: [
                {path: 'assets/styles/**/*.scss', tasks: ['styles']}
                {path: 'assets/js/**/*.js', tasks: ['scripts']}
                {path: 'assets/img/**/*', tasks: ['images']}
            ]
        },
    };

    /**
     * Handle option setting
     *
     * @param Object defaults  Default options
     * @param Object supplied User supplied
     */
    function _setOptions(defaults, supplied)
    {
        if(supplied === undefined) return defaults;

        var options = defaults;

        for(key in supplied) {
            var option = supplied[key];

            if(option !== undefined) {
                options[key] = supplied[key];
            } else if(typeof option === 'object') {
                options[key] = _setOptions(defaults[key], supplied[key]);
            }
        }

        return options;
    };

    /**
     * Deployment task
     *
     * @param  Object options
     * @return Function
     */
    function deploy(options)
    {
        var realOptions = _setOptions(settings.deploy, options);

        return function() {
            return gulp.src(realOptions.files, {base: '.'}).pipe(gulp.dest(realOptions.destination));
        };
    };

    /**
     * Styles task
     *
     * @param  Object options
     * @return Function
     */
    function styles(options)
    {
        var realOptions = _setOptions(settings.styles, options);

        return function() {
            return gulp.src(realOptions.src)
                .pipe(sass(realOptions.sass))
                .on('error', util.log)
                .pipe(autoprefix(realOptions.autoprefix))
                .pipe(gulp.dest(realOptions.public))
                .pipe(bust())
                .pipe(gulp.dest(realOptions.cache));
        };
    };

    /**
     * Scripts task
     *
     * @param  Object options
     * @return Function
     */
    function scripts(options)
    {
        var realOptions = _setOptions(settings.scripts, options);

        return function() {
            return gulp.src(realOptions.src)
                .pipe(concat(realOptions.filename))
                .pipe(gulp.dest(realOptions.public))
                .pipe(bust())
                .pipe(gulp.dest(realOptions.cache));
        };
    };

    /**
     * Images task
     *
     * @param  Object options
     * @return Function
     */
    function images(options)
    {
        var realOptions = _setOptions(settings.images, options);

        return function() {
            return gulp.src(realOptions.src)
                .pipe(gulp.dest(realOptions.public));
        };
    };

    /**
     * Clear task
     *
     * @return Function
     */
    function clear()
    {
        return function(done) {
            return cache.clearAll(done);
        };
    };

    /**
     * Clean task
     *
     * @param  Object options
     * @return Function
     */
    function clean(options)
    {
        var realOptions = _setOptions(settings.clean, options);

        return function(cb) {
            return del(realOptions.paths, cb);
        };
    };

    /**
     * Production task
     *
     * @param  Object options
     * @return Function
     */
    function production()
    {
        return function() {
            // Return the streams in one combined stream
            return merge(styles, scripts, images);
        };
    };

    /**
     * Default task
     *
     * @param  Object options
     * @return Function
     */
    function default(options)
    {
        var realOptions = _setOptions(settings.default, options);

        return function(callback) {

            if(realOptions.clean === true && realOptions.watch === true) {
                sequence('clean', realOptions.tasks, 'watch', callback);
            } else if(realOptions.clean === true && realOptions.watch === false) {
                sequence('clean', realOptions.tasks, callback);
            } else if(realOptions.clean === false && realOptions.watch === true) {
                sequence(realOptions.tasks, 'watch', callback);
            } else {
                sequence(realOptions.tasks, callback);
            }

            notifier.notify(realOptions.notify);
        };
    };

    /**
     * Watch task
     *
     * @param  Object options
     * @return Function
     */
    function watch(options)
    {
        var realOptions = _setOptions(settings.watch, options);

        return function() {
            for(index in realOptions.tasks) {
                var task = realOptions.tasks[index];
                gulp.watch(task.path, task.tasks);
            }
        };
    };

    // Give access to the tasks
    return {
        styles: styles,
        scripts: scripts,
        images: images,
        clear: clear,
        clean: clean,
        production: production,
        deploy: deploy,
        default: default,
        watch: watch
    };

});
<commit_msg>:bug: Fix name conflicts<commit_after>/**
 * gulp-tannwestlake
 * @param Gulp gulp
 */
module.exports = (function(gulp) {

    // Include our dependencies, starting with style stuff
    var sass        = require('gulp-sass'),
        autoprefix  = require('gulp-autoprefixer'),
        minify      = require('gulp-minify-css'),
        rename      = require('gulp-rename'),

        // Scripts
        uglify      = require('gulp-uglify'),
        strip       = require('gulp-strip-debug'),
        concat      = require('gulp-concat'),

        // Images
        png         = require('imagemin-optipng'),
        jpg         = require('imagemin-jpegtran'),
        gif         = require('imagemin-gifsicle'),
        cache       = require('gulp-cache'),

        // Other
        util        = require('gulp-util'),
        del         = require('del'),
        bust        = require('gulp-buster'),
        notify      = require('gulp-notify'),
        notifier    = require('node-notifier'),
        merge       = require('merge-stream')
        sequence    = require('run-sequence');

    // Store default settings for all tasks
    var settings = {

        // Deploy task settings
        deploy: {
            files: ['**/*'],
            destination: '_deploy'
        },

        // Style task settings
        styles: {
            autoprefix: {
                browsers: "last 15 versions"
            },
            public: 'public/styles',
            src: 'assets/styles/**/*.scss',
            cache: 'public/cache',
            sass: {
                sourceComments: 'normal'
            }
        },

        // Script task settings
        scripts: {
            src: 'assets/js/**/*.js',
            filename: 'main.min.js',
            public: 'public/js',
            cache: 'public/cache'
        },

        // Images task settings
        images: {
            src: 'assets/img/**/*',
            public: 'public/img'
        },

        // Clean task settings
        clean: {
            paths: [
                'public/styles',
                'public/js',
                'public/img'
            ],
        },

        // Default task settings
        standard: {
            notify: {message: 'Tasks complete'},
            watch: true,
            clean: true
        },

        // Watch task settings
        watch: {
            tasks: [
                {path: 'assets/styles/**/*.scss', tasks: ['styles']},
                {path: 'assets/js/**/*.js', tasks: ['scripts']},
                {path: 'assets/img/**/*', tasks: ['images']}
            ]
        },
    };

    /**
     * Handle option setting
     *
     * @param Object defaults  Default options
     * @param Object supplied User supplied
     */
    function _setOptions(defaults, supplied)
    {
        if(supplied === undefined) return defaults;

        var options = defaults;

        for(key in supplied) {
            var option = supplied[key];

            if(option !== undefined) {
                options[key] = supplied[key];
            } else if(typeof option === 'object') {
                options[key] = _setOptions(defaults[key], supplied[key]);
            }
        }

        return options;
    };

    /**
     * Deployment task
     *
     * @param  Object options
     * @return Function
     */
    function deploy(options)
    {
        var realOptions = _setOptions(settings.deploy, options);

        return function() {
            return gulp.src(realOptions.files, {base: '.'}).pipe(gulp.dest(realOptions.destination));
        };
    };

    /**
     * Styles task
     *
     * @param  Object options
     * @return Function
     */
    function styles(options)
    {
        var realOptions = _setOptions(settings.styles, options);

        return function() {
            return gulp.src(realOptions.src)
                .pipe(sass(realOptions.sass))
                .on('error', util.log)
                .pipe(autoprefix(realOptions.autoprefix))
                .pipe(gulp.dest(realOptions.public))
                .pipe(bust())
                .pipe(gulp.dest(realOptions.cache));
        };
    };

    /**
     * Scripts task
     *
     * @param  Object options
     * @return Function
     */
    function scripts(options)
    {
        var realOptions = _setOptions(settings.scripts, options);

        return function() {
            return gulp.src(realOptions.src)
                .pipe(concat(realOptions.filename))
                .pipe(gulp.dest(realOptions.public))
                .pipe(bust())
                .pipe(gulp.dest(realOptions.cache));
        };
    };

    /**
     * Images task
     *
     * @param  Object options
     * @return Function
     */
    function images(options)
    {
        var realOptions = _setOptions(settings.images, options);

        return function() {
            return gulp.src(realOptions.src)
                .pipe(gulp.dest(realOptions.public));
        };
    };

    /**
     * Clear task
     *
     * @return Function
     */
    function clear()
    {
        return function(done) {
            return cache.clearAll(done);
        };
    };

    /**
     * Clean task
     *
     * @param  Object options
     * @return Function
     */
    function clean(options)
    {
        var realOptions = _setOptions(settings.clean, options);

        return function(cb) {
            return del(realOptions.paths, cb);
        };
    };

    /**
     * Production task
     *
     * @param  Object options
     * @return Function
     */
    function production()
    {
        return function() {
            // Return the streams in one combined stream
            return merge(styles, scripts, images);
        };
    };

    /**
     * Standard task
     *
     * @param  Object options
     * @return Function
     */
    function standard(options)
    {
        var realOptions = _setOptions(settings.standard, options);

        return function(callback) {

            if(realOptions.clean === true && realOptions.watch === true) {
                sequence('clean', realOptions.tasks, 'watch', callback);
            } else if(realOptions.clean === true && realOptions.watch === false) {
                sequence('clean', realOptions.tasks, callback);
            } else if(realOptions.clean === false && realOptions.watch === true) {
                sequence(realOptions.tasks, 'watch', callback);
            } else {
                sequence(realOptions.tasks, callback);
            }

            notifier.notify(realOptions.notify);
        };
    };

    /**
     * Watch task
     *
     * @param  Object options
     * @return Function
     */
    function watch(options)
    {
        var realOptions = _setOptions(settings.watch, options);

        return function() {
            for(index in realOptions.tasks) {
                var task = realOptions.tasks[index];
                gulp.watch(task.path, task.tasks);
            }
        };
    };

    // Give access to the tasks
    return {
        styles: styles,
        scripts: scripts,
        images: images,
        clear: clear,
        clean: clean,
        production: production,
        deploy: deploy,
        standard: standard,
        watch: watch
    };

});
<|endoftext|>


<commit_before>module.exports = save;

function save(graph, customNodeTransform, customLinkTransform) {
  // Object contains `nodes` and `links` arrays.
  var result = {
    nodes: [],
    links: []
  };

  var nodeTransform = customNodeTransform || defaultTransformForNode;
  var linkTransform = customLinkTransform || defaultTransformForLink;

  graph.forEachNode(saveNode);
  graph.forEachLink(saveLink);

  return JSON.stringify(result);

  function saveNode(node) {
    // Each node of the graph is processed to take only required fields
    // `id` and `data`
    result.nodes.push(nodeTransform(node));
  }

  function saveLink(link) {
    // Each link of the graph is also processed to take `fromId`, `toId` and
    // `data`
    result.links.push(linkTransform(link));
  }

  function defaultTransformForNode(node) {
    var result = {
      id: node.id
    };
    // We don't want to store undefined fields when it's not necessary:
    if (node.data !== undefined) {
      result.data = node.data;
    }

    return result;
  }

  function defaultTransformForLink(link) {
    var result = {
      fromId: link.fromId,
      toId: link.toId,
    };

    if (link.data !== undefined) {
      result.data = link.data;
    }

    return result;
  }
}
<commit_msg>Allow huge graph serialization<commit_after>module.exports = save;

function save(graph, customNodeTransform, customLinkTransform) {
  // Object contains `nodes` and `links` arrays.
  var result = {
    nodes: [],
    links: []
  };

  var nodeTransform = customNodeTransform || defaultTransformForNode;
  var linkTransform = customLinkTransform || defaultTransformForLink;

  graph.forEachNode(saveNode);
  graph.forEachLink(saveLink);

  return '{"nodes": [' + result.nodes.join(',') + '], "links": [' +
  result.links.join(',') + ']}';

  function saveNode(node) {
    // Each node of the graph is processed to take only required fields
    // `id` and `data`
    result.nodes.push(JSON.stringify(nodeTransform(node)));
  }

  function saveLink(link) {
    // Each link of the graph is also processed to take `fromId`, `toId` and
    // `data`
    result.links.push(JSON.stringify(linkTransform(link)));
  }

  function defaultTransformForNode(node) {
    var result = {
      id: node.id
    };
    // We don't want to store undefined fields when it's not necessary:
    if (node.data !== undefined) {
      result.data = node.data;
    }

    return result;
  }

  function defaultTransformForLink(link) {
    var result = {
      fromId: link.fromId,
      toId: link.toId,
    };

    if (link.data !== undefined) {
      result.data = link.data;
    }

    return result;
  }
}
<|endoftext|>


<commit_before>'use strict'

const Models = require('./lib/models')
const RESTv1 = require('./lib/transports/rest.js')
const WSv1 = require('./lib/transports/ws.js')
const RESTv2 = require('./lib/transports/rest2.js')
const WSv2 = require('./lib/transports/ws2.js')

/**
 * Provides access to versions 1 & 2 of the HTTP & WebSocket Bitfinex APIs
 */
class BFX {
  /**
   * @param {Object} opts
   * @param {string} opts.apiKey
   * @param {string} opts.apiSecret
   * @param {string} opts.transform - if true, packets are converted to models
   * @param {string} opts.nonceGenerator - optional
   * @param {string} opts.ws - ws transport options
   * @param {string} opts.rest - rest transport options
   */
  constructor (opts = {
    apiKey: '',
    apiSecret: '',
    transform: false,
    ws: {},
    rest: {}
  }) {
    if (opts.constructor.name !== 'Object') {
      throw new Error([
        'constructor takes an object since version 2.0.0, see:',
        'https://github.com/bitfinexcom/bitfinex-api-node#version-200-breaking-changes\n'
      ].join('\n'))
    }

    this._apiKey = opts.apiKey || ''
    this._apiSecret = opts.apiSecret || ''
    this._transform = opts.transform === true
    this._wsArgs = opts.ws || {}
    this._restArgs = opts.rest || {}
    this._transportCache = {
      rest: {},
      ws: {}
    }
  }

  _getTransportPayload (extraOpts) {
    return Object.assign({
      apiKey: this._apiKey,
      apiSecret: this._apiSecret,
      transform: this._transform
    }, extraOpts)
  }

  /**
   * Returns a new REST API class instance (cached by version)
   *
   * @param {number} version - 1 or 2 (default)
   * @param {Object} extraOpts - passed to transport constructor
   * @return {RESTv1|RESTv2} transport
   */
  rest (version = 2, extraOpts = {}) {
    if (version !== 1 && version !== 2) {
      throw new Error(`invalid http API version: ${version}`)
    }

    if (!this._transportCache.rest[version]) {
      Object.assign(extraOpts, this._restArgs)
      const payload = this._getTransportPayload(extraOpts)

      this._transportCache.rest[version] = version === 2
        ? new RESTv2(payload)
        : new RESTv1(payload)
    }

    return this._transportCache.rest[version]
  }

  /**
   * Returns a new WebSocket API class instance (cached by version)
   *
   * @param {number} version - 1 or 2 (default)
   * @param {Object} extraOpts - passed to transport constructor
   * @return {WSv1|WSv2} transport
   */
  ws (version = 2, extraOpts = {}) {
    if (version !== 1 && version !== 2) {
      throw new Error(`invalid websocket API version: ${version}`)
    }

    if (!this._transportCache.ws[version]) {
      Object.assign(extraOpts, this._wsArgs)
      const payload = this._getTransportPayload(extraOpts)

      this._transportCache.ws[version] = version === 2
        ? new WSv2(payload)
        : new WSv1(payload)
    }

    return this._transportCache.ws[version]
  }
}

module.exports = BFX
module.exports.RESTv1 = RESTv1
module.exports.RESTv2 = RESTv2
module.exports.WSv1 = WSv1
module.exports.WSv2 = WSv2
module.exports.Models = Models
<commit_msg>(refactor) include BFX transport opts in cache key<commit_after>'use strict'

const Models = require('./lib/models')
const RESTv1 = require('./lib/transports/rest.js')
const WSv1 = require('./lib/transports/ws.js')
const RESTv2 = require('./lib/transports/rest2.js')
const WSv2 = require('./lib/transports/ws2.js')

/**
 * Provides access to versions 1 & 2 of the HTTP & WebSocket Bitfinex APIs
 */
class BFX {
  /**
   * @param {Object} opts
   * @param {string} opts.apiKey
   * @param {string} opts.apiSecret
   * @param {string} opts.transform - if true, packets are converted to models
   * @param {string} opts.nonceGenerator - optional
   * @param {string} opts.ws - ws transport options
   * @param {string} opts.rest - rest transport options
   */
  constructor (opts = {
    apiKey: '',
    apiSecret: '',
    transform: false,
    ws: {},
    rest: {}
  }) {
    if (opts.constructor.name !== 'Object') {
      throw new Error([
        'constructor takes an object since version 2.0.0, see:',
        'https://github.com/bitfinexcom/bitfinex-api-node#version-200-breaking-changes\n'
      ].join('\n'))
    }

    this._apiKey = opts.apiKey || ''
    this._apiSecret = opts.apiSecret || ''
    this._transform = opts.transform === true
    this._wsArgs = opts.ws || {}
    this._restArgs = opts.rest || {}
    this._transportCache = {
      rest: {},
      ws: {}
    }
  }

  _getTransportPayload (extraOpts) {
    return Object.assign({
      apiKey: this._apiKey,
      apiSecret: this._apiSecret,
      transform: this._transform
    }, extraOpts)
  }

  /**
   * Returns a new REST API class instance (cached by version)
   *
   * @param {number} version - 1 or 2 (default)
   * @param {Object} extraOpts - passed to transport constructor
   * @return {RESTv1|RESTv2} transport
   */
  rest (version = 2, extraOpts = {}) {
    if (version !== 1 && version !== 2) {
      throw new Error(`invalid http API version: ${version}`)
    }

    const key = `${version}|${JSON.stringify(extraOpts)}`

    if (!this._transportCache.rest[key]) {
      Object.assign(extraOpts, this._restArgs)
      const payload = this._getTransportPayload(extraOpts)

      this._transportCache.rest[key] = version === 2
        ? new RESTv2(payload)
        : new RESTv1(payload)
    }

    return this._transportCache.rest[key]
  }

  /**
   * Returns a new WebSocket API class instance (cached by version)
   *
   * @param {number} version - 1 or 2 (default)
   * @param {Object} extraOpts - passed to transport constructor
   * @return {WSv1|WSv2} transport
   */
  ws (version = 2, extraOpts = {}) {
    if (version !== 1 && version !== 2) {
      throw new Error(`invalid websocket API version: ${version}`)
    }

    const key = `${version}|${JSON.stringify(extraOpts)}`

    if (!this._transportCache.ws[key]) {
      Object.assign(extraOpts, this._wsArgs)
      const payload = this._getTransportPayload(extraOpts)

      this._transportCache.ws[key] = version === 2
        ? new WSv2(payload)
        : new WSv1(payload)
    }

    return this._transportCache.ws[key]
  }
}

module.exports = BFX
module.exports.RESTv1 = RESTv1
module.exports.RESTv2 = RESTv2
module.exports.WSv1 = WSv1
module.exports.WSv2 = WSv2
module.exports.Models = Models
<|endoftext|>


<commit_before>'use strict';

var remote = require('remote');
var url = require('url');

var webView = document.getElementById('mainWebview');

// Open external link in default browser.
webView.addEventListener('new-window', function(e) {
  var currentUrl = url.parse(webView.getUrl());
  var destUrl = url.parse(e.url);
  // Open in browserWindow. for exmaple, attached files.
  if(currentUrl.host === destUrl.host){
    window.open(e.url);
  }
  else{
    require('shell').openExternal(e.url);
  }
});

// Count unread channels.
var timer = setInterval(function() {
  webView.send('retrieveUnreadCount');
}, 1000);

var showUnreadBadge = function(unreadCount){
  switch (process.platform) {
    case 'win32':
      var window = remote.getCurrentWindow();
      if(unreadCount > 0){
        window.setOverlayIcon(__dirname + '/badge.png', 'You have unread channels.');
      }
      else{
        window.setOverlayIcon(null, '');
      }
      break;
    default:
  }
}

webView.addEventListener('ipc-message', function(event){
  switch (event.channel) {
    case 'retrieveUnreadCount':
      var unreadCount = event.args[0];
      showUnreadBadge(unreadCount);
      break;
  }
});
<commit_msg>ウィンドウタイトルを設定<commit_after>'use strict';

var remote = require('remote');
var url = require('url');

var webView = document.getElementById('mainWebview');

webView.addEventListener('page-title-set', function(e){
  document.title = e.title;
});

// Open external link in default browser.
webView.addEventListener('new-window', function(e) {
  var currentUrl = url.parse(webView.getUrl());
  var destUrl = url.parse(e.url);
  // Open in browserWindow. for exmaple, attached files.
  if(currentUrl.host === destUrl.host){
    window.open(e.url, 'Mattermost');
  }
  else{
    require('shell').openExternal(e.url);
  }
});

// Count unread channels.
var timer = setInterval(function() {
  webView.send('retrieveUnreadCount');
}, 1000);

var showUnreadBadge = function(unreadCount){
  switch (process.platform) {
    case 'win32':
      var window = remote.getCurrentWindow();
      if(unreadCount > 0){
        window.setOverlayIcon(__dirname + '/badge.png', 'You have unread channels.');
      }
      else{
        window.setOverlayIcon(null, '');
      }
      break;
    default:
  }
}

webView.addEventListener('ipc-message', function(event){
  switch (event.channel) {
    case 'retrieveUnreadCount':
      var unreadCount = event.args[0];
      showUnreadBadge(unreadCount);
      break;
  }
});
<|endoftext|>


<commit_before>var context = new AudioContext(), // AND THEN THERE WAS SOUND
    sineOscillator = new SineOscillator(context);

var freqRange = document.getElementById("freq"),
    playButton = document.getElementById("play");

playButton.onclick = function() {
  sineOscillator.setFrequency(freqRange.value)
  sineOscillator.togglePlay();
}

freqRange.onmousedown = function() {
  if (sineOscillator.isPlaying()) {
    paused = true;
    sineOscillator.pause();
  }
}

freqRange.onmouseup = function() {
  if (paused) {
    sineOscillator.setFrequency(freqRange.value);
    sineOscillator.play();
  }
}
<commit_msg>updated index.js<commit_after>var context = new AudioContext(), // AND THEN THERE WAS SOUND
    sineOscillator = new SineOscillator(context);

var freqRange = document.getElementById("freq"),
    playButton = document.getElementById("play");

playButton.onclick = function() {
  sineOscillator.setFrequency(freqRange.value)
  sineOscillator.togglePlay();
}

freqRange.onmousedown = function() {
  if (sineOscillator.isPlaying()) {
    paused = true;
    sineOscillator.pause();
  }
}

freqRange.onmouseup = function() {
  if (paused) {
    sineOscillator.setFrequency(freqRange.value);
    sineOscillator.play();
    paused = false;
  }
}
<|endoftext|>


<commit_before>/*! multistream. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
const stream = require('readable-stream')
const once = require('once')

function toStreams2Obj (s) {
  return toStreams2(s, { objectMode: true, highWaterMark: 16 })
}

function toStreams2Buf (s) {
  return toStreams2(s)
}

function toStreams2 (s, opts) {
  if (!s || typeof s === 'function' || s._readableState) return s

  const wrap = new stream.Readable(opts).wrap(s)
  if (s.destroy) {
    wrap.destroy = s.destroy.bind(s)
  }
  return wrap
}

class MultiStream extends stream.Readable {
  constructor (streams, opts) {
    super({ ...opts, autoDestroy: true })

    this._drained = false
    this._forwarding = false
    this._current = null
    this._toStreams2 = (opts && opts.objectMode) ? toStreams2Obj : toStreams2Buf

    if (typeof streams === 'function') {
      this._queue = streams
    } else {
      this._queue = streams.map(this._toStreams2)
      this._queue.forEach(stream => {
        if (typeof stream !== 'function') this._attachErrorListener(stream)
      })
    }

    this._next()
  }

  _read () {
    this._drained = true
    this._forward()
  }

  _forward () {
    if (this._forwarding || !this._drained || !this._current) return
    this._forwarding = true

    let chunk
    while (this._drained && (chunk = this._current.read()) !== null) {
      this._drained = this.push(chunk)
    }

    this._forwarding = false
  }

  _destroy (err, cb) {
    let streams = []
    if (this._current) streams.push(this._current)
    if (typeof this._queue !== 'function') streams = streams.concat(this._queue)

    if (streams.length === 0) {
      cb(err)
    } else {
      let counter = streams.length
      let er = err
      streams.forEach(stream => {
        destroy(stream, err, err => {
          er = er || err
          if (--counter === 0) {
            cb(er)
          }
        })
      })
    }
  }

  _next () {
    this._current = null

    if (typeof this._queue === 'function') {
      this._queue((err, stream) => {
        if (err) return this.destroy(err)
        stream = this._toStreams2(stream)
        this._attachErrorListener(stream)
        this._gotNextStream(stream)
      })
    } else {
      let stream = this._queue.shift()
      if (typeof stream === 'function') {
        stream = this._toStreams2(stream())
        this._attachErrorListener(stream)
      }
      this._gotNextStream(stream)
    }
  }

  _gotNextStream (stream) {
    if (!stream) {
      this.push(null)
      return
    }

    this._current = stream
    this._forward()

    const onReadable = () => {
      this._forward()
    }

    const onClose = () => {
      if (!stream._readableState.ended && !stream.destroyed) {
        const err = new Error('ERR_STREAM_PREMATURE_CLOSE')
        err.code = 'ERR_STREAM_PREMATURE_CLOSE'
        this.destroy(err)
      }
    }

    const onEnd = () => {
      this._current = null
      stream.removeListener('readable', onReadable)
      stream.removeListener('end', onEnd)
      stream.removeListener('close', onClose)
      stream.destroy()
      this._next()
    }

    stream.on('readable', onReadable)
    stream.once('end', onEnd)
    stream.once('close', onClose)
  }

  _attachErrorListener (stream) {
    if (!stream) return

    const onError = (err) => {
      stream.removeListener('error', onError)
      this.destroy(err)
    }

    stream.once('error', onError)
  }
}

MultiStream.obj = streams => (
  new MultiStream(streams, { objectMode: true, highWaterMark: 16 })
)

module.exports = MultiStream

// Normalize stream destroy w/ callback.
function destroy (stream, err, cb) {
  if (!stream.destroy || stream.destroyed) {
    cb(err)
  } else {
    const callback = once(er => cb(er || err))
    stream
      .on('error', callback)
      .on('close', () => callback()))
      .destroy(err, callback)
  }
}
<commit_msg>fix syntax error<commit_after>/*! multistream. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
const stream = require('readable-stream')
const once = require('once')

function toStreams2Obj (s) {
  return toStreams2(s, { objectMode: true, highWaterMark: 16 })
}

function toStreams2Buf (s) {
  return toStreams2(s)
}

function toStreams2 (s, opts) {
  if (!s || typeof s === 'function' || s._readableState) return s

  const wrap = new stream.Readable(opts).wrap(s)
  if (s.destroy) {
    wrap.destroy = s.destroy.bind(s)
  }
  return wrap
}

class MultiStream extends stream.Readable {
  constructor (streams, opts) {
    super({ ...opts, autoDestroy: true })

    this._drained = false
    this._forwarding = false
    this._current = null
    this._toStreams2 = (opts && opts.objectMode) ? toStreams2Obj : toStreams2Buf

    if (typeof streams === 'function') {
      this._queue = streams
    } else {
      this._queue = streams.map(this._toStreams2)
      this._queue.forEach(stream => {
        if (typeof stream !== 'function') this._attachErrorListener(stream)
      })
    }

    this._next()
  }

  _read () {
    this._drained = true
    this._forward()
  }

  _forward () {
    if (this._forwarding || !this._drained || !this._current) return
    this._forwarding = true

    let chunk
    while (this._drained && (chunk = this._current.read()) !== null) {
      this._drained = this.push(chunk)
    }

    this._forwarding = false
  }

  _destroy (err, cb) {
    let streams = []
    if (this._current) streams.push(this._current)
    if (typeof this._queue !== 'function') streams = streams.concat(this._queue)

    if (streams.length === 0) {
      cb(err)
    } else {
      let counter = streams.length
      let er = err
      streams.forEach(stream => {
        destroy(stream, err, err => {
          er = er || err
          if (--counter === 0) {
            cb(er)
          }
        })
      })
    }
  }

  _next () {
    this._current = null

    if (typeof this._queue === 'function') {
      this._queue((err, stream) => {
        if (err) return this.destroy(err)
        stream = this._toStreams2(stream)
        this._attachErrorListener(stream)
        this._gotNextStream(stream)
      })
    } else {
      let stream = this._queue.shift()
      if (typeof stream === 'function') {
        stream = this._toStreams2(stream())
        this._attachErrorListener(stream)
      }
      this._gotNextStream(stream)
    }
  }

  _gotNextStream (stream) {
    if (!stream) {
      this.push(null)
      return
    }

    this._current = stream
    this._forward()

    const onReadable = () => {
      this._forward()
    }

    const onClose = () => {
      if (!stream._readableState.ended && !stream.destroyed) {
        const err = new Error('ERR_STREAM_PREMATURE_CLOSE')
        err.code = 'ERR_STREAM_PREMATURE_CLOSE'
        this.destroy(err)
      }
    }

    const onEnd = () => {
      this._current = null
      stream.removeListener('readable', onReadable)
      stream.removeListener('end', onEnd)
      stream.removeListener('close', onClose)
      stream.destroy()
      this._next()
    }

    stream.on('readable', onReadable)
    stream.once('end', onEnd)
    stream.once('close', onClose)
  }

  _attachErrorListener (stream) {
    if (!stream) return

    const onError = (err) => {
      stream.removeListener('error', onError)
      this.destroy(err)
    }

    stream.once('error', onError)
  }
}

MultiStream.obj = streams => (
  new MultiStream(streams, { objectMode: true, highWaterMark: 16 })
)

module.exports = MultiStream

// Normalize stream destroy w/ callback.
function destroy (stream, err, cb) {
  if (!stream.destroy || stream.destroyed) {
    cb(err)
  } else {
    const callback = once(er => cb(er || err))
    stream
      .on('error', callback)
      .on('close', () => callback())
      .destroy(err, callback)
  }
}
<|endoftext|>


<commit_before>var Emitter = require('events/')
var bl      = require('bl')

module.exports = wreq

function wreq(bundler) {
  var prevError = null
  var pending = null
  var buffer = null

  update()
  bundler.on('update', update)

  return handler

  function update() {
    var p = pending = new Emitter

    bundler.bundle().pipe(bl(function(err, _buffer) {
      if (p !== pending) return
      buffer = _buffer
      pending.emit('ready', prevError = err, pending = false)
    }))
  }

  function handler(req, res, next) {
    next = next || send

    if (pending) {
      return pending.once('ready', function(err) {
        if (err) return next(err)
        return handler(req, res, next)
      })
    }

    if (prevError) return next(prevError)

    res.setHeader('content-type', 'text/javascript')

    return next(null, buffer)

    function send(err, body) {
      if (err) return res.emit(err)
      res.end(body)
    }
  }
}
<commit_msg>feat(wr): conditional header set<commit_after>var Emitter = require('events/')
var bl      = require('bl')

module.exports = wreq

function wreq(bundler) {
  var prevError = null
  var pending = null
  var buffer = null

  update()
  bundler.on('update', update)

  return handler

  function update() {
    var p = pending = new Emitter

    bundler.bundle().pipe(bl(function(err, _buffer) {
      if (p !== pending) return
      buffer = _buffer
      pending.emit('ready', prevError = err, pending = false)
    }))
  }

  function handler(req, res, next) {
    next = next || send

    if (pending) {
      return pending.once('ready', function(err) {
        if (err) return next(err)
        return handler(req, res, next)
      })
    }

    if (prevError) return next(prevError)

    if (res) res.setHeader('content-type', 'text/javascript')

    return next(null, buffer)

    function send(err, body) {
      if (err) return res.emit(err)
      res.end(body)
    }
  }
}
<|endoftext|>


<commit_before>var Path = require("path");
var Dust = require("dustjs-linkedin");
var LoaderUtils = require("loader-utils");
var Async = require("Async");
var FS = require("fs");

// Use the `paths` option to generate a template name based on the
// path of the .dust file.
//
// E.g. if paths is ["C:\MyApp\dust"] and resourcePath is
// "C:\MyApp\dust\home\widgets\welcome.dust" then the template name
// will be "home-widgets-welcome".
var uniqueNumber = 1;

function getTemplateName(paths, resourcePath) {
    // We want to loop through each path and see if it matches part of the file path.
    for (var i = 0; i < paths.length; i ++) {
        var path = paths[i];

        if (resourcePath.indexOf(path) == 0) {
            if (Path.basename(resourcePath) == "index.dust") {
                resourcePath = Path.dirname(resourcePath);
            } else {
                resourcePath = resourcePath.replace(/\.dust$/i, "");
            }

            return resourcePath
                .replace(path + Path.sep, "")
                // If the path includes slashes or spaces, replace them with hyphens.
                .replace(/[\\\/\s]+/g, "-");
        }
    }

    // XXX what to do here?
    // If it's not in a known path, does that mean it's just not a partial, and
    // therefore doesn't need a name? (E.g. we could just return "anonymous123"
    // as long as each .dust file gets a different number?)
    return "template" + (uniqueNumber++);
}

function resolveDependency(ctx, dep, paths, callback) {
    if (dep.partialName) {
        resolvePartialName(dep.partialName, paths, callback);
    } else {
        ctx.resolve(ctx.context, dep.moduleName + ".dust", callback);
    }
}

function resolvePartialNameInPath(name, path, callback) {
    console.log("Looking for", name, "in", path)

    if (name.length === 0)
        name = ["index"];

    var head = name[0],
        dustFile = Path.join(path, (head || "index") + ".dust"),
        subPath = Path.join(path, head);

    FS.exists(dustFile, function(hasDust) {
        // Found it!
        if (hasDust)
            return callback(null, dustFile);

        if (!head)
            return callback(null, false);

        FS.exists(subPath, function(folderExists) {
            // Found a matching folder! We must go deeper.
            if (folderExists) {
                return resolvePartialNameInPath(name.slice(1), subPath, callback);
            }

            // Not found. However, we might just need to try a longer path component.
            // E.g. framework-item-grading-list could be framework/item/grading-list
            // or framework-item/grading/list...
            if (name.length > 1) {
                var newName = name.slice(2);
                newName.unshift(name[0] + "-" + name[1]);
                //name = (name[0] + "-" + name[1]).concat(name.slice(2));
                return resolvePartialNameInPath(newName, path, callback);
            }

            // Not found, or possible to find.
            return callback(null, false);
        });
    });
}

function resolvePartialName(name, paths, callback) {
    if (typeof name === "string")
        return resolvePartialName(name.split(/-/), paths, callback);

    Async.eachSeries(paths, function(path, cb) {
        resolvePartialNameInPath(name, path, function(err, result) {
            if (err)
                return cb(err);

            // Found it (early return)
            if (result)
                return callback(null, result);

            // Try the next path
            return cb();
        });
    }, function(err) {
        if (err)
            return callback(err);

        // If we get here, we didn't find it.
        return callback(undefined);
    });
}

// Find {>".path/to/partial"/} references using a regular expression, and
// record where it was found (so that we can rewrite it later).
//
// This cannot possibly support interpolated template names, because the
// partial name isn't actually known until runtime.
//
// (A solution to this involving `require.context` is left as an exercise
// to the reader.)
function findDependencies(content) {
    var partials = [];
    var partialRegExp = /\{>\s*(?:([\w\d\-]+)|[^"]*"([^"]*)")/g;
    var match;

    while ((match = partialRegExp.exec(content))) {
        var partialName = match[1],
            moduleName = match[2];

        // Ignore interpolated template names, which have to use quotes
        if (moduleName && (moduleName.indexOf('{') > -1))
            continue;

        partials.push({
            partialName: partialName,
            moduleName: moduleName,
            index: match.index,
            length: match[0].length
        });
    }

    return partials;
}

// Replaces {>"./path/to/template"/} references with whatever the template's name
// should be (taking the `paths` option into account).
function rewriteDependencies(content, deps) {
    var index = 0, // Current position in the content string
        chunks = [];

    deps.forEach(function(dep) {
        chunks.push(content.substr(index, dep.index));
        chunks.push('{>' + dep.newName);
        index = dep.index + dep.length;
    });

    if (index < content.length)
        chunks.push(content.substring(index));

    return chunks.join("");
}

// Generate some require statements, so that the partials get loaded when the template
// is required.
function getDependenciesJS(deps) {
    return deps.map(function(dep) {
        return "require(" + JSON.stringify(dep.rawPath) + ")";
    }).join(";\n");
}

module.exports = function(content) {
    var query = LoaderUtils.parseQuery(this.query);

    this.cacheable && this.cacheable();

    // Resolving module references is asynchronous.
    var cb = this.async();

    // Partial paths
    var paths = [];
    if (query.path)
        paths.push(query.path);

    if (query.paths)
        paths.push.apply(paths, query.paths);

    paths.push(this.options.context);

    var deps = findDependencies(content);

    Async.eachSeries(deps, function(dep, callback) {
        resolveDependency(this, dep, paths, function(err, rawPath) {
            if (err)
                return callback(err);

            console.log("Resolved", (dep.partialName || dep.moduleName), "to", rawPath);

            dep.rawPath = rawPath;
            this.addDependency(rawPath);

            var newName = getTemplateName(paths, rawPath);
            if (dep.partialName && dep.partialName != newName)
                return callback(new Error("Partial name doesn't resolve to itself: " + dep.partialName + " -> " + newName));
            dep.newName = newName;

            return callback();
        }.bind(this));
    }.bind(this), function(err) {
        if (err)
            return cb(err);

        content = rewriteDependencies(content, deps);
        var templateName = getTemplateName(paths, this.resourcePath);

        var output = [
            // The output of the compile function requires that the variable 'dust' exists. Without a module system, 'dust'
            // would exist on the window, making it a global variable.
            "var dust = require('dustjs-linkedin');\n",

            // Any require() statements for partials.
            getDependenciesJS(deps),

            // Compile the template returning an stringified IIFE registering the template under the name in 'templateName'.
            Dust.compile(content, templateName) + "\n",

            // Return the template name to make the require statement more meaningful.
            "module.exports = " + JSON.stringify(templateName) + ";"
        ].join("");

        return cb(null, output);
    }.bind(this));

};
<commit_msg>Fix bad JavaScript being generated (missing semicolon, resulted in trying to call the result of require("partial-name"))<commit_after>var Path = require("path");
var Dust = require("dustjs-linkedin");
var LoaderUtils = require("loader-utils");
var Async = require("Async");
var FS = require("fs");

// Use the `paths` option to generate a template name based on the
// path of the .dust file.
//
// E.g. if paths is ["C:\MyApp\dust"] and resourcePath is
// "C:\MyApp\dust\home\widgets\welcome.dust" then the template name
// will be "home-widgets-welcome".
var uniqueNumber = 1;

function getTemplateName(paths, resourcePath) {
    // We want to loop through each path and see if it matches part of the file path.
    for (var i = 0; i < paths.length; i ++) {
        var path = paths[i];

        if (resourcePath.indexOf(path) == 0) {
            if (Path.basename(resourcePath) == "index.dust") {
                resourcePath = Path.dirname(resourcePath);
            } else {
                resourcePath = resourcePath.replace(/\.dust$/i, "");
            }

            return resourcePath
                .replace(path + Path.sep, "")
                // If the path includes slashes or spaces, replace them with hyphens.
                .replace(/[\\\/\s]+/g, "-");
        }
    }

    // XXX what to do here?
    // If it's not in a known path, does that mean it's just not a partial, and
    // therefore doesn't need a name? (E.g. we could just return "anonymous123"
    // as long as each .dust file gets a different number?)
    return "template" + (uniqueNumber++);
}

function resolveDependency(ctx, dep, paths, callback) {
    if (dep.partialName) {
        resolvePartialName(dep.partialName, paths, callback);
    } else {
        ctx.resolve(ctx.context, dep.moduleName + ".dust", callback);
    }
}

function resolvePartialNameInPath(name, path, callback) {
    console.log("Looking for", name, "in", path)

    if (name.length === 0)
        name = ["index"];

    var head = name[0],
        dustFile = Path.join(path, (head || "index") + ".dust"),
        subPath = Path.join(path, head);

    FS.exists(dustFile, function(hasDust) {
        // Found it!
        if (hasDust)
            return callback(null, dustFile);

        if (!head)
            return callback(null, false);

        FS.exists(subPath, function(folderExists) {
            // Found a matching folder! We must go deeper.
            if (folderExists) {
                return resolvePartialNameInPath(name.slice(1), subPath, callback);
            }

            // Not found. However, we might just need to try a longer path component.
            // E.g. framework-item-grading-list could be framework/item/grading-list
            // or framework-item/grading/list...
            if (name.length > 1) {
                var newName = name.slice(2);
                newName.unshift(name[0] + "-" + name[1]);
                //name = (name[0] + "-" + name[1]).concat(name.slice(2));
                return resolvePartialNameInPath(newName, path, callback);
            }

            // Not found, or possible to find.
            return callback(null, false);
        });
    });
}

function resolvePartialName(name, paths, callback) {
    if (typeof name === "string")
        return resolvePartialName(name.split(/-/), paths, callback);

    Async.eachSeries(paths, function(path, cb) {
        resolvePartialNameInPath(name, path, function(err, result) {
            if (err)
                return cb(err);

            // Found it (early return)
            if (result)
                return callback(null, result);

            // Try the next path
            return cb();
        });
    }, function(err) {
        if (err)
            return callback(err);

        // If we get here, we didn't find it.
        return callback(undefined);
    });
}

// Find {>".path/to/partial"/} references using a regular expression, and
// record where it was found (so that we can rewrite it later).
//
// This cannot possibly support interpolated template names, because the
// partial name isn't actually known until runtime.
//
// (A solution to this involving `require.context` is left as an exercise
// to the reader.)
function findDependencies(content) {
    var partials = [];
    var partialRegExp = /\{>\s*(?:([\w\d\-]+)|[^"]*"([^"]*)")/g;
    var match;

    while ((match = partialRegExp.exec(content))) {
        var partialName = match[1],
            moduleName = match[2];

        // Ignore interpolated template names, which have to use quotes
        if (moduleName && (moduleName.indexOf('{') > -1))
            continue;

        partials.push({
            partialName: partialName,
            moduleName: moduleName,
            index: match.index,
            length: match[0].length
        });
    }

    return partials;
}

// Replaces {>"./path/to/template"/} references with whatever the template's name
// should be (taking the `paths` option into account).
function rewriteDependencies(content, deps) {
    var index = 0, // Current position in the content string
        chunks = [];

    deps.forEach(function(dep) {
        chunks.push(content.substr(index, dep.index));
        chunks.push('{>' + dep.newName);
        index = dep.index + dep.length;
    });

    if (index < content.length)
        chunks.push(content.substring(index));

    return chunks.join("");
}

// Generate some require statements, so that the partials get loaded when the template
// is required.
function getDependenciesJS(deps) {
    return deps.map(function(dep) {
        return "require(" + JSON.stringify(dep.rawPath) + ");";
    }).join("\n");
}

module.exports = function(content) {
    var query = LoaderUtils.parseQuery(this.query);

    this.cacheable && this.cacheable();

    // Resolving module references is asynchronous.
    var cb = this.async();

    // Partial paths
    var paths = [];
    if (query.path)
        paths.push(query.path);

    if (query.paths)
        paths.push.apply(paths, query.paths);

    paths.push(this.options.context);

    var deps = findDependencies(content);

    Async.eachSeries(deps, function(dep, callback) {
        resolveDependency(this, dep, paths, function(err, rawPath) {
            if (err)
                return callback(err);

            console.log("Resolved", (dep.partialName || dep.moduleName), "to", rawPath);

            dep.rawPath = rawPath;
            this.addDependency(rawPath);

            var newName = getTemplateName(paths, rawPath);
            if (dep.partialName && dep.partialName != newName)
                return callback(new Error("Partial name doesn't resolve to itself: " + dep.partialName + " -> " + newName));
            dep.newName = newName;

            return callback();
        }.bind(this));
    }.bind(this), function(err) {
        if (err)
            return cb(err);

        content = rewriteDependencies(content, deps);
        var templateName = getTemplateName(paths, this.resourcePath);

        var output = [
            // The output of the compile function requires that the variable 'dust' exists. Without a module system, 'dust'
            // would exist on the window, making it a global variable.
            "var dust = require('dustjs-linkedin');\n",

            // Any require() statements for partials.
            getDependenciesJS(deps),

            // Compile the template returning an stringified IIFE registering the template under the name in 'templateName'.
            Dust.compile(content, templateName) + "\n",

            // Return the template name to make the require statement more meaningful.
            "module.exports = " + JSON.stringify(templateName) + ";"
        ].join("");

        return cb(null, output);
    }.bind(this));

};
<|endoftext|>


<commit_before>var http = require('http')
var uuid = require('node-uuid')
var ncp = require('ncp').ncp
var fs = require('fs')
var crypto = require('crypto')
require('shelljs/global')

const PORT = 6000
const ARM9LOADER_SOURCE_PATH = './arm9loaderhax'

var deleteFolderRecursive = function(path) {
  if( fs.existsSync(path) ) {
    fs.readdirSync(path).forEach(function(file,index){
      var curPath = path + "/" + file;
      if(fs.lstatSync(curPath).isDirectory()) { // recurse
        deleteFolderRecursive(curPath);
      } else {
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}

var getShasums = function(path, installer, otp){
  var algo = 'sha256'
  var shasum = crypto.createHash(algo)
  var installerSha = shasum.update(installer)
  shasum = crypto.createHash(algo)
  var otpSha = shasum.update(otp)
  return {installerSha: installerSha.digest('hex'), otpSha: otpSha.digest('hex')}
}

function handleRequest(req, res){
  switch(req.url){
    case '/':
      var exitWithErr = function(newPath){
        res.writeHead(500)
        res.end("something went wrong, come back later")
        if(newPath){
          deleteFolderRecursive(newPath)
        }
        return
      }

      var exitWithNotValidOtp = function(newPath){
        res.writeHead(422)
        res.end("you are trying to upload something different than 256 bytes, check your otp.bin!")
        if(newPath){
          deleteFolderRecursive(newPath)
        }
        return
      }

      if(req.method == 'POST'){
        var newUuid = uuid.v4()
        var newPath = './'+newUuid
        var totalSize = 0
        var newPathCreated = false
        try{
          ncp(ARM9LOADER_SOURCE_PATH, newPath , function (err) {
            if (err) {
              return exitWithErr(null)
            }else{
              newPathCreated = true
              var f = fs.createWriteStream(newPath + '/data_input/otp.bin')
              req.on('data', function(chunk) {
                f.write(chunk)
                totalSize += chunk.length
                if(totalSize > 256){
                  return exitWithNotValidOtp(newPath)
                }
              })

              req.on('end', function() {
                f.end()
                if(totalSize != 256){
                  return exitWithNotValidOtp(newPath)
                }
                f.on('close', function() {
                  var oldDir = process.cwd()
                  process.chdir(newPath)
                  if (exec('make', {silent:true}).code !== 0) {
                    return exitWithErr(newPath)
                  }else{
                    process.chdir(oldDir)
                    var installer = fs.readFileSync(newPath + '/data_output/arm9loaderhax.3dsx')
                    var otp = fs.readFileSync(newPath + '/data_input/otp.bin')
                    var shasums = getShasums(newPath, installer, otp)
                    res.writeHead(200, "OK", {'Content-Type': 'binary', 'Installer-Sha256': shasums.installerSha, 'OTP-Sha256': shasums.otpSha, 'Presented-by': 'felipejfc'})
                    res.end(installer)
                    deleteFolderRecursive(newPath)
                    return
                  }
                })
              })
            }
          })
        }catch(e){
          return exitWithErr(newPathCreated ? newPath : null)
        }
      } else {
        res.writeHead(405, "Method not supported", {'Content-Type': 'text/plain'})
        res.end('only post is supported.')
        return
      }
      break;
    default:
      res.writeHead(404)
      res.end('not found')
  }
}

var server = http.createServer(handleRequest)

server.listen(PORT, function(){
  console.log("Server listening on: http://localhost:%s", PORT);
});
<commit_msg>remove unnecessary comment<commit_after>var http = require('http')
var uuid = require('node-uuid')
var ncp = require('ncp').ncp
var fs = require('fs')
var crypto = require('crypto')
require('shelljs/global')

const PORT = 6000
const ARM9LOADER_SOURCE_PATH = './arm9loaderhax'

var deleteFolderRecursive = function(path) {
  if( fs.existsSync(path) ) {
    fs.readdirSync(path).forEach(function(file,index){
      var curPath = path + "/" + file;
      if(fs.lstatSync(curPath).isDirectory()) {
        deleteFolderRecursive(curPath);
      } else {
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}

var getShasums = function(path, installer, otp){
  var algo = 'sha256'
  var shasum = crypto.createHash(algo)
  var installerSha = shasum.update(installer)
  shasum = crypto.createHash(algo)
  var otpSha = shasum.update(otp)
  return {installerSha: installerSha.digest('hex'), otpSha: otpSha.digest('hex')}
}

function handleRequest(req, res){
  switch(req.url){
    case '/':
      var exitWithErr = function(newPath){
        res.writeHead(500)
        res.end("something went wrong, come back later")
        if(newPath){
          deleteFolderRecursive(newPath)
        }
        return
      }

      var exitWithNotValidOtp = function(newPath){
        res.writeHead(422)
        res.end("you are trying to upload something different than 256 bytes, check your otp.bin!")
        if(newPath){
          deleteFolderRecursive(newPath)
        }
        return
      }

      if(req.method == 'POST'){
        var newUuid = uuid.v4()
        var newPath = './'+newUuid
        var totalSize = 0
        var newPathCreated = false
        try{
          ncp(ARM9LOADER_SOURCE_PATH, newPath , function (err) {
            if (err) {
              return exitWithErr(null)
            }else{
              newPathCreated = true
              var f = fs.createWriteStream(newPath + '/data_input/otp.bin')
              req.on('data', function(chunk) {
                f.write(chunk)
                totalSize += chunk.length
                if(totalSize > 256){
                  return exitWithNotValidOtp(newPath)
                }
              })

              req.on('end', function() {
                f.end()
                if(totalSize != 256){
                  return exitWithNotValidOtp(newPath)
                }
                f.on('close', function() {
                  var oldDir = process.cwd()
                  process.chdir(newPath)
                  if (exec('make', {silent:true}).code !== 0) {
                    return exitWithErr(newPath)
                  }else{
                    process.chdir(oldDir)
                    var installer = fs.readFileSync(newPath + '/data_output/arm9loaderhax.3dsx')
                    var otp = fs.readFileSync(newPath + '/data_input/otp.bin')
                    var shasums = getShasums(newPath, installer, otp)
                    res.writeHead(200, "OK", {'Content-Type': 'binary', 'Installer-Sha256': shasums.installerSha, 'OTP-Sha256': shasums.otpSha, 'Presented-by': 'felipejfc'})
                    res.end(installer)
                    deleteFolderRecursive(newPath)
                    return
                  }
                })
              })
            }
          })
        }catch(e){
          return exitWithErr(newPathCreated ? newPath : null)
        }
      } else {
        res.writeHead(405, "Method not supported", {'Content-Type': 'text/plain'})
        res.end('only post is supported.')
        return
      }
      break;
    default:
      res.writeHead(404)
      res.end('not found')
  }
}

var server = http.createServer(handleRequest)

server.listen(PORT, function(){
  console.log("Server listening on: http://localhost:%s", PORT);
});
<|endoftext|>


<commit_before>module.exports = function (tasks, limit, cb) {
  if (typeof limit !== 'number') throw new Error('second argument must be a Number')
  var results, len, pending, keys, isErrored
  var isSync = true

  if (Array.isArray(tasks)) {
    results = []
    pending = len = tasks.length
  } else {
    keys = Object.keys(tasks)
    results = {}
    pending = len = keys.length
  }

  function done (err) {
    function end () {
      if (cb) cb(err, results)
      cb = null
    }
    if (isSync) process.nextTick(end)
    else end()
  }

  function each (i, err, result) {
    results[i] = result
    if (err) isErrored = true
    if (--pending === 0 || err) {
      done(err)
    } else if (!isErrored && next < len) {
      var key
      if (keys) {
        key = keys[next]
        next += 1
        tasks[key](function (err, result) { each(key, err, result) })
      } else {
        key = next
        next += 1
        tasks[key](function (err, result) { each(key, err, result) })
      }
    }
  }

  var next = limit
  if (!pending) {
    // empty
    done(null)
  } else if (keys) {
    // object
    keys.some(function (key, i) {
      tasks[key](function (err, result) { each(key, err, result) })
      if (i === limit - 1) return true // early return
    })
  } else {
    // array
    tasks.some(function (task, i) {
      task(function (err, result) { each(i, err, result) })
      if (i === limit - 1) return true // early return
    })
  }

  isSync = false
}
<commit_msg>name function<commit_after>module.exports = runParallelLimit

function runParallelLimit (tasks, limit, cb) {
  if (typeof limit !== 'number') throw new Error('second argument must be a Number')
  var results, len, pending, keys, isErrored
  var isSync = true

  if (Array.isArray(tasks)) {
    results = []
    pending = len = tasks.length
  } else {
    keys = Object.keys(tasks)
    results = {}
    pending = len = keys.length
  }

  function done (err) {
    function end () {
      if (cb) cb(err, results)
      cb = null
    }
    if (isSync) process.nextTick(end)
    else end()
  }

  function each (i, err, result) {
    results[i] = result
    if (err) isErrored = true
    if (--pending === 0 || err) {
      done(err)
    } else if (!isErrored && next < len) {
      var key
      if (keys) {
        key = keys[next]
        next += 1
        tasks[key](function (err, result) { each(key, err, result) })
      } else {
        key = next
        next += 1
        tasks[key](function (err, result) { each(key, err, result) })
      }
    }
  }

  var next = limit
  if (!pending) {
    // empty
    done(null)
  } else if (keys) {
    // object
    keys.some(function (key, i) {
      tasks[key](function (err, result) { each(key, err, result) })
      if (i === limit - 1) return true // early return
    })
  } else {
    // array
    tasks.some(function (task, i) {
      task(function (err, result) { each(i, err, result) })
      if (i === limit - 1) return true // early return
    })
  }

  isSync = false
}
<|endoftext|>


<commit_before>'use strict';

const raml2obj = require('raml2obj');
const pjson = require('./package.json');

/**
 * Render the source RAML object using the config's processOutput function
 *
 * The config object should contain at least the following property:
 * processRamlObj: function that takes the raw RAML object and returns a promise with the rendered HTML
 *
 * @param {(String|Object)} source - The source RAML file. Can be a filename, url, contents of the RAML file,
 * or an already-parsed RAML object.
 * @param {Object} config
 * @param {Function} config.processRamlObj
 * @returns a promise
 */
function render(source, config) {
  config = config || {};
  config.raml2HtmlVersion = pjson.version;

  return raml2obj.parse(source).then((ramlObj) => {
    ramlObj.config = config;

    if (config.processRamlObj) {
      return config.processRamlObj(ramlObj).then((html) => {
        if (config.postProcessHtml) {
          return config.postProcessHtml(html);
        }
        return html;
      });
    }

    return ramlObj;
  });
}

/**
 * @param {String} [mainTemplate] - The filename of the main template, leave empty to use default templates
 * @param {String} [templatesPath] - Optional, by default it uses the current working directory
 * @returns {{processRamlObj: Function, postProcessHtml: Function}}
 */
function getDefaultConfig(mainTemplate, templatesPath) {
  if (!mainTemplate) {
    mainTemplate = './lib/template.nunjucks';

    // When using the default template, make sure that Nunjucks isn't
    // using the working directory since that might be anything
    templatesPath = __dirname;
  }

  return {
    processRamlObj(ramlObj) {
      const nunjucks = require('nunjucks');
      const markdown = require('nunjucks-markdown');
      const marked = require('marked');
      const ramljsonexpander = require('raml-jsonschema-expander');
      const renderer = new marked.Renderer();
      renderer.table = function (thead, tbody) {
        // Render Bootstrap style tables
        return `<table class="table"><thead>${thead}</thead><tbody>${tbody}</tbody></table>`;
      };

      // Setup the Nunjucks environment with the markdown parser
      const env = nunjucks.configure(templatesPath, { autoescape: false });
      markdown.register(env, (md) => marked(md, { renderer }));

      // Parse securedBy and use scopes if they are defined
      ramlObj.renderSecuredBy = function (securedBy) {
        let out = '';
        if (typeof securedBy === 'object') {
          Object.keys(securedBy).forEach((key) => {
            out += `<b>${key}</b>`;

            if (securedBy[key].scopes.length) {
              out += ' with scopes:
';

              securedBy[key].scopes.forEach((scope) => {
                out += `<li>${scope}</li>`;
              });

              out += '
';
            }
          });
        } else {
          out = `<b>${securedBy}</b>`;
        }
        return out;
      };

      // Find and replace the $ref parameters.
      ramlObj = ramljsonexpander.expandJsonSchemas(ramlObj);

      // Render the main template using the raml object and fix the double quotes
      let html = env.render(mainTemplate, ramlObj);
      html = html.replace(/"/g, '"');

      // Return the promise with the html
      return new Promise((resolve) => {
        resolve(html);
      });
    },

    postProcessHtml(html) {
      // Minimize the generated html and return the promise with the result
      const Minimize = require('minimize');
      const minimize = new Minimize({ quotes: true });

      return new Promise((resolve, reject) => {
        minimize.parse(html, (error, result) => {
          if (error) {
            reject(new Error(error));
          } else {
            resolve(result);
          }
        });
      });
    },
  };
}

module.exports = {
  getDefaultConfig,
  render,
};

if (require.main === module) {
  console.log('This script is meant to be used as a library. You probably want to run bin/raml2html if you\'re looking for a CLI.');
  process.exit(1);
}
<commit_msg>allow nunjucks configuration<commit_after>'use strict';

const raml2obj = require('raml2obj');
const pjson = require('./package.json');

/**
 * Render the source RAML object using the config's processOutput function
 *
 * The config object should contain at least the following property:
 * processRamlObj: function that takes the raw RAML object and returns a promise with the rendered HTML
 *
 * @param {(String|Object)} source - The source RAML file. Can be a filename, url, contents of the RAML file,
 * or an already-parsed RAML object.
 * @param {Object} config
 * @param {Function} config.processRamlObj
 * @returns a promise
 */
function render(source, config) {
  config = config || {};
  config.raml2HtmlVersion = pjson.version;

  return raml2obj.parse(source).then((ramlObj) => {
    ramlObj.config = config;

    if (config.processRamlObj) {
      return config.processRamlObj(ramlObj, config).then((html) => {
        if (config.postProcessHtml) {
          return config.postProcessHtml(html);
        }
        return html;
      });
    }

    return ramlObj;
  });
}

/**
 * @param {String} [mainTemplate] - The filename of the main template, leave empty to use default templates
 * @param {String} [templatesPath] - Optional, by default it uses the current working directory
 * @returns {{processRamlObj: Function, postProcessHtml: Function}}
 */
function getDefaultConfig(mainTemplate, templatesPath) {
  if (!mainTemplate) {
    mainTemplate = './lib/template.nunjucks';

    // When using the default template, make sure that Nunjucks isn't
    // using the working directory since that might be anything
    templatesPath = __dirname;
  }

  return {
    processRamlObj(ramlObj) {
      const nunjucks = require('nunjucks');
      const markdown = require('nunjucks-markdown');
      const marked = require('marked');
      const ramljsonexpander = require('raml-jsonschema-expander');
      const renderer = new marked.Renderer();

      renderer.table = function (thead, tbody) {
        // Render Bootstrap style tables
        return `<table class="table"><thead>${thead}</thead><tbody>${tbody}</tbody></table>`;
      };

      // Setup the Nunjucks environment with the markdown parser
      const env = nunjucks.configure(templatesPath, { autoescape: false });

      if(config.setupNunjucks)
        config.setupNunjucks(env);

      markdown.register(env, (md) => marked(md, { renderer }));

      // Parse securedBy and use scopes if they are defined
      ramlObj.renderSecuredBy = function (securedBy) {
        let out = '';
        if (typeof securedBy === 'object') {
          Object.keys(securedBy).forEach((key) => {
            out += `<b>${key}</b>`;

            if (securedBy[key].scopes.length) {
              out += ' with scopes:
';

              securedBy[key].scopes.forEach((scope) => {
                out += `<li>${scope}</li>`;
              });

              out += '
';
            }
          });
        } else {
          out = `<b>${securedBy}</b>`;
        }
        return out;
      };

      // Find and replace the $ref parameters.
      ramlObj = ramljsonexpander.expandJsonSchemas(ramlObj);

      // Render the main template using the raml object and fix the double quotes
      let html = env.render(mainTemplate, ramlObj);
      html = html.replace(/"/g, '"');

      // Return the promise with the html
      return new Promise((resolve) => {
        resolve(html);
      });
    },

    postProcessHtml(html) {
      // Minimize the generated html and return the promise with the result
      const Minimize = require('minimize');
      const minimize = new Minimize({ quotes: true });

      return new Promise((resolve, reject) => {
        minimize.parse(html, (error, result) => {
          if (error) {
            reject(new Error(error));
          } else {
            resolve(result);
          }
        });
      });
    },
  };
}

module.exports = {
  getDefaultConfig,
  render,
};

if (require.main === module) {
  console.log('This script is meant to be used as a library. You probably want to run bin/raml2html if you\'re looking for a CLI.');
  process.exit(1);
}
<|endoftext|>


<commit_before>function Code(data) {
  this.manual = data.manual;
};

Code.prototype.run = function(req, res, next) {
  res.send('Hi! I\'m taskmill-code-dummy, the dummy task runner');
};

module.exports = Code;<commit_msg>expose sent data<commit_after>function Code(data) {
  this.data = data;
};

Code.prototype.run = function(req, res, next) {
  res.send({
      message : 'Hi! I\'m taskmill-code-dummy, the dummy task runner.'
    , data    : this.data
  });
};

module.exports = Code;<|endoftext|>


<commit_before>'use strict';

var through2 = require('through2');
var Combine = require('ordered-read-streams');
var unique = require('unique-stream');

var glob = require('glob');
var micromatch = require('micromatch');
var resolveGlob = require('to-absolute-glob');
var globParent = require('glob-parent');
var extend = require('extend');

var gs = {
  // Creates a stream for a single glob or filter
  createStream: function(ourGlob, negatives, opt) {

    // Remove path relativity to make globs make sense
    ourGlob = resolveGlob(ourGlob, opt);
    var ourOpt = extend({}, opt);
    delete ourOpt.root;

    // Create globbing stuff
    var globber = new glob.Glob(ourGlob, ourOpt);

    // Extract base path from glob
    var basePath = opt.base || globParent(ourGlob) + '/';

    // Create stream and map events from globber to it
    var stream = through2.obj(opt,
      negatives.length ? filterNegatives : undefined);

    var found = false;

    globber.on('error', stream.emit.bind(stream, 'error'));
    globber.once('end', function() {
      if (opt.allowEmpty !== true && !found && globIsSingular(globber)) {
        stream.emit('error',
          new Error('File not found with singular glob: ' + ourGlob));
      }

      stream.end();
    });
    globber.on('match', function(filename) {
      found = true;

      stream.write({
        cwd: opt.cwd,
        base: basePath,
        path: filename,
      });
    });

    return stream;

    function filterNegatives(filename, enc, cb) {
      var matcha = isMatch.bind(null, filename);
      if (negatives.every(matcha)) {
        cb(null, filename); // Pass
      } else {
        cb(); // Ignore
      }
    }
  },

  // Creates a stream for multiple globs or filters
  create: function(globs, opt) {
    if (!opt) {
      opt = {};
    }
    if (typeof opt.cwd !== 'string') {
      opt.cwd = process.cwd();
    }
    if (typeof opt.dot !== 'boolean') {
      opt.dot = false;
    }
    if (typeof opt.silent !== 'boolean') {
      opt.silent = true;
    }
    if (typeof opt.nonull !== 'boolean') {
      opt.nonull = false;
    }
    if (typeof opt.cwdbase !== 'boolean') {
      opt.cwdbase = false;
    }
    if (opt.cwdbase) {
      opt.base = opt.cwd;
    }

    // Only one glob no need to aggregate
    if (!Array.isArray(globs)) {
      globs = [globs];
    }

    var positives = [];
    var negatives = [];

    var ourOpt = extend({}, opt);
    delete ourOpt.root;

    globs.forEach(function(glob, index) {
      if (typeof glob !== 'string' && !(glob instanceof RegExp)) {
        throw new Error('Invalid glob at index ' + index);
      }

      var globArray = isNegative(glob) ? negatives : positives;

      // Create Minimatch instances for negative glob patterns
      if (globArray === negatives && typeof glob === 'string') {
        var ourGlob = resolveGlob(glob, opt);
        glob = micromatch.matcher(ourGlob, ourOpt);
      }

      globArray.push({
        index: index,
        glob: glob,
      });
    });

    if (positives.length === 0) {
      throw new Error('Missing positive glob');
    }

    // Only one positive glob no need to aggregate
    if (positives.length === 1) {
      return streamFromPositive(positives[0]);
    }

    // Create all individual streams
    var streams = positives.map(streamFromPositive);

    // Then just pipe them to a single unique stream and return it
    var aggregate = new Combine(streams);
    var uniqueStream = unique('path');
    var returnStream = aggregate.pipe(uniqueStream);

    aggregate.on('error', function(err) {
      returnStream.emit('error', err);
    });

    return returnStream;

    function streamFromPositive(positive) {
      var negativeGlobs = negatives.filter(indexGreaterThan(positive.index))
        .map(toGlob);
      return gs.createStream(positive.glob, negativeGlobs, opt);
    }
  },
};

function isMatch(file, matcher) {
  if (typeof matcher === 'function') {
    return matcher(file.path);
  }
  if (matcher instanceof RegExp) {
    return matcher.test(file.path);
  }
}

function isNegative(pattern) {
  if (typeof pattern === 'string') {
    return pattern[0] === '!';
  }
  if (pattern instanceof RegExp) {
    return true;
  }
}

function indexGreaterThan(index) {
  return function(obj) {
    return obj.index > index;
  };
}

function toGlob(obj) {
  return obj.glob;
}

function globIsSingular(glob) {
  var globSet = glob.minimatch.set;

  if (globSet.length !== 1) {
    return false;
  }

  return globSet[0].every(function isString(value) {
    return typeof value === 'string';
  });
}

module.exports = gs;
<commit_msg>Fix: Use path.sep instead of '/' for correct Windows pathing<commit_after>'use strict';

var through2 = require('through2');
var Combine = require('ordered-read-streams');
var unique = require('unique-stream');

var glob = require('glob');
var micromatch = require('micromatch');
var resolveGlob = require('to-absolute-glob');
var globParent = require('glob-parent');
var path = require('path');
var extend = require('extend');

var gs = {
  // Creates a stream for a single glob or filter
  createStream: function(ourGlob, negatives, opt) {

    // Remove path relativity to make globs make sense
    ourGlob = resolveGlob(ourGlob, opt);
    var ourOpt = extend({}, opt);
    delete ourOpt.root;

    // Create globbing stuff
    var globber = new glob.Glob(ourGlob, ourOpt);

    // Extract base path from glob
    var basePath = opt.base || globParent(ourGlob) + path.sep;

    // Create stream and map events from globber to it
    var stream = through2.obj(opt,
      negatives.length ? filterNegatives : undefined);

    var found = false;

    globber.on('error', stream.emit.bind(stream, 'error'));
    globber.once('end', function() {
      if (opt.allowEmpty !== true && !found && globIsSingular(globber)) {
        stream.emit('error',
          new Error('File not found with singular glob: ' + ourGlob));
      }

      stream.end();
    });
    globber.on('match', function(filename) {
      found = true;

      stream.write({
        cwd: opt.cwd,
        base: basePath,
        path: filename,
      });
    });

    return stream;

    function filterNegatives(filename, enc, cb) {
      var matcha = isMatch.bind(null, filename);
      if (negatives.every(matcha)) {
        cb(null, filename); // Pass
      } else {
        cb(); // Ignore
      }
    }
  },

  // Creates a stream for multiple globs or filters
  create: function(globs, opt) {
    if (!opt) {
      opt = {};
    }
    if (typeof opt.cwd !== 'string') {
      opt.cwd = process.cwd();
    }
    if (typeof opt.dot !== 'boolean') {
      opt.dot = false;
    }
    if (typeof opt.silent !== 'boolean') {
      opt.silent = true;
    }
    if (typeof opt.nonull !== 'boolean') {
      opt.nonull = false;
    }
    if (typeof opt.cwdbase !== 'boolean') {
      opt.cwdbase = false;
    }
    if (opt.cwdbase) {
      opt.base = opt.cwd;
    }

    // Only one glob no need to aggregate
    if (!Array.isArray(globs)) {
      globs = [globs];
    }

    var positives = [];
    var negatives = [];

    var ourOpt = extend({}, opt);
    delete ourOpt.root;

    globs.forEach(function(glob, index) {
      if (typeof glob !== 'string' && !(glob instanceof RegExp)) {
        throw new Error('Invalid glob at index ' + index);
      }

      var globArray = isNegative(glob) ? negatives : positives;

      // Create Minimatch instances for negative glob patterns
      if (globArray === negatives && typeof glob === 'string') {
        var ourGlob = resolveGlob(glob, opt);
        glob = micromatch.matcher(ourGlob, ourOpt);
      }

      globArray.push({
        index: index,
        glob: glob,
      });
    });

    if (positives.length === 0) {
      throw new Error('Missing positive glob');
    }

    // Only one positive glob no need to aggregate
    if (positives.length === 1) {
      return streamFromPositive(positives[0]);
    }

    // Create all individual streams
    var streams = positives.map(streamFromPositive);

    // Then just pipe them to a single unique stream and return it
    var aggregate = new Combine(streams);
    var uniqueStream = unique('path');
    var returnStream = aggregate.pipe(uniqueStream);

    aggregate.on('error', function(err) {
      returnStream.emit('error', err);
    });

    return returnStream;

    function streamFromPositive(positive) {
      var negativeGlobs = negatives.filter(indexGreaterThan(positive.index))
        .map(toGlob);
      return gs.createStream(positive.glob, negativeGlobs, opt);
    }
  },
};

function isMatch(file, matcher) {
  if (typeof matcher === 'function') {
    return matcher(file.path);
  }
  if (matcher instanceof RegExp) {
    return matcher.test(file.path);
  }
}

function isNegative(pattern) {
  if (typeof pattern === 'string') {
    return pattern[0] === '!';
  }
  if (pattern instanceof RegExp) {
    return true;
  }
}

function indexGreaterThan(index) {
  return function(obj) {
    return obj.index > index;
  };
}

function toGlob(obj) {
  return obj.glob;
}

function globIsSingular(glob) {
  var globSet = glob.minimatch.set;

  if (globSet.length !== 1) {
    return false;
  }

  return globSet[0].every(function isString(value) {
    return typeof value === 'string';
  });
}

module.exports = gs;
<|endoftext|>


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

module.exports = {
  name: 'ember-cli-airbrake',
  included: function(app) {
    app.import("vendor/airbrake-shim.js");
  }
};
<commit_msg>only include airbrake if configured<commit_after>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-cli-airbrake',
  included: function(app) {
    var config = this.project.config(this.app.env);

    if (config.airbrake) {
      app.import("vendor/airbrake-shim.js");
    }
  }
};
<|endoftext|>


<commit_before>var fs = require('fs');
var through2 = require('through2');
var gutil = require('gulp-util');
var Styleguide = require('stylegen').Styleguide;
var chalk = require('chalk');
var error = chalk.bold.red;
var success = chalk.bold.green;

module.exports = function(opts) {
  'use strict';

  opts = opts || {};
  var initializationError = new gutil.PluginError('gulp-stylegen', "No Config-File given, please provide a valid stylguide.(yaml|json) file");
  var initializationErrorFlag = true;

  return through2.obj(function(file, enc, callback) {
    initializationErrorFlag = false;

    if (file.isNull()) {
      return callback(null, file);
    }

    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-stylegen', 'Streaming not supported'));
      return callback();
    }

    opts.configPath = file.path;

    var cwd = opts.cwd || path.basename(file.path);
    console.log(success("initialize styleguide ..."));
    new Styleguide(opts)
    .initialize(cwd)
    .then(function(styleguide) {
      console.log(success("preparing styleguide ..."));
      return styleguide.prepare();
    })
    .then(function(styleguide) {
      console.log(success("reading styleguide ..."));
      return styleguide.read();
    })
    .then(function(styleguide) {
      console.log(success("writing styleguide ..."));
      return styleguide.write();
    })
    .then(function() {
      console.log(success("styleguide written"));
      return callback();
    })
    .catch(function(e) {
      throw new gutil.PluginError('gulp-stylegen', e);
      return callback();
    });

  }, function (cb) {
		if (initializationErrorFlag) {
      console.log(error(initializationError));
    }
		cb();
	});
}
<commit_msg>fixed misplaced plugin-error, which breaks plumber rescue behaviour<commit_after>var fs = require('fs');
var through2 = require('through2');
var gutil = require('gulp-util');
var Styleguide = require('stylegen').Styleguide;
var chalk = require('chalk');
var error = chalk.bold.red;
var success = chalk.bold.green;

module.exports = function(opts) {
  'use strict';

  opts = opts || {};
  var initializationErrorFlag = true;

  return through2.obj(function(file, enc, callback) {
    initializationErrorFlag = false;

    if (file.isNull()) {
      return callback(null, file);
    }

    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-stylegen', 'Streaming not supported'));
      return callback();
    }

    opts.configPath = file.path;

    var cwd = opts.cwd || path.basename(file.path);
    console.log(success("initialize styleguide ..."));

    new Styleguide(opts)
    .initialize(cwd)
    .then(function(styleguide) {
      console.log(success("preparing styleguide ..."));
      return styleguide.prepare();
    })
    .then(function(styleguide) {
      console.log(success("reading styleguide ..."));
      return styleguide.read();
    })
    .then(function(styleguide) {
      console.log(success("writing styleguide ..."));
      return styleguide.write();
    })
    .then(function() {
      console.log(success("styleguide written"));
      return callback();
    })
    .catch(function(e) {
      return callback();
    });

  }, function (cb) {
		if (initializationErrorFlag) {
  		return cb(new gutil.PluginError('gulp-stylegen', "No Config-File given, please provide a valid stylguide.(yaml|json) file"));
    }
    return cb();
	});
}
<|endoftext|>


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

var fs = require("fs");
var spawn = require('child_process').spawn;
var readline = require('readline');

function execute(){
  var commands = Array.prototype.slice.call(arguments);
  var cb = commands.pop();

  if (commands.length === 0) {
    return cb();
  }

  var args = commands.shift();
  var command = args.shift();
  var cmd = spawn(command, args);

  cmd.stdout.pipe(process.stdout);
  cmd.stderr.pipe(process.stderr);
  cmd.on("exit", function(code){
    if (code !== 0) {
      return cb(new Error("Failed to execute " + command + " " + args.join(" ")));
    }
    commands.push(cb);
    execute.apply(null, commands);
  });
}

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

var packageJSON = JSON.parse(fs.readFileSync("./package.json").toString());
console.log("Current version is", packageJSON.version);

rl.question("New version> ", function(version) {
  version = version.trim();
  packageJSON.version = version;
  fs.writeFileSync("./package.json", JSON.stringify(packageJSON, null, "  "));

  execute(
    [ "npm", "publish" ],
    [ "git", "commit", "package.json", "-m", "Release " + version ],
    [ "git", "tag", "-a", version, "-m", "Release " + version ],
    [ "git", "push", "--tags", "origin"],
    [ "git", "push", "origin", "master"],
    function(err){
      if (err) throw err;
      rl.close();
      console.log("DONE");
    }
  );

});
<commit_msg>Use previous version if empty<commit_after>#!/usr/bin/env node

var fs = require("fs");
var spawn = require('child_process').spawn;
var readline = require('readline');

function execute(){
  var commands = Array.prototype.slice.call(arguments);
  var cb = commands.pop();

  if (commands.length === 0) {
    return cb();
  }

  var args = commands.shift();
  var command = args.shift();
  var cmd = spawn(command, args);

  cmd.stdout.pipe(process.stdout);
  cmd.stderr.pipe(process.stderr);
  cmd.on("exit", function(code){
    if (code !== 0) {
      return cb(new Error("Failed to execute " + command + " " + args.join(" ")));
    }
    commands.push(cb);
    execute.apply(null, commands);
  });
}

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

var packageJSON = JSON.parse(fs.readFileSync("./package.json").toString());
console.log("Current version is", packageJSON.version);

rl.question("New version> ", function(version) {
  packageJSON.version = version.trim() || packageJSON.version;
  fs.writeFileSync("./package.json", JSON.stringify(packageJSON, null, "  "));

  execute(
    [ "npm", "publish" ],
    [ "git", "commit", "package.json", "-m", "Release " + version ],
    [ "git", "tag", "-a", version, "-m", "Release " + version ],
    [ "git", "push", "--tags", "origin"],
    [ "git", "push", "origin", "master"],
    function(err){
      if (err) throw err;
      rl.close();
      console.log("DONE");
    }
  );

});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Srijan R Shetty <srijan.shetty+code@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/* Check for the course */
var course = '';
if (process.argv[2]) {
    course = process.argv[2].toLowerCase();
    console.log('Downloading course content for ' + course);
} else {
    console.log('Course Number not providing, exiting');
    process.exit(1);
}

var request = require('request'),
    $       = require('cheerio');

function parse(err, resp, html) {
    if (err) {
        console.log('Error');
    }

    var zipURLS = [];
    var parsedHTML = $.load(html);
    parsedHTML('a').map(function(i, link) {
        var href = $(link).attr('href');
        if(href.match('.zip')) {
            zipURLS.push(href);
        }
    });

    zipURLS.map(function(value, index) {
        console.log(value);
    });
}

var domain = 'https://www.udacity.com/wiki/' + course + '/downloads';
request(domain, parse);
<commit_msg>Minor cleanup<commit_after>/*
 * Copyright (c) 2014 Srijan R Shetty <srijan.shetty+code@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/* Check for the course */
var course = '';
if (process.argv[2]) {
    course = process.argv[2].toLowerCase();
    console.log('Downloading course content for ' + course);
} else {
    console.log('Course Number not providing, exiting');
    process.exit(1);
}

var request = require('request'),
    $       = require('cheerio');

function parse(err, resp, html) {
    if (err) {
        console.log(err);
    }

    var zipURLS = [];
    var parsedHTML = $.load(html);
    parsedHTML('a').map(function(i, link) {
        var href = $(link).attr('href');
        if(href.match('.zip')) {
            zipURLS.push(href);
        }
    });

    zipURLS.map(function(value) {
        console.log(value);
    });
}

var domain = 'https://www.udacity.com/wiki/' + course + '/downloads';
request(domain, parse);
<|endoftext|>


<commit_before>const ansi = {
	black: ["\x1b[30m", "\x1b[39m"],
	red: ["\x1b[31m", "\x1b[39m"],
	green: ["\x1b[32m", "\x1b[39m"],
	yellow: ["\x1b[33m", "\x1b[39m"],
	blue: ["\x1b[34m", "\x1b[39m"],
	magenta: ["\x1b[35m", "\x1b[39m"],
	cyan: ["\x1b[36m", "\x1b[39m"],
	white: ["\x1b[37m", "\x1b[39m"],
	gray: ["\x1B[90m", "\x1b[39m"],

	bgBlack: ["\x1b[40m", "\x1b[49m"],
	bgRed: ["\x1b[41m", "\x1b[49m"],
	bgGreen: ["\x1b[42m", "\x1b[49m"],
	bgYellow: ["\x1b[43m", "\x1b[49m"],
	bgBlue: ["\x1b[44m", "\x1b[49m"],
	bgMagenta: ["\x1b[45m", "\x1b[49m"],
	bgCyan: ["\x1b[46m", "\x1b[49m"],
	bgWhite: ["\x1b[47m", "\x1b[49m"],

	dim: ["\x1b[2m", "\x1b[22m"],
	bold: ["\x1b[1m", "\x1b[22m"],
	hidden: ["\x1b[8m", "\x1b[28m"],
	italic: ["\x1b[3m", "\x1b[23m"],
	underline: ["\x1b[4m", "\x1b[24m"],
	inverse: ["\x1b[7m", "\x1b[27m"],
	strikethrough: ["\x1b[9m", "\x1b[29m"],

	newLine: ["\n", ""],
	tab: ["\t", ""],
	reset: ["\x1b[0m"]
}

module.exports = (function clor(carry, close) {
	const wrap = s => clor(wrap.toString(s))

	wrap.toString = s => carry + (s || "") + (close || ansi.reset[0])

	Object.keys(ansi).forEach(style =>
		Object.defineProperty(wrap, style, {
			get: _ => clor(carry + ansi[style][0], ansi[style][1])
		})
	)

	return wrap
} (""))
<commit_msg>Simplify even more!<commit_after>const ansi = require("./ansi")

module.exports = (function Clor(prev, wrap = ansi.reset[0]) {
	const clor = s => Clor(clor.toString(s))

	clor.toString = (s = "") => prev + s + wrap

	Object.keys(ansi).forEach(k => Object.defineProperty(clor, k, {
		get: _ => Clor(prev + ansi[k][0], ansi[k][1])
	}))

	return clor
} (""))

<|endoftext|>