Parses an email URL.
550398
def parse(url):
    """"""

    conf = {}

    url = urlparse.urlparse(url)
    qs = urlparse.parse_qs(url.query)

    # Remove query strings
    path = url.path[1:]
    path = path.split('?', 2)[0]

    # Update with environment configuration
    conf.update({
        'EMAIL_FILE_PATH': path,
        'EMAIL_HOST_USER': unquote(url.username),
        'EMAIL_HOST_PASSWORD': unquote(url.password),
        'EMAIL_HOST': url.hostname,
        'EMAIL_PORT': url.port,
        'EMAIL_USE_SSL': False,
        'EMAIL_USE_TLS': False,
    })

    if url.scheme in SCHEMES:
        conf['EMAIL_BACKEND'] = SCHEMES[url.scheme]

    # Set defaults for `smtp`
    if url.scheme == 'smtp':
        if not conf['EMAIL_HOST']:
            conf['EMAIL_HOST'] = 'localhost'
        if not conf['EMAIL_PORT']:
            conf['EMAIL_PORT'] = 25

    # Set defaults for `smtps`
    if url.scheme == 'smtps':
        warnings.warn(
            "`smpts` scheme will be deprecated in a future version,"
            " use `submission` instead",
            UserWarning,
        )
        conf['EMAIL_USE_TLS'] = True

    # Set defaults for `submission`/`submit`
    if url.scheme in ('submission', 'submit'):
        conf['EMAIL_USE_TLS'] = True
        if not conf['EMAIL_PORT']:
            conf['EMAIL_PORT'] = 587

    # Query args overwrite defaults
    if 'ssl' in qs and qs['ssl']:
        if qs['ssl'][0] in TRUTHY:
            conf['EMAIL_USE_SSL'] = True
            conf['EMAIL_USE_TLS'] = False
    elif 'tls' in qs and qs['tls']:
        if qs['tls'][0] in TRUTHY:
            conf['EMAIL_USE_SSL'] = False
            conf['EMAIL_USE_TLS'] = True

    # From addresses
    if '_server_email' in qs:
        conf['SERVER_EMAIL'] = qs['_server_email'][0]
    if '_default_from_email' in qs:
        conf['DEFAULT_FROM_EMAIL'] = qs['_default_from_email'][0]

    return conf
863324
public Object parse(URL url, String charset) {
        return parseURL(url, null, charset);
    }
77327
def parse_querystring(self, req, name, field):
        """"""
        return core.get_value(req.params, name, field)
75585
def parse_addresses (self):
        
        # cut off leading mailto: and unquote
        url = urllib.unquote(self.base_url[7:])
        # search for cc, bcc, to and store in headers
        mode = 0 # 0=default, 1=quote, 2=esc
        quote = None
        i = 0
        for i, c in enumerate(url):
            if mode == 0:
                if c == '?':
                    break
                elif c in '<"':
                    quote = c
                    mode = 1
                elif c == '\\':
                    mode = 2
            elif mode==1:
                if c == '"' and quote == '"':
                    mode = 0
                elif c == '>' and quote == '<':
                    mode = 0
            elif mode == 2:
                mode = 0
        if i < (len(url) - 1):
            self.addresses.update(getaddresses(url[:i]))
            try:
                headers = urlparse.parse_qs(url[(i+1):], strict_parsing=True)
                for key, vals in headers.items():
                    if key.lower() in EMAIL_CGI_ADDRESS:
                        # Only the first header value is added
                        self.addresses.update(getaddresses(urllib.unquote(vals[0])))
                    if key.lower() == EMAIL_CGI_SUBJECT:
                        self.subject = vals[0]
            except ValueError as err:
                self.add_warning(_("Error parsing CGI values: %s") % str(err))
        else:
            self.addresses.update(getaddresses(url))
        log.debug(LOG_CHECK, "addresses: %s", self.addresses)
