source: https://github.com/mvertes/co-shell (with minor adaptations)
970357
function promisify (server) {
  const originalEval = server.eval

  server.eval = function (cmd, context, filename, callback) {
    if (cmd.match(/\W*yield\s+/)) {
      cmd = 'co(function* () {' + cmd.replace(/^\s*var\s+/, '') + '})'
    }

    originalEval.call(server, cmd, context, filename, function (err, res) {
      if (err || !isPromise(res)) {
        return callback(err, res)
      }

      res.then(
        result => callback(null, result),
        callback
      )
    })
  }

  return server
}
770562
function conform(src, conf) {
  var dest = {};

  var rec = function(dest, src, conf) {
    Object.keys(conf).forEach(function(key) {
      if((typeof conf[key] === 'object' && !Array.isArray(conf[key]))) {
        dest[key] = rec({}, src[key] || {}, conf[key]);
      } else if(typeof conf[key] === 'object' && Array.isArray(conf[key])) {
        dest[key] = conf[key];
      } else {
        if(Object.prototype.hasOwnProperty.call(src, key)) {
          dest[key] = src[key];
        } else {
          dest[key] = src[key] || conf[key];
        }
      }
    });

    return dest;
  };

  return rec(dest, src, conf);
}
591473
function palette({ baseColor: themeColor = baseColor, src = 'css/rsuite.min.css', dist } = {}, doneCallback) {

  try {
    if (!dist) {
      throw  `ERROR: [option.dist] is required`;
    }
  } catch (e) {
    console.log(e.red);
    return;
  }

  const originColors = color.calcColors(baseColor);
  const themeColors = color.calcColors(themeColor);
  const distPath = Path.dirname(dist);

  const ensureDir = path => new Promise((resolve) => {
    fse.ensureDir(path, () => resolve());
  });

  const readData = path => new Promise(resolve => {
    fs.readFile(path, 'utf-8', (err, data) => {
      resolve(data || '');
    });
  });

  const writeData = (path, data) => new Promise((resolve, reject) => {
    fs.writeFile(path, data, (err) => {
      if (err) {
        reject(err);
      }
      resolve();
    });
  });

  const handleCallback = (...args) => doneCallback && doneCallback(args);

  const generateThemes = async function () {
    try {
      await ensureDir(distPath);
      let data = await readData(Path.join(rootPath, src));
      originColors.forEach((color, index) => {
        data = data.replace(new RegExp(color, 'g'), themeColors[index]);
      });
      await  writeData(dist, data);
      console.log(`Palette ${dist}` + '[SUCCESS]'.green);
      handleCallback();
    } catch (e) {
      console.log(`Palette ${dist}` + '[FAILD]'.red);
      handleCallback(e);
    }
  };

  generateThemes();

  return module.exports;
}
821262
function bundle(srcFiles, destDir, optionsFn) {
    return gulp.src(srcFiles, {
        read: false
    })
    .pipe(tap(function(file) {
        var options = {};
        if (optionsFn) options = optionsFn(file);
        var fileName = options.fileName || path.basename(file.path);

        if (options.standalone)
            console.log(`Creating ${options.standalone} in ${destDir}/${fileName}`);
        else
            console.log(`Creating ${destDir}/${fileName}`);

        file.contents = browserify(file.path, options)
            .ignore("buffer")
            .ignore("dotenv")
        .bundle()
            .on("error", function (err) {
                console.log(err);
            });
        file.path = path.join(file.base, fileName);
    }))
    .pipe(buffer())
    .pipe(sourcemaps.init({
        loadMaps: true
    }))
    .pipe(uglify({
        preserveComments: function(node, comment) {
            return comment.value.includes("Copyright Arm");
        }
    }))
    .pipe(sourcemaps.write(".", {
        sourceRoot: path.relative(destDir, nodeDir)
    }))
    .pipe(gulp.dest(destDir));
}
392870
function CliStripNodeJake(argv)
{
    const nodeRegex = /^(.*)\/node$/;
    const yakeRegex = /(.*)yake(.*)$/;
    const taskFileRegex = /\.\/(.*)\.js(\s*)$/;
    // let argsNoNode;
    let argNoNodeNoYake;
    /**
     * Strip ['....node', '....yake'] or ['....yake'] or [./<....>.js] from the start of the argv array
     */

    if (argv[0].match(nodeRegex))
    {
        argNoNodeNoYake = argv.slice(1);
        if (argv[1].match(nodeRegex))
        {
            argNoNodeNoYake = argv.slice(2);
        }
    }
    else if (argv[0].match(yakeRegex))
    {
        argNoNodeNoYake = argv.slice(1);
    }
    else if (argv[0].match(taskFileRegex))
    {
        argNoNodeNoYake = argv.slice(1);
    }
    else
    {
        argNoNodeNoYake = argv.slice();
    }

    return argNoNodeNoYake;
}
313296
function ls (args, cb) {
  args = args.join("/").split("@").join("/")
  if (args.substr(-1) === "/") args = args.substr(0, args.length - 1)
  ls_(args, function(er, files) {
    files = files || []
    output.write(npm.config.get("outfd"), files.join("\n"), cb_)
    function cb_ () { cb(null, files) }
  })
}
922857
function transposeVarDependencies() {
    var map = {};
    sourcePackages.forEach(function(p) {
      if (p.vars) {
        p.vars.forEach(function(v) {
          map[v] = p.name;
        });
      }
    });
    sourcePackages.forEach(function(p) {
      var deps = [];
      var varDeps = [];
      p.dependencies.forEach(function(d) {
        var normalized = map[d] || d;
        if (deps.indexOf(normalized) === -1) {
          deps.push(normalized);
        }
        if (d in map) {
          varDeps.push(d);
        }
      });
      p.dependencies = deps;
      if (varDeps.length) {
        p.varDependencies = varDeps;
      }
    });
  }
