Injects *ANSI* escape codes into :class:`AnsiEscapeCodes` class.
163541
def _set_ansi_escape_codes():
    

    AnsiEscapeCodes["reset"] = "\033[0m"

    for foreground_code_name, foreground_code in FOREGROUND_ANSI_ESCAPE_CODES:
        AnsiEscapeCodes[foreground_code_name] = "\033[{0}".format(foreground_code)

    for background_code_name, background_code in BACKGROUND_ANSI_ESCAPE_CODES:
        AnsiEscapeCodes[background_code_name] = "\033[{0}".format(background_code)

    for background_code_name, background_code in BACKGROUND_ANSI_ESCAPE_CODES:
        for foreground_code_name, foreground_code in FOREGROUND_ANSI_ESCAPE_CODES:
            AnsiEscapeCodes["{0}{1}".format(foreground_code_name,
                                            "{0}{1}".format(background_code_name[0].upper(),
                                                            background_code_name[1:]))] = "\033[{0}\033[{1}".format(
                foreground_code, background_code)
1006874
def prune_overridden(ansi_string):
    
    multi_seqs = set(p for p in RE_ANSI.findall(ansi_string) if ';' in p[1])  # Sequences with multiple color codes.

    for escape, codes in multi_seqs:
        r_codes = list(reversed(codes.split(';')))

        # Nuke everything before {/all}.
        try:
            r_codes = r_codes[:r_codes.index('0') + 1]
        except ValueError:
            pass

        # Thin out groups.
        for group in CODE_GROUPS:
            for pos in reversed([i for i, n in enumerate(r_codes) if n in group][1:]):
                r_codes.pop(pos)

        # Done.
        reduced_codes = ';'.join(sorted(r_codes, key=int))
        if codes != reduced_codes:
            ansi_string = ansi_string.replace(escape, '\033[' + reduced_codes + 'm')

    return ansi_string
1196843
def ansi_code(name):
    """"""
    try:
        obj = colorama
        for part in name.split("."):
            obj = getattr(obj, part)
        return obj
    except AttributeError:
        return ""
1078707
def shellsafe(s, quote='', doescape=True):
    """"""
    if sys.version[0] == '2' and not isinstance(s,unicode): #pylint: disable=undefined-variable
        s = unicode(s,'utf-8') #pylint: disable=undefined-variable
    if len(s) > 1024:
        raise ValueError("Variable value rejected for security reasons: too long")
    if quote:
        if quote in s:
            if doescape:
                s = escape(s,quote)
            else:
                raise ValueError("Variable value rejected for security reasons: " + s)
        return quote + s + quote
    else:
        for c in s:
            if c in DISALLOWINSHELLSAFE:
                raise ValueError("Variable value rejected for security reasons: " + s)
        return s
197661
static void escape(final char[] text, final int offset, final int len, final Writer writer,
                       final UriEscapeType escapeType, final String encoding)
                       throws IOException {

        if (text == null || text.length == 0) {
            return;
        }

        final int max = (offset + len);

        int readOffset = offset;

        for (int i = offset; i < max; i++) {

            final int codepoint = Character.codePointAt(text, i);

            /*
             * Shortcut: most characters will be alphabetic, and we won't need to do anything at
             * all for them. No need to use the complete UriEscapeType check system at all.
             */
            if (UriEscapeType.isAlpha(codepoint)) {
                continue;
            }

            /*
             * Check whether the character is allowed or not
             */
            if (escapeType.isAllowed(codepoint)) {
                continue;
            }



            /*
             * At this point we know for sure we will need some kind of escape, so we
             * can write all the contents pending up to this point.
             */

            if (i - readOffset > 0) {
                writer.write(text, readOffset, (i - readOffset));
            }

            if (Character.charCount(codepoint) > 1) {
                // This is to compensate that we are actually reading two char[] positions with a single codepoint.
                i++;
            }

            readOffset = i + 1;


            /*
             * -----------------------------------------------------------------------------------------
             *
             * Perform the real escape
             *
             * -----------------------------------------------------------------------------------------
             */

            final byte[] charAsBytes;
            try {
                charAsBytes = new String(Character.toChars(codepoint)).getBytes(encoding);
            } catch (final UnsupportedEncodingException e) {
                throw new IllegalArgumentException("Exception while escaping URI: Bad encoding '" + encoding + "'", e);
            }
            for (final byte b : charAsBytes) {
                writer.write('%');
                writer.write(printHexa(b));
            }


        }


        /*
         * -----------------------------------------------------------------------------------------------
         * Final cleaning: return the original String object if no escape was actually needed. Otherwise
         *                 append the remaining unescaped text to the string builder and return.
         * -----------------------------------------------------------------------------------------------
         */

        if (max - readOffset > 0) {
            writer.write(text, readOffset, (max - readOffset));
        }

    }
