Ejemplo n.º 1
0
def main():
    """Get a pylint error description by an error code."""

    parser = argparse.ArgumentParser(description=(
        'Get a verbose description of a pylint error by an error code.'))
    parser.add_argument('code',
                        metavar='error code',
                        type=str,
                        help='a pylint error code either r1710 or R1710')
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version=f'plerr v{__version__}')
    args = parser.parse_args()

    root = pathlib.Path(__file__).resolve().parent
    try:
        error = next(root.rglob(f'*{args.code.upper()}.md'))
        content = error.read_bytes()
        print(highlight(content, MarkdownLexer(), TerminalFormatter()))
        sys.exit(0)
    except StopIteration:
        print(f'Cannot find {args.code} pylint error by such error code.',
              file=sys.stderr)
        sys.exit(1)
Ejemplo n.º 2
0
 def method_not_allowed(ex):
     return render_template(
         'paste_show.html',
         text=highlight(method_not_allowed_text, MarkdownLexer(),
                        HtmlFormatter()),
         lines=method_not_allowed_text.count('\n') + 1,
     ), 405
Ejemplo n.º 3
0
    def rate_limit(ex):
        text = f"""
# Too Many Requests

**Limit: {app.config.get('RATELIMIT_DEFAULT')}**"""
        return render_template('view/view.html',
                               text=highlight(text, MarkdownLexer(),
                                              HtmlFormatter()),
                               lines=text.count('\n') + 1), 429
Ejemplo n.º 4
0
    def too_large(ex):
        text = f"""
# Too many characters

Limit: {app.config['MAX_PASTE_LENGTH']}"""
        return render_template(
            'view/view.html',
            text=highlight(text, MarkdownLexer(), HtmlFormatter()),
            lines=text.count('\n') + 1,
        ), 413
Ejemplo n.º 5
0
def render_link(post):
    if post.is_self:
        content = highlight(post.selftext, MarkdownLexer(),
                            TerminalFormatter())
        content = urwidify_content(content)
        return urwid.Filler(urwid.ListBox(content),
                            valign='top',
                            height=('relative', 100))
    else:
        return render_web(post)
Ejemplo n.º 6
0
def readme():
    '''
    Show CogniVal README.md.
―
    '''
    ctx = context.get_context()
    cognival_path = ctx.cognival_path
    with open(cognival_path / 'README.md') as f:
        highlighted_str = highlight(f.read(), MarkdownLexer(),
                                    TerminalFormatter())
    page_list([highlighted_str.encode('utf-8')])
Ejemplo n.º 7
0
        def unknown_error(ex):
            tb = traceback.format_exc()
            try:
                mail.send(
                    Message(subject=f'Error From {request.host_url}',
                            recipients=[app.config['MAIL_RECIPIENT']],
                            body=render_template('email/error.txt.jinja',
                                                 tb=tb),
                            html=render_template('email/error.html.jinja',
                                                 tb=tb)))
            except Exception:
                pass  # Ignore, we're going to log it anyway

            app.logger.exception(
                f'Unknown error at endpoint: {request.full_path}')
            return render_template('view/view.html',
                                   text=highlight(unknown_error_text,
                                                  MarkdownLexer(),
                                                  HtmlFormatter()),
                                   lines=unknown_error_text.count('\n') +
                                   1), 500
    def __init__(self, parent, text_widget, initial_content):
        self.parent = parent
        self.syntax_and_themes = SyntaxAndThemes(self)
        self.settings = parent.settings
        self.text = text_widget
        self.font_family = parent.font_family
        self.font_size = parent.font_size
        self.previousContent = initial_content

        self.lexer = MarkdownLexer()
        self.comment_color = None
        self.string_color = None
        self.number_color = None
        self.keyword_color = None
        self.type_color = None
        self.operator_color = None
        self.bultin_function_color = None
        self.class_color = None
        self.namespace_color = None
        self.class_name_color = None
        self.function_name_color = None
        self.text_color = None
