github.com/sindresorhus/is-reachable/blob/master/index.js
979422
function getAddress (hostname) {
  if (net.isIP(hostname)) {
    return Promise.resolve(hostname);
  }
  return pify(dns.lookup)(hostname);
}
87493
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Blob requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/git/trees/#get-a-tree-recursively
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/git/trees/:ref_or_sha?recursive
    const { owner } = req.params;
    const repoName = req.params.repo;
    const refOrSha = req.params.ref_or_sha;
    const recursive = typeof req.query.recursive !== 'undefined' && req.query.recursive !== '';
    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;

    const repPath = resolveRepositoryPath(options, owner, repoName);

    async function dirEntryToJson({
      oid: sha, type, path, mode,
    }) {
      return {
        path,
        mode,
        type,
        sha,
        url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${sha}`,
      };
    }

    async function fileEntryToJson({
      oid: sha, type, path, mode,
    }) {
      const { object: content } = await getObject(repPath, sha);

      return {
        path,
        mode,
        type,
        sha,
        size: content.length,
        url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/blobs/${sha}`,
      };
    }

    async function collectTreeEntries(tree, result, treePath, deep) {
      const entries = tree.entries.map(({
        oid, type, mode, path,
      }) => {
        return {
          oid, type, mode, path: joinPaths(treePath, path),
        };
      });
      result.push(...entries);
      if (deep) {
        const treeEntries = entries.filter(entry => entry.type === 'tree');
        for (let i = 0; i < treeEntries.length; i += 1) {
          const { oid, path } = treeEntries[i];
          /* eslint-disable no-await-in-loop */
          const { object: subTree } = await getObject(repPath, oid);
          await collectTreeEntries(subTree, result, path, deep);
        }
      }
      return result;
    }

    async function treeEntriesToJson(tree, deep) {
      const result = [];
      await collectTreeEntries(tree, result, '', deep);
      return Promise.all(result.map(async (entry) => {
        /* eslint arrow-body-style: "off" */
        return entry.type === 'blob'
          ? fileEntryToJson(entry) : dirEntryToJson(entry);
      }));
    }

    resolveTree(repPath, refOrSha)
      .then(async ({ oid: sha, object: tree }) => {
        res.json({
          sha,
          url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${sha}`,
          tree: await treeEntriesToJson(tree, recursive),
          truncated: false,
        });
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'ReadObjectFail' || err.code === 'ResolveRefError') {
          options.logger.debug(`[treeHandler] resource not found: ${err.message}`);
          res.status(404).json({
            message: 'Not Found',
            documentation_url: 'https://developer.github.com/v3/git/trees/#get-a-tree',
          });
        } else {
          options.logger.debug(`[treeHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
1287610
function f_indekslenen_ve_takip_edilen_kalem_idler(_tahta_id) {

        var db_kalem = require("./db_kalem");
        return result.dbQ.Q.all([
                db_kalem.f_db_kalem_indeksli_idler(_tahta_id),
                db_kalem.f_db_kalem_takip_idler(_tahta_id)
            ])
            .then(function (_ress) {

                var indeksliler = _ress[0],
                    takipteki_kalemler = _ress[1];

                return indeksliler.unionXU(takipteki_kalemler);
            });
    }
1197869
function isSafeToCreateProjectIn(root, name) {
  const validFiles = [
    '.DS_Store',
    'Thumbs.db',
    '.git',
    '.gitignore',
    '.idea',
    'README.md',
    'LICENSE',
    'web.iml',
    '.hg',
    '.hgignore',
    '.hgcheck',
  ];
  console.log();

  const conflicts = fs
    .readdirSync(root)
    .filter(file => !validFiles.includes(file));
  if (conflicts.length < 1) {
    return true;
  }

  console.log(
    `The directory ${chalk.green(name)} contains files that could conflict:`
  );
  console.log();
  for (const file of conflicts) {
    console.log(`  ${file}`);
  }
  console.log();
  console.log(
    'Either try using a new directory name, or remove the files listed above.'
  );

  return false;
}
522705
function accessible() {
  // eslint-disable-next-line no-underscore-dangle
  new chai.Assertion(this._obj).to.be.instanceof(Array);
  // eslint-disable-next-line no-underscore-dangle
  const errors = this._obj
    .filter(test => test.result)
    .reduce((all, test) => all.concat(test.result.violations), [])
    .filter(test => test)
    .map(test => `${JSON.stringify(test, null, 2)}`);

  this.assert(
    errors.length === 0,
    `expected no accessibility violations but got:\n\t${errors[0]}`,
    'expected accessibilty errors but received none',
  );
}
1195836
function f_indekslenen_ve_takip_edilen_ihale_idleri(_tahta_id) {
        return result.dbQ.Q.all([
            f_tahta_ihale_indeksli_idler(_tahta_id),
            f_tahta_ihale_takip_idler(_tahta_id)
        ]).then(function (_ress) {
            console.log("indekslenen_ve_takip_edilen_ihale_idleri SONUCU:");
            console.log(JSON.stringify(_ress));
            var indexliler = _ress[0],
                takiptekiler = _ress[1];

            return _.union(indexliler, takiptekiler);
        })
    }
706633
function findValidPhantomJsBinary(libPath) {
  return kew.fcall(function () {
    var libModule = require(libPath)
    if (libModule.location &&
        getTargetPlatform() == libModule.platform &&
        getTargetArch() == libModule.arch) {
      var resolvedLocation = path.resolve(path.dirname(libPath), libModule.location)
      if (fs.statSync(resolvedLocation)) {
        return checkPhantomjsVersion(resolvedLocation).then(function (matches) {
          if (matches) {
            return kew.resolve(resolvedLocation)
          }
        })
      }
    }
    return false
  }).fail(function () {
    return false
  })
}
924628
function _rawGithubUrl (resolvedPackageRoot) {
  var { packageJson, relativeFile } = resolvedPackageRoot
  const orgRepo = _githubOrgRepo(packageJson && packageJson.repository && packageJson.repository.url)
  if (orgRepo) {
    return `https://raw.githubusercontent.com/${orgRepo}/v${packageJson.version}/${relativeFile}`
  }
}
1374568
function(method, url, headers, data, callback) {

		var r = new XMLHttpRequest();
		var error = this.error;

		// Binary?
		var binary = false;
		if (method === 'blob') {
			binary = method;
			method = 'GET';
		}

		method = method.toUpperCase();

		// Xhr.responseType 'json' is not supported in any of the vendors yet.
		r.onload = function(e) {
			var json = r.response;
			try {
				json = JSON.parse(r.responseText);
			}
			catch (_e) {
				if (r.status === 401) {
					json = error('access_denied', r.statusText);
				}
			}

			var headers = headersToJSON(r.getAllResponseHeaders());
			headers.statusCode = r.status;

			callback(json || (method === 'GET' ? error('empty_response', 'Could not get resource') : {}), headers);
		};

		r.onerror = function(e) {
			var json = r.responseText;
			try {
				json = JSON.parse(r.responseText);
			}
			catch (_e) {}

			callback(json || error('access_denied', 'Could not get resource'));
		};

		var x;

		// Should we add the query to the URL?
		if (method === 'GET' || method === 'DELETE') {
			data = null;
		}
		else if (data && typeof (data) !== 'string' && !(data instanceof FormData) && !(data instanceof File) && !(data instanceof Blob)) {
			// Loop through and add formData
			var f = new FormData();
			for (x in data) if (data.hasOwnProperty(x)) {
				if (data[x] instanceof HTMLInputElement) {
					if ('files' in data[x] && data[x].files.length > 0) {
						f.append(x, data[x].files[0]);
					}
				}
				else if (data[x] instanceof Blob) {
					f.append(x, data[x], data.name);
				}
				else {
					f.append(x, data[x]);
				}
			}

			data = f;
		}

		// Open the path, async
		r.open(method, url, true);

		if (binary) {
			if ('responseType' in r) {
				r.responseType = binary;
			}
			else {
				r.overrideMimeType('text/plain; charset=x-user-defined');
			}
		}

		// Set any bespoke headers
		if (headers) {
			for (x in headers) {
				r.setRequestHeader(x, headers[x]);
			}
		}

		r.send(data);

		return r;

		// Headers are returned as a string
		function headersToJSON(s) {
			var r = {};
			var reg = /([a-z\-]+):\s?(.*);?/gi;
			var m;
			while ((m = reg.exec(s))) {
				r[m[1]] = m[2];
			}

			return r;
		}
	}
1057022
function (version, semverIndex)
	{
		const splittedVersion = version.split('.');
		splittedVersion[ semverIndex ] = parseInt(splittedVersion[ semverIndex ], 10) + 1;
		while (semverIndex < 2)
		{
			splittedVersion[ ++semverIndex ] = '0';
		}
		return splittedVersion.join('.');
	}
1296106
function (cb) {
      async.map(self._repos, function (repo, repoCb) {
        self._client.gitdata.getReference({
          user: self._repoParts[repo].org,
          repo: self._repoParts[repo].repo,
          ref: branchDestFull
        }, function (err, res) {
          // Allow not found.
          if (err && err.code === NOT_FOUND) {
            repoCb(null, {
              repo: repo,
              exists: false,
              sha: null
            });
            return;
          }

          // Real error.
          if (self._checkAndHandleError(err, "branch.getDestRefs - " + repo, repoCb)) {
            return;
          }

          // Error if existing branches are not allowed.
          var sha = res.object.sha;
          if (!self._allowExisting) {
            self._checkAndHandleError(
              new Error("Found existing dest branch in repo: " + repo + " with sha: " + sha),
              null,
              repoCb);
            return;
          }

          // Have an allowed, existing branch.
          repoCb(null, {
            repo: repo,
            exists: true,
            sha: sha
          });
        });
      }, cb);
    }
53341
function(index)
  {
    //Check the index value
    if(index >= nutty._middlewares.length){ return; }

    //Call the middleware
    nutty._middlewares[index](args, function(error)
    {
      //Check for undefined error
      if(typeof error === 'undefined'){ var error = null; }

      //Check for error
      if(error && error instanceof Error)
      {
        //Throw the error
        throw error;
      }

      //Next middleware on the list
      return middlewares_recursive(index + 1);
    });
  }
564538
function checkRequiredFiles() {
  const indexHtmlExists = fse.existsSync(paths.indexHtml);
  const indexJsExists = fse.existsSync(paths.indexJs);

  if (!indexHtmlExists || !indexJsExists) {
    logError('\nSome required files couldn\'t be found. Make sure these all exist:\n');
    logError(`\t- ${paths.indexHtml}`);
    logError(`\t- ${paths.indexJs}\n`);

    process.exit(1);
  }
}
616478
async function publish(auth, rootPath) {
    // check if version does not exist yet
    // check if user is allowed to publish
    // check if version is larger than last version
    // names cant contain _- etc, maybe just stick to lowercase letters?
    // if projectKey, check that we can access the file?

    package = fs.readJsonSync(path.join(rootPath, constants.INCLUDE_FILE));
    code = fs.readJsonSync(path.join(rootPath, '.gas/publish.json'));

    const versionUrl = package.version.replace(/\./g, '_');
    // TODO
    // console.log(semver.valid(package.version));
    // console.log(versionUrl);

    try {
        const authenticated = await authWithFirebase(auth);
        const token = await firebase.auth().currentUser.getIdToken();
        const userId = firebase.auth().currentUser.uid;
        let url;
        let result;

        // Set a packageName to active
        url = `${constants.FIREBASE_DATABASE_URL}/packages/${package.name}.json?auth=${token}`;
        result = await request({
            url,
            method: "PATCH",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: {
                status: 'active',
            },
        });

        // Patch users in a package
        url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/userIds/${userId}.json?auth=${token}`;
        result = await request({
            url,
            method: "PATCH",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: {
                status: 'active',
            },
        });

        // Set version of a package to active
        url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/versions.json?auth=${token}`;
        result = await request({
            url,
            method: "PATCH",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: {
                [versionUrl]: true,
            },
        });

        // Patch a version in a package
        url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/version/${versionUrl}.json?auth=${token}`;
        result = await request({
            url,
            method: "PATCH",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: {
                code,
                dependencies: package.dependencies,
                description: package.description,
                homepage: package.homepage,
                license: package.license,
                readme: 'README.md',
                repository: package.repository,
                projectKey: package.projectKey,
                timestamp: {
                    ".sv": "timestamp",
                },
                userId,
            },
        });

        return true;
    } catch (err) {
        err.origin = 'test';
        await error.log(err);
        return false;
    }
}
451711
function checkStability() {
		db.query(
			"SELECT is_stable, asset, SUM(amount) AS `amount` \n\
			FROM outputs JOIN units USING(unit) WHERE address=? AND sequence='good' AND is_spent=0 GROUP BY asset ORDER BY asset DESC LIMIT 1", 
			[addrInfo.address],
			function(rows){
				if (rows.length === 0) {
					cb("This textcoin either was already claimed or never existed in the network");
				} else {
					var row = rows[0];
					if (false && !row.is_stable) {
						cb("This payment is not confirmed yet, try again later");
					} else {
						if (row.asset) { // claiming asset
							opts.asset = row.asset;
							opts.amount = row.amount;
							opts.fee_paying_addresses = [addrInfo.address];
							storage.readAsset(db, row.asset, null, function(err, objAsset){
								if (err && err.indexOf("not found" !== -1)) {
									if (!conf.bLight) // full wallets must have this asset
										throw Error("textcoin asset "+row.asset+" not found");
									return network.requestHistoryFor([opts.asset], [], checkStability);
								}
								asset = opts.asset;
								opts.to_address = addressTo;
								if (objAsset.fixed_denominations){ // indivisible
									opts.tolerance_plus = 0;
									opts.tolerance_minus = 0;
									indivisibleAsset.composeAndSaveIndivisibleAssetPaymentJoint(opts);
								}
								else{ // divisible
									divisibleAsset.composeAndSaveDivisibleAssetPaymentJoint(opts);
								}
							});
						} else {// claiming bytes
							opts.send_all = true;
							opts.outputs = [{address: addressTo, amount: 0}];
							opts.callbacks = composer.getSavingCallbacks(opts.callbacks);
							composer.composeJoint(opts);
						}
					}
				}
			}
		);		
	}
968963
function startForeverWithIndex( index, doneCB ) {
  log( 'Attempting to start ' + index + ' as daemon.');

  var config;
  var appendConfig = function(prop, value) {
    log('Adding to config: ' + prop + ', ' + value);
    if(value !== undefined) {
      config[prop] = value;
    }
  };
  done = doneCB || this.async();
  findProcessWithIndex( index, function(process) {
    // if found, be on our way without failing.
    if( typeof process !== 'undefined' ) {
      warn( index + ' is already running.');
      log( forever.format(true, [process]) );
      done();
    }
    else {
      gruntRef.file.mkdir(logDir);
      // 'forever start -o out.log -e err.log -c node -a -m 3 index.js';
      config = {
        command: commandName,
        append: true,
        max: 3,
        killSignal: killSignal
      };
      appendConfig('errFile', errFile);
      appendConfig('outFile', outFile);
      appendConfig('logFile', logFile);
      forever.startDaemon( index, config );
      log( 'Logs can be found at ' + logDir + '.' );
      done();
    }
  });
}
1215969
function __pandocAvailable(cb) {
      var test = spawn('pandoc', ['--help']);
      test.on('error', function() {
        console.error('Pandoc not found');
        cb('Pandoc not found');
      });
      test.on('exit', function() { cb(null); });
      test.stdin.end();
    }