/* Parse a link and determine whether it links to GitHub.
960276
function parse(node) {
  var link = {}
  var url = node.url || node.href || ''
  var start
  var end
  var page

  if (
    url.slice(0, GH_URL_PREFIX_LENGTH) !== GH_URL_PREFIX ||
    node.children.length !== 1 ||
    node.children[0].type !== 'text' ||
    toString(node).slice(0, GH_URL_PREFIX_LENGTH) !== GH_URL_PREFIX
  ) {
    return
  }

  start = GH_URL_PREFIX_LENGTH
  end = usernameEnd(url, GH_URL_PREFIX_LENGTH)

  if (end === -1 || url.charCodeAt(end) !== CC_SLASH) {
    return
  }

  link.user = url.slice(start, end)

  start = end + 1
  end = projectEnd(url, start)

  if (end === -1 || url.charCodeAt(end) !== CC_SLASH) {
    return
  }

  link.project = url.slice(start, end)

  start = end + 1
  end = url.indexOf('/', start)

  if (end === -1) {
    return
  }

  page = url.slice(start, end)

  if (page !== parse.COMMIT && page !== parse.ISSUE && page !== parse.PULL) {
    return
  }

  link.page = page
  start = end + 1

  if (page === parse.COMMIT) {
    end = shaEnd(url, start, true)
  } else {
    end = issueEnd(url, start)
  }

  if (end === -1) {
    return
  }

  link.reference = url.slice(start, end)
  link.comment = url.charCodeAt(end) === CC_HASH && url.length > end + 1

  return link
}
473126
function resolveLink(srcUrl, targetUrl) {
  // Parse the src URL
  var srcUrlObj = url.parse(srcUrl);

  // If there isn't a protocol
  // DEV: `node@0.8` has this as `undefined`, `node@0.10` has this as `null`
  if (!srcUrlObj.protocol) {
    // With no protocol, we have everything in pathname. Add on `//` and force treatment of `host`
    var tmpSrcUrl = '//' + srcUrl;
    var tmpSrcUrlObj = url.parse(tmpSrcUrl, null, true);

    // If this new hostname has a TLD, then keep it as the srcUrlObj
    // DEV: We are trading accuracy for size (technically not all dots mean a tld
    //   If we want to be accurate, use https://github.com/ramitos/tld.js/blob/305a285fd8f5d618417178521d8729855baadb37/src/tld.js
    if (tmpSrcUrlObj.hostname && tldRegexp.test(tmpSrcUrlObj.hostname)) {
      srcUrl = tmpSrcUrl;
      srcUrlObj = tmpSrcUrlObj;
    }
  }

  // Fallback pathname
  srcUrlObj.pathname = srcUrlObj.pathname || '/';

  // If we still have no protocol
  // DEV: `node@0.8` has this as `undefined`, `node@0.10` has this as `null`
  if (!srcUrlObj.protocol) {
    // Parse our targetUrl
    var targetUrlObj = url.parse(targetUrl);

    // If there is a hostname
    // DEV: `node@0.8` has this as `undefined`, `node@0.10` has this as `null`
    if (srcUrlObj.hostname) {
      // If the hostname is the same as our original, add on a protocol
      if (srcUrlObj.hostname === targetUrlObj.hostname) {
        srcUrlObj.protocol = targetUrlObj.protocol;
      // Otherwise, default to HTTP
      } else {
        srcUrlObj.protocol = 'http:';
      }
    // Otherwise, pickup the target protocol and hostname
    } else {
      srcUrlObj.protocol = targetUrlObj.protocol;
      srcUrlObj.hostname = targetUrlObj.hostname;
    }
  }

  // Return our completed src url
  return url.format(srcUrlObj);
}
326485
function parseRepoURL(inputUrl) {
  if (!inputUrl) {
    throw new ServerlessError('URL is required');
  }

  const url = URL.parse(inputUrl.replace(/\/$/, ''));

  // check if url parameter is a valid url
  if (!url.host) {
    throw new ServerlessError('The URL you passed is not a valid URL');
  }

  switch (url.hostname) {
    case 'github.com': {
      return parseGitHubURL(url);
    }
    case 'bitbucket.org': {
      return parseBitbucketURL(url);
    }
    case 'gitlab.com': {
      return parseGitlabURL(url);
    }
    default: {
      const msg =
        'The URL you passed is not one of the valid providers: "GitHub", "Bitbucket", or "GitLab".';
      throw new ServerlessError(msg);
    }
  }
}
1006115
function parseSpans(text) {
		var links = parseLinks(text);
		/*Represented as
		[{
		href: "http://yada",
		start: startIndex,
		end: endIndex
		}]*/
		var spans = [];
		var lastSpan = null;
		
		function isPrefixedLinkSpan(span)
		{
			return span && "href" in span && span.prefix && "proposed" in span.prefix;
		}
		
		function isTextSpan(span)
		{
			return span && !("href" in span);
		}
		
		function addTextSpan(text) {
			//if the last span was a candidate
			if (isPrefixedLinkSpan(lastSpan)) {
				//make sure there is a valid suffix
				if (regexen.matchMarkdownLinkSuffix.test(text))	{
					//is there any valid whitespace remaining?
					text = RegExp.$3;
					//use the title (if specified)
					if (RegExp.$2) {
						lastSpan.title = RegExp.$2;
					}
					//use the proposed link text for the verified link
					lastSpan.text = lastSpan.prefix.proposed.linkText;
					
					//if there was valid prefix text, use it
					if (lastSpan.prefix.proposed.text) {
						lastSpan.prefix.text = lastSpan.prefix.proposed.text;
						delete lastSpan.prefix["proposed"]; //clean up proposal	
					}
					else {
						spans.splice(spans.length - 2, 1); //remove prefix
						lastSpan = lastSpan.prefix;
					}
				}
				else {
					delete lastSpan.prefix["proposed"]; //clean up proposal...no match...no modification
				}
				delete lastSpan["prefix"]; //clean up prefix scratchwork
			}
			if (text) {
				lastSpan = {
					text : text
				};
				spans.push(lastSpan);
			}
		}
		
		function addLinkSpan(linkSpan) {
			var span = {
				href : linkSpan.href
			};

			if (isTextSpan(lastSpan) && regexen.matchMarkdownLinkPrefix.test(lastSpan.text))	{
				lastSpan.proposed = { text: RegExp.$1, linkText: RegExp.$2 };
				span.prefix = lastSpan;
			}
		
			lastSpan = span;
			spans.push(lastSpan);
		}
		
		//No links found, all text
		if (links.length === 0) {
			addTextSpan(text);
		} 
		//One or more links found
		else {
			var firstLink = links[0],
			lastLink = links[links.length - 1];
			
			//Was there text before the first link?
			if (firstLink.start > 0) {
				addTextSpan(text.substring(0, firstLink.start));
			}
			//Handle single link
			if (links.length === 1) {
				addLinkSpan(firstLink);
			} else {
				//push the firstLink
				addLinkSpan(firstLink);
				var prevLink = firstLink;
				
				//loop from the second
				for (var i = 1; i < links.length; i++) {
					//is there text between?
					if (links[i].start - prevLink.end >= 1) {
						addTextSpan(text.substring(prevLink.end, links[i].start));
					}
					//add link
					addLinkSpan(prevLink = links[i]);
				}
			}
			//Was there text after the links?
			if (lastLink.end < (text.length)) {
				addTextSpan(text.substring(lastLink.end));
			}
		}
		return spans;
	}
