from https://github.com/mrdoob/three.js/blob/86424d9b318f617254eb857b31be07502ea27ce9/rollup.config.js
777187
function glsl () {
  return {
    transform(glsl, id) {
      if (/\.glsl$/.test(id) === false) return
			// remove comments and fix new line chars
      var shaderAsText = glsl
        .replace(/[ \t]*\/\/.*\n/g, '') // remove //
        .replace(/[ \t]*\/\*[\s\S]*?\*\//g, '') // remove /* */
        .replace(/\n{2,}/g, '\n') // # \n+ to \n
      //
      var shaderAsBase64 = 'data:text/plain;base64,' + new Buffer(shaderAsText).toString('base64')
			//
      var moduleApi = { text: shaderAsText, base64: shaderAsBase64 }
      // add module wrapper
			var code = 'export default ' + JSON.stringify(moduleApi) + ';'
      return {
        code: code,
        map: {mappings: ''}
      }
    }
  }
}
520764
function mergeScaleConfig(/* config objects ... */) {
	return helpers$1.merge({}, [].slice.call(arguments), {
		merger: function(key, target, source, options) {
			if (key === 'xAxes' || key === 'yAxes') {
				var slen = source[key].length;
				var i, type, scale;

				if (!target[key]) {
					target[key] = [];
				}

				for (i = 0; i < slen; ++i) {
					scale = source[key][i];
					type = valueOrDefault$8(scale.type, key === 'xAxes' ? 'category' : 'linear');

					if (i >= target[key].length) {
						target[key].push({});
					}

					if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
						// new/untyped scale or type changed: let's apply the new defaults
						// then merge source scale to correctly overwrite the defaults.
						helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
					} else {
						// scales type are the same
						helpers$1.merge(target[key][i], scale);
					}
				}
			} else {
				helpers$1._merger(key, target, source, options);
			}
		}
	});
}
92953
function uploadNewBackup(s3, backupTmpFilePath, bucket, key) {
  return new Promise((resolve, reject) => {
    debug(`Uploading from ${backupTmpFilePath} to ${bucket}/${key}`);

    function uploadFromStream(s3, bucket, key) {
      const pass = new stream.PassThrough();

      const params = {
        Bucket: bucket,
        Key: key,
        Body: pass
      };
      s3.upload(params, function(err, data) {
        debug('S3 upload done');
        if (err) {
          debug(err);
          reject(new VError(err, 'Upload failed'));
          return;
        }
        debug('Upload succeeded');
        debug(data);
        resolve();
      }).httpUploadProgress = (progress) => {
        debug(`S3 upload progress: ${progress}`);
      };

      return pass;
    }

    const inputStream = fs.createReadStream(backupTmpFilePath);
    const s3Stream = uploadFromStream(s3, bucket, key);
    inputStream.pipe(s3Stream);
  });
}
1214106
function watchAngularBindings(done) {
  rollupWatch(rollupConfigs.angularOns).on('event', event => {
    switch (event.code) {
      case 'BUNDLE_START':
        $.util.log(`Bundling 'angularjs' ...`);
        break;
      case 'BUNDLE_END':
        copyAngularBindings();
        $.util.log(`Finished 'angularjs' bundle`);
        break;
      case 'ERROR':
        throw new Error('Encountered an error while bundling\n\n', event.error);
      case 'FATAL':
        $.util.log($.util.colors.red('Encountered an unrecoverable error\n\n', event.error));
        process.exit(1);
        break;
    }
  });
  done();
}
578224
function previewJs() {
  return rollup({
    input: 'previewer-src/app.js',
    plugins: [
      commonjs,
      babel(babelrc)
    ]
  })
  .then(bundle => {
    return bundle.write({
      file: 'build/app.gen.js',
      format: 'umd',
      sourcemap: 'inline'
    });
  });
}
866139
function glitch ( params ) {
	params = sanitizeInput( params );

	let inputFn;
	let outputFn;

	const worker = new Worker( URL.createObjectURL(new Blob(["function isImageData ( imageData ) {\n\treturn (\n\t\timageData && \n\t\ttypeof imageData.width === 'number' &&\n\t\ttypeof imageData.height === 'number' &&\n\t\timageData.data &&\n\t\ttypeof imageData.data.length === 'number' &&\n\t\ttypeof imageData.data === 'object'\n\t);\n}\n\nconst base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst base64Map = base64Chars.split( '' );\nconst reversedBase64Map = { };\n\nbase64Map.forEach( ( val, key ) => { reversedBase64Map[val] = key; } );\n\nvar maps = {\n\tbase64Map,\n\treversedBase64Map\n};\n\nconst reversedBase64Map$1 = maps.reversedBase64Map;\n\n// https://github.com/mutaphysis/smackmyglitchupjs/blob/master/glitch.html\n// base64 is 2^6, byte is 2^8, every 4 base64 values create three bytes\nfunction base64ToByteArray ( base64URL ) {\t\n\tconst result = [ ];\n\tlet prev;\n\n\tconst srcURL = base64URL.replace( 'data:image/jpeg;base64,', '' );\n\n\tfor ( var i = 0, len = srcURL.length; i < len; i++ ) {\n\t\tconst char = srcURL[ i ];\n\t\tconst currentChar = reversedBase64Map$1[ srcURL[ i ] ];\n\t\tconst digitNum = i % 4;\n\n\t\tswitch ( digitNum ) {\n\t\t\t// case 0: first digit - do nothing, not enough info to work with\n\t\t\tcase 1: // second digit\n\t\t\t\tresult.push( prev << 2 | currentChar >> 4 );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 2: // third digit\n\t\t\t\tresult.push( ( prev & 0x0f ) << 4 | currentChar >> 2 );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 3: // fourth digit\n\t\t\t\tresult.push( ( prev & 3 ) << 6 | currentChar );\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprev = currentChar;\n\t}\n\n\treturn result;\n}\n\n// http://stackoverflow.com/a/10424014/229189\n\nfunction jpgHeaderLength ( byteArr ) {\n\tlet result = 417;\n\n\t// https://en.wikipedia.org/wiki/JPEG#Syntax_and_structure\n\t// looks for the first occurence of 0xFF, 0xDA in the byteArray\n\t// which is the start of scan\n\tfor ( let i = 0, len = byteArr.length; i < len; i++ ) {\n\t\tif ( byteArr[i] === 0xFF && byteArr[i + 1] === 0xDA ) {\n\t\t\tresult = i + 2;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction glitchByteArray ( byteArray, seed, amount, iterationCount ) {\n\tconst headerLength = jpgHeaderLength( byteArray );\n\tconst maxIndex = byteArray.length - headerLength - 4;\n\n\tconst amountPercent = amount / 100;\n\tconst seedPercent   = seed / 100;\n\n\tfor ( var iterationIndex = 0; iterationIndex < iterationCount; iterationIndex++ ) {\n\t\tconst minPixelIndex = ( maxIndex / iterationCount * iterationIndex ) | 0;\n\t\tconst maxPixelIndex = ( maxIndex / iterationCount * ( iterationIndex + 1 ) ) | 0;\n\t\t\n\t\tconst delta = maxPixelIndex - minPixelIndex;\n\t\tlet pixelIndex = ( minPixelIndex + delta * seedPercent ) | 0;\n\n\t\tif ( pixelIndex > maxIndex ) {\n\t\t\tpixelIndex = maxIndex;\n\t\t}\n\n\t\tconst indexInByteArray = ~~( headerLength + pixelIndex );\n\n\t\tbyteArray[indexInByteArray] = ~~( amountPercent * 256 );\n\t}\n\n\treturn byteArray;\n}\n\nconst base64Map$1 = maps.base64Map;\n\nfunction byteArrayToBase64 ( byteArray ) {\n\tconst result = [ 'data:image/jpeg;base64,' ];\n\tlet byteNum;\n\tlet previousByte;\n\n\tfor ( let i = 0, len = byteArray.length; i < len; i++ ) {\n\t\tconst currentByte = byteArray[i];\n\t\tbyteNum = i % 3;\n\n\t\tswitch ( byteNum ) {\n\t\t\tcase 0: // first byte\n\t\t\t\tresult.push( base64Map$1[ currentByte >> 2 ] );\n\t\t\t\tbreak;\n\t\t\tcase 1: // second byte\n\t\t\t\tresult.push( base64Map$1[( previousByte & 3 ) << 4 | ( currentByte >> 4 )] );\n\t\t\t\tbreak;\n\t\t\tcase 2: // third byte\n\t\t\t\tresult.push( base64Map$1[( previousByte & 0x0f ) << 2 | ( currentByte >> 6 )] );\n\t\t\t\tresult.push( base64Map$1[currentByte & 0x3f] );\n\t\t\t\tbreak;\n\t\t}\n\n\t\tpreviousByte = currentByte;\n\t}\n\n\tif ( byteNum === 0 ) {\n\t\tresult.push( base64Map$1[( previousByte & 3 ) << 4] );\n\t\tresult.push( '==' );\n\t} else {\n\t\tif ( byteNum === 1 ) {\n\t\t\tresult.push( base64Map$1[( previousByte & 0x0f ) << 2] );\n\t\t\tresult.push( '=' );\n\t\t}\n\t}\n\n\treturn result.join( '' );\n}\n\nfunction glitchImageData ( imageData, base64URL, params ) {\n\tif ( isImageData( imageData ) ) {\n\t\tconst byteArray = base64ToByteArray( base64URL );\n\t\tconst glitchedByteArray = glitchByteArray( byteArray, params.seed, params.amount, params.iterations );\n\t\tconst glitchedBase64URL = byteArrayToBase64( glitchedByteArray );\n\t\treturn glitchedBase64URL;\n\t} else {\n\t\tthrow new Error( 'glitchImageData: imageData seems to be corrupt.' );\n\t\treturn;\n\t}\n}\n\nonmessage = msg => {\n\tconst imageData = msg.data.imageData;\n\tconst params = msg.data.params;\n\tconst base64URL = msg.data.base64URL;\n\n\tif ( imageData && base64URL && params ) {\n\t\ttry {\n\t\t\t// phantomjs seems to have some memory loss so we need to make sure\n\t\t\tif ( typeof imageData.width === 'undefined' && typeof msg.data.imageDataWidth === 'number' ) {\n\t\t\t\timageData.width = msg.data.imageDataWidth;\n\t\t\t}\n\n\t\t\tif ( typeof imageData.height === 'undefined' && typeof msg.data.imageDataHeight === 'number' ) {\n\t\t\t\timageData.height = msg.data.imageDataHeight;\n\t\t\t}\n\n\t\t\tconst glitchedBase64URL = glitchImageData( imageData, base64URL, params );\n\t\t\tsuccess( glitchedBase64URL );\n\n\t\t} catch ( err ) {\n\t\t\tfail( err );\n\t\t}\n\n\t} else {\n\t\tif ( msg.data.imageData ) {\n\t\t\tfail( 'Parameters are missing.' );\n\t\t} else {\n\t\t\tfail( 'ImageData is missing.' );\n\t\t}\n\t}\n\t\n\tself.close();\n};\n\nfunction fail ( err ) {\n\tself.postMessage( { err: err.message || err } );\n}\n\nfunction success ( base64URL ) {\n\tself.postMessage( { base64URL: base64URL } );\n}\n"],{type:'text/javascript'})) );
	
	const api = { getParams, getInput, getOutput };
	const inputMethods = { fromImageData, fromImage };
	const outputMethods = { toImage, toDataURL, toImageData };

	function getParams () {
		return params;
	}

	function getInput () {
		const result = objectAssign( { }, api );

		if ( ! inputFn ) {
			objectAssign( result, inputMethods );
		}

		return result;
	}

	function getOutput () {
		const result = objectAssign( { }, api );

		if ( ! outputFn ) {
			objectAssign( result, outputMethods );
		}

		return result;
	}

	function noTransform ( x ) { return x; }

	function fromImage ( inputOptions ) { return setInput( imageToImageData, inputOptions ); }
	function fromImageData ( inputOptions ) { return setInput( noTransform, inputOptions ); }

	function toDataURL ( outputOptions ) { return setOutput( noTransform ); }
	function toImage ( outputOptions ) { return setOutput( base64URLToImage, outputOptions, true ); }
	function toImageData ( outputOptions ) { return setOutput( base64URLToImageData, outputOptions, true ); }

	function setInput ( fn, inputOptions, canResolve ) {		
		inputFn = () => {
			return new Promise( ( resolve, reject ) => {
				if ( canResolve ) {
					fn( inputOptions, resolve, reject );
				} else {
					if ( fn === noTransform ) {
						resolve( inputOptions );
					} else {
						try {
							resolve( fn( inputOptions, resolve, reject ) );
						} catch ( err ) {
							reject( err );
						}
					}
				}
			} );
		};

		if ( isReady() ) {
			return getResult();
		} else {
			return getOutput();
		}
	}

	function setOutput ( fn, outputOptions, canResolve ) {
		outputFn = base64URL => {
			return new Promise( ( resolve, reject ) => {
				if ( canResolve ) {
					fn( base64URL, outputOptions, resolve, reject );
				} else {
					if ( fn === noTransform ) {
						resolve( base64URL );
					} else {
						fn( base64URL, outputOptions )
							.then( resolve, reject );
					}
				}
			} );
		};

		if ( isReady() ) {
			return getResult();
		} else {
			return getInput();
		}
	}

	function isReady () {
		return inputFn && outputFn;
	}

	function getResult () {
		return new Promise( ( resolve, reject ) => {
			inputFn()
				.then( imageData => {
					return glitch( imageData, params );
				}, reject )
				.then( base64URL => {
					outputFn( base64URL )
						.then( resolve, reject );
				}, reject );
		} );
	}

	function glitch ( imageData, params ) {
		return new Promise( ( resolve, reject ) => {
			imageDataToBase64( imageData, params.quality )
				.then( base64URL => {
					return glitchInWorker( imageData, base64URL, params );
				}, reject )
				.then( resolve, reject );
		} );
	}

	function glitchInWorker ( imageData, base64URL, params ) {
		return new Promise( ( resolve, reject ) => {
			worker.addEventListener( 'message', event => {
				if ( event.data && event.data.base64URL ) {
					resolve( event.data.base64URL );
				} else {
					if ( event.data && event.data.err ) {
						reject( event.data.err );
					} else {
						reject( event );
					}
				}
			} );

			worker.postMessage( {
				params: params,
				base64URL: base64URL,
				imageData: imageData,

				// phantomjs tends to forget about those two
				// so we send them separately
				imageDataWidth: imageData.width,
				imageDataHeight: imageData.height
			} );
		} );
	}

	return getInput();
}
1061727
function Rollbar(options, api, logger, platform) {
	  this.options = _.merge(options);
	  this.logger = logger;
	  Rollbar.rateLimiter.configureGlobal(this.options);
	  Rollbar.rateLimiter.setPlatformOptions(platform, this.options);
	  this.api = api;
	  this.queue = new Queue(Rollbar.rateLimiter, api, logger, this.options);
	  this.notifier = new Notifier(this.queue, this.options);
	  this.telemeter = new Telemeter(this.options);
	  this.lastError = null;
	  this.lastErrorHash = 'none';
	}