Ejemplo n.º 9
0
def main():
    """Get a pylint error description by an error code."""

    parser = argparse.ArgumentParser(description=(
        'Get a verbose description of a pylint error by an error code.'))
    parser.add_argument('code',
                        metavar='code',
                        type=str,
                        help='A pylint error code e.g. R1710')
    args = parser.parse_args()

    root = pathlib.Path(__file__).resolve().parent
    error = list(root.rglob('*{}.md'.format(args.code)))
    try:
        print(
            highlight(error[0].read_bytes(), MarkdownLexer(),
                      TerminalFormatter()))
        sys.exit(0)
    except IndexError:
        print('Cannot find {} pylint error by such error code.'.format(
            args.code),
              file=sys.stderr)
        sys.exit(1)
Ejemplo n.º 10
0
    def unknown_error(ex):
        @copy_current_request_context
        def send_message(message):
            try:
                mail.send(message)
            except Exception:
                pass  # Ignore, we're going to log it anyway

        tb = traceback.format_exc()
        message = Message(subject=f'Error From {request.host_url}',
                          recipients=[app.config['MAIL_RECIPIENT']],
                          body=render_template('email/error.txt.jinja', tb=tb),
                          html=render_template('email/error.html.jinja',
                                               tb=tb))
        thread = threading.Thread(target=send_message, args=(message, ))
        thread.start()

        app.logger.exception(
            f'Unknown error at endpoint: {request.method} {request.full_path}')
        return render_template('paste_show.html',
                               text=highlight(unknown_error_text,
                                              MarkdownLexer(),
                                              HtmlFormatter()),
                               lines=unknown_error_text.count('\n') + 1), 500
Ejemplo n.º 11
0
style_menu.add_command(label=lang['style'][2], command=lambda: textbox.tagger('underline'))

syntax_menu.add_command(label='Python 3', command=lambda: textbox.set_lexer(Python3Lexer()))
syntax_menu.add_command(label='C/C++', command=lambda: textbox.set_lexer(CppLexer()))
syntax_menu.add_command(label='C#', command=lambda: textbox.set_lexer(CSharpLexer()))
syntax_menu.add_command(label='Java', command=lambda: textbox.set_lexer(JavaLexer()))
syntax_menu.add_command(label='Rust', command=lambda: textbox.set_lexer(RustLexer()))
syntax_menu.add_command(label='Go', command=lambda: textbox.set_lexer(GoLexer()))
syntax_menu.add_command(label='HTML', command=lambda: textbox.set_lexer(HtmlLexer()))
syntax_menu.add_command(label='CSS', command=lambda: textbox.set_lexer(CssLexer()))
syntax_menu.add_command(label='Javascript', command=lambda: textbox.set_lexer(JavascriptLexer()))
syntax_menu.add_command(label='PHP', command=lambda: textbox.set_lexer(PhpLexer()))
syntax_menu.add_command(label='SQL', command=lambda: textbox.set_lexer(SqlLexer()))
syntax_menu.add_command(label='Batch', command=lambda: textbox.set_lexer(BatchLexer()))
syntax_menu.add_command(label='Bash', command=lambda: textbox.set_lexer(BashLexer()))
syntax_menu.add_command(label='Markdown', command=lambda: textbox.set_lexer(MarkdownLexer()))

for font_name in settings["fonts"]:
	font_menu.add_command(label=font_name, command=lambda font_name=font_name: textbox.change_font(font_name, 0))

for size in range(settings["min_font_size"], 
	settings["max_font_size"] + settings["font_size_interval"], 
	settings["font_size_interval"]):
	font_size_menu.add_command(label=size, command=lambda size=size: textbox.change_font(size, 1))

for song in os.listdir('sound'):
	favorites_menu.add_command(label=song, command=lambda song=song: play_song(f'sound/{song}'))