1012581
def escape(ident):
    """"""

    string = []
    length = len(ident)
    start_dash = length > 0 and ident[0] == '-'
    if length == 1 and start_dash:
        # Need to escape identifier that is a single `-` with no other characters
        string.append('\\{}'.format(ident))
    else:
        for index, c in enumerate(ident):
            codepoint = util.uord(c)
            if codepoint == 0x00:
                string.append('\ufffd')
            elif (0x01 <= codepoint <= 0x1F) or codepoint == 0x7F:
                string.append('\\{:x} '.format(codepoint))
            elif (index == 0 or (start_dash and index == 1)) and (0x30 <= codepoint <= 0x39):
                string.append('\\{:x} '.format(codepoint))
            elif (
                codepoint in (0x2D, 0x5F) or codepoint >= 0x80 or (0x30 <= codepoint <= 0x39) or
                (0x30 <= codepoint <= 0x39) or (0x41 <= codepoint <= 0x5A) or (0x61 <= codepoint <= 0x7A)
            ):
                string.append(c)
            else:
                string.append('\\{}'.format(c))
    return ''.join(string)
527250
def supports_ansi_escape_codes(fd):
    

    if os.isatty(fd):
        return True

    if not is_win:
        return False

    # Check for cygwin/msys terminal
    handle = winapi._get_osfhandle(fd)
    if handle == winapi.INVALID_HANDLE_VALUE:
        return False

    if winapi.GetFileType(handle) != winapi.FILE_TYPE_PIPE:
        return False

    file_name = _get_file_name_for_handle(handle)
    match = re.match(
        "^\\\\(cygwin|msys)-[a-z0-9]+-pty[0-9]+-(from|to)-master$", file_name)
    return match is not None
1178561
def shell_escape(text, _safe=re.compile(r"^[-._,+a-zA-Z0-9]+$")):
    """"""
    if not text or _safe.match(text):
        return text

    squote = type(text)("'")
    return squote + text.replace(squote, type(text)(r"'\''")) + squote
37374
static void escape(final char[] text, final int offset, final int len, final Writer writer,
                       final PropertiesKeyEscapeLevel escapeLevel)
                       throws IOException {

        if (text == null || text.length == 0) {
            return;
        }

        final int level = escapeLevel.getEscapeLevel();

        final int max = (offset + len);

        int readOffset = offset;

        for (int i = offset; i < max; i++) {

            final int codepoint = Character.codePointAt(text, i);


            /*
             * Shortcut: most characters will be ASCII/Alphanumeric, and we won't need to do anything at
             * all for them
             */
            if (codepoint <= (ESCAPE_LEVELS_LEN - 2) && level < ESCAPE_LEVELS[codepoint]) {
                continue;
            }

            /*
             * Shortcut: we might not want to escape non-ASCII chars at all either.
             */
            if (codepoint > (ESCAPE_LEVELS_LEN - 2) && level < ESCAPE_LEVELS[ESCAPE_LEVELS_LEN - 1]) {

                if (Character.charCount(codepoint) > 1) {
                    // This is to compensate that we are actually escaping two char[] positions with a single codepoint.
                    i++;
                }

                continue;

            }


            /*
             * At this point we know for sure we will need some kind of escape, so we
             * copy all the contents pending up to this point.
             */

            if (i - readOffset > 0) {
                writer.write(text, readOffset, (i - readOffset));
            }

            if (Character.charCount(codepoint) > 1) {
                // This is to compensate that we are actually reading two char[] positions with a single codepoint.
                i++;
            }

            readOffset = i + 1;


            /*
             * -----------------------------------------------------------------------------------------
             *
             * Perform the real escape, attending the different combinations of SECs and UHEXA
             *
             * -----------------------------------------------------------------------------------------
             */

            if (codepoint < SEC_CHARS_LEN) {
                // We will try to use a SEC

                final char sec = SEC_CHARS[codepoint];

                if (sec != SEC_CHARS_NO_SEC) {
                    // SEC found! just write it and go for the next char
                    writer.write(ESCAPE_PREFIX);
                    writer.write(sec);
                    continue;
                }

            }

            /*
             * No SEC-escape was possible, so we need uhexa escape.
             */

            if (Character.charCount(codepoint) > 1) {
                final char[] codepointChars = Character.toChars(codepoint);
                writer.write(ESCAPE_UHEXA_PREFIX);
                writer.write(toUHexa(codepointChars[0]));
                writer.write(ESCAPE_UHEXA_PREFIX);
                writer.write(toUHexa(codepointChars[1]));
                continue;
            }

            writer.write(ESCAPE_UHEXA_PREFIX);
            writer.write(toUHexa(codepoint));

        }


        /*
         * -----------------------------------------------------------------------------------------------
         * Final cleaning: append the remaining unescaped text to the string builder and return.
         * -----------------------------------------------------------------------------------------------
         */

        if (max - readOffset > 0) {
            writer.write(text, readOffset, (max - readOffset));
        }

    }