568626
def convert(self, value, param, ctx):
        
        rxp = '^[^@]+?@[-.a-z0-9]+$'
        regex = re.compile(rxp, re.I)
        try:
            if regex.match(value):
                value = value.split("@")
                return value
            else:
                self.fail('%s is not a valid email address' % value, param,
                          ctx)
        except ValueError:
            self.fail('%s is not a valid email address' % value, param, ctx)
305521
def parse_url(url):
    
    split_url = url.split('/', 3)
    if len(split_url) == 3:
        # http://foo.com
        path = '/'
    elif len(split_url) == 4:
        path = '/' + split_url[3]
    else:
        raise ValueError('Invalid URL: %s' % url)

    try:
        parse_result = urlparse(url)
    except Exception:
        raise ValueError('Invalid URL: %s' % url)

    protocol = parse_result.scheme
    protocol = protocol.lower()
    if protocol not in ('http', 'https'):
        raise ValueError('Invalid URL protocol "%s"' % protocol)

    split_netloc = parse_result.netloc.split(':')
    domain = split_netloc[0]
    domain = domain.lower()

    if len(split_netloc) == 2:
        try:
            port = int(split_netloc[1])
        except:
            raise ValueError('Invalid port: "%s"' % split_netloc[1])
    elif protocol == 'https':
        port = 443
    elif protocol == 'http':
        port = 80
    else:
        raise ValueError('Invalid scheme: "%s"' % protocol)

    return protocol, domain, port, path