713523
function bin(argv) {
  // setup config
  var config = require('../config/config.js')

  program
  .option('-d, --database <database>', 'Database')
  .parse(argv)

  var defaultDatabase = 'media'

  config.database = program.database || config.database || defaultDatabase
  var url = process.argv[2] || 'https://www.reddit.com/r/perfectloops/top/?sort=top&t=all&count=25&after=t3_4j0v4f'

  qpm_media.getLastSeen(function(err, ret){
    if (err) {
      console.error(err)
    } else {
      console.log(ret[0][0].uri);
    }
  })


}
889089
function (id) {
            if (!paths.has(id)) {
                return;
            }

            var code = [
                    `import shimWorker from 'rollup-plugin-bundle-worker';`,
                    `export default new shimWorker(${JSON.stringify(paths.get(id))}, function (window, document) {`,
                    `var self = this;`,
                    fs.readFileSync(id, 'utf-8'),
                    `\n});`
                ].join('\n');

            return code;
        }
1167818
function (config) {
    config = config || {};
    Appender.call(this, config);

    /**
     * Log file name, initialized from the configuration. Folders up to the
     * file must exist beforehand.
     * fileName is really the _base_ file name. The real file names will be
     * prepended by a timestamp.
     */
    this.fileName = config.fileName;

    /**
     * The policy used to determine when we should roll the log file. It can be 
     * either time based (roll every x mins), size based (roll when the size
     * of the file is more than x bytes), or both (the first one happening).
     * { time: <timeInMinutes>, size: <sizeInBytes> }
     */
    this.triggeringPolicy = config.triggeringPolicy;

    /**
     * True to log strings instead of objects
     */
    this.appendStrings = (typeof config.appendStrings !== 'undefined') ?
      config.appendStrings :
      true;

    /**
     * The file stream, initialized by the "start" function
     */
    this.stream = null;
  }
