parse an email to an unicode name, email tuple
490820
def parse_email(self, email):
        
        splitted = safe_unicode(email).rsplit(",", 1)
        if len(splitted) == 1:
            return (False, splitted[0])
        elif len(splitted) == 2:
            return (splitted[0], splitted[1])
        else:
            raise ValueError("Could not parse email '{}'".format(email))
448014
def _get_non_space_email(self, doc) -> List:
        
        result_lst = []
        for e in doc:
            if "mail:" in e.text.lower():
                idx = e.text.lower().index("mail:") + 5
                value = e.text[idx:]
                tmp_doc = self._nlp(value)
                tmp_email_matches = self._like_email_matcher(tmp_doc)
                for match_id, start, end in tmp_email_matches:
                    span = tmp_doc[start:end]
                    if self._check_domain(self._tokenizer.tokenize(span.text)):
                        result_lst.append((span.text, idx+e.idx, idx+e.idx+len(value)))

        return result_lst
596106
function (unicode) {
                var unicodeNameIndex = unicodeName[unicode];
                if (undefined !== unicodeNameIndex) {
                    return postName[unicodeNameIndex];
                }

                return 'uni' + unicode.toString(16).toUpperCase();
            }
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)
364760
def parse_email_url(url):
    """"""

    conf = {}

    url = urlparse.urlparse(url)

    # 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': url.username,
        'EMAIL_HOST_PASSWORD': url.password,
        'EMAIL_HOST': url.hostname,
        'EMAIL_PORT': url.port,
    })

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

    if url.scheme == 'smtps':
        conf['EMAIL_USE_TLS'] = True
    else:
        conf['EMAIL_USE_TLS'] = False

    return conf
1262900
def ucnstring_to_unicode(ucn_string):
    """"""
    ucn_string = ucnstring_to_python(ucn_string).decode('utf-8')

    assert isinstance(ucn_string, text_type)
    return ucn_string
565770
def extract_emails(text):
    """"""
    text = text.replace(u'\u2024', '.')
    emails = []
    for m in EMAIL_RE.findall(text):
        emails.append(m[0])
    return emails
1098265
def validate_email():
    
    user_regex = re.compile(
        r"(^[-!#$%&'*+/=?^`{}|~\w]+(\.[-!#$%&'*+/=?^`{}|~\w]+)*$"
        r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]'
        r'|\\[\001-\011\013\014\016-\177])*"$)', re.IGNORECASE | re.UNICODE)

    domain_regex = re.compile(
        r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
        r'(?:[A-Z]{2,6}|[A-Z0-9-]{2,})$'
        r'|^\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)'
        r'(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$', re.IGNORECASE | re.UNICODE)

    domain_whitelist = ('localhost',)

    def email_validator(field, data):
        if field.value is None:
            return

        value = str(field.value)

        if '@' not in value:
            raise ValidationError('email')

        user_part, domain_part = value.rsplit('@', 1)

        if not user_regex.match(user_part):
            raise ValidationError('email')

        if domain_part in domain_whitelist:
            return

        if not domain_regex.match(domain_part):
            raise ValidationError('email')

    return email_validator
1363243
@Nullable
    public OAuthConnection parse(String email) {
        String domain = extractDomain(email);
        if (domain == null) {
            return null;
        }

        domain = domain.toLowerCase();
        for (OAuthConnection c : connections) {
            String mainDomain = domainForConnection(c);
            if (domain.equalsIgnoreCase(mainDomain)) {
                return c;
            }

            List<String> aliases = c.valueForKey(DOMAIN_ALIASES_KEY, List.class);
            if (aliases != null) {
                for (String d : aliases) {
                    if (d.equalsIgnoreCase(domain)) {
                        return c;
                    }
                }
            }
        }
        return null;
    }
519041
def fetch_email(M, msg_id):
    """"""
    res, data = M.fetch(msg_id, '(RFC822)')
    if res == 'OK':
        # Data here is a list with 1 element containing a tuple
        # whose 2nd element is a long string containing the email
        # The content is a bytes that must be decoded
        raw_msg_txt = data[0][1]
        # In Python3, we call message_from_bytes, but this function doesn't
        # exist in Python 2.
        try:
            msg = email.message_from_bytes(raw_msg_txt)
        except AttributeError:
            msg = email.message_from_string(raw_msg_txt)
        # At this point, we have a message containing bytes (not unicode)
        # fields that will still need to be decoded, ideally according to the
        # character set specified in the message.
        return msg
    else:
        return None