81706
function bin(argv) {
  ws(argv, function(err, res) {
    if (err) {
      console.err(err);
    } else {
      console.log(res);
    }
  });
}
1183287
function rel2absSeg(jPath,ind) {
        
        var seg = jPath.getSeg(ind),
        letter = seg.pathSegTypeAsLetter.toLowerCase(),
        args,ref;
        
        if (seg.pathSegTypeAsLetter !== letter) return; //déjà en absolu
        
        args = [ind,letter.toUpperCase()];
        ref = jPath.getCurPt(ind);
        
        if (letter === 'h') args.push(ref.x+seg.x);
        else if (letter === 'v') args.push(ref.y+seg.y);
        else if (letter === "m") args.push(seg.x,seg.y);
        else if (letter !== "z") {
            
            args.push(ref.x+seg.x,ref.y+seg.y);
            
            switch (letter) {
                case 'c' : args.push(ref.x+seg.x1,ref.y+seg.y1,ref.x+seg.x2,ref.y+seg.y2); break;
                case 'q' : args.push(ref.x+seg.x1,ref.y+seg.y1); break;
                case 'a' : args.push(seg.r1,seg.r2,seg.angle,seg.largArcFlag,seg.sweepFlag); break;
                case 's' : args.push(ref.x+seg.x2,ref.y+seg.y2); break;
            }
        }
        
        jPath.replaceSeg.apply(jPath,args);
    }
