<commit_before># -*- Mode: Python -*-

import re
import sys
import time
import zlib
import coro

from urllib import splitquery
from urlparse import parse_qs
from cgi import escape

favicon = (
    'AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAA'
    'AAAAAAD///8A////AP///wD9/f0A2uXsKbTN3FVFqeHlQqfe6mqhva1bsuLKj8Pfhu/v7w////8A'
    '////AP///wD///8A////AP///wD8/f0AabXfuTat7v1lrs26V7Hc0G242LSBxN2cSqvd4E2s3d2K'
    'wNKNv9LYR/z8/AH///8A////AP///wDv8/YSk7zSfkir3uJpt9i5ldToh5XU6IeV1OiHldToh5XU'
    '<KEY>'
    '<KEY>'
    'ldToh5TU54eQzeCKlNTnh5XU6IeV1OiHjcjbjYa/0ZKSzd+G5unqGY7E4ohqsc+0PVdfzQQFBvoE'
    'Bgb6OFFY0JXU6IeGwNKSAAAA/5DN4IqV1OiHWX+KtQUGBvoJDQ73UXN+vbjR2VI5pOD2WrLcyz1X'
    'X81FYmvHea29mwIDA/2U1OeHhsDSkgAAAP+QzeCKjsvdjAUGB/pql6WqlNPnh4O7zJScx9R1Xq3Y'
    'xXnA26Q9V1/NGiYp6Sc3PN4rPkTbldToh4bA0pIAAAD/kM3ginquvpsCAwP9lNPmh5XU6IeV1OiH'
    'j8LShmGs1cB9wtygPVdfzSw+RNs7VFvPLD9F25XU6IeGwNKSAAAA/5DN4IqDu8yUAAAA/YjC1JGV'
    '<KEY>'
    '<KEY>'
    '<KEY>'
    'ldToh5XU6IeV1OiHldToh5XU6IeV1OiHk83ghuTn6Rr///8Ah8Likzat7v2GxdqUldToh5XU6IeV'
    '<KEY>'
    '2s2PzeKNldToh5XU6IeV1OiHldToh5XU6IeV1OiHlNTnh6rJ02P6+voD////AP///wD///8A////'
    'AJXH4382quv8VanQzl+028dgtNvEisnekFux2spIq97je7jPnr3R10r6+voD////AP///wD///8A'
    '////AP///wD///8A7/HxD7/P10dSruDVPqbg7mSdu7NKrOHecrrirejr7Rf///8A////AP///wD/'
    '//8A/B8AAOAPAADgBwAAgAMAAIABAAAAAQAAAAEAAAAAAAAAAAAAAAEAAIABAACAAQAAgAMAAOAH'
    'AADwDwAA/B8AAA=='
    ).decode ('base64')

from __main__ import *

# all this CSS magic is stolen from looking at the output from pident.artefact2.com
css = """
<style type="text/css">
body { font-family: monospace; }
table > tbody > tr:nth-child(odd) {
	background-color:#f0f0f0;
}
table > tbody > tr:nth-child(even) {
	background-color:#e0e0e0;
}
table { width:100%; }
tr.inrow { border:1px green; }
tr.plus > td { background-color:#80ff80; }
tr.minus > td { background-color:#ff8080; }
a.alert { color:#ff0000; }
</style>
"""

def shorten (s, w=20):
    if len(s) > w:
        return s[:w] + '&hellip;'
    else:
        return s

def shorthex (s):
    return shorten (hexify (s))

