Github redirects users back to this URL when t
556482
public function githubCallback()
    {
        $code   = $this->getParam('code', null);
        $github = $this->settings['phpci']['github'];

        if (!is_null($code)) {
            $http   = new HttpClient();
            $url    = 'https://github.com/login/oauth/access_token';
            $params = array('client_id' => $github['id'], 'client_secret' => $github['secret'], 'code' => $code);
            $resp   = $http->post($url, $params);

            if ($resp['success']) {
                parse_str($resp['body'], $resp);

                $this->settings['phpci']['github']['token'] = $resp['access_token'];
                $this->storeSettings();

                $response = new b8\Http\Response\RedirectResponse();
                $response->setHeader('Location', PHPCI_URL . 'settings?linked=1');
                return $response;
            }
        }

        $response = new b8\Http\Response\RedirectResponse();
        $response->setHeader('Location', PHPCI_URL . 'settings?linked=2');
        return $response;
    }
1049784
def oauth_only(function):
    """"""

    def check_for_oauth(self, *args, **kwargs):
        """
        Returns False if GitHubTools instance is not authenticated, or return
        the decorated fucntion if it is.
        """
        if not self.is_authenticated:
            self.oops("To use putgist you have to set your GETGIST_TOKEN")
            self.oops("(see `putgist --help` for details)")
            return False
        return function(self, *args, **kwargs)

    return check_for_oauth
7202
function(url, branch) {
  this.url = url;
  if (url.startsWith('https://api.github.com/repos/')) {
    this.path = url.substring(29);
    this.apiUrl = url;
  }
  else if (url.startsWith('https://github.com/')) {
    this.path = url.substring(19);
    this.apiUrl = 'https://api.github.com/repos/' + this.path;
  }
  else {
    throw new Error('Unsupported URL format: ' + url);
  }
  
  this.branch = branch ? branch : 'master';
  
  if (typeof window === 'undefined') {
    this.request = require('request');
    this.requestOptions = {headers: {'User-Agent': 'limberest'}};
  } 
  else {
    this.request = require('browser-request');
    this.requestOptions = {};
  }
}
733620
def get_auth():
    """"""
    import getpass
    user = input("User Name: ")  # noqa
    pswd = getpass.getpass('Password: ')
    return Github(user, pswd)
962034
def authorize_url(self, state=None):
        '''
        
        '''
        if not self._client_id:
            raise ApiAuthError('No client id.')
        kw = dict(client_id=self._client_id)
        if self._redirect_uri:
            kw['redirect_uri'] = self._redirect_uri
        if self._scope:
            kw['scope'] = self._scope
        if state:
            kw['state'] = state
        return 'https://github.com/login/oauth/authorize?%s' % _encode_params(kw)
884516
async function initRepo({ repository, token, endpoint, gitFs, localDir }) {
  const opts = hostRules.find({ platform: 'gitlab' }, { token, endpoint });
  if (!opts.token) {
    throw new Error(`No token found for GitLab repository ${repository}`);
  }
  hostRules.update({ ...opts, platform: 'gitlab', default: true });
  config = {};
  get.reset();
  config.repository = urlEscape(repository);
  config.gitFs = gitFs;
  config.localDir = localDir;
  let res;
  try {
    res = await get(`projects/${config.repository}`);
    if (res.body.archived) {
      logger.info(
        'Repository is archived - throwing error to abort renovation'
      );
      throw new Error('archived');
    }
    if (res.body.default_branch === null) {
      throw new Error('empty');
    }
    config.defaultBranch = res.body.default_branch;
    config.baseBranch = config.defaultBranch;
    logger.debug(`${repository} default branch = ${config.baseBranch}`);
    // Discover our user email
    config.email = (await get(`user`)).body.email;
    logger.debug('Bot email=' + config.email);
    delete config.prList;
    // istanbul ignore if
    if (config.gitFs) {
      logger.debug('Enabling Git FS');
      const { host } = URL.parse(opts.endpoint);
      const url = GitStorage.getUrl({
        gitFs,
        auth: 'oauth2:' + opts.token,
        hostname: host || 'gitlab.com',
        repository,
      });
      config.storage = new GitStorage();
      await config.storage.initRepo({
        ...config,
        url,
      });
    } else {
      config.storage = new Storage();
      await config.storage.initRepo(config);
    }
    await Promise.all([getPrList(), getFileList()]);
  } catch (err) /* istanbul ignore next */ {
    logger.debug('Caught initRepo error');
    if (err.message.includes('HEAD is not a symbolic ref')) {
      throw new Error('empty');
    }
    if (['archived', 'empty'].includes(err.message)) {
      throw err;
    }
    if (err.statusCode === 403) {
      throw new Error('forbidden');
    }
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    logger.info({ err }, 'Unknown GitLab initRepo error');
    throw err;
  }
  return {};
}
1151730
def _github_count(self, url):
        
        url = self.url_api + url + "&per_page=1"
        # if we have authentication details use them as we get better
        # rate-limiting.
        if self.username and self.auth_token:
            auth = (self.username, self.auth_token)
        else:
            auth = None
        try:
            info = self.py3.request(url, auth=auth)
        except (self.py3.RequestException):
            return
        if info and info.status_code == 200:
            return int(info.json()["total_count"])
        if info.status_code == 422:
            if not self.repo_warning:
                self.py3.notify_user("Github repo cannot be found.")
                self.repo_warning = True
        return "?"