521590
function pluck(path, cb) {
  var tasks = [];
  fs.readFile(path, 'utf8', function (err, str) {
    if (err) return cb(err);

    /**
     * Skip binary-files
     */

    if (isBinary(str)) return;

    /**
     * Pointer within the file
     */

    var lines = str.split('\n'),
        linum = 0;

    while (lines.length) {
      var line = lines.shift(); linum++;

      /**
       * Check for task-comment
       */

      if (!pattern.test(line)) continue;

      /**
       * Old-style comments
       * @see http://www.riedquat.de/TR/trunk/TODO_Syntax/
       */

      var matches = line.match(isoPattern);
      if (matches != null) {
        matches = matches.toString().split(':');
        var labels = ['#'+matches[0].toLowerCase()],
            added = new Date(matches[1]),
            assignee = '@'+matches[2].replace(/[\\s]*/, '-'),
            linestart = linum,
            title = matches[3],
            body = '';
      }

      /**
       * New-style comments
       *
       * TODO Write a comment specification
       *    | Should be located at the address below
       *
       * TODO Share patterns between modules
       *    | Perhaps even make all of them global
       *
       * @see http://hkjels.github.com/ntask/syntax.html
       */

      else {
        var added = new Date(),
            assignee = (line.match(/@[\w\[\d\]-_]*/g)||['@none'])[0],
            title = line.replace(new RegExp('.*('+KEYWORDS+')'), '')
              .replace(assignee, '')
              .replace(/[^a-z0-9\!\]\)]*$/i, '').trim(),
            linestart = linum,
            body = (function body() {
              var next = lines.shift();
              if (/[\\s]*[\\\*\%\-(" )"]{0,3}[\|]/g.test(next)) {
                linum++;
                return next.split('|').slice(1).join('').trim()+'\n'+body();
              }
              else {
                lines.unshift(next);
                return '';
              }
            })(),
            labels = ((title+body).match(/#[\w]*[\[\]a-f0-9\.]*/gi) || [])
              .map(lowertrim).filter(minlength),
            keyword = line.match(new RegExp('.*('+KEYWORDS+')'))[1].toLowerCase();
            labels.unshift('#'+keyword);
      }
      var done = labels.indexOf('#done') != -1;

      /**
       * Parsed task-object ready for model-validation
       */

      var task = {
          added: added
        , assignee: assignee
        , body: body
        , done: done
        , file: path
        , labels: labels
        , line: linestart
        , title: title
      };
      tasks.push(task);
    }
    cb(false, tasks);
  });
}
992015
function buildSingleModule (app, mod, conf, args) {
  if (!mod) {
    mod = conf.moduleConf.module;
  }
  conf = getConf(app, mod);
  del.sync(path.join(conf.modulePath, 'dist'));
  var allPromise = taskList.all($, conf.appConf, conf.moduleConf, args);
  var sassPromise = taskList.sass($, conf.appConf, conf.moduleConf, args);
  var lessPromise = taskList.less($, conf.appConf, conf.moduleConf, args);
  var athenaMatePromise = taskList.athena_mate($, conf.appConf, conf.moduleConf, args);
  var stylesAllinonePromise = taskList.allinone($, conf.appConf, conf.moduleConf, args);
  var transImagesPromise = taskList.trans_images($, conf.appConf, conf.moduleConf, args);
  var stylesPromise = taskList.styles($, conf.appConf, conf.moduleConf, args);
  var scriptsPromise = taskList.scripts($, conf.appConf, conf.moduleConf, args);
  var compressPromise = taskList.compress($, conf.appConf, conf.moduleConf, args);
  var fontsPromise = taskList.fonts($, conf.appConf, conf.moduleConf, args);
  var imagesPromise = taskList.images($, conf.appConf, conf.moduleConf, args);
  var revPromise = taskList.rev($, conf.appConf, conf.moduleConf, args);
  var revNoHashPromise = taskList.rev_no_hash($, conf.appConf, conf.moduleConf, args);
  var fetchCommonPromise = taskList.fetch_common($, conf.appConf, conf.moduleConf, args);
  var tempPromise = taskList.temp($, conf.appConf, conf.moduleConf, args);

  $.util.log($.util.colors.green('开始编译模块' + mod + '！'));
  return allPromise(mod, conf.modulePath, conf.appPath)
    .then(sassPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(lessPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(athenaMatePromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(stylesAllinonePromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(transImagesPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(stylesPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(scriptsPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(imagesPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(compressPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(fontsPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(function () {
      // 是否启用md5
      return new Promise(function (resolve, reject) {
        var support = conf.moduleConf.support;
        var useHash = support.useHash ? support.useHash : {
          enable: true
        };
        var enable = useHash.enable === undefined ? true : useHash.enable;
        if (enable) {
          resolve();
        } else {
          reject();
        }
      });
    })
    .then(revPromise.bind(null, mod, conf.modulePath, conf.appPath), revNoHashPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(fetchCommonPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(tempPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(function (result) {
      $.util.log($.util.colors.green('结束编译模块' + mod + '！'));
      return Promise.resolve(result);
    }).catch(function (e) {
      if (e) {
        console.log(e.plugin);
        if (e.stack) {
          console.log(e.stack);
        }
      }
    });
}
7542
function bundle(input, nc, options, complete) {
  const bundlePath = path.join(nc, 'lib', 'nexe.js');
  const mapfile = options.output + '.map';
  let ws = fs.createWriteStream(bundlePath);

  const igv = '__filename,__dirname,_process';
  let insertGlobalVars = { isNexe: true },
    wantedGlobalVars = igv.split(',');

  // parse insertGlobalVars.
  Object.keys(insertGlobals.vars).forEach(function(x) {
    if (wantedGlobalVars.indexOf(x) === -1) {
      insertGlobalVars[x] = undefined;
    }
  });

  let paths = [path.join(nc, 'lib')];

  if (options.browserifyPaths) {
    paths = paths.concat(options.browserifyPaths);
  }

  _log('executing browserify via API');
  let bproc = browserify([input], {
    debug: options.debug,
    commondir: false,
    paths: paths,
    builtins: false,
    insertGlobalVars: insertGlobalVars,
    detectGlobals: true,
    browserField: false,
  });

  if (options.browserifyExcludes && Array.isArray(options.browserifyExcludes)) {
    for (let i = 0; i < options.browserifyExcludes.length; i++) {
      let lib = options.browserifyExcludes[i];
      _log("Excluding '%s' from browserify bundle", lib);
      bproc.exclude(lib);
    }
  }

  // copy the excludes code for requires for now.
  if (options.browserifyRequires && Array.isArray(options.browserifyRequires)) {
    for (let i = 0; i < options.browserifyRequires.length; i++) {
      let lib = options.browserifyRequires[i];
      let name = lib.file || lib; // for  object format.
      // if `lib` is object then fetch all params without `file`
      // otherwise returns empty object
      let opts =
        (lib instanceof Object &&
          Object.keys(lib)
            .filter(key => key !== 'file')
            .reduce((acc, key) => {
              return (acc[key] = lib[key]), acc;
            }, {})) ||
        {};

      _log("Force including '%s' in browserify bundle", name);
      bproc.require(lib, opts);
    }
  }

  if (options.debug) {
    bproc.require(require.resolve('source-map-support'));
  }

  let bprocbun = bproc
    .bundle() // bundle
    .pipe(ws); // pipe to file

  // error on require errors, still can't contionue. ffs browserify
  bprocbun.on('error', function(err) {
    _log('error', '[browserify] ' + err);
  });

  ws.on('error', function(err) {
    console.log(err);
    _log('error', 'Failed to save stdout to disk');
    process.exit(1);
  });

  ws.on('close', function() {
    var source = fs.readFileSync(bundlePath, 'utf8');
    source = source.replace(/[^\x00-\x7F]/g, '');

    // write the source modified to nexe.js
    fs.writeFile(bundlePath, source, 'utf8', function(err) {
      if (err) {
        _log('error', 'failed to save source');
        process.exit(1);
      }

      complete();
    });
  });
}
663859
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.getRandomUnseenFragment(null, config).then(function(ret){
    console.table(ret.ret[0])
    ret.conn.close()
  }).catch(function (err) {
    console.error(err)
  })


}
953684
function transpileJavaScriptToPHP ({ js, variables }) {

    // match all local variables (let, const or var)
    let localVariablesRegex = /[^a-zA-Z0-9_](?:let|const|var)\s+(?:\[([^\]]+)\]|([a-zA-Z0-9_]+))/g // local variables

    let allVariables = (variables || []).map (x => x); // clone the array
    // process the variables created in destructuring assignments as well
    let localVariablesMatches
    while (localVariablesMatches = localVariablesRegex.exec (js)) {
        if (localVariablesMatches[1]) {
            // this is a destructuring assignment like
            // let [ a, b, c ] = 'a-b-c'.split ('-')
            let matches = localVariablesMatches[1].trim ().split (', ') // split the destructuring assignment by comma
            matches.forEach (x => allVariables.push (x.trim ())) // trim each variable name
        } else {
            // this is a single variable assignment
            allVariables.push (localVariablesMatches[2].trim ()) // add it to the list of local variables
        }
    }

    // match all variables instantiated in the catch()-block of a try-catch clause
    let catchClauseRegex = /catch \(([^)]+)\)/g
    let catchClauseMatches
    while (catchClauseMatches = catchClauseRegex.exec (js)) {
        allVariables.push (catchClauseMatches[1])
    }

    // append $ to all variables in the method (PHP syntax demands $ at the beginning of a variable name)
    let phpVariablesRegexes = allVariables.map (x => [ "([^$$a-zA-Z0-9\\.\\>'_/])" + x + "([^a-zA-Z0-9'_/])", '$1$$' + x + '$2' ])

    // support for php syntax for object-pointer dereference
    // convert all $variable.property to $variable->property
    let variablePropertiesRegexes = allVariables.map (x => [ "([^a-zA-Z0-9\\.\\>'_])" + x + '\\.', '$1' + x + '->' ])

    // transpile JS → PHP
    let phpBody = regexAll (js, phpRegexes.concat (phpVariablesRegexes).concat (variablePropertiesRegexes))

    return phpBody
}
473528
function globs(sourcePath, ignore, commands, done) {
  var expression = /\$g\[(.+?)\]/g;
  var result = [];
  each(commands, function(command, next) {
    var map = {};
    var match;
    var matches = [];
    while ((match = expression.exec(command))) matches.push(match);
    each(matches, function(patternMatch, next) {
      find(patternMatch[1], sourcePath, ignore, function(err, relativePaths) {
        if (err) return next(err);
        map[patternMatch[1]] = relativePaths;
        next();
      });
    }, function(err) {
      if (err) return next(err);
      result.push(command.replace(expression, function(match, matchKey) {
        return map[matchKey].join(' ');
      }));
      next();
    });
  }, function(err) {
    if (err) return done(err);
    done(undefined, result);
  });
}
499353
function CliDispatch (action, dir, baseDir) {
  this.action = action
  this.dir = dir
  this.baseDir = baseDir
}
805065
function Buildit$run() {
		var externals, locals, define, out, patterns, walked, that = this;

		define = invert(this.define);
		externals = [];
		locals = {};
		patterns = [];

		each(this.exports, function(filepath, name) {
			var fullpath;

			fullpath = path.join(that.cwd, filepath + '.js');

			patterns.push(fullpath);
		});

		each(this.extensions, function(filepath) {
			var fullpath;

			fullpath = path.join(that.cwd, filepath + '.js');

			patterns.push(fullpath);
		});

		each(this.define, function(filepath, name) {
			var fullpath;

			fullpath = path.join(that.cwd, filepath + '.js');

			patterns.push(fullpath);
		});

		walked = walk(patterns, this.cwd);

		Array.prototype.push.apply(externals, walked.externals);
		unique(externals);

		each(walked.locals, function(file, name) {
			locals[name] = file;
		});

		each(this.define, function(filepath, name) {
			if (!locals.hasOwnProperty(filepath)) {
				throw new Error('Module "' + filepath + '" not found');
			}
		});

		each(this.exports, function(filepath, name) {
			if (!locals.hasOwnProperty(filepath)) {
				throw new Error('Module "' + filepath + '" not found');
			}
		});

		each(this.extensions, function(filepath) {
			if (!locals.hasOwnProperty(filepath)) {
				throw new Error('Module "' + filepath + '" not found');
			}
		});

		out = '';
		out += print.header(this.name, externals);
		out += print.library(externals);
		out += print.mappings(locals, this.cwd);
		out += print.machinery();

		each(locals, function(file, name) {
			out += print.file(name, file.source) + (define[name] ? print.define(define[name], name) : '');
		});

		each(this.extensions, function(filepath) {
			out += print.extension(filepath);
		});

		out += print.exports(this.exports);
		out += print.footer();

		return out;
	}