class handler:

    def __init__ (self):
        self.pending_send = []

    def match (self, request):
        return request.path.startswith ('/admin/')

    safe_cmd = re.compile ('[a-z]+')

    def handle_request (self, request):
        parts = request.path.split ('/')[2:] # ignore ['', 'admin']
        subcmd = parts[0]
        if not subcmd:
            subcmd = 'status'
        method_name = 'cmd_%s' % (subcmd,)
        if self.safe_cmd.match (subcmd) and hasattr (self, method_name):
            request['content-type'] = 'text/html'
            request.set_deflate()
            method = getattr (self, method_name)
            request.push (
                '\r\n'.join ([
                        '<!DOCTYPE HTML><html><head><meta charset="UTF-8"><title>Caesure admin</title>',
                        css,
                        '</head><body>',
                        '<h1>caesure admin</h1>',
                        ])
                )
            self.menu (request)
            try:
                method (request, parts)
            except SystemExit:
                raise
            except:
                request.push ('<strong>something went wrong</strong><br><br>')
                request.push ('<pre>%r</pre>' % (coro.compact_traceback(),))
            request.push ('<hr>')
            self.menu (request)
            request.push ('</body></html>')
            request.done()
        else:
            request.error (400)

    def menu (self, request):
        request.push (
            '&nbsp;&nbsp;<a href="/admin/reload">reload</a>'
            '&nbsp;&nbsp;<a href="/admin/status">status</a>'
            '&nbsp;&nbsp;<a href="/admin/block/">blocks</a>'
            '&nbsp;&nbsp;<a href="/admin/send/">send</a>'
            '&nbsp;&nbsp;<a href="/admin/connect/">connect</a>'
            '&nbsp;&nbsp;<a href="/admin/shutdown/">shutdown</a>'
            )

    def cmd_status (self, request, parts):
        db = the_block_db
        RP = request.push
        RP ('<h3>last block</h3>')
        RP ('hash[es]: %s' % (escape (repr (db.num_block[db.last_block]))))
        RP ('<br>num: %d' % (db.last_block,))
        RP ('<h3>connections</h3>')
        RP ('<table><thead><tr><th>packets</th><th>address</th><tr></thead>')
        for conn in the_connection_list:
            try:
                addr, port = conn.getpeername()
                RP ('<tr><td>%d</td><td>%s:%d</td></tr>' % (conn.packet_count, addr, port))
            except:
                RP ('<br>dead connection</br>')
        RP ('</table><hr>')

    def dump_block (self, request, b, num, name):
        RP = request.push
        RP ('\r\n'.join ([
            '<br>block: %d' % (num,),
            '<br>name: %s' % (name,),
            '<br>prev: %s' % (b.prev_block,),
            '<br>merk: %s' % (hexify (b.merkle_root),),
            '<br>time: %s (%s)' % (b.timestamp, time.ctime (b.timestamp)),
            '<br>bits: %s' % (b.bits,),
            '<br>nonce: %s' % (b.nonce,),
            '<br><a href="https://blockexplorer.com/b/%d">block explorer</a>' % (num,),
            '<br><a href="https://blockchain.info/block/%s">blockchain.info</a>' % (name,),
        ]))
        #RP ('<pre>%d transactions\r\n' % len(b.transactions))
        RP ('<table><thead><tr><th>num</th><th>ID</th><th>inputs</th><th>outputs</th></tr></thead>')
        for i in range (len (b.transactions)):
            self.dump_tx (request, b.transactions[i], i)
        RP ('</table>')
        #RP ('</pre>')
        
    def cmd_block (self, request, parts):
        db = the_block_db
        RP = request.push<commit_msg>fix connection list output on admin/status/<commit_after># -*- Mode: Python -*-

import re
import sys
import time
import zlib
import coro

from urllib import splitquery
from urlparse import parse_qs
from cgi import escape

favicon = (
    'AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAA'
    'AAAAAAD///8A////AP///wD9/f0A2uXsKbTN3FVFqeHlQqfe6mqhva1bsuLKj8Pfhu/v7w////8A'
    '////AP///wD///8A////AP///wD8/f0AabXfuTat7v1lrs26V7Hc0G242LSBxN2cSqvd4E2s3d2K'
    '<KEY>'
    '<KEY>'
    '<KEY>'
    '<KEY>'
    '<KEY>'
    '<KEY>'
    '<KEY>'
    '<KEY>'
    '<KEY>AP87VV3OapinqCU1'
    'OeAlNTrgTG14wFl/iracx9R1rdHlYlut08holaOqSmpzwk9xfL2BucmWbZupp0pqc8JKanPCSmpz'
    'wnKhsaOLx9mOTG12wUJfZ8l8sMCbuNLZU////wBFn9DiXbHYxpXU6IeV1OiHldToh5XU6IeV1OiH'
    'ldToh5XU6IeV1OiHldToh5XU6IeV1OiHk83ghuTn6Rr///8Ah8Likzat7v2GxdqUldToh5XU6IeV'
    '1OiHldToh5XU6IeV1OiHldToh5XU6IeV1OiHlNTnh7fO1lD///8A////AP39/<KEY>'
    '2s2PzeKNldToh5XU6IeV1OiHldToh5XU6IeV1OiHlNTnh6rJ02P6+voD////AP///wD///8A////'
    'AJXH4382quv8VanQzl+028dgtNvEisnekFux2spIq97je7jPnr3R10r6+voD////AP///wD///8A'
    '////AP///wD///8A7/HxD7/P10dSruDVPqbg7mSdu7NKrOHecrrirejr7Rf///8A////AP///wD/'
    '//8A/B8AAOAPAADgBwAAgAMAAIABAAAAAQAAAAEAAAAAAAAAAAAAAAEAAIABAACAAQAAgAMAAOAH'
    'AADwDwAA/B8AAA=='
    ).decode ('base64')

from __main__ import *

