Extract the IRC colours from the start of the string.

    Extracts the colours from the start, and returns the colour code in our
    format, and then the rest of the message.
195412
def extract_irc_colours(msg):
    
    # first colour
    fore, msg = _extract_irc_colour_code(msg)

    if not fore:
        return '[]', msg
    if not len(msg) or msg[0] != ',':
        return '[{}]'.format(_ctos(fore)), msg

    msg = msg[1:]  # strip comma

    # second colour
    back, msg = _extract_irc_colour_code(msg)

    if back:
        return '[{},{}]'.format(_ctos(fore), _ctos(back)), msg
    else:
        return '[{}]'.format(_ctos(fore)), ',' + msg
1272847
function message( data , color ) {
	var k , messageString = '' ;

	if ( data.mon ) {
		messageString = '\n' ;

		if ( color ) {
			for ( k in data.mon ) {
				messageString += string.ansi.green + k + string.ansi.reset + ': ' +
					string.ansi.cyan + data.mon[ k ] + string.ansi.reset + '\n' ;
			}
		}
		else {
			for ( k in data.mon ) { messageString += k + ': ' + data.mon[ k ] + '\n' ; }
		}
	}
	else if ( Array.isArray( data.messageData ) && data.isFormat ) {
		//if ( color ) { messageString = string.ansi.italic + string.formatMethod.apply( { color: true } , data.messageData ) ; }
		//else { messageString = string.formatMethod.apply( { color: false } , data.messageData ) ; }

		messageString = string.formatMethod.apply( color ? formatColor : format , data.messageData ) ;
	}
	else if ( data.messageData instanceof Error ) {
		messageString = string.inspectError( { style: color ? 'color' : 'none' } , data.messageData ) ;
	}
	else if ( typeof data.messageData !== 'string' ) {
		messageString = string.inspect( { style: color ? 'color' : 'none' } , data.messageData ) ;
	}
	else {
		// Even if messageData is not an array, it may contains markup, so it should be formated anyway
		//messageString = data.messageData ;
		messageString = string.formatMethod.call( color ? formatColor : format , data.messageData ) ;
	}

	return messageString ;
}
246844
def format(message, colour = nil, style = nil)
      c = @map[:colour][colour.to_sym] unless colour.nil?

      if style.nil?
        t = 0
      else
        t = @map[:style][style.to_sym]
      end

      "\e[#{t};#{c}m#{message}\e[0m"
    end
764571
def irc_format!(*settings, string)
      string = string.dup

      attributes = settings.select {|k| @@attributes.has_key?(k)}.map {|k| @@attributes[k]}
      colors = settings.select {|k| @@colors.has_key?(k)}.map {|k| @@colors[k]}
      if colors.size > 2
        raise ArgumentError, "At most two colors (foreground and background) might be specified"
      end

      attribute_string = attributes.join
      color_string = if colors.empty?
                       ""
                     else
                       "\x03#{colors.join(",")}"
                     end

      prepend = attribute_string + color_string
      append = @@attributes[:reset]

      # attributes act as toggles, so e.g. underline+underline = no
      # underline. We thus have to delete all duplicate attributes
      # from nested strings.
      string.delete!(attribute_string)

      # Replace the reset code of nested strings to continue the
      # formattings of the outer string.
      string.gsub!(/#{@@attributes[:reset]}/, @@attributes[:reset] + prepend)
      string.insert(0, prepend)
      string << append
      return string
    end
355718
def extract_first_part(message, boundary):
    
    first_message = message.split(boundary)[1].lstrip()
    if first_message.endswith(b'\r\n'):
        first_message = first_message[:-2]
    else:
        first_message = first_message[:-1]
    return first_message
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)
184963
def htmlcolor_to_rgb(str_color):
    
    if not (str_color.startswith('#') and len(str_color) == 7):
        raise ValueError("Bad html color format. Expected: '#RRGGBB' ")
    result = [1.0 * int(n, 16) / 255 for n in (str_color[1:3], str_color[3:5], str_color[5:])]
    return result
142503
def color(string, status=True, warning=False, bold=True):
    
    attr = []
    if status:
        # green
        attr.append('32')
    if warning:
        # red
        attr.append('31')
    if bold:
        attr.append('1')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
