This method filter only merged PR and
 fetch missing required attributes for pull requests
 :merged_at - is a date, when issue PR was merged.
 More correct to use merged date, rather than closed date.
973549
def filter_merged_pull_requests(pull_requests)
      print "Fetching merged dates...\r" if options[:verbose]
      closed_pull_requests = @fetcher.fetch_closed_pull_requests

      pull_requests.each do |pr|
        fetched_pr = closed_pull_requests.find do |fpr|
          fpr["number"] == pr["number"]
        end
        if fetched_pr
          pr["merged_at"] = fetched_pr["merged_at"]
          closed_pull_requests.delete(fetched_pr)
        end
      end

      pull_requests.reject! do |pr|
        pr["merged_at"].nil?
      end

      pull_requests
    end
1304070
def exclude_issues_without_labels(issues)
      return issues if issues.empty?
      return issues if issues.first.key?("pull_request") && options[:add_pr_wo_labels]
      return issues if !issues.first.key?("pull_request") && options[:add_issues_wo_labels]

      issues.reject do |issue|
        issue["labels"].empty?
      end
    end
482936
def get_version_and_release_date(requirement, version=None,
                                 verbose=False, response=None):
    
    try:
        if not response:
            url = get_pypi_url(requirement, version)
            response = requests.get(url)

        # see if the url is 404'ing because it has been redirected
        if response.status_code == 404:
            root_url = url.rpartition('/')[0]
            res = requests.head(root_url)
            if res.status_code == 301:
                new_location = res.headers['location'] + '/json'
                response = requests.get(new_location)

        response = response.json()
    except requests.HTTPError:
        if version:
            if verbose:
                print('{} ({}) isn\'t available on PyPI '
                      'anymore!'.format(requirement, version))
        else:
            if verbose:
                print('{} isn\'t on PyPI. Check that the project '
                      'still exists!'.format(requirement))
        return None, None
    except ValueError:
        if verbose:
            print('Decoding the JSON response for {} ({}) '
                  'failed'.format(requirement, version))
        return None, None

    try:
        if version:
            if version in response['releases']:
                release_date = response['releases'][version][0]['upload_time']
            else:
                return None, None
        else:
            version = response['info'].get('stable_version')

            if not version:
                versions = {
                    v: parse_version(v) for v in response['releases'].keys()
                    if not parse_version(v).is_prerelease()
                }

                # if we still don't have a version, let's pick up a prerelease one
                if not versions:
                    versions = {
                        v: parse_version(v) for v in response['releases'].keys()
                    }

                if versions:
                    version = max(versions.items(), key=operator.itemgetter(1))[0]
                    release_date = (
                        response['releases'][str(version)][0]['upload_time']
                    )
                else:
                    return None, None

        return version, datetime.fromtimestamp(time.mktime(
            time.strptime(release_date, '%Y-%m-%dT%H:%M:%S')
        ))
    except IndexError:
        if verbose:
            print('{} ({}) didn\'t return a date property'.format(requirement,
                                                                  version))
        return None, None
1164370
private void mergeCompleted(SegmentProperties segmentProperties, UpdateableSegmentMetadata transactionMetadata, MergeSegmentOperation mergeOp) {
        // We have processed a MergeSegmentOperation, pop the first operation off and decrement the counter.
        StorageOperation processedOperation = this.operations.removeFirst();
        assert processedOperation != null && processedOperation instanceof MergeSegmentOperation : "First outstanding operation was not a MergeSegmentOperation";
        MergeSegmentOperation mop = (MergeSegmentOperation) processedOperation;
        assert mop.getSourceSegmentId() == transactionMetadata.getId() : "First outstanding operation was a MergeSegmentOperation for the wrong Transaction id.";
        int newCount = this.mergeTransactionCount.decrementAndGet();
        assert newCount >= 0 : "Negative value for mergeTransactionCount";

        // Post-merger validation. Verify we are still in agreement with the storage.
        long expectedNewLength = this.metadata.getStorageLength() + mergeOp.getLength();
        if (segmentProperties.getLength() != expectedNewLength) {
            throw new CompletionException(new DataCorruptionException(String.format(
                    "Transaction Segment '%s' was merged into parent '%s' but the parent segment has an unexpected StorageLength after the merger. Previous=%d, MergeLength=%d, Expected=%d, Actual=%d",
                    transactionMetadata.getName(),
                    this.metadata.getName(),
                    segmentProperties.getLength(),
                    mergeOp.getLength(),
                    expectedNewLength,
                    segmentProperties.getLength())));
        }

        updateMetadata(segmentProperties);
        updateMetadataForTransactionPostMerger(transactionMetadata, mop.getStreamSegmentId());
    }
958494
def get_combined_status(self):
        
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + "/status"
        )
        return github.CommitCombinedStatus.CommitCombinedStatus(self._requester, headers, data, completed=True)
126290
def merged(revision)
      # By hand, build a list of all branches known to be merged into master
      git_args = ['branch', '-a', '--merged', revision]
      all_merged = []
      @repo.git_output(git_args).lines.each do |line|
        line.strip!
        all_merged << Branch.new(@repo, line)
      end

      # Filter the contents of this collection according to the big list
      merged = []
      @branches.each do |candidate|
        # For some reason Set#include? does not play nice with our overridden comparison operators
        # for branches, so we need to do this the hard way :(
        merged << candidate if all_merged.detect { |b| candidate == b }
      end

      BranchCollection.new(@repo, merged)
    end