1103185
def parse_utf_html(url=os.path.join(DATA_PATH, 'utf8_table.html')):
    
    utf = pd.read_html(url)
    utf = [df for df in utf if len(df) > 1023 and len(df.columns) > 2][0]
    utf = utf.iloc[:1024] if len(utf) == 1025 else utf
    utf.columns = 'char name hex'.split()
    utf.name = utf.name.str.replace('<control>', 'CONTTROL CHARACTER')
    multiascii = [' '] * len(utf)
    asc = [' '] * len(utf)
    rows = []
    for i, name in enumerate(utf.name):
        if i < 128 and str.isprintable(chr(i)):
            asc[i] = chr(i)
        else:
            asc[i] = ' '
        big = re.findall(r'CAPITAL\ LETTER\ ([a-z0-9A-Z ]+$)', name)
        small = re.findall(r'SMALL\ LETTER\ ([a-z0-9A-Z ]+$)', name)
        pattern = r'(?P<description>' \
                      r'(?P<lang>LATIN|GREEK|COPTIC|CYRILLIC)?[\s]*' \
                      r'(?P<case>CAPITAL|SMALL)?[\s]*' \
                      r'(?P<length>CHARACTER|LETTER)?[\s]*' \
                      r'(?P<ukrainian>BYELORUSSIAN-UKRAINIAN)?[\s]*' \
                      r'(?P<name>[-_><a-z0-9A-Z\s ]+)[\s]*' \
                      r'\(?(?P<code_point>U\+[- a-fA-F0-9]{4,8})?\)?)[\s]*'  # noqa
        match = re.match(pattern, name)
        gd = match.groupdict()
        gd['char'] = chr(i)
        gd['suffix'] = None
        gd['wordwith'] = None

        withprefix = re.match(r'(?P<prefix>DOTLESS|TURNED|SMALL)(?P<name>.*)' +
                              r'(?P<wordwith>WITH|SUPERSCRIPT|SUBSCRIPT|DIGRAPH)\s+(?P<suffix>[-_><a-z0-9A-Z\s ]+)',
                              gd['name'])
        if withprefix:
            gd.update(withprefix.groupdict())

        withsuffix = re.match(r'(?P<name>.*)(?P<wordwith>WITH|SUPERSCRIPT|SUBSCRIPT|DIGRAPH)\s+' +
                              r'(?P<suffix>[-_><a-z0-9A-Z\s ]+)',
                              gd['name'])
        if withsuffix:
            gd.update(withsuffix.groupdict())

        gd['code_point'] = gd['code_point'] or format_hex(i, num_bytes=4, prefix='U+').upper()
        if i < 128:
            gd['ascii'] = chr(i)
        else:
            multiascii = gd['name']
            if gd['suffix'] and gd['wordwith']:
                multiascii = NAME_ACCENT.get(gd['suffix'], "'")
            else:
                if big:
                    m = big[0]
                    multiascii[i] = m
                    if len(m) == 1:
                        asc[i] = m
                elif small:
                    multiascii[i] = small[0].lower()
                    if len(multiascii[i]) == 1:
                        asc[i] = small[0].lower()
        rows.append(gd)
    df = pd.DataFrame(rows)
    df.multiascii = df.multiascii.str.strip()
    df['ascii'] = df['ascii'].str.strip()
    df.name = df.name.str.strip()
    return df
319849
def email(self, name, to, from_addr, subject, body, header, owner=None, **kwargs):
        
        return Email(self.tcex, name, to, from_addr, subject, body, header, owner=owner, **kwargs)
30110
def to_utf8(obj):
    
    if isinstance(obj, unicode_type):
        return _utf8(obj)
    elif isinstance(obj, dict):
        return dict((to_utf8(k), to_utf8(v)) for (k, v) in obj.items())
    elif isinstance(obj, list):
        return list(to_utf8(i) for i in obj)
    elif isinstance(obj, tuple):
        return tuple(to_utf8(i) for i in obj)

    return obj
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
1365362
def convert_raw_tuple(value_tuple, format_string):
     
    values = []
    for v, c in zip(value_tuple, format_string):
        if v is None:
            # append None
            values.append(v)
        elif c == u"s":
            # string
            values.append(v)
        elif c == u"S":
            # string, split using space as delimiter
            values.append([s for s in v.split(u" ") if len(s) > 0])
        elif c == u"i":
            # int
            values.append(int(v))
        elif c == u"U":
            # Unicode
            values.append(convert_unicode_field(v))
        elif c == u"A":
            # ASCII
            values.append(convert_ascii_field(v))
        #elif c == u"x":
        #    # ignore
        #    pass
    return tuple(values)
542404
def parse(self):
        
        data = json.loads(sys.argv[1])
        self.config_path = self.decode(data['config_path'])
        self.subject = self.decode(data['subject'])
        self.text = self.decode(data['text'])
        self.html = self.decode(data['html'])
        self.send_as_one = data['send_as_one']
        if 'files' in data:
            self.parse_files(data['files'])
        self.ccs = data['ccs']
        self.addresses = data['addresses']
        if not self.addresses:
            raise ValueError(
                'Atleast one email address is required to send an email')
185027
def _parse_email(self, val):
        

        ret = {
            'type': None,
            'value': None
        }

        try:

            ret['type'] = val[1]['type']

        except (KeyError, ValueError, TypeError):

                pass

        ret['value'] = val[3].strip()

        try:

            self.vars['email'].append(ret)

        except AttributeError:

            self.vars['email'] = []
            self.vars['email'].append(ret)