570551
function isUrl (obj) {
    if(isString(obj)){
        if((obj.indexOf('http://') > -1 || obj.indexOf('https://') > -1) 
        	&& obj.indexOf('.') > -1)
        	return true
        else
        	return false
    }else{
        return false;
    }
}
748587
function(inlines) {
  if (this.match(/^!/)) {
    var n = this.parseLink(inlines);
    if (n === 0) {
      inlines.push({ t: 'Str', c: '!' });
      return 1;
    } else if (inlines[inlines.length - 1] &&
               inlines[inlines.length - 1].t == 'Link') {
      inlines[inlines.length - 1].t = 'Image';
      return n+1;
    } else {
      throw "Shouldn't happen";
    }
  } else {
    return 0;
  }
}
1033548
def is_likely_link(text):
    '''
    '''
    text = text.lower()

    # Check for absolute or relative URLs
    if (
        text.startswith('http://')
        or text.startswith('https://')
        or text.startswith('ftp://')
        or text.startswith('/')
        or text.startswith('//')
        or text.endswith('/')
        or text.startswith('../')
    ):
        return True

    # Check if it has a alphanumeric file extension and not a decimal number
    dummy, dot, file_extension = text.rpartition('.')

    if dot and file_extension and len(file_extension) <= 4:
        file_extension_set = frozenset(file_extension)

        if file_extension_set \
           and file_extension_set <= ALPHANUMERIC_CHARS \
           and not file_extension_set <= NUMERIC_CHARS:
            if file_extension in COMMON_TLD:
                return False

            file_type = mimetypes.guess_type(text, strict=False)[0]

            if file_type:
                return True
            else:
                return False
