python类Github()的实例源码

classifier.py 文件源码 项目:ClassifyHub 作者: Top-Ranger 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def _get_entry(self, languages, known_languages):
        entry = []
        for language in known_languages:
            if language in languages:
                entry += [languages[language]]
            else:
                entry += [0]
        sum_entry = sum(entry)
        if sum_entry != 0:
            entry = [x / sum_entry for x in entry]
        return entry

    ##
    # \brief Classifies the reoisitory based on the learned <em>Decision Tree</em>.
    #
    # \param data GitHub repository as github.Github object.
    # \return Dictionary {CLASS: PROBABILITY}, where CLASS is a string containing the class label and
    #         PROBABILITY is a float in [0.0, 1.0] containing the probability that the repository belongs to the class.
test_classifier.py 文件源码 项目:ClassifyHub 作者: Top-Ranger 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def setUp(self):
        # setup config
        configserver._CONGIF['maximum_cache_age'] = 366000 # About 1000 years
        configserver._CONGIF['cache_path'] = './tests/cache'
        configserver._CONGIF['model_path'] = './tests/models'

        self.classifier = classifier.get_all_classifiers()
        self.github_list = [github.Github('Top-Ranger', 'kana-keyboard'),
                            github.Github('Top-Ranger', 'CHI2016-SUR-datasets'),
                            github.Github('Top-Ranger', 'SPtP_learningdb'),
                            github.Github('Top-Ranger', 'SUR213'),
                            github.Github('Top-Ranger', 'bakery'),
                            github.Github('Top-Ranger', 'fooling_dnn'),
                            github.Github('Top-Ranger', 'harbour-hiragana'),
                            github.Github('Top-Ranger', 'harbour-katakana'),
                            github.Github('Top-Ranger', 'harbour-reversi'),
                            github.Github('Top-Ranger', 'qnn'),
                            github.Github('Top-Ranger', 'SPtP')]
protocols.py 文件源码 项目:gitorg 作者: mariocj89 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def __init__(self, *, api_url=_DEFAULT_BASE_URL, clone_protocol="ssh", **kwargs):
        super().__init__(**kwargs)
        self._clone_protocol = self.CloneProtocol(clone_protocol)
        self._gh = github.Github(
            login_or_token=os.environ.get("GITHUB_TOKEN"),
            base_url=api_url
        )
pr_from_new_release.py 文件源码 项目:mattermost-openshift 作者: goern 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def create_pr_to_master(target_branch):
    """create a github pr from target_branch to master"""
    git = Github(os.environ.get('GITHUB_ACCESS_TOKEN'))
    repo = git.get_user().get_repo('mattermost-openshift')

    print(repo.pulls_url)

    repo.create_pull('automated update',
                     'This PR is generated as part of an automated update triggered by a new Mattermost release.', 'master', target_branch)
statuspage.py 文件源码 项目:statuspage 作者: jayfk 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_repo(token, name, org):
    gh = Github(token)
    if org:
        return gh.get_organization(org).get_repo(name=name)
    return gh.get_user().get_repo(name=name)
index.py 文件源码 项目:commit-telegram-bot 作者: BetaF1sh 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def handle(self):
        client = Github(self.username, self.password)
        today_commit_events = get_today_commit_events(client.get_user(self.username))

        if len(today_commit_events) == 0:
            return False
        else:
            return True
tfgithub.py 文件源码 项目:aws-lambda-github-webhook 作者: chuyskywalker 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def get_github():
    with open(os.path.join(os.path.dirname(__file__), "..", "ghtoken.txt")) as f:
        ghtoken = f.read().strip()
    return github.Github(ghtoken)
repo.py 文件源码 项目:rellu 作者: robotframework 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_repository(name, username=None, password=None, auth_required=False):
    username = username or os.getenv('GITHUB_USERNAME')
    password = password or os.getenv('GITHUB_PASSWORD')
    if auth_required and not (username and password):
        raise Exit('Mandatory GitHub username/password not given.')
    return Github(username, password).get_repo(name)