1209626
function checkUrl(link, baseUrl, cache, options, retry)
{
	var cached;
	
	if (retry === undefined)
	{
		if (isString(link) === true)
		{
			link = linkObj(link);
			linkObj.resolve(link, baseUrl, options);
		}
		
		// TODO :: move out to an `linkObj.invalidate()` to share with `HtmlChecker()` ?
		if (link.url.resolved === null)
		{
			link.broken = true;
			link.brokenReason = "BLC_INVALID";
			linkObj.clean(link);
			return Promise.resolve(link);
		}
		
		cached = cache.get(link.url.parsed);
		
		if (cached !== undefined)
		{
			return Promise.resolve(cached).then( function(response)
			{
				// Cloned to avoid unexpected mutations as a result of user changes
				response = extend({}, response);
				
				copyResponseData(response, link, options);
				
				link.http.cached = true;
				
				return link;
			});
		}
	}
	
	var request = bhttp.request(link.url.resolved,  // TODO :: https://github.com/joepie91/node-bhttp/issues/3
	{
		discardResponse: true,
		headers: { "user-agent":options.userAgent },
		method: retry!==405 ? options.requestMethod : "get"
	})
	.then( function(response)
	{
		response = simpleResponse(response);
		
		if (response.statusCode===405 && options.requestMethod==="head" && options.retry405Head===true && retry!==405)
		{
			// Retry possibly broken server with "get"
			return checkUrl(link, baseUrl, cache, options, 405);
		}
		
		// TODO :: store ALL redirected urls in cache
		if (options.cacheResponses===true && response.url!==link.url.resolved)
		{
			cache.set(response.url, response);  // TODO :: store `request` instead to be consistent?
		}
		
		return response;
	})
	.catch( function(error)
	{
		// The error will be stored as a response
		return error;
	});
	
	if (retry === undefined)
	{
		// Send response to cache -- it will be available to `cache.get()` before being resolved
		if (options.cacheResponses === true)
		{
			cache.set(link.url.parsed, request);
		}
		
		// Send linkObj to caller
		return request.then( function(response)
		{
			copyResponseData(response, link, options);
			
			link.http.cached = false;
			
			return link;
		});
	}
	else
	{
		return request;
	}
}
406433
function getFileUrl (repo, path, sha, line) {
  var url = "https://github.com/" + repo + "/blob/";

  if (sha) {
    url += sha + "/";
  }

  url += path;

  if (line) {
    url += "#L" + line;
  }

  return url;
}
770971
def ask_github_password(username = nil)
      username ||= github_username
      print "Github password for #{username} (never stored): "
      if $stdin.tty?
        password = askpass
        puts ''
        password
      else
        # in testing
        $stdin.gets.chomp
      end
    rescue Interrupt
      abort
    end
