FIXME Use pygments instead. must be mututally exclusive
489246
def highlight_multi_regex(str_, pat_to_color, reflags=0):
    
    #import colorama
    # from colorama import Fore, Style
    #color = Fore.MAGENTA
    # color = Fore.RED
    #match = re.search(pat, str_, flags=reflags)

    colored = str_

    to_replace = []
    for pat, color in pat_to_color.items():
        matches = list(re.finditer(pat, str_, flags=reflags))

        for match in matches:
            start = match.start()
            end = match.end()
            to_replace.append((end, start, color))

    for tup in reversed(sorted(to_replace)):
        end, start, color = tup
        colored_part = color_text(colored[start:end], color)
        colored = colored[:start] + colored_part + colored[end:]

    return colored
320445
def fill_between(self, canvas, X, lower, upper, color=None, label=None, **kwargs):
        
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")
556610
def fix_shapes(self):
        
        for i in xrange(self.n_chunks):
            for side in ['left', 'right', 'top', 'bottom']:
                edge = getattr(self, side).ravel()[i]
                if side in ['left', 'right']:
                    shp = [edge.todo.size, 1]
                else:
                    shp = [1, edge.todo.size]
                edge.done = edge.done.reshape(shp)
                edge.data = edge.data.reshape(shp)
                edge.todo = edge.todo.reshape(shp)
905691
def fixpix(data, mask, kind='linear'):
    """"""
    if data.shape != mask.shape:
        raise ValueError

    if not numpy.any(mask):
        return data

    x = numpy.arange(0, data.shape[0])
    for row, mrow in zip(data, mask):
        if numpy.any(mrow):  # Interpolate if there's some pixel missing
            valid = (mrow == numpy.False_)
            invalid = (mrow == numpy.True_)
            itp = interp1d(x[valid], row[valid], kind=kind, copy=False)
            row[invalid] = itp(x[invalid]).astype(row.dtype)
    return data
529129
def colorize(string, stack):
  ''''''
  codes = optimize(stack)
  if len(codes):
    prefix = SEQ % ';'.join(map(str, codes))
    suffix = SEQ % STYLE.reset
    return prefix + string + suffix
  else:
    return string
1151072
def fix_e251(self, result):
        """"""
        line_index = result['line'] - 1
        target = self.source[line_index]

        # This is necessary since pycodestyle sometimes reports columns that
        # goes past the end of the physical line. This happens in cases like,
        # foo(bar\n=None)
        c = min(result['column'] - 1,
                len(target) - 1)

        if target[c].strip():
            fixed = target
        else:
            fixed = target[:c].rstrip() + target[c:].lstrip()

        # There could be an escaped newline
        #
        #     def foo(a=\
        #             1)
        if fixed.endswith(('=\\\n', '=\\\r\n', '=\\\r')):
            self.source[line_index] = fixed.rstrip('\n\r \t\\')
            self.source[line_index + 1] = self.source[line_index + 1].lstrip()
            return [line_index + 1, line_index + 2]  # Line indexed at 1

        self.source[result['line'] - 1] = fixed
1324493
def pygmentify(value, **kwargs):
    """"""
    soup = BeautifulSoup(value, 'html.parser')
    for pre in soup.find_all('pre'):

        # Get code
        code = ''.join([to_string(item) for item in pre.contents])
        code = code.replace('&lt;', '<')
        code = code.replace('&gt;', '>')
        code = code.replace('&#39;', "'")
        code = code.replace('&quot;', '"')
        code = code.replace('&amp;', '&')

        # Get lexer by language
        class_list = pre.get('class', [])
        lexers = []
        options = {
            'stripall': True
        }

        # Collect all found lexers
        for c in class_list:
            try:
                lexers.append(get_lexer_by_name(c, **options))
            except ClassNotFound:
                pass

        # Get first lexer match or none
        try:
            lexer = lexers[0]
        except IndexError:
            lexer = None

        # If no lexer, try guessing
        if lexer is None:
            try:
                lexer = guess_lexer(pre.text, **options)
                class_list += [alias for alias in lexer.aliases]
            except ClassNotFound:
                pass

        if lexer is not None:

            # Get formatter
            formatter = HtmlFormatter(**kwargs)

            # Highlight code
            highlighted = highlight(code, lexer, formatter)
            class_string = ' '.join([c for c in class_list])
            highlighted = highlighted.replace(
                '<div class="%s"><pre>' % kwargs['cssclass'],
                '<div class="%s"><pre class="%s">' % (kwargs['cssclass'], class_string)
            )
            pre.replace_with(highlighted)

    return soup.decode(formatter=None).strip()
278975
def get_pygments_style(style):
    """"""
    if isinstance(style, StyleMeta):
        return style
    if '.' in style:  # by python package/module
        module, name = style.rsplit('.', 1)
        return getattr(__import__(module, None, None, ['__name__']), name)
    else:             # by name
        if style == 'sphinx':
            from sphinx.pygments_styles import SphinxStyle
            return SphinxStyle
        elif style == 'pyramid':
            from sphinx.pygments_styles import PyramidStyle
            return PyramidStyle
        elif style == 'none':
            from sphinx.pygments_styles import NoneStyle
            return NoneStyle
        else:
            return get_style_by_name(style)
513658
def on_install(self, editor):
        
        self._clear_caches()
        self._update_style()
        super(PygmentsSH, self).on_install(editor)
201513
function setupShapeColor() {
    var bgOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bgOpacity;
    r.eleFillStyle(context, node, bgOpy);
  }