get_git_month_log.py 文件源码 项目:minitools 作者: tiberiuichim 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def main():

    parser = ArgumentParser(description="Retrieve Github activity")
    parser.add_argument('month', type=int, help='Month for activity log')
    args = parser.parse_args()
    g = Github(GITHUB_USERNAME, GITHUB_PASS)
    usr = g.get_user(GITHUB_USERNAME)

    year = datetime.now().year
    this = (year, int(args.month))
    tpl = "{0} - {1}: {2}"

    for event in usr.get_public_events():
        # go back in history until the start date is reached
        if event.type != u"PushEvent":
            continue

        if month(event.created_at.date()) > this:
            continue
        # if month(event.created_at.date()) < this:
        #     break

        repo_url = event._repo.value.html_url
        if not is_work_repo(repo_url):
            continue
        repo = repo_url.split('/')[-1]
        commits = event.payload['commits']
        for commit in commits:
            if GITHUB_AUTHOR not in commit['author']['name'].lower():
                continue

            print(tpl.format(event.created_at.date(),
                             repo,
                             commit['message']))
git.py 文件源码 项目:yoda 作者: yoda-pa 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def process(input):
    gh_username = setup.get_gh_username()
    gh_password = setup.decrypt_password()
    gh = github.Github(gh_username, gh_password)
    click.echo(chalk.blue('you are in git module'))
    click.echo('input = %s' % input)
    USER_CONFIG_FILE_PATH = get_config_file_paths()['USER_CONFIG_FILE_PATH']
    USER_CONFIG_FOLDER_PATH = get_folder_path_from_file_path(USER_CONFIG_FILE_PATH)
    repo = porcelain.init(USER_CONFIG_FOLDER_PATH)
    porcelain.add(repo)
    porcelain.commit(repo, "A sample commit")
    porcelain.remote_add(repo, ".yoda", "https://github.com/manparvesh/.yoda")
    porcelain.push(repo, "https://github.com/manparvesh/.yoda")
epithet.py 文件源码 项目:epithet 作者: phildini 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_repos(key, org, repo, url):
    if url:
        g = Github(key, base_url=url)
    else:
        g = Github(key)
    if org:
        g_org = g.get_organization(login=org)
    else:
        g_org = g.get_user()

    if repo:
        repos = [g_org.get_repo(repo)]
    else:
        repos = g_org.get_repos()
    return repos
pullrequest.py 文件源码 项目:github-reviewboard-sync 作者: Apptimize-OSS 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _get_current_repo(github, repo, remote='origin'):
    """
    Gets the github repo associated with the
    provided repo

    :param Github github:
    :param Repo repo:
    :param unicode remote:
    :return: The github repository assocated with
        the provided repo
    :rtype: github.Repository.Repository
    """
    owner, repo = _get_org_and_name_from_remote(repo.remotes[remote])
    return github.get_repo('{0}/{1}'.format(owner, repo))
pullrequest.py 文件源码 项目:github-reviewboard-sync 作者: Apptimize-OSS 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _instantiate_github(username):
    """
    Gets a github object that has been authenticated.
    If authentication fails it asks the user for their
    password agains

    :param unicode username:
    :rtype: Github
    """
    password = get_github_password(username)
    count = 0
    while True:
        count += 1
        github = Github(login_or_token=username, password=password)
        try:
            auth = github.get_user().create_authorization(
                scopes=['repo'],
                note='github-reviewboard-sync {0}'.format(str(uuid4())))
            return github, auth
        except BadCredentialsException as exc:
            _LOG.error('The password was not valid for "{0}"'.format(username))
            if count == 3:
                raise AuthenticationException('Failed to authenticate three times. '
                                              'Is "{0}" the correct username?'.format(username))
            password = get_github_password(username, refresh=True)
        except TwoFactorException as exc:
            user = github.get_user()
            onetime_password =input('Github 2-Factor code: ')
            authorization = user.create_authorization(
                scopes=['repo'],
                note='github-reviewboard-sync {0}'.format(str(uuid4())),
                onetime_password=onetime_password)
            return Github(authorization.token), authorization