155833
function injectCode(code, id) {
  var pre = document.getElementById(id);
  pre.textContent = code;
  code = pre.innerHTML;
  code = prettyPrintOne(code, 'js');
  pre.innerHTML = code;
}
1114907
def add_expr(src, code, indicator)
      case indicator
      when '='
        @escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
      when '=='
        @escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
      when '==='
        add_expr_debug(src, code)
      end
    end
607725
def escape(value, quote=True):
    '''
    
    '''
    def escape_one(match):
        return SPECIAL_CHARS[match.group(0)]

    if isinstance(value, string_types):
        value = SPECIAL_CHARS_REGEX.sub(escape_one, value)
        if quote:
            value = "'" + value + "'"
    return text_type(value)
1346011
def _handle_ansi_color_codes(self, s):
    """"""
    parts = HtmlReporter._ANSI_COLOR_CODE_RE.split(s)
    ret = []
    span_depth = 0
    # Note that len(parts) is always odd: text, code, text, code, ..., text.
    for i in range(0, len(parts), 2):
      ret.append(parts[i])
      if i + 1 < len(parts):
        for code in parts[i + 1].split(';'):
          if code == 0:  # Reset.
            while span_depth > 0:
              ret.append('</span>')
              span_depth -= 1
          else:
            ret.append('<span class="ansi-{}">'.format(code))
            span_depth += 1
    while span_depth > 0:
      ret.append('</span>')
      span_depth -= 1

    return ''.join(ret)
1095662
def obfuscatable_class(tokens, index, **kwargs):
    
    tok = tokens[index]
    token_type = tok[0]
    token_string = tok[1]
    if index > 0:
        prev_tok = tokens[index-1]
    else: # Pretend it's a newline (for simplicity)
        prev_tok = (54, '\n', (1, 1), (1, 2), '#\n')
    prev_tok_string = prev_tok[1]
    if token_type != tokenize.NAME:
        return None # Skip this token
    if token_string.startswith('__'): # Don't mess with specials
        return None
    if prev_tok_string == "class":
        return token_string
695335
def style_ansi(raw_code, lang=None):
    
    lexer = 0
    if lang:
        try:
            lexer = get_lexer_by_name(lang)
        except ValueError:
            print col(R, 'Lexer for %s not found' % lang)
    lexer = None
    if not lexer:
        try:
            if guess_lexer:
                lexer = pyg_guess_lexer(raw_code)
        except:
            pass
    if not lexer:
        lexer = get_lexer_by_name(def_lexer)
    tokens = lex(raw_code, lexer)
    cod = []
    for t, v in tokens:
        if not v:
            continue
        _col = code_hl_tokens.get(t)
        if _col:
            cod.append(col(v, _col))
        else:
            cod.append(v)
    return ''.join(cod)
526409
def hash_coloured_escapes(text):
    """"""
    ansi_code = int(sha256(text.encode('utf-8')).hexdigest(), 16) % 230
    prefix, suffix = colored('SPLIT', ansi_code=ansi_code).split('SPLIT')
    return prefix, suffix
5241
def add_escape(self, idx, char):
        

        self.fmt.append_text(self.fmt._unescape.get(
            self.format[self.str_begin:idx], char))