# all this CSS magic is stolen from looking at the output from pident.artefact2.com
css = """
<style type="text/css">
body { font-family: monospace; }
table > tbody > tr:nth-child(odd) {
	background-color:#f0f0f0;
}
table > tbody > tr:nth-child(even) {
	background-color:#e0e0e0;
}
table { width:100%; }
tr.inrow { border:1px green; }
tr.plus > td { background-color:#80ff80; }
tr.minus > td { background-color:#ff8080; }
a.alert { color:#ff0000; }
</style>
"""

def shorten (s, w=20):
    if len(s) > w:
        return s[:w] + '&hellip;'
    else:
        return s

def shorthex (s):
    return shorten (hexify (s))

class handler:

    def __init__ (self):
        self.pending_send = []

    def match (self, request):
        return request.path.startswith ('/admin/')

    safe_cmd = re.compile ('[a-z]+')

    def handle_request (self, request):
        parts = request.path.split ('/')[2:] # ignore ['', 'admin']
        subcmd = parts[0]
        if not subcmd:
            subcmd = 'status'
        method_name = 'cmd_%s' % (subcmd,)
        if self.safe_cmd.match (subcmd) and hasattr (self, method_name):
            request['content-type'] = 'text/html'
            request.set_deflate()
            method = getattr (self, method_name)
            request.push (
                '\r\n'.join ([
                        '<!DOCTYPE HTML><html><head><meta charset="UTF-8"><title>Caesure admin</title>',
                        css,
                        '</head><body>',
                        '<h1>caesure admin</h1>',
                        ])
                )
            self.menu (request)
            try:
                method (request, parts)
            except SystemExit:
                raise
            except:
                request.push ('<strong>something went wrong</strong><br><br>')
                request.push ('<pre>%r</pre>' % (coro.compact_traceback(),))
            request.push ('<hr>')
            self.menu (request)
            request.push ('</body></html>')
            request.done()
        else:
            request.error (400)

    def menu (self, request):
        request.push (
            '&nbsp;&nbsp;<a href="/admin/reload">reload</a>'
            '&nbsp;&nbsp;<a href="/admin/status">status</a>'
            '&nbsp;&nbsp;<a href="/admin/block/">blocks</a>'
            '&nbsp;&nbsp;<a href="/admin/send/">send</a>'
            '&nbsp;&nbsp;<a href="/admin/connect/">connect</a>'
            '&nbsp;&nbsp;<a href="/admin/shutdown/">shutdown</a>'
            )

    def cmd_status (self, request, parts):
        db = the_block_db
        RP = request.push
        RP ('<h3>last block</h3>')
        RP ('hash[es]: %s' % (escape (repr (db.num_block[db.last_block]))))
        RP ('<br>num: %d' % (db.last_block,))
        RP ('<h3>connections</h3>')
        RP ('<table><thead><tr><th>packets</th><th>address</th><tr></thead>')
        for conn in the_connection_list:
            try:
                addr, port = conn.conn.getpeername()
                RP ('<tr><td>%d</td><td>%s:%d</td></tr>' % (conn.packet_count, addr, port))
            except:
                RP ('<br>dead connection</br>')
        RP ('</table><hr>')

    def dump_block (self, request, b, num, name):
        RP = request.push
        RP ('\r\n'.join ([
            '<br>block: %d' % (num,),
            '<br>name: %s' % (name,),
            '<br>prev: %s' % (b.prev_block,),
            '<br>merk: %s' % (hexify (b.merkle_root),),
            '<br>time: %s (%s)' % (b.timestamp, time.ctime (b.timestamp)),
            '<br>bits: %s' % (b.bits,),
            '<br>nonce: %s' % (b.nonce,),
            '<br><a href="https://blockexplorer.com/b/%d">block explorer</a>' % (num,),
            '<br><a href="https://blockchain.info/block/%s">blockchain.info</a>' % (name,),
        ]))
        #RP ('<pre>%d transactions\r\n' % len(b.transactions))
        RP ('<table><thead><tr><th>num</th><th>ID</th><th>inputs</th><th>outputs</th></tr></thead>')
        for i in range (len (b.transactions)):
            self.dump_tx (request, b.transactions[i], i)
        RP ('</table>')
        #RP ('</pre>')
        
    def cmd_block (self, request, parts):
        db = the_block_db
        RP = request.push
{'fraction_non_alphanumeric': 0.17707964601769913, 'fraction_numerical': 0.03150442477876106, 'mean_word_length': 2.311163199531204, 'pattern_counts': {'":': 0, '<': 191, '<?xml version=': 0, '>': 205, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 6, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4062350', 'n_tokens_mistral': 4664, 'n_tokens_neox': 4450, 'n_words': 670}