1167381
function rollbackFiles(job, iFile, cb) {
   if (isUndefined(cb)) {
      cb = iFile;
      iFile = 0;
   }

   if (iFile === job.document.files.length) {
      cb();
      return;
   } 

   var file = job.document.files[iFile];
   var filePath = path.resolve(job.document.workingDirectory || '', file.fileName);
   if (!fs.existsSync(filePath + '.old')) {
      rollbackFiles(job, iFile + 1, cb);
      return;
   }

   job.inProgress({ operation: job.operation, step: 'rolling back file', fileName: file.fileName }, function(err) {
      showJobsError(err);
      copyFile(filePath + '.old', filePath, function(fileErr) {
         rollbackFiles(job, iFile + 1, function(rollbackError) {
            cb(rollbackError || fileErr);
         });
      });
   });
}
735669
function(config, onload, onprogress, onerror) {

		var character = new THREE.MD2Character();

		character.onLoadComplete = function() {
			if (onload) onload( character );
		};

		character.loadParts( config );

	}
851625
async function buildIifeAmd() {
  // create a bundle
  const bundle = await rollup.rollup({
    input: 'src/index.js',
    external: ['riot'],
    plugins: [
      nodeResolve({
        jsnext: true,
        main: true,
        browser: true
      }),
      commonjs({
        include: 'node_modules/**',
        namedExports: namedExports
      }),
      buble()
    ]
  });
  await bundle.write({
    format: 'iife',
    name: 'riotx',
    globals: {
      riot: 'riot'
    },
    banner: banner,
    intro: intro,
    file: 'dist/riotx.js',
    sourcemap: true
  });
  await bundle.write({
    format: 'amd',
    banner: banner,
    intro: intro,
    file: 'dist/amd.riotx.js',
    sourcemap: true
  });
}
371414
function transpile() {
        return rollup.rollup({
            entry: path.join(dirs.source, files.main)
        }).then(function (bundle) {
            return bundle.write({
                // output format - 'amd', 'cjs', 'es6', 'iife', 'umd'
                format: 'umd',
                dest: path.join(dirs.build, files.main),
                sourceMap: false,
                banner: grunt.config('banner'),
                intro: 'mx.version = \'' + grunt.config('pkg').version + '\';\n',
                footer: '\n',
                moduleName: 'mx'
            });
        });
    }