701382
def valid_at(self, valid_date):
        ''''''
        is_valid = db.Q(validity__end__gt=valid_date,
                        validity__start__lte=valid_date)
        no_validity = db.Q(validity=None)
        return self(is_valid | no_validity)
967528
def _out_of_date(rw_file):
    
    with open(rw_file) as in_handle:
        for line in in_handle:
            if line.startswith("sys.path.append"):
                file_version = line.split("/lib/python")[0].split("Cellar/manta/")[-1]
                if file_version != programs.get_version_manifest("manta"):
                    return True
    return False
1117087
def clean_publish_dates(self):
        
        if self.end_date:
            if not self.start_date:
                raise ValidationError("""The End Date requires a Start Date value.""")
            elif self.end_date <= self.start_date:
                raise ValidationError("""The End Date must not precede the Start Date.""")
1357362
function getPRsForRepo(repo) {
  print(['Fetching PRs for ', clc.yellow.bold(`${repo.owner.login}/${repo.name}`)], debug);
  return new Promise((resolve, reject) => {
    github.pullRequests.getAll({
      user: repo.owner.login,
      repo: repo.name,
      state: 'open'
    }, (err, prs) => {
      if (err) {
        return reject(err);
      }
      return resolve(prs.filter((pr) => {
        return pr && pr.head;
      }));
    });
  });
}
1293648
function mergeNewAndOldMeta(old, updated) {
  const merged = {
    firstPublishTime: old.firstPublishTime || updated.publishTime
  };

  if (!Object.keys(old).length) {
    return updated;
  }

  if (old.history && updated.history) {
    merged.history = old.history.concat(updated.history);
  }

  return Object.assign(old, updated, merged);
}
997090
def check_auto_merge_labeler(repo: GithubRepository, pull_id: int
                             ) -> Optional[CannotAutomergeError]:
    
    url = ("https://api.github.com/repos/{}/{}/issues/{}/events"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     pull_id,
                                     repo.access_token))

    response = requests.get(url)

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

    payload = json.JSONDecoder().decode(response.content.decode())
    relevant = [event
                for event in payload
                if event['event'] == 'labeled' and
                event['label']['name'] in AUTO_MERGE_LABELS]
    if not relevant:
        return CannotAutomergeError('"automerge" label was never added.')

    return check_collaborator_has_write(repo, relevant[-1]['actor']['login'])
951693
def attempt_sync_with_master(pr: PullRequestDetails
                             ) -> Union[bool, CannotAutomergeError]:
    
    master_sha = get_master_sha(pr.repo)
    remote = pr.remote_repo
    url = ("https://api.github.com/repos/{}/{}/merges"
           "?access_token={}".format(remote.organization,
                                     remote.name,
                                     remote.access_token))
    data = {
        'base': pr.branch_name,
        'head': master_sha,
        'commit_message': 'Update branch (automerge)'.format(pr.branch_name)
    }
    response = requests.post(url, json=data)

    if response.status_code == 201:
        # Merge succeeded.
        log('Synced #{} ({!r}) with master.'.format(pr.pull_id, pr.title))
        return True

    if response.status_code == 204:
        # Already merged.
        return False

    if response.status_code == 409:
        # Merge conflict.
        return CannotAutomergeError("There's a merge conflict.")

    if response.status_code == 403:
        # Permission denied.
        return CannotAutomergeError(
            "Spurious failure. Github API requires me to be an admin on the "
            "fork repository to merge master into the PR branch. Hit "
            "'Update Branch' for me before trying again.")

    raise RuntimeError('Sync with master failed for unknown reason. '
                       'Code: {}. Content: {}.'.format(response.status_code,
                                                       response.content))
1088642
def get_filtered_pull_requests(pull_requests)
      pull_requests = filter_array_by_labels(pull_requests)
      pull_requests = filter_merged_pull_requests(pull_requests)
      puts "Filtered pull requests: #{pull_requests.count}" if options[:verbose]
      pull_requests
    end
887799
def request_fetch(self, user, repo, request, pull=False, force=False): #pragma: no cover
        '''
        '''
        raise NotImplementedError
965234
def merge_versioned(releases, schema=None, merge_rules=None):
    
    if not merge_rules:
        merge_rules = get_merge_rules(schema)

    merged = OrderedDict()
    for release in sorted(releases, key=lambda release: release['date']):
        release = release.copy()

        # Don't version the OCID.
        ocid = release.pop('ocid')
        merged[('ocid',)] = ocid

        releaseID = release['id']
        date = release['date']
        # Prior to OCDS 1.1.4, `tag` didn't set "omitWhenMerged": true.
        tag = release.pop('tag', None)

        flat = flatten(release, merge_rules)
        processed = process_flattened(flat)

        for key, value in processed.items():
            # If value is unchanged, don't add to history.
            if key in merged and value == merged[key][-1]['value']:
                continue

            if key not in merged:
                merged[key] = []

            merged[key].append(OrderedDict([
                ('releaseID', releaseID),
                ('releaseDate', date),
                ('releaseTag', tag),
                ('value', value),
            ]))

    return unflatten(merged, merge_rules)
413061
def created_at(self):
        
        if self._created_at:
            return self._created_at
        elif not self.abstract:
            return self.read_meta()._created_at

        raise EmptyDocumentException()