765112
def decode_irc!(string, encoding = :irc)
      if encoding == :irc
        # If incoming text is valid UTF-8, it will be interpreted as
        # such. If it fails validation, a CP1252 -> UTF-8 conversion
        # is performed. This allows you to see non-ASCII from mIRC
        # users (non-UTF-8) and other users sending you UTF-8.
        #
        # (from http://xchat.org/encoding/#hybrid)
        string.force_encoding("UTF-8")
        if !string.valid_encoding?
          string.force_encoding("CP1252").encode!("UTF-8", {:invalid => :replace, :undef => :replace})
        end
      else
        string.force_encoding(encoding).encode!({:invalid => :replace, :undef => :replace})
        string = string.chars.select { |c| c.valid_encoding? }.join
      end

      return string
    end
57111
def from_irc(cls, text):
        
        from .grammars.irc import parse as parse_irc
        if isinstance(text, bytes):
            original_bytes = text
            text = text.decode('utf8')
        else:
            original_bytes = text.encode('utf8')
        instance = parse_irc(text)
        instance.original_type = 'irc'
        instance.original_bytes = original_bytes
        return instance
146689
def highlight_regex(str_, pat, reflags=0, color='red'):
    
    #import colorama
    # from colorama import Fore, Style
    #color = Fore.MAGENTA
    # color = Fore.RED
    #match = re.search(pat, str_, flags=reflags)
    matches = list(re.finditer(pat, str_, flags=reflags))

    colored = str_

    for match in reversed(matches):
        #pass
        #if match is None:
        #    return str_
        #else:
        start = match.start()
        end = match.end()
        #colorama.init()
        colored_part = color_text(colored[start:end], color)
        colored = colored[:start] + colored_part + colored[end:]
        # colored = (colored[:start] + color + colored[start:end] +
        #            Style.RESET_ALL + colored[end:])
        #colorama.deinit()
    return colored
123651
def _hex_to_rgb(color):
    
    if color[0] == '#':
        color = color[1:]
    if len(color) == 3:
        color = color[0] * 2 + color[1] * 2 + color[2] * 2
    if len(color) != 6:
        raise ValueError('Input #{0} is not in #RRGGBB format'.format(color))
    return [int(n, 16) for n in (color[:2], color[2:4], color[4:])]
1004103
def color_str(self):
        ""
        s = self.s
        for k, v in sorted(self.atts.items()):
            # (self.atts sorted for the sake of always acting the same.)
            if k not in xforms:
                # Unsupported SGR code
                continue
            elif v is False:
                continue
            elif v is True:
                s = xforms[k](s)
            else:
                s = xforms[k](s, v)
        return s
86802
def from_html(html_style_colour_str: str):
        
        html_style_colour_str = html_style_colour_str.lstrip("#")
        components = list(map("".join, zip(*[iter(html_style_colour_str)]*2)))
        return ColourData(*(int(colour, 16) for colour in components))
268071
def coloringfromstring(s):
    
    try:
        AST = compiler.parse(s)
    except SyntaxError:
        return
    else:
        try:
            if len(AST.getChildren()) > 1:
                ST = AST.getChildren()[1]
                if isinstance(ST, Stmt) and isinstance(ST.getChildren()[0],
                                                                     Discard):
                    d = ST.getChildren()[0].asList()[0]
        except (TypeError, AttributeError):
            pass
        else:
            if isinstance(d,Dict) and len(d.items) > 0:
                if all([isctype(i[0],str) for i in d.items]):
                    if all([isinstance(i[1],List) for i in d.items]):
                        if all([all([isctype(j,str) for j in i[1]]) for i in 
                                                                      d.items]):
                            return eval(s)
36459
function _retrieveColor(palette, color, hue = '500', format) {
    if (typeof palette !== 'string' || typeof color !== 'string' || typeof hue !== 'string' || typeof format !== 'string') {
        throw new TypeError('Expected a string');
    }

    let hexColor;
    let result;

    try {
        hexColor = (palette === 'md') ? colors[palette][color][hue].hex : colors[palette][color];

        switch (format) {
            case 'rgb':
                result = _toRGB(hexColor);
                result = `rgb(${result.r}, ${result.g}, ${result.b})`;
                break;
            case 'hex':
                result = `#${hexColor}`;
                break;
            case 'raw':
                result = _toRGB(hexColor);
                result.hex = hexColor;
                break;
            default:
        }
    } catch (err) {
        throw new RangeError('No matching color.');
    }
    return result;
}
354622
def colorize(str, sev: :normal_s)
      return str unless color_enabled?

      cc = COLOR_CODE
      color = cc.key?(sev) ? cc[sev] : ''
      "#{color}#{str.sub(cc[:esc_m], color)}#{cc[:esc_m]}"
    end