452947
def __blackpkg(self, bl, repo, pkg):
        
        if bl.startswith("*") and bl.endswith("*"):
            if bl[1:-1] in pkg:
                self.black.append(self.__add(repo, pkg))
        elif bl.endswith("*"):
            if pkg.startswith(bl[:-1]):
                self.black.append(self.__add(repo, pkg))
        elif bl.startswith("*"):
            if pkg.endswith(bl[1:]):
                self.black.append(self.__add(repo, pkg))
        if bl not in self.black and "*" not in bl:
            self.black.append(bl)
248883
def message(obj, commit='HEAD', skip_merge_commits=False):
    """"""
    from ..kwalitee import check_message
    options = obj.options
    repository = obj.repository

    if options.get('colors') is not False:
        colorama.init(autoreset=True)
        reset = colorama.Style.RESET_ALL
        yellow = colorama.Fore.YELLOW
        green = colorama.Fore.GREEN
        red = colorama.Fore.RED
    else:
        reset = yellow = green = red = ''

    try:
        sha = 'oid'
        commits = _pygit2_commits(commit, repository)
    except ImportError:
        try:
            sha = 'hexsha'
            commits = _git_commits(commit, repository)
        except ImportError:
            click.echo('To use this feature, please install pygit2. '
                       'GitPython will also work but is not recommended '
                       '(python <= 2.7 only).',
                       file=sys.stderr)
            return 2

    template = '{0}commit {{commit.{1}}}{2}\n\n'.format(yellow, sha, reset)
    template += '{message}{errors}'

    count = 0
    ident = '    '
    re_line = re.compile('^', re.MULTILINE)
    for commit in commits:
        if skip_merge_commits and _is_merge_commit(commit):
            continue
        message = commit.message
        errors = check_message(message, **options)
        message = re.sub(re_line, ident, message)
        if errors:
            count += 1
            errors.insert(0, red)
        else:
            errors = [green, 'Everything is OK.']
        errors.append(reset)

        click.echo(template.format(commit=commit,
                                   message=message.encode('utf-8'),
                                   errors='\n'.join(errors)))

    if min(count, 1):
        raise click.Abort
593010
def color_parts(parts):
    """"""
    return parts._replace(
        title=Fore.GREEN + parts.title + Style.RESET_ALL,
        doi=Fore.CYAN + parts.doi + Style.RESET_ALL
    )
1072481
def every(colors, output_dir=CACHE_DIR):
    """"""
    colors = flatten_colors(colors)
    template_dir = os.path.join(MODULE_DIR, "templates")
    template_dir_user = os.path.join(CONF_DIR, "templates")
    util.create_dir(template_dir_user)

    join = os.path.join  # Minor optimization.
    for file in [*os.scandir(template_dir),
                 *os.scandir(template_dir_user)]:
        if file.name != ".DS_Store" and not file.name.endswith(".swp"):
            template(colors, file.path, join(output_dir, file.name))

    logging.info("Exported all files.")
    logging.info("Exported all user files.")
1307511
def fix(args):
    
    p = OptionParser(fix.__doc__)
    p.add_option("--ignore_sym_pat", default=False, action="store_true",
        help="Do not fix names matching symbol patterns i.e." + \
        " names beginning or ending with gene symbols or a series of numbers." + \
        " e.g. `ARM repeat superfamily protein`, `beta-hexosaminidase 3`," + \
        " `CYCLIN A3;4`, `WALL ASSOCIATED KINASE (WAK)-LIKE 10`")
    p.set_outfile()
    opts, args = p.parse_args(args)

    if len(args) < 1:
        sys.exit(not p.print_help())

    csvfile, = args
    fp = open(csvfile)
    fw = must_open(opts.outfile, "w")
    for row in fp:
        if row[0] == '#':
            continue
        if row.strip() == "":
            continue
        atoms = row.rstrip("\r\n").split("\t")
        name, hit, ahrd_code, desc = atoms[:4] \
                if len(atoms) > 2 else \
                (atoms[0], None, None, atoms[-1])

        newdesc = fix_text(desc, ignore_sym_pat=opts.ignore_sym_pat)
        if hit and hit.strip() != "" and newdesc == Hypothetical:
            newdesc = "conserved " + newdesc
        print("\t".join(atoms[:4] + [newdesc] + atoms[4:]), file=fw)
1179158
def _get_pygments_extensions():
    """"""
    # NOTE: Leave this import here to keep startup process fast!
    import pygments.lexers as lexers

    extensions = []
    for lx in lexers.get_all_lexers():
        lexer_exts = lx[2]

        if lexer_exts:
            # Reference: This line was included for leaving untrimmed the
            # extensions not starting with `*`
            other_exts = [le for le in lexer_exts if not le.startswith('*')]
            # Reference: This commented line was replaced by the following one
            # to trim only extensions that start with '*'
            # lexer_exts = [le[1:] for le in lexer_exts]
            lexer_exts = [le[1:] for le in lexer_exts if le.startswith('*')]
            lexer_exts = [le for le in lexer_exts if not le.endswith('_*')]
            extensions = extensions + list(lexer_exts) + list(other_exts)

    return sorted(list(set(extensions)))
269570
def merge(args):
    
    p = OptionParser(merge.__doc__)
    p.add_option("--colorlist", default="black,red,pink,blue,green",
                 help="The color palette [default: %default]")
    opts, args = p.parse_args(args)

    if len(args) < 1:
        sys.exit(not p.print_help())

    colorlist = opts.colorlist.split(",")
    assert len(colorlist) >= len(args), "Need more colors in --colorlist"

    g = BiGraph()
    for a, c in zip(args, colorlist):
        g.read(a, color=c)

    g.draw("merged.png")