music_menu.add_command(label=lang['music'][0], command=open_audio)
music_menu.add_cascade(label=lang['music'][1], menu=favorites_menu)
music_menu.add_separator()
Ejemplo n.º 12
0
class CommentDisplay(urwid.WidgetWrap):
    mardown_lexer = MarkdownLexer()
    terminal_formatter = TerminalFormatter()

    def __init__(self, post):
        self.collapsed = set()
        self.root = urwid.WidgetPlaceholder(
            urwid.ListBox([urwid.Text('loading')]))
        super().__init__(self.root)
        self.create_comment_list(post)

    def render_comments(self, index=0):
        cmts = []
        skipdepth = 9999
        for i in range(len(self.comments)):
            if self.comments[i].depth > skipdepth:
                continue
            else:
                skipdepth = 9999
            if self.comments[i].id in self.collapsed:
                if self.comments[i].depth < skipdepth:
                    skipdepth = self.comments[i].depth
            cmts.append(self.render_comment(self.comments[i], i))

        cmts.append(urwid.Text(''))
        self.root.original_widget = urwid.ListBox(cmts)
        self.root.original_widget.focus_position = index

    def render_comment(self, comment, index):
        if type(comment) is praw.models.Comment:
            content = highlight(comment.body, self.mardown_lexer,
                                self.terminal_formatter)
            content = urwidify_content(content)
            header = SelectableButton('[{}] {} | {} | /u/{}{}'.format(
                '+' if comment.id in self.collapsed else '-',
                '*' if comment.score_hidden else comment.score,
                arrow.get(comment.created_utc).to('local').humanize(),
                comment.author.name if comment.author is not None else
                '[deleted]', ' (op)' if comment.is_submitter else ''))
            urwid.connect_signal(header, 'click', self.toggle_collapse,
                                 (comment.id, index))
            lb = urwid.Pile([
                urwid.AttrMap(header,
                              'comment_header',
                              focus_map='comment_header_active')
            ] + ([] if comment.id in self.collapsed else content))
        else:
            loadmore = urwid.Button('load more comments')
            urwid.connect_signal(loadmore, 'click', self.expand_at, index)
            lb = urwid.AttrMap(loadmore, None, focus_map='selected')

        return urwid.Padding(lb, left=comment.depth * 2)

    def toggle_collapse(self, button, data):
        if data[0] in self.collapsed:
            self.collapsed.remove(data[0])
        else:
            self.collapsed.add(data[0])
        self.render_comments(self.root.original_widget.focus_position)

    def create_comment_list(self, post):
        self.comments = []
        flats = [self.flatten_comments(c) for c in list(post.comments)]
        for flat in flats:
            self.comments += flat
        self.render_comments()

    def expand_at(self, button, index):
        if type(self.comments[index]) is praw.models.MoreComments:
            olddepth = self.comments[index].depth
            fst = self.comments[:index]
            lst = self.comments[index + 1:]

            cmts = self.comments[index].comments(update=False)

            cs = [self.flatten_comments(c, depth=olddepth) for c in cmts]
            mid = []
            for c in cs:
                mid += c

            self.comments = fst + mid + lst
            self.render_comments(self.root.original_widget.focus_position)
            #self.root.original_widget = urwid.ListBox([urwid.Text(repr(mid))])

    def flatten_comments(self, cobj, depth=0):
        cobj.depth = depth
        out = [cobj]

        if type(cobj) is praw.models.Comment:
            for reply in cobj.replies:
                out += self.flatten_comments(reply, depth + 1)
        return out
