Parses the result of github.com/explore and extracts the
trending repositories.
18138
function parseGitHubTrendingRepos(err, body) {
    if (err) { return tubesio.finish(err); }

    // Load the raw HTML into a cheerio object so we can traverse
    // the data using CSS selectors ala jQuery.
    var $ = cheerio.load(body),
        result = {
            title: $('title').text(),
            trending: []
        };

    // Iterate over the trending repositories extracting the names
    // and hyperlinks.
    $('#trending-repositories > ol > li').each(function (i, e) {
        result.trending.push({
            name: us.trim($(e).find('h3').text()),
            href: 'https://github.com' + $(e).find('a').last().attr('href')
        });
    });

    // Return our results object
    tubesio.finish(result); 
}
610807
def get_pr_checks(pr: PullRequestDetails) -> Dict[str, Any]:
    
    url = ("https://api.github.com/repos/{}/{}/commits/{}/check-runs"
           "?access_token={}".format(pr.repo.organization,
                                     pr.repo.name,
                                     pr.branch_sha,
                                     pr.repo.access_token))
    response = requests.get(
        url,
        headers={'Accept': 'application/vnd.github.antiope-preview+json'})

    if response.status_code != 200:
        raise RuntimeError(
            'Get check-runs failed. Code: {}. Content: {}.'.format(
                response.status_code, response.content))

    return json.JSONDecoder().decode(response.content.decode())
898380
async function getPkgReleases({ lookupName, registryUrls }) {
  const versions = [];
  const dependency = getDependencyParts(lookupName);
  if (!is.nonEmptyArray(registryUrls)) {
    logger.error(`No repositories defined for ${dependency.display}`);
    return null;
  }
  const repositories = registryUrls.map(repository =>
    repository.replace(/\/?$/, '/')
  );
  logger.debug(
    `Found ${repositories.length} repositories for ${dependency.display}`
  );
  const repoForVersions = {};
  for (let i = 0; i < repositories.length; i += 1) {
    const repoUrl = repositories[i];
    logger.debug(
      `Looking up ${dependency.display} in repository #${i} - ${repoUrl}`
    );
    const mavenMetadata = await downloadMavenXml(
      dependency,
      repoUrl,
      'maven-metadata.xml'
    );
    if (mavenMetadata) {
      const newVersions = extractVersions(mavenMetadata).filter(
        version => !versions.includes(version)
      );
      const latestVersion = getLatestVersion(newVersions);
      if (latestVersion) {
        repoForVersions[latestVersion] = repoUrl;
      }
      versions.push(...newVersions);
      logger.debug(`Found ${newVersions.length} new versions for ${dependency.display} in repository ${repoUrl}`); // prettier-ignore
    }
  }

  if (versions.length === 0) {
    logger.info(`No versions found for ${dependency.display} in ${repositories.length} repositories`); // prettier-ignore
    return null;
  }
  logger.debug(`Found ${versions.length} versions for ${dependency.display}`);
  const latestVersion = getLatestVersion(versions);
  const repoUrl = repoForVersions[latestVersion];
  const dependencyInfo = await getDependencyInfo(
    dependency,
    repoUrl,
    latestVersion
  );

  return {
    ...dependency,
    ...dependencyInfo,
    releases: versions.map(v => ({ version: v })),
  };
}
394754
def __parse_results(self,results):
        
        reslist = []
        cursor = 0
        match  = RE_RESULTS.search(results,cursor)
        while match:
            doc = {}
            doc['bibcode'] = match.group('bibcode')
            doc['confidence'] = self.__get_confidence_level(match.group('confidence'))
            doc['refstring'] = match.group('refstring')
            reslist.append(doc)
            cursor = match.end()
            match  = RE_RESULTS.search(results,cursor)
        return reslist
332988
def get_urls(session, name, data, find_changelogs_fn, **kwargs):
    
    # if this package has valid meta data, build up a list of URL candidates we can possibly
    # search for changelogs on
    if "versions" in data:
        candidates = set()
        for version, item in data["versions"].items():
            if "homepage" in item and item["homepage"] is not None:
                if isinstance(item["homepage"], list):
                    candidates.add(*item["homepage"])
                else:
                    candidates.add(item["homepage"])
            if "repository" in item and item["repository"] is not None:
                if "url" in item["repository"]:
                    repo = item["repository"]["url"]
                elif "path" in item["repository"]:
                    repo = item["repository"]["path"]
                else:
                    continue
                repo = repo.replace("git://", "https://").replace(".git", "")
                candidates.add(repo)
        return find_changelogs_fn(session=session, name=name, candidates=candidates)
    return set(), set()