480959
function parseUrl(url, params) {
  var paramsStr = '';

  if (typeof params === 'string') {
    paramsStr = params;
  } else if ((typeof params === 'undefined' ? 'undefined' : _typeof(params)) === 'object') {
    Object.keys(params).forEach(function (key) {
      if (url.indexOf(key + '=') < 0) {
        paramsStr += '&' + key + '=' + encodeURIComponent(params[key]);
      }
    });
  }
  // add a timestampe to remove cache
  paramsStr += '&_time=' + getNow();

  if (paramsStr[0] === '&') {
    paramsStr = paramsStr.substr(1);
  }

  return url + (url.indexOf('?') === -1 ? '?' : '&') + paramsStr;
}
1161348
function parseText(text, options, callback) {
	var out = {
			html: ''
		},
		expanded,
		words,
		x = 0,
		i;

	// is a text string
	if (text && utils.isString(text) && text !== '') {

		// break texts into words
		words = [text];
		if (text.indexOf(' ') > -1) {
			words = text.split(' ');
		}

		// add html links
		i = words.length;
		while (x < i) {
			var cn = options.className,
				word = utils.trim(words[x]);

			// the . is not need for valid url, but is inforced here
			if (word.indexOf('http:') === 0 || word.indexOf('https:') === 0 && word.indexOf('.') > 0) {

				// check url is valid 
				if (validUrl.isUri(word)) {
					if (!out.url) {
						out.url = [];
					}
					expanded = getExpandedUrl(word, options);
					var address = word;
					if (expanded) {
						address = expanded;
						out.url.push({
							match: word,
							expanded: expanded
						});
					} else {
						out.url.push({
							match: word
						});
					}
					words[x] = '<a class="' + cn.auto + ' ' + cn.url + '" href="' + address + '">' + address + '</a>';
				}



			} else if (word.indexOf('@') > 0 && word.indexOf('.') > 0) {

				// check email is valid
				var email = addrs.parseOneAddress(word);
				if (email) {
					delete email.parts;
					delete email.name;
					if (!out.email) {
						out.email = [];
					}
					out.email.push(email);
					words[x] = '<a class="' + cn.auto + ' ' + cn.email + '" href="mailto:' + email.address + '">' + word + '</a>';
				}

			} else if (word.indexOf('@') === 0) {

				if (!out.account) {
					out.account = [];
				}
				out.account.push({
					match: word,
					username: word.replace('@', ''),
					domain: 'twitter.com'
				});
				words[x] = '<a class="' + cn.auto + ' ' + cn.username + '" href="https://twitter.com/' + word.replace('@', '') + '">' + escapeHtml(word, options) + '</a>';


			} else if (word.indexOf('#') === 0) {

				if (!out.category) {
					out.category = [];
				}
				out.category.push(word.replace(/#/g, '').toLowerCase());
				words[x] = '<a class="' + cn.auto + ' ' + cn.tag + '" href="https://twitter.com/search?q=' + word + '&amp;src=hash">' + escapeHtml(word, options) + '</a>';


			} else if (word.indexOf('pic.twitter.com/') === 0) {

				if (!out.media) {
					out.media = [];
				}
				expanded = getExpandedUrl('https://' + word, options);
				out.media.push({
					match: word,
					type: 'image',
					url: 'https://' + word,
					expanded: expanded
				});
				words[x] = '<a class="' + cn.auto + ' ' + cn.photo + '" href="' + expanded + '">' + expanded + '</a>';


			} else if (word.indexOf('vine.co/v/') === 0) {

				if (!out.media) {
					out.media = [];
				}
				out.media.push({
					match: word,
					type: 'video',
					url: 'https://' + word
				});
				words[x] = '<a class="' + cn.auto + ' ' + cn.video + '" href="https://' + word + '">' + escapeHtml(word, options) + '</a>';


			} else {
				expanded = getExpandedUrl(word, options);
				if (expanded) {
					if (!out.url) {
						out.url = [];
					}
					out.url.push({
						match: word,
						expanded: expanded
					});
					words[x] = '<a class="' + cn.auto + ' ' + cn.url + '" href="' + expanded + '">' + escapeHtml(word, options) + '</a>';
				} else {
					words[x] = escapeHtml(word, options);
				}
			}
			x++;
		}
		out.html = words.join(' ');
		if(options.parseDates){
			out = addTimeTags(out, options);	
		}
		
	}
	callback(null, out);

}
457749
def parse(self, charset=None, headers=None):
        

        if headers:
            self.headers = headers
        else:
            # Parse headers only from last response
            # There could be multiple responses in `self.head`
            # in case of 301/302 redirect
            # Separate responses
            if self.head:
                responses = self.head.rsplit(b'\nHTTP/', 1)
                # Cut off the 'HTTP/*' line from the last response
                _, response = responses[-1].split(b'\n', 1)
                response = response.decode('utf-8', 'ignore')
            else:
                response = u''
            if six.PY2:
                # email_from_string does not work with unicode input
                response = response.encode('utf-8')
            self.headers = email.message_from_string(response)

        if charset is None:
            if isinstance(self.body, six.text_type):
                self.charset = 'utf-8'
            else:
                self.detect_charset()
        else:
            self.charset = charset.lower()

        self._unicode_body = None
733893
def parse_address(address: str) -> str:
    
    display_name, parsed_address = email.utils.parseaddr(address)

    return parsed_address or address
465865
function urlFormat(obj) {
  // ensure it's an object, and not a string url.
  // If it's an obj, this is a no-op.
  // this way, you can call url_format() on strings
  // to clean up potentially wonky urls.
  if (typeof(obj) === 'string') obj = urlParse(obj);

  var auth = obj.auth || '';
  if (auth) {
    auth = auth.split('@').join('%40');
    for (var i = 0, l = nonAuthChars.length; i < l; i++) {
      var nAC = nonAuthChars[i];
      auth = auth.split(nAC).join(encodeURIComponent(nAC));
    }
    auth += '@';
  }

  var protocol = obj.protocol || '',
      host = (obj.host !== undefined) ? auth + obj.host :
          obj.hostname !== undefined ? (
              auth + obj.hostname +
              (obj.port ? ':' + obj.port : '')
          ) :
          false,
      pathname = obj.pathname || '',
      query = obj.query &&
              ((typeof obj.query === 'object' &&
                objectKeys(obj.query).length) ?
                 querystring.stringify(obj.query) :
                 '') || '',
      search = obj.search || (query && ('?' + query)) || '',
      hash = obj.hash || '';

  if (protocol && protocol.substr(-1) !== ':') protocol += ':';

  // only the slashedProtocols get the //.  Not mailto:, xmpp:, etc.
  // unless they had them to begin with.
  if (obj.slashes ||
      (!protocol || slashedProtocol[protocol]) && host !== false) {
    host = '//' + (host || '');
    if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  } else if (!host) {
    host = '';
  }

  if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  if (search && search.charAt(0) !== '?') search = '?' + search;

  return protocol + host + pathname + search + hash;
}
140437
def parse(cls, url, default_scheme='http', encoding='utf-8'):
        ''''''
        if url is None:
            return None

        url = url.strip()
        if frozenset(url) & C0_CONTROL_SET:
            raise ValueError('URL contains control codes: {}'.format(ascii(url)))

        scheme, sep, remaining = url.partition(':')

        if not scheme:
            raise ValueError('URL missing scheme: {}'.format(ascii(url)))

        scheme = scheme.lower()

        if not sep and default_scheme:
            # Likely something like example.com/mystuff
            remaining = url
            scheme = default_scheme
        elif not sep:
            raise ValueError('URI missing colon: {}'.format(ascii(url)))

        if default_scheme and '.' in scheme or scheme == 'localhost':
            # Maybe something like example.com:8080/mystuff or
            # maybe localhost:8080/mystuff
            remaining = '{}:{}'.format(scheme, remaining)
            scheme = default_scheme

        info = URLInfo()
        info.encoding = encoding

        if scheme not in RELATIVE_SCHEME_DEFAULT_PORTS:
            info.raw = url
            info.scheme = scheme
            info.path = remaining

            return info

        if remaining.startswith('//'):
            remaining = remaining[2:]

        path_index = remaining.find('/')
        query_index = remaining.find('?')
        fragment_index = remaining.find('#')

        try:
            index_tuple = (path_index, query_index, fragment_index)
            authority_index = min(num for num in index_tuple if num >= 0)
        except ValueError:
            authority_index = len(remaining)

        authority = remaining[:authority_index]
        resource = remaining[authority_index:]

        try:
            index_tuple = (query_index, fragment_index)
            path_index = min(num for num in index_tuple if num >= 0)
        except ValueError:
            path_index = len(remaining)

        path = remaining[authority_index + 1:path_index] or '/'

        if fragment_index >= 0:
            query_index = fragment_index
        else:
            query_index = len(remaining)

        query = remaining[path_index + 1:query_index]
        fragment = remaining[query_index + 1:]

        userinfo, host = cls.parse_authority(authority)
        hostname, port = cls.parse_host(host)
        username, password = cls.parse_userinfo(userinfo)

        if not hostname:
            raise ValueError('Hostname is empty: {}'.format(ascii(url)))

        info.raw = url
        info.scheme = scheme
        info.authority = authority
        info.path = normalize_path(path, encoding=encoding)
        info.query = normalize_query(query, encoding=encoding)
        info.fragment = normalize_fragment(fragment, encoding=encoding)

        info.userinfo = userinfo
        info.username = percent_decode(username, encoding=encoding)
        info.password = percent_decode(password, encoding=encoding)

        info.host = host
        info.hostname = hostname
        info.port = port or RELATIVE_SCHEME_DEFAULT_PORTS[scheme]

        info.resource = resource

        return info
1006222
def parse_domain(url):
    
    domain_match = lib.DOMAIN_REGEX.match(url)
    if domain_match:
        return domain_match.group()
923039
def user_parse(data):
        """"""
        id_ = data.get('id')
        yield 'id', id_
        yield 'email', data.get('email')
        yield 'first_name', data.get('first_name')
        yield 'last_name', data.get('last_name')
        yield 'username', data.get('name')
        yield 'picture', 'http://graph.facebook.com/{0}/picture?' \
                         'type=large'.format(id_)
        yield 'link', data.get('link')
        yield 'locale', data.get('locale')
        yield 'gender', data.get('gender')

        location = data.get('location', {}).get('name')
        if location:
            split_location = location.split(', ')
            yield 'city', split_location[0].strip()
            if len(split_location) > 1:
                yield 'country', split_location[1].strip()
807624
def parse(url, engine=None, conn_max_age=0, ssl_require=False):
    """"""

    if url == 'sqlite://:memory:':
        # this is a special case, because if we pass this URL into
        # urlparse, urlparse will choke trying to interpret "memory"
        # as a port number
        return {
            'ENGINE': SCHEMES['sqlite'],
            'NAME': ':memory:'
        }
        # note: no other settings are required for sqlite

    # otherwise parse the url as normal
    config = {}

    url = urlparse.urlparse(url)

    # Split query strings from path.
    path = url.path[1:]
    if '?' in path and not url.query:
        path, query = path.split('?', 2)
    else:
        path, query = path, url.query
    query = urlparse.parse_qs(query)

    # If we are using sqlite and we have no path, then assume we
    # want an in-memory database (this is the behaviour of sqlalchemy)
    if url.scheme == 'sqlite' and path == '':
        path = ':memory:'

    # Handle postgres percent-encoded paths.
    hostname = url.hostname or ''
    if '%2f' in hostname.lower():
        # Switch to url.netloc to avoid lower cased paths
        hostname = url.netloc
        if "@" in hostname:
            hostname = hostname.rsplit("@", 1)[1]
        if ":" in hostname:
            hostname = hostname.split(":", 1)[0]
        hostname = hostname.replace('%2f', '/').replace('%2F', '/')

    # Lookup specified engine.
    engine = SCHEMES[url.scheme] if engine is None else engine

    port = (str(url.port) if url.port and engine in [SCHEMES['oracle'], SCHEMES['mssql']]
            else url.port)

    # Update with environment configuration.
    config.update({
        'NAME': urlparse.unquote(path or ''),
        'USER': urlparse.unquote(url.username or ''),
        'PASSWORD': urlparse.unquote(url.password or ''),
        'HOST': hostname,
        'PORT': port or '',
        'CONN_MAX_AGE': conn_max_age,
    })

    # Pass the query string into OPTIONS.
    options = {}
    for key, values in query.items():
        if url.scheme == 'mysql' and key == 'ssl-ca':
            options['ssl'] = {'ca': values[-1]}
            continue

        options[key] = values[-1]

    if ssl_require:
        options['sslmode'] = 'require'

    # Support for Postgres Schema URLs
    if 'currentSchema' in options and engine in (
        'django.contrib.gis.db.backends.postgis',
        'django.db.backends.postgresql_psycopg2',
        'django.db.backends.postgresql',
        'django_redshift_backend',
    ):
        options['options'] = '-c search_path={0}'.format(options.pop('currentSchema'))

    if options:
        config['OPTIONS'] = options

    if engine:
        config['ENGINE'] = engine

    return config
998614
function parseUrl(url) {
        if (Core.isBlank(url)) {
            return null;
        }
        var matches = url.match(httpRegex);
        if (matches === null) {
            return null;
        }
        //log.debug("matches: ", matches);
        var scheme = matches[1];
        var host = matches[3];
        var port = matches[4];
        var parts = null;
        if (!Core.isBlank(port)) {
            parts = url.split(port);
        }
        else {
            parts = url.split(host);
        }
        // make sure we use port as a number
        var portNum = Core.parseIntValue(port);
        var path = parts[1];
        if (path && _.startsWith(path, '/')) {
            path = path.slice(1, path.length);
        }
        //log.debug("parts: ", parts);
        return {
            scheme: scheme,
            host: host,
            port: portNum,
            path: path
        };
    }
381299
@Nullable
    private String extractDomain(String email) {
        int indexAt = email.indexOf(AT_SYMBOL) + 1;
        if (indexAt == 0) {
            return null;
        }
        String domain = email.substring(indexAt);
        if (domain.isEmpty()) {
            return null;
        }
        return domain;
    }