__init__.py 文件源码 项目:telescope 作者: geier 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def main():
    user = os.environ.get('GH_USER') or USER
    logging.info("tracking stars for user {}".format(user))
    logging.info("If this is not your username, change it in the python file")
    user = Github(os.environ.get('GH_TOKEN') or TOKEN or get_token()).get_user(USER)

    for repo in user.get_starred():
        repo_ = {
            'name': repo.full_name,
            'description': repo.description,
            'releases': list(),
        }
        logging.info("getting {}".format(repo.full_name))
        for release in repo.get_releases():
            release_date = parse_date(release.raw_data['published_at'])
            if NOW - release_date < dt.timedelta(days=DAYS):
                repo_['releases'].append(release.raw_data)
            else:
                break  # TODO XXX we assume, that those releases are ordered
        for tag in repo.get_tags():
            sha = tag.raw_data['commit']['sha']
            commit = repo.get_commit(sha)
            tag_date = parse_date(commit.raw_data['commit']['author']['date'])
            if (NOW - tag_date < dt.timedelta(days=DAYS)):
                if tag.name not in [r['name'] for r in repo_['releases']]:
                    tag.raw_data['tag_name'] = ''
                    tag.raw_data['published_at'] = commit.raw_data['commit']['author']['date']
                    repo_['releases'].append(tag.raw_data)
            else:
                break
        if repo_['releases']:
            print(format_repo(repo_))
gh2md.py 文件源码 项目:gh2md 作者: mattduck 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def parse_args(args):
    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument(
        'repo',
        help='Github repo to export, in format "owner/repo_name".',
        type=str,
        action='store',
        # TODO - validate this is in correct format.
    )
    parser.add_argument(
        'outpath',
        help='Path to write exported issues.',
        type=str,
        action='store',
    )
    parser.add_argument(
        '-l',
        '--login',
        help='Prompt to login as this Github user. If provided, this takes '
             'precedence over any token found in the environment. If not '
             'provided and no token is found, you will be prompted to login as '
             'the repository owner.',
        type=str,
        action='store',
        dest='login_user',
    )
    parser.add_argument(
        '-t',
        '--token',
        help='Automatically login with this Github API token. If --login is '
             'provided, this is ignored.',
        type=str,
        action='store',
        dest='token',
    )
    return parser.parse_args(args)
gh2md.py 文件源码 项目:gh2md 作者: mattduck 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def export_issues_to_markdown_file(repo, outpath):
    formatted_issues = []
    for issue in repo.get_issues(state='all'):
        # The Github API includes pull requests as "issues". Skip
        # closed PRs, as they will add a lot of noise to the export.
        try:
            if issue.pull_request and issue.state.lower() == 'closed':
                continue
        except:
            traceback.print_exc()
            print("Caught exception checking whether issue is PR, skipping")
            continue

        # Try multiple times to process the issue and append to main issue list
        try:
            formatted_issue = process_issue_to_markdown(issue)
        except:
            traceback.print_exc()
            print("Couldn't process issue due to exceptions, skipping")
            continue
        else:
            formatted_issues.append(formatted_issue)

    full_markdown_export = templates_markdown.BASE.format(
        repo_name=repo.full_name,
        repo_url=repo.html_url,
        issues="\n".join(formatted_issues),
        date=datetime.datetime.now().strftime('%Y.%m.%d at %H:%M:%S')
    )

    print("Exported {} issues".format(len(formatted_issues)))
    print("Writing to file: {}".format(outpath))
    with open(outpath, 'wb') as out:
        out.write(full_markdown_export.encode('utf-8'))
    return None
gh2md.py 文件源码 项目:gh2md 作者: mattduck 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def github_login(login_user=None, token=None, fallback_user=None):
    assert login_user or token or fallback_user
    per_page = 100

    if login_user:
        password = getpass.getpass("Github password for {} :".format(login_user))
        return Github(login_or_token=login_user, password=password, per_page=per_page)

    if token:
        return Github(login_or_token=token, per_page=per_page)

    password = getpass.getpass("Github password for {} :".format(fallback_user))
    return Github(login_or_token=fallback_user, password=password, per_page=per_page)
gh2md.py 文件源码 项目:gh2md 作者: mattduck 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def print_rate_limit(gh):
    limit = gh.get_rate_limit()
    print("Github API rate limit: {}".format(limit.rate.raw_data))
utils.py 文件源码 项目:charingcross 作者: bfirsh 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def github_from_request(request):
    provider = request.user.social_auth.get(provider='github-org')
    return github.Github(provider.extra_data['access_token'])
github_to_aws_migration.py 文件源码 项目:analytics-platform-ops 作者: ministryofjustice 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def main():
    github = Github(GITHUB_TOKEN)
    org = github.get_organization(GITHUB_ORG)

    for member in org.get_members():
        create_user_role(member.login)

    for team in org.get_teams():
        create_team_bucket(team.slug)
        for member in team.get_members():
            attach_bucket_policy(team.slug, member.login)


问题


面经


文章

微信
公众号

扫码关注公众号