428604
function parseVersion(str) {
  var match = /git version ([0-9\.]+)/.exec(str);

  if (match) {
    return match[1];
  } else {
    throw new Error('Unable to parse version response', str);
  }
}
129488
function parseHref(href) {
  var match = str(href).match(/([^#]*)(#.*)/);
  if (!match) return { path:href };
  return { path:match[1], fragment:match[2] };
}
1198987
function dependencyMatch (expected, actual) {
  // expand github:user/repo#hash to git://github.com/...
  if (expected.indexOf('github:') === 0) {
    expected = expected.replace(/^github:/, 'git://github.com/')
    var parsed = url.parse(expected)
    parsed.pathname += '.git'
    expected = url.format(parsed)
  }

    // normalize git+https prefix
  actual = actual.replace(/^git\+https/, 'git')
  expected = expected.replace(/^git\+https/, 'git')

  expected = ngu(expected)
  actual = ngu(actual)

  expected.url = expected.url.replace('https://', 'git://')
  actual.url = actual.url.replace('https://', 'git://')

  if (expected.url !== actual.url) {
    return false
  }

  if (actual.branch && actual.branch.indexOf(expected.branch) !== 0) {
    return false
  }

  return true
}
952774
function parseSshGitUrl(gitUrl){
		try {
			/* try ssh:// protocol */
			var url = new URL(gitUrl);
			return {
				host : url.hostname,
				port : url.port
			};
					
		} catch(e){
			/* try scp-like uri */
			try {
				/* [user@]host.xz:path/to/repo.git/ */
				var scp = gitUrl.split(":"); //$NON-NLS-0$
				var hostPart = scp[0].split("@"); //$NON-NLS-0$
				var host = hostPart.length > 1 ? hostPart[1] : hostPart[0];
				return {
					host : host,
					port : 22
				};
				
			} catch(ex){
				/* admit failure */
				return {
					host : "",
					port : ""
				};
			}
		}
	}
1192956
function toRepoUrl(url) {
  if (url.startsWith('git@')) {
    if (argv.useSSH) {
      return url;
    }
    // have an ssh url need an http url
    const m = url.match(/(https?:\/\/([^/]+)\/|git@(.+):)([\w\d-_/]+)(.git)?/);
    return `https://${m[3]}/${m[4]}.git`;
  }
  if (url.startsWith('http')) {
    if (!argv.useSSH) {
      return url;
    }
    // have a http url need an ssh url
    const m = url.match(/(https?:\/\/([^/]+)\/|git@(.+):)([\w\d-_/]+)(.git)?/);
    return `git@${m[2]}:${m[4]}.git`;
  }
  if (!url.includes('/')) {
    url = `Caleydo/${url}`;
  }
  if (argv.useSSH) {
    return `git@github.com:${url}.git`;
  }
  return `https://github.com/${url}.git`;
}
173232
def parse_apidoc(
    file_or_branch,
    from_github=False,
    save_github_version=True
) -> List['ApiEndpoint']:
    """"""
    apis = []  # type: List[ApiEndpoint]
    regex = r'(?P<group>\([^)]*\)){0,1} *(?P<type_>{[^}]*}){0,1} *'
    regex += r'(?P<field>[^ ]*) *(?P<description>.*)$'
    param_regex = re.compile(r'^@apiParam {1,}' + regex)
    success_regex = re.compile(r'^@apiSuccess {1,}' + regex)
    if from_github:
        text = download_api(file_or_branch)
        if save_github_version:
            save_apidoc(text)
    else:
        with open(file_or_branch) as f:
            text = f.read()
    for line in text.split('\n'):
        line = line.replace('\n', '')
        if line.startswith('@api '):
            if apis:
                if not apis[-1].retcode:
                    apis[-1].retcode = 200
            split_line = line.split(' ')
            assert len(split_line) >= 3
            method = split_line[1]
            uri = split_line[2]
            assert method[0] == '{'
            assert method[-1] == '}'
            method = method[1:-1]
            if not uri.startswith(API_URI_BASE):
                warnings.warn(_("Wrong api url: {}").format(uri))  # noqa: Q000
            title = ' '.join(split_line[3:])
            apis.append(ApiEndpoint(method, uri, title))
        elif line.startswith('@apiParam '):
            res = next(param_regex.finditer(line)).groupdict()
            apis[-1].add_param(**res)
        elif line.startswith('@apiSuccess '):
            res = next(success_regex.finditer(line)).groupdict()
            apis[-1].add_success(**res)
    if apis:
        if not apis[-1].retcode:
            apis[-1].retcode = 200
    return apis
817538
function parseLinks(target, resp) {
  target._links = parseLinkHeader(resp.headers.get('link'));
  target._linkTemplates = parseLinkHeader(resp.headers.get('link-template'));
  return resp
}
147623
def linkcode_resolve(domain, info):
    
    if domain != 'py':
        return None

    modname = info['module']
    fullname = info['fullname']

    submod = sys.modules.get(modname)
    if submod is None:
        return None

    obj = submod
    for part in fullname.split('.'):
        try:
            obj = getattr(obj, part)
        except:
            return None
    if hasattr(obj, '__wrapped__'):
        obj = obj.__wrapped__

    try:
        fn = inspect.getsourcefile(obj)
    except:
        fn = None
    if not fn:
        return None

    try:
        _, lineno = inspect.findsource(obj)
    except:
        lineno = None

    if lineno:
        linespec = "#L%d" % (lineno + 1)
    else:
        linespec = ""

    fn = os.path.relpath(fn, start=os.path.dirname(fuel.__file__))

    github = "https://github.com/mila-udem/fuel/blob/master/fuel/{}{}"
    return github.format(fn, linespec)
432933
function ensureUrl (v) {
  if (typeof v === 'string') {
    return url.parse(v)
  } else if (v instanceof url.Url) {
    return v
  } else if (url.URL && v instanceof url.URL) { // check for url.URL because it wasn't added until Node.js 6.13.0
    return url.parse(v.toString())
  } else {
    return v
  }
}
385581
def parse_link(link_str):
    
    atts = {}
    help_str = "--link option '%s' (format rel,href,att1=val1...)" % (link_str)
    try:
        segs = link_str.split(',')
        # First segments are relation and subject
        atts['rel'] = segs.pop(0)
        atts['href'] = segs.pop(0)
        if (atts['href'] == ''):
            raise ClientFatalError("Missing uri in " + help_str)
        # Remaining segments are attributes
        for term in segs:
            (k, v) = term.split('=')
            if (k == '' or v == ''):
                raise ClientFatalError(
                    "Bad attribute (%s) in " %
                    (term) + help_str)
            atts[k] = v
    except ValueError as e:
        raise ClientFatalError("Bad component of " + help_str)
    except IndexError as e:
        raise ClientFatalError("Incomplete component of " + help_str)

    return(atts)