290790
def _load_github_hooks(github_url='https://api.github.com'):
    
    try:
        resp = requests.get(github_url + '/meta')
        if resp.status_code == 200:
            return resp.json()['hooks']
        else:
            if resp.headers.get('X-RateLimit-Remaining') == '0':
                reset_ts = int(resp.headers['X-RateLimit-Reset'])
                reset_string = time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                             time.gmtime(reset_ts))
                raise ServiceUnavailable('Rate limited from GitHub until ' +
                                         reset_string)
            else:
                raise ServiceUnavailable('Error reaching GitHub')
    except (KeyError, ValueError, requests.exceptions.ConnectionError):
        raise ServiceUnavailable('Error reaching GitHub')
208624
def _submit_to_github(self):
        """"""
        # Get reference to the main window
        if self.parent() is not None:
            if getattr(self.parent(), 'main', False):
                # This covers the case when the dialog is attached
                # to the internal console
                main = self.parent().main
            else:
                # Else the dialog is attached to the main window
                # directly
                main = self.parent()
        else:
            main = None

        # Getting description and traceback
        title = self.title.text()
        description = self.input_description.toPlainText()
        traceback = self.error_traceback[:-1]  # Remove last EOL

        # Render issue
        if main is not None:
            issue_text = main.render_issue(description=description,
                                           traceback=traceback)
        else:
            issue_text = description

        try:
            if main is None:
                org = 'ccordoba12'
            else:
                org = 'spyder-ide'
            github_backend = GithubBackend(org, 'spyder', parent_widget=main)
            github_report = github_backend.send_report(title, issue_text)
            if github_report:
                self.close()
        except Exception:
            ret = QMessageBox.question(
                      self, _('Error'),
                      _("An error occurred while trying to send the issue to "
                        "Github automatically. Would you like to open it "
                        "manually?<br><br>"
                        "If so, please make sure to paste your clipboard "
                        "into the issue report box that will appear in a new "
                        "browser tab before clicking <i>Submit</i> on that "
                        "page."))
            if ret in [QMessageBox.Yes, QMessageBox.Ok]:
                QApplication.clipboard().setText(issue_text)
                issue_body = (
                    " \n<!---   *** BEFORE SUBMITTING: PASTE CLIPBOARD HERE "
                    "TO COMPLETE YOUR REPORT ***   ---!>\n")
                if main is not None:
                    main.report_issue(body=issue_body, title=title,
                                      open_webpage=True)
                else:
                    pass
872375
def validate(self, url):
        ''' 
        '''

        # Preview must provide the live URL of the repository
        if not url.startswith('http') or not 'github' in url:
            bot.error('Test of preview must be given a Github repostitory.')
            return False

        if not self._validate_preview(url):
            return False

        return True
1248061
function parseGithubURL(url) {
  var githubUrlRe = /github\.com\/([^/]+)\/([^/]+)\/pull\/([0-9]+)/;
  var match = url.match(githubUrlRe);

  if (!match) {
    return null;
  }

  return {
    owner: match[1],
    repo: match[2],
    number: match[3]
  };
}
1062991
def github_request(self, path, callback, access_token=None,
                       post_args=None, **kwargs):
        
        url = self._API_URL + path
        all_args = {}
        if access_token:
            all_args["access_token"] = access_token
            all_args.update(kwargs)
        if all_args:
            url += "?" + auth.urllib_parse.urlencode(all_args)
        callback = self.async_callback(self._on_github_request, callback)
        http = self._get_auth_http_client()
        if post_args is not None:
            http.fetch(url, method="POST",
                       user_agent='Tinman/Tornado',
                       body=auth.urllib_parse.urlencode(post_args),
                       callback=callback)
        else:
            http.fetch(url, user_agent='Tinman/Tornado', callback=callback)
932292
def _raise_redirect_exceptions(response):
    
    if response.status_code not in [301, 302, 307]:
        return None
    new_url = urljoin(response.url, response.headers['location'])
    if 'reddits/search' in new_url:  # Handle non-existent subreddit
        subreddit = new_url.rsplit('=', 1)[1]
        raise InvalidSubreddit('`{0}` is not a valid subreddit'
                               .format(subreddit))
    elif not RE_REDIRECT.search(response.url):
        raise RedirectException(response.url, new_url)
    return new_url
249403
def _remote_github_url_to_string(remote_url):
    """"""
    # TODO: make this work with https URLs
    match = re.search('git@github\.com:(.*)\.git', remote_url)
    if not match:
        raise EnvironmentError('Remote is not a valid github URL')
    identifier = match.group(1)
    return re.sub('\W', ':', identifier)