Ejemplo n.º 13
0
            md_path = os.path.join(path, name)
            if not '.git' in md_path and md_path.endswith('.md'):
                with open(md_path, 'r') as f:
                    for lines in f.readlines():
                        if re.search(pattern, lines):
                            if not any(filter in lines
                                       for filter in black_list):
                                match = (
                                    (re.sub('\*\*', '', lines)).lstrip() + '\n'
                                )  # .replace('`', "'")
                                if match.startswith('- ['):
                                    split = match.split(']')
                                    found += max(split, key=len).replace('[', '') + \
                                             ' [.](https://radare2.securisec.com%s' % split[-1].strip('(')
                                else:
                                    if match.startswith('>'):
                                        match = ''.join(list(match)[1:])
                                    if match.startswith('#'):
                                        match = ''.join(list(match)[1:])
                                    if match.startswith(' _'):
                                        match = re.sub(
                                            '_', '', ''.join(list(match)[1:]))
                                    found += match

    pydoc.pipepager(highlight(found, MarkdownLexer(), TerminalFormatter()),
                    cmd='less -R')
except IndexError:
    print 'Usage: %s search_param' % sys.argv[0]
except NameError:
    print 'pip install Pygments'
Ejemplo n.º 14
0
 def rate_limit(ex):
     text = rate_limit_text.format(app.config.get('RATELIMIT_DEFAULT'))
     return render_template('paste_show.html',
                            text=highlight(text, MarkdownLexer(),
                                           HtmlFormatter()),
                            lines=text.count('\n') + 1), 429
Ejemplo n.º 15
0
    line = []
    for tch in nobr:
        if tch[2]:
            lines.append(deepcopy(line))
            line = []
        line.append((tch[0], tch[1]))
    lines.append(deepcopy(line))

    out = []
    for ln in lines:
        out.append(urwid.SelectableIcon(ln, cursor_position=0))
    return out


if __name__ == '__main__':
    from pygments import highlight
    from pygments.lexers import MarkdownLexer
    from pygments.formatters import TerminalFormatter
    import json

    with open('/tmp/testmdraw', 'r') as f:
        text = '\n'.join(f.readlines())

    content = highlight(text, MarkdownLexer(), TerminalFormatter())
    content = urwidify_content(content)

    json.dump(get_palette(), open('/tmp/mdstyles', 'w'), indent=4)


    print(content)
Ejemplo n.º 16
0
 def not_found(ex):
     return render_template(
         'paste_show.html',
         text=highlight(not_found_text, MarkdownLexer(), HtmlFormatter()),
         lines=not_found_text.count('\n') + 1,
     ), 404
Ejemplo n.º 17
0
 def not_found(ex):
     return render_template('view/view.html',
                            text=highlight(not_found_text, MarkdownLexer(),
                                           HtmlFormatter()),
                            lines=not_found_text.count('\n') + 1,
                            status=404)
Ejemplo n.º 18
0
from style import NightOwl
from pygments.formatters.html import HtmlFormatter
from pygments import highlight
from pygments.lexers import CLexer, MarkdownLexer

if __name__ == "__main__":
    samples = {
        "samples/sample.c": CLexer(),
        "samples/sample.md": MarkdownLexer()
    }

    formatter = HtmlFormatter(style=NightOwl)
    formatter.style.background_color = '#011627'

    with open('test.html', 'w') as out_file:
        out_file.truncate()
        out_file.write(
            "<html><head><link rel='stylesheet' href='base.css'><style>{}</style></head><body>"
            .format(formatter.get_style_defs('div.highlight pre')))

        files = samples.keys()
        files.sort()

        for key in files:
            with open(key, 'r') as sample_file:
                out_file.write(
                    highlight(sample_file.read(), samples[key], formatter))
        out_file.write("</body></html>")
Ejemplo n.º 19
0
 def load_markdown_syntax(self):
     self.master.lexer = MarkdownLexer()
     self.master.initial_highlight()
Ejemplo n.º 20
0
 def missing_csrf(e):
     return render_template('paste_show.html',
                            text=highlight(
                                csrf_message.format(e.description),
                                MarkdownLexer(), HtmlFormatter()),
                            lines=csrf_message.count('\n') + 1), 400