227777
function commitlint () {
  const baseDir = getBaseDir()

  co(function * () {
    const readOptions = {
      cwd: baseDir,
      edit: '.git/COMMIT_EDITMSG'
    }

    debug('commitlint.read options: %o', readOptions)

    const gitMsgFilePath = path.join(readOptions.cwd, readOptions.edit)

    if (!fs.existsSync(gitMsgFilePath)) {
      debug(`can not found "${gitMsgFilePath}"`)
      throw new Error('无法读取 git commit 信息')
    }

    const [message, config] = yield Promise.all([read(readOptions), load()])

    debug('git commit message: %o', message)
    debug('commitlint config: %o', config)

    const rules = config.rules
    const options = config.parserPreset ? { parserOpts: config.parserPreset.parserOpts } : {}
    const report = yield lint(message[0], rules, options)
    const formatted = format({
      results: [report]
    })

    console.log()
    console.log(Array.isArray(formatted) ? formatted.join('\n') : formatted)
    console.log()

    process.exit(report.errors.length ? 1 : 0)
  }).catch(error => {
    log.error(error.message)
    process.exit(1)
  })
}
542578
function configure() {
    var java = path.normalize(path.join(__dirname, "..", "jre", "bin", "java"+ClosureCompiler.JAVA_EXT));
    console.log("  Configuring bundled JRE for platform '"+platformPostfix()+"' ...");
    if (!/^win/.test(process.platform)) {
        var jre = path.normalize(path.join(__dirname, "..", "jre"));
        console.log("  | 0755 "+jre);
        fs.chmodSync(jre, 0755);
        console.log("  | 0755 "+path.join(jre, "bin"));
        fs.chmodSync(path.join(jre, "bin"), 0755);
        console.log("  | 0755 "+java);
        fs.chmodSync(java, 0755);
        console.log("  Complete.\n");
    } else {
        console.log("  Complete (not necessary).\n");
    }
}
1260915
function updateConfigs (args, newVersion) {
  const dotgit = DotGitignore()
  Bump.pkgFiles.concat(Bump.lockFiles).forEach(function (filename) {
    let configPath = path.resolve(process.cwd(), filename)
    try {
      if (dotgit.ignore(configPath)) return
      let stat = fs.lstatSync(configPath)
      if (stat.isFile()) {
        let data = fs.readFileSync(configPath, 'utf8')
        let indent = detectIndent(data).indent
        let newline = detectNewline(data)
        let config = JSON.parse(data)
        checkpoint(args, 'bumping version in ' + filename + ' from %s to %s', [config.version, newVersion])
        config.version = newVersion
        writeFile(args, configPath, stringifyPackage(config, indent, newline))
        // flag any config files that we modify the version # for
        // as having been updated.
        configsToUpdate[filename] = true
      }
    } catch (err) {
      if (err.code !== 'ENOENT') console.warn(err.message)
    }
  })
}