41891
def from_github(repo: GithubRepository,
                    pull_id: int) -> 'PullRequestDetails':
        
        url = ("https://api.github.com/repos/{}/{}/pulls/{}"
               "?access_token={}".format(repo.organization,
                                         repo.name,
                                         pull_id,
                                         repo.access_token))

        response = requests.get(url)

        if response.status_code != 200:
            raise RuntimeError(
                'Pull check failed. Code: {}. Content: {}.'.format(
                    response.status_code, response.content))

        payload = json.JSONDecoder().decode(response.content.decode())
        return PullRequestDetails(payload, repo)
995189
@SuppressWarnings("deprecation")
    public /*abstract*/ void parseAssociatedNames(Item item, Collection<GitHubRepositoryName> result) {
        if (Util.isOverridden(
                GitHubRepositoryNameContributor.class,
                getClass(),
                "parseAssociatedNames",
                Job.class,
                Collection.class
        )) {
            // if this impl is legacy, it cannot contribute to non-jobs, so not an error
            if (item instanceof Job) {
                parseAssociatedNames((Job<?, ?>) item, result);
            }
        } else  if (Util.isOverridden(
                GitHubRepositoryNameContributor.class,
                getClass(),
                "parseAssociatedNames",
                AbstractProject.class,
                Collection.class
        )) {
            // if this impl is legacy, it cannot contribute to non-projects, so not an error
            if (item instanceof AbstractProject) {
                parseAssociatedNames((AbstractProject<?, ?>) item, result);
            }
        } else {
            throw new AbstractMethodError("you must override the new overload of parseAssociatedNames");
        }
    }
1223634
def _parse(res, params, n, api, **kwds):
    """"""
    cursor = "cursor" in params
    if not cursor:
        start = params["start"]
    if n == 0:
        return ""
    _json = res.get('search-results', {}).get('entry', [])
    # Download the remaining information in chunks
    while n > 0:
        n -= params["count"]
        if cursor:
            pointer = res['search-results']['cursor'].get('@next')
            params.update({'cursor': pointer})
        else:
            start += params["count"]
            params.update({'start': start})
        res = download(url=URL[api], params=params, accept="json", **kwds).json()
        _json.extend(res.get('search-results', {}).get('entry', []))
    return _json
1205235
def github_repos(organization, github_url, github_token):
    """"""
    # Get github repos
    headers = {"Authorization": "token {}".format(github_token)}
    next_cursor = None

    while next_cursor is not False:
        params = {'query': query, 'variables': {
            'organization': organization, 'cursor': next_cursor}}
        response = requests.post(github_url, headers=headers, json=params)
        result = response.json()
        if response.status_code != 200 or 'errors' in result:
            raise ValueError("Github api error %s" % (
                response.content.decode('utf8'),))

        repos = jmespath.search(
            'data.organization.repositories.edges[].node', result)
        for r in repos:
            yield r
        page_info = jmespath.search(
            'data.organization.repositories.pageInfo', result)
        if page_info:
            next_cursor = (page_info['hasNextPage'] and
                           page_info['endCursor'] or False)
        else:
            next_cursor = False
720262
def get(self):
        """"""
        if self.gist:
            content = self.github.read_gist_file(self.gist)
            self.local.save(content)
1222476
def _grab_version(self):
        """"""
        original_version = self.vcs.version
        logger.debug("Extracted version: %s", original_version)
        if original_version is None:
            logger.critical('No version found.')
            sys.exit(1)
        suggestion = utils.cleanup_version(original_version)
        new_version = utils.ask_version("Enter version", default=suggestion)
        if not new_version:
            new_version = suggestion
        self.data['original_version'] = original_version
        self.data['new_version'] = new_version
522749
def print_hits(results):
    "  "
    print_search_stats(results)
    for hit in results['hits']['hits']:
        # get created date for a repo and fallback to authored_date for a commit
        created_at = parse_date(hit['_source'].get('created_at', hit['_source']['authored_date']))
        print('/%s/%s/%s (%s): %s' % (
                hit['_index'], hit['_type'], hit['_id'],
                created_at.strftime('%Y-%m-%d'),
                hit['_source']['description'].split('\n')[0]))

    print('=' * 80)
    print()
1151586
def _fetch(self):
        '''
        
        '''
        origin = self.repo.remotes[0]
        try:
            fetch_results = origin.fetch()
        except AssertionError:
            fetch_results = origin.fetch()

        new_objs = False
        for fetchinfo in fetch_results:
            if fetchinfo.old_commit is not None:
                log.debug(
                    '%s has updated \'%s\' for remote \'%s\' '
                    'from %s to %s',
                    self.role,
                    fetchinfo.name,
                    self.id,
                    fetchinfo.old_commit.hexsha[:7],
                    fetchinfo.commit.hexsha[:7]
                )
                new_objs = True
            elif fetchinfo.flags in (fetchinfo.NEW_TAG,
                                     fetchinfo.NEW_HEAD):
                log.debug(
                    '%s has fetched new %s \'%s\' for remote \'%s\'',
                    self.role,
                    'tag' if fetchinfo.flags == fetchinfo.NEW_TAG else 'head',
                    fetchinfo.name,
                    self.id
                )
                new_objs = True

        cleaned = self.clean_stale_refs()
        return True if (new_objs or cleaned) else None
421091
function _githubOrgRepo (gitUrl) {
  if (!gitUrl) {
    return null
  }
  const match = gitUrl.match(/.*?(:\/\/|@)github\.com[/:](.*?)(#.*?)?$/)
  return match && match[2] && match[2].replace(/\.git$/, '')
}
907420
def parse_url(self):
        """"""
        url = urlparse(self.url).path

        # handle git
        url = url.split('.git')[0]

        if ':' in url:
            url = url.split(':')[1]

        # Ony capture last two list items
        try:
            project, repo = url.split('/')[-2:]
        except ValueError:
            raise ParserError('"{}" is not a valid repository URL.'.format(self.url))

        return project, repo
642322
function analyzeDiff (diff, sha, conf) {
  var options = _.merge({
    "onProgress": function onProgress (err, result, todo) {
      if (err) {
        console.error("[Github-Todos] Error", err);
      } else if (result && result.type === "comment") {
        console.log("[Github-Todos] Added comment to issue #%s (%s) - %s", result.issue, result.title, result.url);
      } else if (result && result.type === "issue") {
        console.log("[Github-Todos] Created issue #%s (%s) - %s", result.number, result.title, result.url);
      } else if (!result) {
        console.log("[Github-Todos] Skipped - \"%s\"", todo.title);
      } else {
        console.error("[Github-Todos] Unknown result", result);
      }
      if (result && result.url && conf["open-url"]) {
        open(result.url);
      }
    }
  }, conf);

  function done (/* injectedIssues */) {
    if (process.env.DRY_RUN) {
      console.error("[Github-Todos] Dry Run: Aborting git push");
      process.exit(123);
    } else {
      console.log("[Github-Todos] OK.");
    }
  }

  return todos.fromDiff(conf.repo, diff, sha, options).spread(function (results, todos) {
    if (!conf["inject-issue"]) {
      return false;
    }

    console.log("[Github-Todos] Injecting issue numbers to files…");

    return git.dirty().then(null, function (err) {
      // Ignore error but warn user
      if (process.env.DEBUG) {
        console.error(err.stack || err);
      }
      console.error("[Github-Todos] Warning: could not check if repository is dirty");
      return false;
    }).then(function (dirty) {
      var injects = generateInjects(todos, results);

      if (process.env.DRY_RUN) {
        throw new Error("Simulated execution (DRY_RUN set)");
      }

      return stash(dirty)()
        .then(injectIssues(injects))
        .then(add)
        .then(commit)
        .then(unstash(dirty))
        .then(null, function (err) {
          console.error("[Github-Todos] Warning: failed injecting issues, you may need to do it manually in following files:");
          console.error("[Github-Todos] %s", err);
          _.each(injects, function (inject) {
            console.log("[Github-Todos]  * %s, line %s: Issue #%s", inject.file, inject.line, inject.issue);
          });
        });
    });
  }).then(done);
}
283825
def probe_git():
    """"""
    try:
        repo = git.Repo()
    except git.InvalidGitRepositoryError:
        LOGGER.warning(
            "We highly recommend keeping your model in a git repository."
            " It allows you to track changes and to easily collaborate with"
            " others via online platforms such as https://github.com.\n")
        return
    if repo.is_dirty():
        LOGGER.critical(
            "Please git commit or git stash all changes before running"
            " the memote suite.")
        sys.exit(1)
    return repo