import re
import gdb
import sys
from builtins import chr

if sys.version_info[0] > 2:
    # Python 3 stuff
    Iterator = object
    # Python 3 folds these into the normal functions.
    imap = map
    izip = zip
    # Also, int subsumes long
    long = int
else:
    # Python 2 stuff
    class Iterator:
        """Compatibility mixin for iterators

        Instead of writing next() methods for iterators, write
        __next__() methods and use this mixin to make them work in
        Python 2 as well as Python 3.

        Idea stolen from the "six" documentation:
        <http://pythonhosted.org/six/#six.Iterator>
        """

        def next(self):
            return self.__next__()

    # In Python 2, we still need these from itertools
    from itertools import imap, izip

# Try to use the new-style pretty-printing if available.
_use_gdb_pp = True
try:
    import gdb.printing
except ImportError:
    _use_gdb_pp = False

# Try to install type-printers.
_use_type_printing = False
try:
    import gdb.types
    if hasattr(gdb.types, 'TypePrinter'):
        _use_type_printing = True
except ImportError:
    pass

def make_type_re(typename):
    return re.compile('^std::__[a-zA-Z0-9]+::' + typename + '<.*>$')

def get_node_value(it, ptr):
    t = gdb.lookup_type(it.type.name + '::__node_pointer')
    return ptr.cast(t)['__value_']

def get_node_value_from_pointer(ptr):
    return get_node_value(ptr.dereference(), ptr)

def get_node_value_from_iterator(it):
    return get_node_value(it, it['__ptr_'])

# Starting with the type ORIG, search for the member type NAME.  This
# handles searching upward through superclasses.  This is needed to
# work around http://sourceware.org/bugzilla/show_bug.cgi?id=13615.
def find_type(orig, name):
    typ = orig.strip_typedefs()
    while True:
        search = str(typ) + '::' + name
        try:
            return gdb.lookup_type(search)
        except RuntimeError:
            pass
        # The type was not found, so try the superclass.  We only need
        # to check the first superclass, so we don't bother with
        # anything fancier here.
        field = typ.fields()[0]
        if not field.is_base_class:
            raise ValueError("Cannot find type %s::%s" % (orig, name))
        typ = field.type

def pair_to_tuple(val):
    if make_type_re('__compressed_pair').match(val.type.name):
        t1 = val.type.template_argument(0)
        t2 = val.type.template_argument(1)

        base1 = val.type.fields()[0].type
        base2 = val.type.fields()[1].type

        return ((val if base1.template_argument(2) else
                 val.cast(base1)["__value_"]).cast(t1),
                (val if base2.template_argument(2) else
                 val.cast(base2)["__value_"]).cast(t2))
    return (val['first'], val['second'])

void_type = gdb.lookup_type('void')

def ptr_to_void_ptr(val):
    if gdb.types.get_basic_type(val.type).code == gdb.TYPE_CODE_PTR:
        return val.cast(void_type.pointer())
    else:
        return val

class StringPrinter:
    "Print a std::basic_string of some kind"

    def __init__(self, typename, val):
        self.val = val
        self.typename = typename

    def to_string(self):
        # Make sure &string works, too.
        type = self.val.type
        if type.code == gdb.TYPE_CODE_REF:
            type = type.target()

        ss = pair_to_tuple(self.val['__r_'])[0]['__s']
        if '__short_mask' in self.val.type.fields():
            __short_mask = int(self.val['__short_mask'])
            if (ss['__size_'] & __short_mask) == 0:
                len = ss['__size_'] >> 1 if __short_mask == 1 else ss['__size_']
                ptr = ss['__data_']
            else:
                sl = pair_to_tuple(self.val['__r_'])[0]['__l']
                len = sl['__size_']
                ptr = sl['__data_']
        else:
            if (ss['__is_long_']) == 0:
                len = ss['__size_']
                ptr = ss['__data_']
            else:
                sl = pair_to_tuple(self.val['__r_'])[0]['__l']
                len = sl['__size_']
                ptr = sl['__data_']

        return u''.join(chr(ptr[i]) for i in range(len))

    def display_hint(self):
        return 'string'

class SmartPtrIterator(Iterator):
    "An iterator for smart pointer types with a single 'child' value"

    def __init__(self, val):
        self.val = val

    def __iter__(self):
        return self

    def __next__(self):
        if self.val is None:
            raise StopIteration
        self.val, val = None, self.val
        return ('get()', val)

class SharedPointerPrinter:
    "Print a shared_ptr or weak_ptr"

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val

    def children (self):
        v = self.val['__ptr_']
        return SmartPtrIterator(v)

    def to_string(self):
        state = 'empty'
        refcounts = self.val['__cntrl_']
        if refcounts != 0:
            usecount = refcounts['__shared_owners_'] + 1
            weakcount = refcounts['__shared_weak_owners_']
            if usecount == 0:
                state = 'expired, weak %d' % weakcount
            else:
                state = 'count %d, weak %d' % (usecount, weakcount)

        if self.val['__ptr_'] == 0:
            return '%s (%s) = %s <nullptr>' % (self.typename, state,
                                               self.val['__ptr_'])
        return '%s (%s) = %s => %s' % (self.typename, state,
                                       self.val['__ptr_'],
                                       self.val['__ptr_'].dereference())

class UniquePointerPrinter:
    "Print a unique_ptr"

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val

    def children (self):
        v = pair_to_tuple(self.val['__ptr_'])[0]
        return SmartPtrIterator(v)

    def to_string(self):
        v = pair_to_tuple(self.val['__ptr_'])[0]
        if v == 0:
            return '%s<%s> = %s <nullptr>' % (str(self.typename),
                                              str(v.type.target()), str(v))
        return '%s<%s> = %s => %s' % (str(self.typename), str(v.type.target()),
                                      str(v), v.dereference())

class PairPrinter:
    "Print a std::pair"

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val

    def children(self):
        vals = pair_to_tuple(self.val)
        return [('first', vals[0]), ('second', vals[1])]

    def to_string(self):
        return 'pair'

#    def display_hint(self):
#        return 'array'

class TuplePrinter:
    "Print a std::tuple"

    class _iterator(Iterator):
        def __init__(self, head):
            self.head = head['__base_']
            self.fields = self.head.type.fields()
            self.count = 0

        def __iter__(self):
            return self

        def __next__(self):
            if self.count >= len(self.fields):
                raise StopIteration
            field = self.head.cast(self.fields[self.count].type)['__value_']
            self.count += 1
            return ('[%d]' % (self.count - 1), field)

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val

    def children(self):
        return self._iterator(self.val)

    def to_string(self):
        if len(self.val.type.fields()) == 0:
            return 'empty %s' % (self.typename)
        return 'tuple'

class OptionalPrinter:
    "Print a std::optional"

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val

    def to_string(self):
        if not self.val['__engaged_']:
            return 'empty %s ' % (str(self.typename))
        return '%s : %s' % (str(self.typename), self.val['__val_'].to_string())

#    def display_hint(self):
#        return 'array'

class ListPrinter:
    "Print a std::list"

    class _iterator(Iterator):
        def __init__(self, nodetype, head):
            self.nodetype = nodetype
            self.base = head['__next_']
            self.head = head.address
            self.count = 0

        def __iter__(self):
            return self

        def __next__(self):
            if self.base == self.head:
                raise StopIteration
            elt = self.base.cast(self.nodetype).dereference()
            self.base = elt['__next_']
            count = self.count
            self.count = self.count + 1
            return ('[%d]' % count, elt['__value_'])

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val

    def children(self):
        nodebase = find_type(self.val.type, '__node_base')
        nodetype = find_type(nodebase, '__node_pointer')
        nodetype = nodetype.strip_typedefs()
        return self._iterator(nodetype, self.val['__end_'])

    def to_string(self):
        if self.val['__end_']['__next_'] == self.val['__end_'].address:
            return 'empty %s' % (self.typename)
        return '%s' % (self.typename)

#    def display_hint(self):
#        return 'array'

class ListIteratorPrinter:
    "Print std::list::iterator"

    def __init__(self, typename, val):
        self.val = val
        self.typename = typename

    def to_string(self):
        return get_node_value_from_pointer(self.val['__ptr_'])

class ForwardListPrinter:
    "Print a std::forward_list"

    class _iterator(Iterator):
        def __init__(self, head):
            self.node = head
            self.count = 0

        def __iter__(self):
            return self

        def __next__(self):
            if self.node == 0:
                raise StopIteration

            result = ('[%d]' % self.count, self.node['__value_'])
            self.count += 1
            self.node = self.node['__next_']
            return result

    def __init__(self, typename, val):
        self.val = val
        self.typename = typename
        self.head = pair_to_tuple(val['__before_begin_'])[0]['__next_']

    def children(self):
        return self._iterator(self.head)

    def to_string(self):
        if self.head == 0:
            return 'empty %s' % (self.typename)
        return '%s' % (self.typename)

class VectorPrinter:
    "Print a std::vector"

    class _iterator(Iterator):
        def __init__(self, start, finish_or_size, bits_per_word, bitvec):
            self.bitvec = bitvec
            if bitvec:
                self.item = start
                self.so = 0
                self.size = finish_or_size
                self.bits_per_word = bits_per_word
            else:
                self.item = start
                self.finish = finish_or_size
            self.count = 0

        def __iter__(self):
            return self

        def __next__(self):
            count = self.count
            self.count = self.count + 1
            if self.bitvec:
                if count == self.size:
                    raise StopIteration
                elt = self.item.dereference()
                if elt & (1 << self.so):
                    obit = 1
                else:
                    obit = 0
                self.so = self.so + 1
                if self.so >= self.bits_per_word:
                    self.item = self.item + 1
                    self.so = 0
                return ('[%d]' % count, obit)
            else:
                if self.item == self.finish:
                    raise StopIteration
                elt = self.item.dereference()
                self.item = self.item + 1
                return ('[%d]' % count, elt)

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val
        self.is_bool = 0
        for f in val.type.fields():
            if f.name == '__bits_per_word':
                self.is_bool = 1

    def children(self):
        if self.is_bool:
            return self._iterator(self.val['__begin_'], self.val['__size_'],
                                  self.val['__bits_per_word'], self.is_bool)
        else:
            return self._iterator(self.val['__begin_'], self.val['__end_'], 0,
                                  self.is_bool)

    def to_string(self):
        if self.is_bool:
            length = self.val['__size_']
            capacity = pair_to_tuple(
                self.val['__cap_alloc_'])[0] * self.val['__bits_per_word']
            if length == 0:
                return 'empty %s<bool> (capacity=%d)' % (self.typename,
                                                         int(capacity))
            else:
                return '%s<bool> (length=%d, capacity=%d)' % (
                    self.typename, int(length), int(capacity))
        else:
            start = ptr_to_void_ptr(self.val['__begin_'])
            finish = ptr_to_void_ptr(self.val['__end_'])
            end = ptr_to_void_ptr(pair_to_tuple(self.val['__end_cap_'])[0])
            size_of_value_type = self.val.type.template_argument(0).sizeof
            length = (finish - start) / size_of_value_type
            capacity = (end - start) / size_of_value_type
            if length == 0:
                return 'empty %s (capacity=%d)' % (self.typename,
                                                   int(capacity))
            else:
                return '%s (length=%d, capacity=%d)' % (
                    self.typename, int(length), int(capacity))

    def display_hint(self):
        return 'array'

class VectorIteratorPrinter:
    "Print std::vector::iterator"

    def __init__(self, typename, val):
        self.val = val

    def to_string(self):
        return self.val['__i'].dereference()

class VectorBoolIteratorPrinter:
    "Print std::vector<bool>::iterator"

    def __init__(self, typename, val):
        self.segment = val['__seg_'].dereference()
        self.ctz = val['__ctz_']

    def to_string(self):
        if self.segment & (1 << self.ctz):
            return 1
        else:
            return 0

class DequePrinter:
    "Print a std::deque"

    class _iterator(Iterator):
        def __init__(self, size, block_size, start, map_begin, map_end):
            self.block_size = block_size
            self.count = 0
            self.end_p = size + start
            self.end_mp = map_begin + self.end_p / block_size
            self.p = 0
            self.mp = map_begin + start / block_size
            if map_begin == map_end:
                self.p = 0
                self.end_p = 0
            else:
                self.p = self.mp.dereference() + start % block_size
                self.end_p = self.end_mp.dereference(
                ) + self.end_p % block_size

        def __iter__(self):
            return self

        def __next__(self):
            old_p = self.p

            self.count += 1
            self.p += 1
            if (self.p - self.mp.dereference()) == self.block_size:
                self.mp += 1
                self.p = self.mp.dereference()

            if (self.mp > self.end_mp) or ((self.p > self.end_p) and
                                           (self.mp == self.end_mp)):
                raise StopIteration

            return ('[%d]' % int(self.count - 1), old_p.dereference())

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val
        self.size = pair_to_tuple(val['__size_'])[0]

    def to_string(self):
        if self.size == 0:
            return 'empty %s' % self.typename
        else:
            return '%s (size=%d)' % (self.typename, long(self.size))

    def children(self):
        if self.size == 0:
            return []
        block_map = self.val['__map_']
        size_of_value_type = self.val.type.template_argument(0).sizeof
        block_size = self.val['__block_size']
        if block_size.is_optimized_out:
            # Warning, this is pretty flaky
            block_size = 4096 / size_of_value_type if size_of_value_type < 256 else 16
        return self._iterator(self.size, block_size, self.val['__start_'],
                              block_map['__begin_'], block_map['__end_'])

#    def display_hint (self):
#        return 'array'

class DequeIteratorPrinter:
    "Print std::deque::iterator"

    def __init__(self, typename, val):
        self.val = val

    def to_string(self):
        return self.val['__ptr_'].dereference()

class StackOrQueuePrinter:
    "Print a std::stack or std::queue"

    def __init__(self, typename, val):
        self.typename = typename
        self.visualizer = gdb.default_visualizer(val['c'])

    def children(self):
        return self.visualizer.children()

    def to_string(self):
        return '%s = %s' % (self.typename, self.visualizer.to_string())

    def display_hint(self):
        if hasattr(self.visualizer, 'display_hint'):
            return self.visualizer.display_hint()
        return None

class BitsetPrinter:
    "Print a std::bitset"

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val
        self.bit_count = val.type.template_argument(0)

    def to_string(self):
        return '%s (length=%d)' % (self.typename, self.bit_count)

    def children(self):
        words = self.val['__first_']
        words_count = self.val['__n_words']
        bits_per_word = self.val['__bits_per_word']
        word_index = 0
        result = []

        while word_index < words_count:
            bit_index = 0
            word = words[word_index]
            while word != 0:
                if (word & 0x1) != 0:
                    result.append(
                        ('[%d]' % (word_index * bits_per_word + bit_index), 1))
                word >>= 1
                bit_index += 1
            word_index += 1

        return result

class SetPrinter:
    "Print a std::set or std::multiset"

    # Turn an RbtreeIterator into a pretty-print iterator.
    class _iterator(Iterator):
        def __init__(self, rbiter):
            self.rbiter = rbiter
            self.count = 0

        def __iter__(self):
            return self

        def __len__(self):
            return len(self.rbiter)

        def __next__(self):
            item = self.rbiter.__next__()
            item = item.dereference()['__value_']
            result = (('[%d]' % self.count), item)
            self.count += 1
            return result

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val
        self.rbiter = RbtreeIterator(self.val['__tree_'])

    def to_string(self):
        length = len(self.rbiter)
        if length == 0:
            return 'empty %s' % self.typename
        else:
            return '%s (count=%d)' % (self.typename, int(length))

    def children(self):
        return self._iterator(self.rbiter)

#    def display_hint (self):
#        return 'set'

class RbtreeIterator(Iterator):
    def __init__(self, rbtree):
        self.node = rbtree['__begin_node_']
        self.size = pair_to_tuple(rbtree['__pair3_'])[0]
        self.node_pointer_type = gdb.lookup_type(
            rbtree.type.strip_typedefs().name + '::__node_pointer')
        self.count = 0

    def __iter__(self):
        return self

    def __len__(self):
        return int(self.size)

    def get_tree_min (self, node) :
        while node.dereference()['__left_'] :
            node = node.dereference()['__left_']
            pass
        return node

    def tree_is_left_child (self, node) :
        parent_node = node.cast (self.node_pointer_type).dereference()['__parent_']
        if node == parent_node.dereference() ['__left_'] :
            return True
        return False

    def __next__(self):
        if self.count == self.size:
            raise StopIteration

        self.count += 1
        node = self.node.cast(self.node_pointer_type)
        result = node
        # Compute the next node.
        if node.dereference()['__right_'] :
            self.node = self.get_tree_min (node.dereference()['__right_'])
            return result
        while node and (not self.tree_is_left_child (node)) :
            node = node.cast (self.node_pointer_type).dereference()['__parent_']
            pass
        self.node = node.cast (self.node_pointer_type).dereference()['__parent_']
        return result

class RbtreeIteratorPrinter:
    "Print std::set::iterator"

    def __init__(self, typename, val):
        self.val = val

    def to_string(self):
        return get_node_value_from_iterator(self.val)

class MapPrinter:
    "Print a std::map or std::multimap"

    # Turn an RbtreeIterator into a pretty-print iterator.
    class _iterator(Iterator):
        def __init__(self, rbiter):
            self.rbiter = rbiter
            self.count = 0

        def __iter__(self):
            return self

        def __len__(self):
            return len(self.rbiter)

        def __next__(self):
            item = self.rbiter.__next__()
            item = item.dereference()['__value_']
            result = ('[%d] %s' % (self.count, str(item['__cc']['first'])),
                      item['__cc']['second'])
            self.count += 1
            return result

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val
        self.rbiter = RbtreeIterator(val['__tree_'])

    def to_string(self):
        length = len(self.rbiter)
        if length == 0:
            return 'empty %s' % self.typename
        else:
            return '%s (count=%d)' % (self.typename, int(length))

    def children(self):
        return self._iterator(self.rbiter)

#    def display_hint (self):
#        return 'map'

class MapIteratorPrinter:
    "Print std::map::iterator"

    def __init__(self, typename, val):
        self.val = val

    def to_string(self):
        value = get_node_value_from_iterator(self.val['__i_'])
        return '[%s] %s' % pair_to_tuple(value['__cc'])

class HashtableIterator(Iterator):
    def __init__(self, hashtable):
        self.node = pair_to_tuple(hashtable['__p1_'])[0]['__next_']
        self.size = pair_to_tuple(hashtable['__p2_'])[0]

    def __iter__(self):
        return self

    def __len__(self):
        return self.size

    def __next__(self):
        if self.node == 0:
            raise StopIteration
        hash_node_type = gdb.lookup_type(self.node.dereference().type.name +
                                         '::__node_pointer')
        node = self.node.cast(hash_node_type).dereference()
        self.node = node['__next_']
        value = node['__value_']
        try:
            # unordered_map's value is a union of __nc and __cc.
            value = value['__nc']
        except gdb.error:
            pass
        return value

class HashtableIteratorPrinter:
    "Print std::unordered_set::iterator"

    def __init__(self, typename, val):
        self.val = val

    def to_string(self):
        return get_node_value_from_pointer(self.val['__node_'])

class UnorderedMapIteratorPrinter:
    "Print std::unordered_map::iterator"

    def __init__(self, typename, val):
        self.val = val

    def to_string(self):
        value = get_node_value_from_pointer(self.val['__i_']['__node_'])
        return '[%s] %s' % pair_to_tuple(value['__cc'])

class UnorderedSetPrinter:
    "Print a std::unordered_set"

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val
        self.hashtable = val['__table_']
        self.size = pair_to_tuple(self.hashtable['__p2_'])[0]
        self.hashtableiter = HashtableIterator(self.hashtable)

    def hashtable(self):
        return self.hashtable

    def to_string(self):
        if self.size == 0:
            return 'empty %s' % self.typename
        else:
            return '%s (count=%d)' % (self.typename, self.size)

    def children(self):
        result = []
        count = 0
        for elt in self.hashtableiter:
            result.append(('[%d]' % count, str(elt)))
            count += 1
        return result

class UnorderedMapPrinter:
    "Print a std::unordered_map"

    def __init__(self, typename, val):
        self.typename = typename
        self.val = val
        self.hashtable = val['__table_']
        self.size = pair_to_tuple(self.hashtable['__p2_'])[0]
        self.hashtableiter = HashtableIterator(self.hashtable)

    def hashtable(self):
        return self.hashtable

    def to_string(self):
        if self.size == 0:
            return 'empty %s' % self.typename
        else:
            return '%s (count=%d)' % (self.typename, self.size)

    def children(self):
        result = []
        count = 0
        for elt in self.hashtableiter:
            pair_type = str(elt.type.strip_typedefs()).replace('__hash_value_type', 'pair')
            pair = elt.cast(gdb.lookup_type(pair_type))
            result.append(('[%d] %s' % (count, str(pair['first'])), pair['second']))
            #result.append(('[%d] %s' % (count, str(elt['__cc']['first'])),
            #               elt['__cc']['second']))
            count += 1
        return result

#    def display_hint (self):
#        return 'map'

# A "regular expression" printer which conforms to the
# "SubPrettyPrinter" protocol from gdb.printing.

class RxPrinter(object):
    def __init__(self, name, function):
        super(RxPrinter, self).__init__()
        self.name = name
        self.function = function
        self.enabled = True

    def invoke(self, value):
        if not self.enabled:
            return None
        return self.function(self.name, value)

# A pretty-printer that conforms to the "PrettyPrinter" protocol from
# gdb.printing.  It can also be used directly as an old-style printer.

class Printer(object):
    def __init__(self, name):
        super(Printer, self).__init__()
        self.name = name
        self.subprinters = []
        self.lookup = []
        self.enabled = True

    def add(self, name, function):
        printer = RxPrinter('std::' + name, function)
        self.subprinters.append(printer)
        self.lookup.append((make_type_re(name), printer))

    @staticmethod
    def get_basic_type(type):
        # If it points to a reference, get the reference.
        if type.code == gdb.TYPE_CODE_REF:
            type = type.target()

        # Get the unqualified type, stripped of typedefs.
        type = type.unqualified().strip_typedefs()

        return type.tag

    def __call__(self, val):
        typename = self.get_basic_type(val.type)
        if not typename:
            return None

        for (regexp, printer) in self.lookup:
            if regexp.match(typename):
                return printer.invoke(val)

        # Cannot find a pretty printer.  Return None.
        return None

printer = None

class FilteringTypePrinter(object):
    def __init__(self, match, name):
        self.match = match
        self.name = name
        self.enabled = True

    class _recognizer(object):
        def __init__(self, match, name):
            self.match = match
            self.name = name
            self.type_obj = None

        def recognize(self, type_obj):
            if type_obj.tag is None:
                return None

            if self.type_obj is None:
                if not self.match in type_obj.tag:
                    # Filter didn't match.
                    return None
                try:
                    self.type_obj = gdb.lookup_type(self.name).strip_typedefs()
                except:
                    pass
            if self.type_obj == type_obj:
                return self.name
            return None

    def instantiate(self):
        return self._recognizer(self.match, self.name)

def add_one_type_printer(obj, match, name):
    printer = FilteringTypePrinter(match, 'std::' + name)
    gdb.types.register_type_printer(obj, printer)

def register_type_printers(obj):
    global _use_type_printing

    if not _use_type_printing:
        return

    for pfx in ('', 'w'):
        add_one_type_printer(obj, 'basic_string', pfx + 'string')
        add_one_type_printer(obj, 'basic_ios', pfx + 'ios')
        add_one_type_printer(obj, 'basic_streambuf', pfx + 'streambuf')
        add_one_type_printer(obj, 'basic_istream', pfx + 'istream')
        add_one_type_printer(obj, 'basic_ostream', pfx + 'ostream')
        add_one_type_printer(obj, 'basic_iostream', pfx + 'iostream')
        add_one_type_printer(obj, 'basic_stringbuf', pfx + 'stringbuf')
        add_one_type_printer(obj, 'basic_istringstream', pfx + 'istringstream')
        add_one_type_printer(obj, 'basic_ostringstream', pfx + 'ostringstream')
        add_one_type_printer(obj, 'basic_stringstream', pfx + 'stringstream')
        add_one_type_printer(obj, 'basic_filebuf', pfx + 'filebuf')
        add_one_type_printer(obj, 'basic_ifstream', pfx + 'ifstream')
        add_one_type_printer(obj, 'basic_ofstream', pfx + 'ofstream')
        add_one_type_printer(obj, 'basic_fstream', pfx + 'fstream')
        add_one_type_printer(obj, 'basic_regex', pfx + 'regex')
        add_one_type_printer(obj, 'sub_match', pfx + 'csub_match')
        add_one_type_printer(obj, 'sub_match', pfx + 'ssub_match')
        add_one_type_printer(obj, 'match_results', pfx + 'cmatch')
        add_one_type_printer(obj, 'match_results', pfx + 'smatch')
        add_one_type_printer(obj, 'regex_iterator', pfx + 'cregex_iterator')
        add_one_type_printer(obj, 'regex_iterator', pfx + 'sregex_iterator')
        add_one_type_printer(obj, 'regex_token_iterator',
                             pfx + 'cregex_token_iterator')
        add_one_type_printer(obj, 'regex_token_iterator',
                             pfx + 'sregex_token_iterator')

    # Note that we can't have a printer for std::wstreampos, because
    # it shares the same underlying type as std::streampos.
    add_one_type_printer(obj, 'fpos', 'streampos')
    add_one_type_printer(obj, 'basic_string', 'u16string')
    add_one_type_printer(obj, 'basic_string', 'u32string')

    for dur in ('nanoseconds', 'microseconds', 'milliseconds', 'seconds',
                'minutes', 'hours'):
        add_one_type_printer(obj, 'duration', dur)

    add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand0')
    add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand')
    add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937')
    add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937_64')
    add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux24_base')
    add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux48_base')
    add_one_type_printer(obj, 'discard_block_engine', 'ranlux24')
    add_one_type_printer(obj, 'discard_block_engine', 'ranlux48')
    add_one_type_printer(obj, 'shuffle_order_engine', 'knuth_b')

def register_libcxx_printers(obj):
    "Register libc++ pretty-printers with objfile Obj."

    global _use_gdb_pp
    global printer

    if _use_gdb_pp:
        gdb.printing.register_pretty_printer(obj, printer)
    else:
        if obj is None:
            obj = gdb
        obj.pretty_printers.append(printer)

    register_type_printers(obj)

def build_libcxx_dictionary():
    global printer

    printer = Printer("libc++")

    # libc++ objects requiring pretty-printing.
    printer.add('basic_string', StringPrinter)
    printer.add('bitset', BitsetPrinter)
    printer.add('deque', DequePrinter)
    printer.add('list', ListPrinter)
    printer.add('map', MapPrinter)
    printer.add('multimap', MapPrinter)
    printer.add('multiset', SetPrinter)
    printer.add('priority_queue', StackOrQueuePrinter)
    printer.add('queue', StackOrQueuePrinter)
    printer.add('tuple', TuplePrinter)
    printer.add('pair', PairPrinter)
    printer.add('set', SetPrinter)
    printer.add('stack', StackOrQueuePrinter)
    printer.add('unique_ptr', UniquePointerPrinter)
    printer.add('vector', VectorPrinter)  # Includes vector<bool>.
    #printer.add('shared_ptr', SharedPointerPrinter)
    #printer.add('weak_ptr', SharedPointerPrinter)
    printer.add('unordered_map', UnorderedMapPrinter)
    printer.add('unordered_set', UnorderedSetPrinter)
    printer.add('unordered_multimap', UnorderedMapPrinter)
    printer.add('unordered_multiset', UnorderedSetPrinter)
    printer.add('forward_list', ForwardListPrinter)
    # For std::array the default GDB pretty-printer seems reasonable.

    printer.add('__list_iterator', ListIteratorPrinter)
    printer.add('__list_const_iterator', ListIteratorPrinter)
    printer.add('__tree_iterator', RbtreeIteratorPrinter)
    printer.add('__tree_const_iterator', RbtreeIteratorPrinter)
    printer.add('__hash_iterator', HashtableIteratorPrinter)
    printer.add('__hash_const_iterator', HashtableIteratorPrinter)
    printer.add('__hash_map_iterator', UnorderedMapIteratorPrinter)
    printer.add('__hash_map_const_iterator', UnorderedMapIteratorPrinter)
    printer.add('__map_iterator', MapIteratorPrinter)
    printer.add('__map_const_iterator', MapIteratorPrinter)
    printer.add('__deque_iterator', DequeIteratorPrinter)
    printer.add('__wrap_iter', VectorIteratorPrinter)
    printer.add('__bit_iterator', VectorBoolIteratorPrinter)

    printer.add('optional', OptionalPrinter)

build_libcxx_dictionary()


import numpy as np
import os
import gym
import torch
import torch.nn as nn
from torch.autograd import Variable

USE_CUDA = torch.cuda.is_available()

def get_checkpoint_file(d, fid):
    return os.path.join(d, 'checkpoint{:d}'.format(fid))

def make_game():
    return gym.make('Pong-v0')

def to_tensor_f32(x):
    t_ = torch.from_numpy(np.float32(np.ascontiguousarray(x)))
    if USE_CUDA:
        t_ = t_.cuda()
    return t_

def to_tensor_int(x):
    # noinspection PyArgumentList
    t_ = torch.LongTensor(x)
    if USE_CUDA:
        t_ = t_.cuda()
    return t_

def to_numpy(t):
    if USE_CUDA:
        x = t.cpu().numpy()
    else:
        x = t.numpy()
    return x

# hyperparameters
H = 200  # number of hidden layer neurons
D = 80 * 80  # input dimensionality: 80x80 grid

# noinspection PyPep8Naming,PyPep8Naming
def prepro(I):
    """ prepro 210x160x3 uint8 frame into 6400 (80x80) 1D float vector """
    I = I[35:195]  # crop
    I = I[::2, ::2, 0]  # downsample by factor of 2
    I[I == 144] = 0  # erase background (background type 1)
    I[I == 109] = 0  # erase background (background type 2)
    I[I != 0] = 1  # everything else (paddles, ball) just set to 1
    return I.astype(np.float).ravel()

class PolicyNet(nn.Module):
    def __init__(self):
        super(PolicyNet, self).__init__()
        self.net = nn.Sequential(
            nn.Linear(D, H),
            nn.ReLU(inplace=True),
            nn.Linear(H, 2),
            nn.LogSoftmax()
        )
        if USE_CUDA:
            self.cuda()

    def forward(self, x):
        return self.net(x)

    def save(self, fname):
        torch.save(self.state_dict(), fname)

    def load(self, fname):
        self.load_state_dict(torch.load(fname))

class Policy:
    def __init__(self, cpdir, cpid):
        self.x0 = None
        self.net = PolicyNet()
        self.net.load(get_checkpoint_file(cpdir, cpid))
        self.rng = np.random.RandomState(42)

    def __call__(self, s):
        cur_x = prepro(s)
        x = cur_x - self.x0 if self.x0 is not None else np.zeros(D)
        self.x0 = cur_x

        # forward the policy network and sample an action from the returned probability
        x_tv = Variable(to_tensor_f32(x), requires_grad=False).unsqueeze(0)
        action_prob_log_tv = self.net.forward(x_tv)
        action_prob_log = to_numpy(action_prob_log_tv.data)[0]
        aprob = np.exp(action_prob_log)
        y = self.rng.choice(2, p=aprob)
        button_action = 2 if y == 0 else 3
        return button_action

def make_policy(cpdir, cpid):
    pol = Policy(cpdir, cpid)
    return pol


# This problem was asked by Two Sigma.
#
# Given two sorted iterators, merge it into one iterator.
#
# For example, given these two iterators:
#
# foo = iter([5, 10, 15])
# bar = iter([3, 8, 9])
# You should be able to do:
#
# for num in merge_iterators(foo, bar):
#     print(num)
#
# # 3
# # 5
# # 8
# # 9
# # 10
# # 15
#
# Bonus: Make it work without pulling in the contents of the iterators in memory.

def merge(*iterators):
    # python iterators do NOT allow to get the current value, so we will have
    # to have a separate store

    values = [next(iterator) for iterator in iterators]

    while True:
        if not iterators:
            return

        # pick the smallest
        idx, val = min(enumerate(values), key=lambda x: x[1])

        # advance the idx-th pointer
        try:
            iterator = iterators[idx]
            values[idx] = next(iterator)
        except StopIteration:
            # exhausted iterator, remove it!
            del iterators[idx]
            del values[idx]

        yield val

assert list(merge(iter([1, 2, 3]))) == [1, 2, 3]
assert list(merge(iter([5, 10, 15]), iter(3, 8, 9))) == [3, 5, 8, 9, 10, 15]
assert list(merge(iter([10, 20, 30]), iter([15, 25]), iter([17]))) == [10, 15, 17, 20, 25, 30]


#Modified by smartbuilds.io
#Date: 27.09.20
#Desc: This web application serves a motion JPEG stream
# main.py

# import packages

import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-vs', '--videosource', default='r', help='-vs r for robot, -vs w for webcam.')
ap.add_argument('-em', '--enablemotors', default='e', help='-en e for enable, -en d for disable.')
args = vars(ap.parse_args())

from flask import Flask, render_template, Response, request
from json import loads
import threading
from queue import Queue
from motor_process import motor_control_process
from camera import VideoCamera
from motor_control import MotorController
from motor_process import motor_control_process

pi_camera = VideoCamera(flip=False, videosource=args['videosource'])
motor_controller = MotorController(robot_mode=('e'==args['enablemotors']))
key_presses = Queue()
motors = threading.Thread(target=motor_control_process,
                          args=(motor_controller,key_presses)).start()
print("Motor motion process has started on the server.")
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/video_feed')
def video_feed():
    return Response(pi_camera.gen(), mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/motor_control', methods=['POST'])
def motor_control():
    if request.method == 'POST':
        keystrokes = request.json['data']
        key_presses.put(keystrokes) # put the whole list in the queue as one item
    return ""

if __name__ == "__main__":
    threading.Thread(target=lambda: app.run(host='0.0.0.0', port=5000, debug=False, use_reloader=False)).start()


graph = [list(map(int, input().split())) for _ in range(7)]

res = 0
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
visit = [[0] * 7 for _ in range(7)]

def dfs(x, y):
    global res
    visit[x][y] = 1
    if x == 6 and y == 6:
        res += 1
        return
    else:
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < 7 and 0 <= ny < 7:
                if graph[nx][ny] == 0 and visit[nx][ny] == 0:
                    visit[nx][ny] = 1
                    dfs(nx, ny)
                    visit[nx][ny] = 0

dfs(0, 0)
print(res)


#!/usr/bin/env python

"""Defines and implements some helper classes and functions for the unit tests.
"""

__author__    = "Ole Weider <ole.weidner@rutgers.edu>"
__copyright__ = "Copyright 2014, http://radical.rutgers.edu"
__license__   = "MIT"

def _exception_test_helper(exception, expected_type):
    """Test whether an exception has a specific type.
    """
    if type(exception) != expected_type:
        assert False, "Expected exception type {0} but got {1}".format(expected_type, type(exception))
    else:
        assert True


from zkay.examples.scenario import ScenarioBuilder
a = 'a'
sb = ScenarioBuilder('Rehom', 'code/RehomArgs.zkay').set_users(a)
sb.set_deployment_transaction(owner=a)
sb.add_transaction('add_hom', [2], user=a)
sb.add_state_assertion('y', expected_value=2, should_decrypt=True)
sb.add_transaction('un_hom', [3], user=a)
sb.add_state_assertion('z', expected_value=3, should_decrypt=True)
sb.add_balance_assertion(0)
SCENARIO = sb.build()


import contextlib
import json
import logging
import os
import random
from collections import OrderedDict
from functools import partial

import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing.text import Tokenizer

class DataLoader():
    """
    A class used to package related data processing constants and methods
    for training and executing an encoder-decoder model. It can be initialized with training=False
    to simpy get the initialized constants and word_list.json used for
    beam_search in the caption module.

    Attributes
    ----------
    WORD_EMBED_SIZE : int
        size of word embedding in decoder model
    IMAGE_SIZE : int
        size of length and width dimension for encoder input
    DATA_GEN_ARGS : dict
        a dictionary of image transformations to pass to ImageDataGenerator
    AUTOTUNE : obj
        lazy declaration of parameters and optimizes dataprocessing parameters
        when datasets are consumed, i.e. PARALLEL_CALLS and BUFFER_SIZE
    PARALLEL_CALLS : int
        number of paralllel calls to make when mapping over a batch
    BUFFER_SIZE: int
        number of batches to prefetch
    TRAIN_P, VAL_P, TEST_P: int
        percentage splits of dataset, should all add up to 1

    Methods
    -------
    get_train_dataset, get_val_dataset, get_test_dataset
        returns dataset to be consumed by training, validating, and testing
        processes respectively in ModelTrainer class

    batch_convert_to_words(captions, references=True)
        converts references and hypotheses from int sequences to words

    batch_sample_target(target)
        selects random caption from each list in target

    load(img, path=False)
        loads image from image_id or path img and resizes and converts to array

    preprocess_input(x), unprocess_input(x)
        transforms and reverses transform image tensor/array x respectively
        using transformations expected by encoder

    create_word_embedding_matrix
        creates glove embeddings of size WORD_EMBED_SIZE, must download correct
        glove embedding file to resize to other dimensions
    """

    WORD_EMBED_SIZE = 300
    IMAGE_SIZE = 299
    DATA_GEN_ARGS = dict(rotation_range=45,
                         shear_range=0.20,
                         width_shift_range=0.2,
                         height_shift_range=0.2,
                         zoom_range=0.3,
                         horizontal_flip=True,
                         vertical_flip=False,
                         )
    AUTOTUNE = tf.data.experimental.AUTOTUNE
    PARALLEL_CALLS = AUTOTUNE
    BUFFER_SIZE = AUTOTUNE
    TRAIN_P, VAL_P, TEST_P = 0.9, 0.05, 0.05

    WORDS_PATH = f"{os.path.abspath('.')}/training/data/word_list.json"
    ANNOTATIONS_PATH = f"{os.path.abspath('.')}/training/data/annotations"
    IMAGES_PATH = f"{os.path.abspath('.')}/training/data/images"
    EMBEDDINGS_PATH = f"{os.path.abspath('.')}/training/data/glove.42B.300d.txt"

    logger = logging.getLogger('__main__.data_loading')

    def __init__(self, batch_size=32, vocab_size=10240, shuffle_size=8000, training=True):
        """
        Parameters
        ----------
        batch_size : int, optional
            number of image/caption pairs to batch from dataset; reduce if oom
        vocab_size : int, optional
            number of words to use in model from original MSCOCO corpus
            gathered from captions
        shuffle_size : int, optional
            how big the shuffle window is when shuffling the dataset
        training : bool
            whether DataLoader is going to be used to train or to help
            execute models; if train=False non-class methods should not be used
        """
        assert (vocab_size > 3 and
                vocab_size < 28040), "vocab_size not in range"
        self.vocab_size = vocab_size
        if (not os.path.exists(self.WORDS_PATH) or training):
            coco_train_file = f'{self.ANNOTATIONS_PATH}/captions_train2017.json'
            coco_val_file = f'{self.ANNOTATIONS_PATH}/captions_val2017.json'
            coco_files = [coco_train_file, coco_val_file]

            img_to_caps = OrderedDict()
            logger.info("Processing json data")
            with contextlib.ExitStack() as stack:
                files = [stack.enter_context(open(fname, 'r'))
                         for fname in coco_files]
                for f in files:
                    self._coco(f, img_to_caps)

            self.tokenizer = Tokenizer(num_words=self.vocab_size,
                                       oov_token="<unk>",
                                       filters='!"#$%&()*+,-./:;=?@[\\]^_`{|}~\t\n')
            logger.info("Fitting tokenizer on corpus")
            self.tokenizer.fit_on_texts(tf.nest.flatten(img_to_caps.values()))
            self.tokenizer.index_word[0] = '<pad>'
            self.tokenizer.word_index['<pad>'] = 0

            if not os.path.exists(self.WORDS_PATH):
                self._create_word_list(self.WORDS_PATH)

        if training:
            # set instance variables
            self.DATASET_SIZE = len(img_to_caps.values())
            self.batch_size = batch_size
            self.shuffle_size = shuffle_size

            self.image_datagen = ImageDataGenerator(**self.DATA_GEN_ARGS)

            # set functions
            self.batch_load = partial(tf.map_fn, self.load, dtype='float32')
            self.batch_transform = partial(tf.map_fn, self._transform,
                                           dtype='float32')
            self.batch_preprocess = partial(tf.map_fn, self._preprocess,
                                            dtype='float32')
            # captions list
            captions = self._process_captions(list(img_to_caps.values()))
            # data splits
            self.train, self.val, self.test = self._split_data(list(
                img_to_caps.keys()), captions)

    def _create_word_list(self, path):
        # create word_list at indicated path
        logger.info(f"Creating word_list.json at {WORDS_PATH}")
        data = []
        for i in range(self.vocab_size + 1):
            data.append(self.tokenizer.index_word[i])
        with open(path, 'w') as p:
            json.dump(data, p, indent=4)

    def _train_mapper(self, paths, seq_lists):
        # wrapper over _map_train_batch to map over tensors from train dataset
        return tf.numpy_function(self._map_train_batch, [paths, seq_lists],
                                 [tf.float32, tf.int32])

    def _validate_mapper(self, paths, seqs):
        # wrapper over _map_validate_batch to map over tensors from val dataset
        return tf.numpy_function(self._map_validate_batch, [paths, seqs],
                                 [tf.float32, tf.int32])

    def _transform(self, img):
        # wrapper over random_transform to be used in tensor mapping
        return tf.numpy_function(self.image_datagen.random_transform,
                                 [img], [tf.float32])

    def _preprocess(self, img):
        # wrapper over preprocess_input to be used in tensor mapping
        return tf.numpy_function(self.preprocess_input, [img],
                                 [tf.float32])

    def _map_train_batch(self, paths, captions):
        # core map function over train batches
        imgs = self.batch_load(paths)
        imgs = self.batch_transform(imgs)
        imgs = self.batch_preprocess(imgs)
        captions = self.batch_sample_target(captions)
        return imgs, captions

    def _map_validate_batch(self, paths, captions):
        # core map function over validate batches
        imgs = self.batch_load(paths)
        imgs = self.batch_preprocess(imgs)
        return imgs, captions

    def _split_data(self, x_list, y_list):
        # combines each member from x_list and y_list into an (x, y)
        # tuple and splits the resulting list into train, validate, and test
        # sublists to be later converted into datasets
        logger.info("Splitting data into train, val, and test datasets")
        train_split = int(self.TRAIN_P * self.DATASET_SIZE)
        val_split = int((self.TRAIN_P + self.VAL_P) * self.DATASET_SIZE)

        dataset_list = list(zip(x_list, y_list))
        # don't shuffle data before split, need inherent ordering
        # to train after restarting DataLoader
        train, validate, test = np.split(dataset_list,
                                         [train_split, val_split])
        return train, validate, test

    def _make_datasets(self, xy_list):
        # converts a list of (x, y) tuples into two separate datasets of
        # x and y respectively
        images = [x for x, y in xy_list]
        captions = [y for x, y in xy_list]
        images_ds = tf.data.Dataset.from_tensor_slices(
            (tf.convert_to_tensor(images, dtype='int32')))
        captions_ds = tf.data.Dataset.from_tensor_slices(
            (tf.convert_to_tensor(captions, dtype='int32')))
        return images_ds, captions_ds

    def _coco(self, json_file, d):
        # load json data into ordered dictionary of image_id : captions pairs
        annotations = json.load(json_file)
        for annot in annotations['annotations']:
            path = int(annot['image_id'])
            l = d.get(path, [])
            l.append(f"<start> {annot['caption']} <end>")
            d[path] = l

    def _process_captions(self, captions):
        # preprocesses captions by tokenizing, cropping, padding, and removing
        # any caption list with more than 5 captions, prefering to remove
        # shorter captions
        logger.info("Processing captions data")
        min_len, max_len = 10, 18
        end = self.tokenizer.word_index['<end>']

        # return False if sequence is not of acceptable length
        def F(s): return min_len <= len(s) <= max_len

        # pad sequences up to max length with <pad>
        def P(s): return tf.keras.preprocessing.sequence.pad_sequences(
            s, padding='post', maxlen=max_len)

        # return number of sequences over max allowed of 5
        def R(s): return len(s) - 5

        # returns indices of R sequences with least number of words
        def Z(captions):
            over = len(captions) - 5
            size_list = [len(c) for c in captions]
            res = sorted(range(len(size_list)),
                         key=lambda sub: size_list[sub])[:over]
            return res

        # tokenize captions
        captions = [self.tokenizer.texts_to_sequences(
            cap_list) for cap_list in captions]

        # crop sequences of incorrect length
        captions = [[cap if F(cap) else cap[:max_len - 1] + [end]
                     for cap in cap_list] for cap_list in captions]

        # remove cap_lists that have length > 5
        captions = [[c for i, c in enumerate(c_l) if i not in Z(
            c_l)] if R(c_l) else c_l for c_l in captions]

        # pad sequences to length max-length
        captions = [P(cap_list) for cap_list in captions]

        return captions

    def get_train_dataset(self):
        """Returns training dataset optimized to be consumed batchwise over
        many epochs
        """
        train_dataset = (
            tf.data.Dataset.zip((self._make_datasets(self.train)))
            .cache()
            .shuffle(self.shuffle_size)
            .batch(self.batch_size, drop_remainder=True)
            .map(self._train_mapper, num_parallel_calls=self.PARALLEL_CALLS)
            .prefetch(self.BUFFER_SIZE))

        return train_dataset

    def get_val_dataset(self):
        """Returns validation dataset optimized to be consumed batchwise over
        many epochs
        """
        val_dataset = (
            tf.data.Dataset.zip((self._make_datasets(self.val)))
            .cache()
            .shuffle(self.shuffle_size)
            .batch(self.batch_size, drop_remainder=True)
            .map(self._validate_mapper, num_parallel_calls=self.PARALLEL_CALLS)
            .prefetch(self.BUFFER_SIZE)
        )
        return val_dataset

    def get_test_dataset(self):
        """Returns test dataset optimized to be consumed batchwise over
        a single epoch
        """
        test_dataset = (
            tf.data.Dataset.zip((self._make_datasets(self.test)))
            .batch(self.batch_size, drop_remainder=True)
            .map(self._validate_mapper, num_parallel_calls=self.PARALLEL_CALLS)
            .prefetch(self.BUFFER_SIZE)
        )
        return test_dataset

    def batch_convert_to_words(self, captions, references=True):
        """Converts integer tensor to array of strings with same nested
        structure except not a tensor and converted from int32 to tokens from
        tokenizer with <start> and <end> tokens removed

        Parameters
        ----------
        captions : tensor of int
            either a tensor of shape (batch, list_size, padded_sequence_length)
            for references or (batch, padded_sequence_length) for hypotheses"""
        captions = captions.numpy()
        # tokenize sequences
        T = self.tokenizer.sequences_to_texts
        end = self.tokenizer.word_index['<end>']
        # find where the sequence ends with <end> token
        def E(caption): return np.where(caption == end)[0][0]

        sentences = []
        if references:
            filtered = [[sentence[1:E(sentence)]
                         for sentence in lst] for lst in captions]
            sentences = [T(lst) for lst in filtered]
        else:
            filtered = [sentence[1:E(sentence)] for sentence in captions]
            sentences = T(filtered)
        return sentences

    @classmethod
    def batch_sample_target(cls, target):
        """Returns a tensor of randomly selected sequences, from each list, of
        size (batch, padded_sequence_length)

        Parameters
        ----------
        target : int tensor of shape (batch, list_size, padded_sequence_length)
        """
        list_size = target.shape[1]  # should be 5
        return tf.cast([sample[np.random.randint(list_size)] for
                        sample in target], dtype='int32')

    @classmethod
    def load(cls, img, path=False):
        """Loads image and resizes / converts to array

        Parameters
        ----------
        img : str -- image_id or path to image, specified with path parameter
        path : bool -- indicates whether img is a path to an image"""
        if not path:
            img = f"{cls.IMAGES_PATH}/{img:012d}.jpg"
        img = image.load_img(img, target_size=(cls.IMAGE_SIZE, cls.IMAGE_SIZE))
        img = image.img_to_array(img)
        return img

    @classmethod
    def preprocess_input(cls, x):
        """transforms image tensor/array x using transformations expected by
        encoder

        Parameters
        ----------
        x : image array/tensor"""
        x /= 255.
        x -= 0.5
        x *= 2.
        return x

    @classmethod
    def unprocess_input(cls, x):
        """undoes transform image tensor/array x using transformations expected by
        encoder

        Parameters
        ----------
        x : transformed image array/tensor"""
        x /= 2.
        x += 0.5
        x *= 255.
        return x

    def create_word_embedding_matrix(self):
        """creates glove embeddings of size WORD_EMBED_SIZE, must download
        correct glove embedding file to resize to other dimensions"""

        logger.info(f"Creating word_embedding_matrix from {EMBEDDINGS_PATH}")
        word_embed_dict = dict()

        with open(self.EMBEDDINGS_PATH, 'r') as file:
            for line in file:
                values = line.split()
                word = values[0]
                # only map words that are in model vocabulary
                if self.tokenizer.word_index.get(word, self.vocab_size + 1) <= self.vocab_size:
                    embedding = np.asarray(values[1:], dtype='float32')
                    word_embed_dict[word] = embedding

        index_embed_matrix = np.zeros(
            (self.vocab_size + 1, self.WORD_EMBED_SIZE))
        for i in range(self.vocab_size + 1):
            w = self.tokenizer.index_word[i]
            word_embedding = word_embed_dict.get(w)
            if word_embedding is not None:
                index_embed_matrix[i] = word_embedding

        return index_embed_matrix


import os
import random
import hangman_art as art
import hangman_words as word

# Select a random word from the word list
chosen_word = random.choice(word.word_list)

# Print the hangman ASCII art
print(art.logo)

# Set the initial number of lives
lives = 6

# Initialize a flag variable to track the game state
flag = 1

# Create a list to store the current display of letters
display = ['_'] * len(chosen_word)

# Variables to store guessed and not-in-the-word letters
you_guess_it = ''
it_not_in = ''

# Main game loop, continues until all letters are guessed or lives run out
while '_' in display:
  flag = 1

  # Ask the user to input a letter guess
  guess = input("Guess a letter:  ").lower()
  os.system('clear') # Clear the console screen

  if guess in you_guess_it:
    # Check if the letter has already been guessed
    print(f"You've already guessed {guess}")

  # Iterate through each character in the chosen word
  for i in range(len(chosen_word)):
    if guess in chosen_word[i]:
      # If the guessed letter is in the chosen word, update the display
      flag = 0
      display[i] = guess
      you_guess_it += guess

  # Print the current display of letters
  print("".join(display))

  if flag == 0:
    # If the guessed letter is correct, print the corresponding hangman stage
    print(art.stages[lives])

  if flag == 1:
    # If the guessed letter is incorrect, reduce a life and print the corresponding hangman stage
    print(art.stages[lives])
    it_not_in = guess
    print(f"You guessed {it_not_in}, that's not in the word. You lose a life.")
    lives -= 1

  if lives < 0:
    # If lives run out, end the game and print he lose
    flag = 1
    print("You Lose!")
    break

# Game ended, and the player won
if flag == 0:
  print("You Win!")


import math

import torch

from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module

class GraphConvolution(Module):
    """
    Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
    """

    def __init__(self, in_features, out_features, adj, bias=False, activation=None):
        super(GraphConvolution, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.adj = adj
        # self.adj = adj.to_dense()
        self.weight = Parameter(torch.FloatTensor(in_features, out_features))
        if bias:
            self.bias = Parameter(torch.FloatTensor(out_features))
        else:
            self.register_parameter('bias', None)
        self.reset_parameters()
        self.activation = activation

    def reset_parameters(self):
        stdv = 1. / math.sqrt(self.weight.size(1))
        self.weight.data.uniform_(-stdv, stdv)
        if self.bias is not None:
            self.bias.data.uniform_(-stdv, stdv)

    # def forward(self, input, adj):
    def forward(self, input):
        support = torch.mm(input, self.weight)
        #output = torch.spmm(self.adj, support)
        output = torch.mm(self.adj, support)
        if self.bias is not None:
            pre_ac = output + self.bias
        else:
            pre_ac = output
        if self.activation:
            return self.activation(pre_ac)
        else:
            return pre_ac

    def __repr__(self):
        return self.__class__.__name__ + ' (' \
               + str(self.in_features) + ' -> ' \
               + str(self.out_features) + ')'


from os import path
import sys

import django

from django.conf import settings

if not settings.configured:
    settings_dict = dict(
        INSTALLED_APPS=(
            'django_record',
            'django_record.tests'
        ),
        DATABASES={
            "default": {
                "ENGINE": "django.db.backends.sqlite3",
            }
        },
    )

    # configure settings
    settings.configure(**settings_dict)
    if django.VERSION >= (1, 7):
        django.setup()

def runtests():
    sys.path.insert(0, path.dirname(path.abspath(__file__)))

    # test for django under 1.8
    try:
        from django.test.simple import DjangoTestSuiteRunner
        runner_class = DjangoTestSuiteRunner
        test_args = ['tests']

    # test for django 1.8+
    except ImportError:
        from django.test.runner import DiscoverRunner
        runner_class = DiscoverRunner
        test_args = ['django_record']

    # run tests
    failures = runner_class(
        verbosity=2, interactive=True, failfast=False
    ).run_tests(test_args)

    # exit with errors
    sys.exit(failures)

if __name__ == '__main__':
    runtests()


from predict import Predict
from sys import exit
from args import *
from db import *
import json

data = {
	"type" : None,
	"ratio" : {},
	"top" : []
}

try:
	cnx = connect(**base)
	svms, ngrams = select_last_weights(cnx)
	indexes = select_indexes(cnx)

	predict = Predict(svms, indexes, ngrams)
	uid = predict.text([text]).pop()
	predict.calc()

	data["type"] = predict.type(uid)
	data["ratio"] = predict.ratio(uid)
	data["top"] = predict.top()
except:
	pass
finally:
	data = json.dumps(data)
	print(data)
	exit(0)


import discord
import asyncio
from datetime import datetime, timedelta
import time
from discord.ext import commands, tasks
from discord.utils import get
from collections.abc import Sequence
import random #for random embed colors
import sqlite3
class Mute(commands.Cog):
    def __init__(self, client):
        self.bot = client

    @commands.Cog.listener()
    async def on_ready(self):
        self.poll_mutes.start()
    @commands.command(usage="<member> <time> [reason]")
    @commands.guild_only()
    @commands.has_permissions(administrator=True)
    async def mute(self, ctx, member : discord.Member, length='inf', *, reason="None"):
        """
        Mute a user.
        """
        await ctx.trigger_typing()
        db = sqlite3.connect('main.sqlite')
        cursor = db.cursor()

        current_time = int(time.time())
        datetime_obj = datetime.fromtimestamp(current_time)
        if length.endswith('m'):
            if int(length.replace('m','')) < 1:
                return await ctx.send("The minimum mute time is 1 minute.")
            unmuteTime = datetime_obj + timedelta(minutes=int(length.replace('m', '')))
        elif length.endswith('h'):
            unmuteTime = datetime_obj + timedelta(hours=int(length.replace('h', '')))
        elif length.endswith('d'):
            unmuteTime = datetime_obj + timedelta(hours=int(length.replace('d', '')))
        elif length == 'inf':
            unmuteTime = datetime_obj + timedelta(weeks=52142) #1000 years
        else:
            return await ctx.send("Invalid unit of time! Some examples of accepted forms of time is `24h, 2m, 4d, 19h`")
        user_id = member.id
        guild = ctx.guild
        role = get(guild.roles, name="Muted")
        if role:
            cursor.execute(f"SELECT user_id FROM mutes WHERE guild_id = {guild.id}")
            result = cursor.fetchone()
            if result:
                embed = discord.Embed(color=0xff2d2d)
                embed.add_field(name="Error:", value=f"{member} is already muted. Perhaps you meant to unmute them?", inline=False)
                embed.set_footer(text=f"{ctx.author}", icon_url=ctx.author.avatar_url)
                await ctx.send(embed=embed)
            elif role in member.roles:
                embed = discord.Embed(color=0xff2d2d)
                embed.add_field(name="Error:", value=f"{member} already has the muted role. To mute them, you need to remove it.", inline=False)
                embed.set_footer(text=f"{ctx.author}", icon_url=ctx.author.avatar_url)
                await ctx.send(embed=embed)
            else:
                sql=("INSERT INTO mutes(guild_id, user_id, endtime) VALUES(?, ?, ?)")
                val=(guild.id, user_id, unmuteTime)
                cursor.execute(sql, val)
                db.commit()

                await member.add_roles(role)
                embed=discord.Embed()

                #Log-related
                now = datetime.now()
                current_time = now.strftime("%H:%M:%S")
                logMessage = f"``[({current_time})]`` - **User Muted**"
                logMessage += f"```User: {member} (ID: {member.id})"

                embed.set_author(name=f"Muted: {member}", icon_url=member.avatar_url)
                embed.add_field(name="Reason:", value=f"{reason}", inline=True)
                if length.endswith('s'):
                    embed.add_field(name="Time:", value=f'{length.replace("s", "")} seconds', inline=True)
                    logMessage += f"\nLength: {length.replace('s', '')} seconds"
                elif length.endswith('m'):
                    embed.add_field(name="Time:", value=f'{length.replace("m", "")} minutes', inline=True)
                    logMessage += f"\nLength: {length.replace('m', '')} minutes"
                elif length.endswith('h'):
                    embed.add_field(name="Time:", value=f'{length.replace("h", "")} hours', inline=True)
                    logMessage += f"\nLength: {length.replace('h', '')} hours"
                elif length.endswith('d'):
                    embed.add_field(name="Time:", value=f'{length.replace("d", "")} days', inline=True)
                    logMessage += f"\nLength: {length.replace('d', '')} days"
                else:
                    embed.add_field(name="Time:", value=f'Permanent', inline=True)
                    logMessage += "\nLength: Permanent"

                logMessage += f"\nReason: {reason}```"

                embed.set_footer(text=f"{ctx.author}", icon_url=ctx.author.avatar_url)
                await ctx.send(embed=embed)

                cursor.execute(f"SELECT channel_id, enabled, memberMuted FROM logs WHERE guild_id = '{guild.id}'")
                result = cursor.fetchone()
                if result == None:
                    pass
                elif result[1] == 'false':
                    pass
                elif result[2] == 0:
                    pass
                else:
                    channelid = result[0]
                    channel = self.bot.get_channel(int(channelid))
                    await channel.send(logMessage)
                    cursor.close()
                    db.close()

        else:
            await ctx.send("The muted role is not set up! Creating and adding to the user now...")
            guild = ctx.guild
            await guild.create_role(name='Muted', color=discord.Colour.dark_grey(), hoist=False, mentionable=False, reason='Configuring the muted role.')
            role = get(guild.roles, name="Muted")
            await role.edit(position=1)
            overwrite = discord.PermissionOverwrite()
            overwrite.send_messages = False
            overwrite.add_reactions = False
            overwrite.speak = False
            for category in guild.categories:
                try:
                    await category.set_permissions(role, overwrite=overwrite)
                except:
                    pass
            await member.add_roles(role)

    @commands.command(usage="<member> [reason]")
    @commands.guild_only()
    @commands.has_permissions(administrator=True)
    async def unmute(self, ctx, member : discord.Member, *, reason=None):
        """
        Unmute someone who is muted.
        """
        if reason is None:
            reason = "None"
        await ctx.trigger_typing()
        guild = ctx.guild
        db = sqlite3.connect('main.sqlite')
        cursor = db.cursor()
        cursor.execute(f"SELECT channel_id, enabled, memberMuted FROM logs WHERE guild_id = '{guild.id}'")
        result = cursor.fetchone()
        channel=None
        if result is None:
            pass
        elif result[1] == 'false':
            pass
        elif result[2] == 0:
            pass
        else:
            channel = self.bot.get_channel(int(result[0]))
        now = datetime.now()

        current_time = now.strftime("%H:%M:%S")
        logMessage = f"``[({current_time})]`` - **User Unmuted**"
        logMessage += f"```User: {member} (ID: {member.id})"
        logMessage += f"\nUnmuted by: {ctx.author} (ID: {ctx.author.id})"
        logMessage += f"\nReason: {reason}```"

        cursor.execute(f"SELECT * FROM mutes WHERE guild_id={guild.id} AND user_id={member.id}")
        result = cursor.fetchone()
        role = get(guild.roles, name="Muted")

        if role in member.roles and result:
            await member.remove_roles(role)

            embed=discord.Embed()
            embed.set_author(name=f"Unmuted: {member}", icon_url=member.avatar_url)
            embed.add_field(name="Reason:", value=f"{reason}", inline=False)
            embed.set_footer(text=f"{ctx.author}", icon_url=ctx.author.avatar_url)

            cursor.execute(f"DELETE FROM mutes WHERE guild_id ={guild.id} AND user_id={member.id}")
            db.commit()
            cursor.close()
            db.close()

            await ctx.send(embed=embed)
            if channel:
                await channel.send(logMessage)

        elif not role in member.roles and result:

            embed=discord.Embed()
            embed.set_author(name=f"Unmuted: {member}", icon_url=member.avatar_url)
            embed.add_field(name="Reason:", value=f"{reason}", inline=False)
            embed.set_footer(text=f"{ctx.author}", icon_url=ctx.author.avatar_url)

            cursor.execute(f"DELETE FROM mutes WHERE guild_id ={guild.id} AND user_id={member.id}")
            db.commit()
            cursor.close()
            db.close()

            await ctx.send(embed=embed)
            if channel:
                await channel.send(logMessage)
        else:
            return await ctx.send("That member is not muted.")

    @tasks.loop(seconds=5)
    async def poll_mutes(self):
        try:
            db = sqlite3.connect('main.sqlite')
            cursor = db.cursor()
            cursor.execute("SELECT * FROM mutes")
            mutes = cursor.fetchall()
            for mute in mutes:
                endTime = mute[2]
                endTimeObj = datetime.strptime(endTime, '%Y-%m-%d %H:%M:%S')
                currentTime = datetime.now()
                if currentTime > endTimeObj:
                    guild_id = mute[0]
                    guild = self.bot.get_guild(int(guild_id))
                    role = get(guild.roles, name="Muted")
                    if not role:
                        pass
                    user = guild.get_member(int(mute[1]))
                    if role in user.roles:
                        await user.remove_roles(role)
                        cursor.execute(f"DELETE FROM mutes WHERE guild_id={guild_id} AND user_id={user.id}")
                        db.commit()
                        cursor.execute(f"SELECT channel_id, enabled, memberMuted FROM logs WHERE guild_id = {guild.id}")
                        result = cursor.fetchone()
                        if not result:
                            pass
                        elif result[1] == 'true' and result[2] == 1:
                            currentTime = currentTime.strftime("%H:%M:%S")
                            logMessage = f"``[({current_time})]`` - **User Unmuted**"
                            logMessage += f"```User: {member} (ID: {member.id})"
                            logMessage += f"\nReason: Automatic```"
                            await channel.send(logMessage)
        except Exception as e:
            print(e)

def setup(client):
    client.add_cog(Mute(client))
    now = datetime.now()
    print(f'{now} | Loaded mute module.')


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# JMMidiBassPedalController v3.0
# File: src/StringUtilities.py
# By:   Josef Meile <jmeile@hotmail.com> @ 28.10.2020
# This project is licensed under the MIT License. Please see the LICENSE.md file
# on the main folder of this code. An online version can be found here:
# https://github.com/jmeile/JMMidiBassPedalController/blob/master/LICENSE.md
#
"""Module with some string utilities."""

import re
import os

def multiple_split(source_string, separators, split_by = '\n'):
  """
  This function allows the user to split a  string by using different
  separators.

  Note: This version is faster than using the (s)re.split method (I tested it
  with timeit).

  Parameters:
  * source_string: string to be splitted
  * separators: string containing the characters used to split the source
    string.
  * split_by: all the ocurrences of the separators will be replaced by this
    character, then the split will be done. It defaults to '|' (pipe)
  """
  translate_to = split_by * len(separators)
  translation = str.maketrans(separators, translate_to)
  return source_string.translate(translation).split(split_by)

def read_text_file(file_path):
  """
  Gets the contents of a text file
  """
  if not os.path.isfile(file_path):
    return False, ""

  file_pointer = open(file_path)
  contents = file_pointer.read()
  file_pointer.close()
  return True, contents


# -*- coding: gb18030 -*-
#
# $Id: DspPanel.py,v 1.25 2008-07-03 10:00:26 fangpengjun Exp $

"""
implement rewawrds panel class
"""

from guis import *
import csdefine
from guis.controls.Control import Control
from guis.common.PyGUI import PyGUI
from guis.tooluis.CSRichText import CSRichText
from guis.controls.StaticText import StaticText
from guis.tooluis.richtext_plugins.PL_Font import PL_Font
from guis.general.npctalk.Rewards import RW_TYPE_ITEM
from guis.general.npctalk.Rewards import RW_TYPE_MONEY
from guis.general.npctalk.Rewards import RW_TYPE_OTHER
from guis.general.npctalk.Rewards import RW_TYPE_SKILL
from guis.general.npctalk.Rewards import RW_TYPE_AIM
from guis.general.npctalk.Rewards import CRewardPanel
from guis.general.npctalk.Rewards import CRewardItem
from guis.general.npctalk.Rewards import RW_TYPE_FIXED_RANDOM_ITEM
from ItemsFactory import ObjectItem
from ItemsFactory import SkillItem
from FactionMgr import factionMgr
from LabelGather import labelGather
from CrondScheme import Scheme
from Time import Time
from bwdebug import *
from GUIFacade import *
import Font

class DspPanel( Control ) :
	def __init__( self, pyBinder = None ) :
		wnd = GUI.load( 'guis/general/questlist/dspItem.gui' )
		uiFixer.firstLoadFix( wnd )
		Control.__init__( self,wnd  )
		self.__pyDivit = PyGUI( wnd.divition )
		self.__pyDivit.visible = False
		title = wnd.title
		self.__pyTitle = PyGUI( title )
		self.__pyPoint = PyGUI( title.point )
		self.__pyLbTitle = StaticText( title.lbText )
		self.__pyLbTitle.font = "STLITI.TTF"
		self.__pyLbTitle.color = ( 231, 205, 140, 255 )
		self.__pyLbTitle.limning = Font.LIMN_OUT
		self.__pyLbTitle.limnColor = ( 0, 0, 0,255 )
		self.__pyLbTitle.text = ""
		self.__pyStateItem = None
		self.width = pyBinder.width
		self.pyItems_ = []
		self.__viewCols = 1

	# ----------------------------------------------------------------
	# private
	# ----------------------------------------------------------------
	def __addItemRewards( self, pyPanel, rewards ) : # 在面板中添加物品
		if rewards is not None:
			for reward in rewards :
				schemeInfo = reward.query( "schemeInfo" )
				if schemeInfo:
					cmd, presistMinute = schemeInfo.split("|")
					presistMinute = int( presistMinute )
					scheme = Scheme()
					scheme.init( cmd )
					year, month, day, hour, minute = Time.localtime( Time.time() - presistMinute * 60 )[:5]
					nextTime = scheme.calculateNext( year, month, day, hour, minute )
					if nextTime > Time.time():
						continue
				pyItem = CRewardItem[RW_TYPE_ITEM]()
				pyItem.canbeSelected = False
				pyItem.updateItem( ObjectItem( reward ) )
				pyPanel.addItem( pyItem )
		else:
			pyItem = CRewardItem[RW_TYPE_ITEM]()
			pyItem.canbeSelected = False
			pyItem.updateItem( None )
			pyPanel.addItem( pyItem )
		if len( pyPanel.pyItems ) <= 0:
			pyPanel.setCommon()
			pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_4" )
		else:
			pyPanel.layout_()
		self.addItem( pyPanel )
		self.height = pyPanel.bottom

	# ----------------------------------------------------------------
	# public
	# ----------------------------------------------------------------
	def addItem( self, pyItem ) :
		pyItem.index = self.itemCount
		self.addPyChild( pyItem )
		self.pyItems_.append( pyItem )
		self.layoutItems_( self.itemCount - 1 )

	def addDescription( self, dsp ) :
		pyItem = DspItem()
		self.addItem( pyItem )
		self.height = pyItem.bottom
		pyItem.width = self.width - pyItem.left
		pyItem.title = labelGather.getText( "QuestHelp:dspPanel", "itemTitle_1" )
		pyItem.description = dsp
		pyItem.visualSplitter( False )
#		self.__setScrollState()

	def addObjectText( self, dsp ):
		if dsp.strip() == "":return
		pyItem = DspItem()
		self.addItem( pyItem )
	#	self.height = pyItem.bottom
		pyItem.width = self.width - pyItem.left
#		pyItem.title = labelGather.getText( "QuestHelp:dspPanel", "itemTitle_2" )
		pyItem.description = dsp
		pyItem.visualSplitter( False )
		self.height = pyItem.bottom
#		self.__setScrollState()

	def addFinishState( self, conditions ) : # 一个任务可能有多个任务条件
		if conditions == {} : return
		aimPanel = CRewardPanel[RW_TYPE_AIM]()
		aimPanel.width = self.width
		aimPanel.clearItems()
#		aimPanel.title = labelGather.getText( "QuestHelp:dspPanel", "itemTitle_3" )
		tempConditions = []
		for index, condition in conditions.items():
			tempConditions.append( index )
		tempConditions.sort() # 任务条件按index排序
		for index in tempConditions:
			condition = conditions[index]
			condText = labelGather.getText( "QuestHelp:dspPanel", "conditions" ) % ( condition["title"], condition["tag"], condition["stateText"],condition["forceTips"] )
			pyAimItem = CRewardItem[RW_TYPE_AIM]()
			pyAimItem.aimCondition = condText
			pyAimItem.aimIndex = index
			pyAimItem.maxWidth = self.width
			aimPanel.addItem( pyAimItem )
		self.addItem( aimPanel )
		self.height = aimPanel.bottom

		self.__pyStateItem = aimPanel

	def addCommonRewards( self, singleRewards, otherRewards ) : # 固定物品奖励，金钱，经验等
		pyPanel = None
		if singleRewards is not None :
			pyPanel = CRewardPanel[RW_TYPE_ITEM]()
			pyPanel.setCommon()
			pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_1" )
			self.__addItemRewards( pyPanel, singleRewards._items )
		if len( otherRewards ) > 0 :
			if pyPanel is None :
				pyPanel = CRewardPanel[RW_TYPE_OTHER]()
				pyPanel.setCommon()
				pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_4" )
			else :
				pyPanel = self
			for reward in otherRewards:
				if reward.type() == csdefine.QUEST_REWARD_MONEY:
					# 金钱奖励
					moneyPanel = CRewardPanel[RW_TYPE_MONEY]()
					money = reward._amount
					moneyPanel.setMoney( money )
					pyPanel.addItem( moneyPanel )
					pyPanel.height += moneyPanel.height
				elif reward.type() == csdefine.QUEST_REWARD_MULTI_MONEY:
					# 多倍金钱奖励
					moneyPanel = CRewardPanel[RW_TYPE_MONEY]()
					money = reward._amount
					multiFlag = reward._multiFlag
					moneyPanel.setMoney( money, multiFlag )
					pyPanel.addItem( moneyPanel )
					pyPanel.height += moneyPanel.height
				else:
					rwardItem = CRewardItem[RW_TYPE_OTHER]()
					if reward.type() == csdefine.QUEST_REWARD_TITLE:# 称号奖励
						arg = reward._amount
					elif reward.type() == csdefine.QUEST_REWARD_PRESTIGE:
						npcPrestigeID = reward._prestigeID
						prestigeName = factionMgr.getName( npcPrestigeID )
						arg = prestigeName+"  "+str( reward._amount ) # 声望，势力
					else:
						arg = reward.getDescription() # 经验，潜能奖励
					rwardItem.setValueText( reward.type(), arg )
					pyPanel.addItem( rwardItem )
					pyPanel.height += rwardItem.height

			if pyPanel != self :
				self.addItem( pyPanel )
				self.height  = pyPanel.bottom
#				self.__setScrollState()

	def addFixedItemReward( self, reward ):
		if reward is not None:
			if reward.type() == csdefine.QUEST_REWARD_FIXED_RANDOM_ITEMS: #固定随机物品
				if not reward.isItem:										# 只显示奖励描述，该值的设置见QuestReward.py。 by cwl
					pyRewardItem = CRewardItem[RW_TYPE_FIXED_RANDOM_ITEM]()
					pyRewardItem.setValueText( reward.type(), "      "+reward.str )
					self.addItem( pyRewardItem )
					self.height = pyRewardItem.bottom
				else:
					pyPanel = CRewardPanel[RW_TYPE_ITEM]()
					pyPanel.setCommon()
					pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_6" )
					self.__addItemRewards( pyPanel, reward._items )		# 附加物品显示
					#self.__setScrollState()

	def addSingleItemReward( self, rewards ) : #固定奖励
		if rewards is None : return
		pyPanel = CRewardPanel[RW_TYPE_ITEM]()
		pyPanel.setCommon()
		pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_1" )
		self.__addItemRewards( pyPanel, rewards._items )

	def addRandomItemsReward( self, rewards ) : # 随机奖励
		if rewards is None : return
		pyPanel = CRewardPanel[RW_TYPE_ITEM]()
		pyPanel.setCommon()
		pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_2" )
		self.__addItemRewards( pyPanel, rewards._items )

	def addOptionItemReward( self, rewards ) : # 可选奖励
		if rewards is None : return
		pyPanel = CRewardPanel[RW_TYPE_ITEM]()
		pyPanel.setCommon()
		pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_3" )
		self.__addItemRewards( pyPanel, rewards._items )

	def addRoleLevelReward( self, rewards ):
		if rewards is None : return
		pyPanel = CRewardPanel[RW_TYPE_ITEM]()
		pyPanel.setCommon()
		pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_5" )
		self.__addItemRewards( pyPanel, rewards._items )

	def getCurrentPercentage( self, completedTasksNum, rewards ):
		sonRewards = rewards.sonRewards
		currentReward = sonRewards.get( completedTasksNum )
		maxReward = sonRewards.get( len( sonRewards ) )
		percentage = ( float( currentReward[0].getDescription() )/float( maxReward[0].getDescription() ) ) * 100
		percentage = int( round( percentage ) )
		return percentage

	def addRewardsQuestPartCompleted( self, questID, rewards ): #完成部分任务目标可以获得的奖励
		if rewards is None:return
		completedTasksNum = GUIFacade.getCompletedTasksNum( questID )
		percentageStr = ""
		if completedTasksNum == 0 or completedTasksNum == 1:
			percentage = 0
			completedTasksNum = 1		#如果没有完成任何的目标，显现的是最少的奖励（即是完成一个任务目标的奖励）
			percentageStr = PL_Font.getSource( "+%s%%"%percentage, fc = "c3" )
		else:
			percentage = self.getCurrentPercentage( completedTasksNum, rewards )
			percentageStr = PL_Font.getSource( "+%s%%"%percentage, fc = "c4" )
		sonRewards = rewards.sonRewards.get( completedTasksNum )
		pyPanel = None
		tipNum = 0
		isLastSecondTarget = completedTasksNum +1 == len( rewards.sonRewards )		# 倒数第二个才显示未知物品
		if self.checkHasItemReward( rewards.sonRewards ) and not self.checkSonRewardHasItemReward( sonRewards ) and isLastSecondTarget:	#显示个空的物品

			pyItemPanel = CRewardPanel[RW_TYPE_ITEM]()
			pyItemPanel.setCommon()
			if tipNum == 0:
				tipNum += 1
				pyItemPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_1" ) + percentageStr
			else:
				pyItemPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_1" )
			self.__addItemRewards( pyItemPanel, None )

		for reward in sonRewards:
			if pyPanel is None:
				pyPanel = CRewardPanel[RW_TYPE_OTHER]()
				pyPanel.setCommon()
				pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_4" )
			if reward.type() == csdefine.QUEST_REWARD_MONEY:
				# 金钱奖励
				moneyPanel = CRewardPanel[RW_TYPE_MONEY]()
				money = reward._amount
				moneyPanel.setMoney( money )
				pyPanel.addItem( moneyPanel )
				pyPanel.height += moneyPanel.height
			elif reward.type() == csdefine.QUEST_REWARD_MULTI_MONEY:
				# 多倍金钱奖励
				moneyPanel = CRewardPanel[RW_TYPE_MONEY]()
				money = reward._amount
				multiFlag = reward._multiFlag
				moneyPanel.setMoney( money, multiFlag )
				pyPanel.addItem( moneyPanel )
				pyPanel.height += moneyPanel.height
			elif reward.type() == csdefine.QUEST_REWARD_ITEMS:
				pyItemPanel = CRewardPanel[RW_TYPE_ITEM]()
				pyItemPanel.setCommon()
				if tipNum == 0:
					tipNum += 1
					pyItemPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_1" ) + percentageStr
				else:
					pyItemPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_1" )
				self.__addItemRewards( pyItemPanel, reward._items )
			else:
				rwardItem = CRewardItem[RW_TYPE_OTHER]()
				if reward.type() == csdefine.QUEST_REWARD_TITLE:# 称号奖励
					arg = reward._amount
				elif reward.type() == csdefine.QUEST_REWARD_PRESTIGE:
					npcPrestigeID = reward._prestigeID
					prestigeName = factionMgr.getName( npcPrestigeID )
					arg = prestigeName+"  "+str( reward._amount ) # 声望，势力
				else:
					arg = reward.getDescription() # 经验，潜能奖励
				rwardItem.setValueText( reward.type(), arg )
				pyPanel.addItem( rwardItem )
				pyPanel.height += rwardItem.height
		if tipNum == 0:
			tipNum += 1
			pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_4" ) + percentageStr
		else:
			pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_4" )
		self.addItem( pyPanel )
		self.height  = pyPanel.bottom

	def addSkillRewards( self, skillRewards ):
		if not len( skillRewards ):return
		pyPanel = CRewardPanel[RW_TYPE_SKILL]()
		pyPanel.title = labelGather.getText( "QuestHelp:dspPanel", "CRewardTitle_7" )
		for index, skReward in enumerate( skillRewards ):
			pyItem = CRewardItem[RW_TYPE_SKILL]()
			pyItem.index = index
			pyItem.canbeSelected = False
			pyItem.foucs = True
			skillInfo = SkillItem( skReward._skill )
			pyItem.updateItem( skillInfo )
			pyPanel.addItem( pyItem )
			pyPanel.layout_()
		self.addItem( pyPanel )
		self.height = pyPanel.bottom

	def checkHasItemReward( self, rewards ):
		"""
		判断全部奖励是否包含物品奖励
		"""
		hasItemReward = False
		for rewards in rewards.itervalues():
			for reward in rewards:
				if reward.type() == csdefine.QUEST_REWARD_ITEMS:
					hasItemReward = True
		return hasItemReward

	def checkSonRewardHasItemReward( self, rewards ):
		"""
		判断子奖励中是否包含物品奖励
		"""
		hasItemReward = False
		for reward in rewards:
			if reward.type() == csdefine.QUEST_REWARD_ITEMS:
				hasItemReward = True
		return hasItemReward

	def addFeastText( self, dsp ):
		if dsp.strip() == "":return
		pyItem = DspItem()
		self.addItem( pyItem )
		self.height = pyItem.bottom
		pyItem.width = self.width - pyItem.left
		pyItem.title = ""
		pyItem.description = dsp
		pyItem.visualSplitter( False )

	# ---------------------------------------
	def resetFinishState( self, conditions ) :
		for pyItem in self.__pyStateItem.pyItems:
			aimIndex = pyItem.aimIndex
			condition = conditions.get( aimIndex, None )
			if condition is None:return
			conditionText = "%s: %s  %s" %( condition["title"], condition["tag"], condition["stateText"] )
			pyItem.aimCondition = conditionText

	#--------------------------------------------
	# propected
	#---------------------------------------------
	def layoutItems_( self, startIndex = 0 ) :
		itemCount = self.itemCount
		if itemCount == 0 : return
		if startIndex >= itemCount : return
		pyItem = self.pyItems_[startIndex]
		pyItem.left = 0
		if startIndex == 0 :
			pyItem.top = 15
		else :
			pyItem.top = self.pyItems_[startIndex - 1].bottom
		for pyNextItem in self.pyItems_[( startIndex + 1 ):] :
			pyNextItem.left = 0
			pyNextItem.top = pyItem.bottom
			pyItem = pyNextItem

	#-----------------------------------------------
	# property methods
	#-----------------------------------------------

	def _getItems( self ) :
		return self.pyItems_[:]

	def _getItemCount( self ) :
		return len( self.pyItems_ )

	def _setDivtVisible( self, visible ):
		self.__pyDivit.visible = visible

	def _getDivtVisible( self ):
		return self.__pyDivit.visible

	def _getTitle( self ):
		return self.__pyLbTitle.text

	def _setTitle( self, title ):
		self.__pyLbTitle.text = title
		self.__pyLbTitle.left = self.__pyPoint.right + 5.0

	#----------------------------------------
	# properties
	#----------------------------------------
	itemCount = property( _getItemCount )							# get the number of items
	pyItems = property( _getItems )
	divtVisible = property( _getDivtVisible, _setDivtVisible )
	title = property( _getTitle, _setTitle )
# --------------------------------------------------------------------
# implement
# --------------------------------------------------------------------
from guis.controls.Control import Control
from guis.controls.StaticText import StaticText
from  guis.general.npctalk.Rewards import CSRichText

class DspItem( Control ) :
	__cg_item = None

	def __init__( self ) :
		if DspItem.__cg_item is None :
			DspItem.__cg_item = GUI.load( "guis/general/questlist/dsppanel.gui" )

		item = util.copyGuiTree( DspItem.__cg_item )
		uiFixer.firstLoadFix( item )
		Control.__init__( self, item )
		self.__pyLbTitle = StaticText( item.lbTitle )
		self.__pyRTDsp = CSRichText( item.rtDsp )
		self.__pyRTDsp.opGBLink = True
		self.__spliter = item.spliter

	# ----------------------------------------------------------------
	# public
	# ----------------------------------------------------------------
	def visualSplitter( self, visible ) :
		self.__spliter.visible = visible

	# ----------------------------------------------------------------
	# property methods
	# ----------------------------------------------------------------
	def _getTitle( self ) :
		return self.__pyLbTitle.text

	def _setTitle( self, title ) :
		self.__pyLbTitle.text = title

	# -------------------------------------------------
	def _getDescription( self ) :
		return self.__pyRTDsp.text

	def _setDescription( self, dsp ) :
		dsp = PL_Font.getSource( dsp, fc = ( 230, 227, 185, 255 ) )
		self.__pyRTDsp.text = dsp
		self.height = self.__pyRTDsp.bottom + 5

	def _setWidth( self, width ) :
		Control._setWidth( self, width )
		self.__pyRTDsp.maxWidth = width - self.__pyRTDsp.left

	# ----------------------------------------------------------------
	# properties
	# ----------------------------------------------------------------
	title = property( _getTitle, _setTitle )
	description = property( _getDescription, _setDescription )
	width = property( Control._getWidth, _setWidth )


import heapq
def minCostToConnectRopes(ropes):
    if not ropes and len(ropes):
        return 0
    heapq.heapify(ropes)
    cost=0
    while ropes:
        a,b=heapq.heappop(ropes),heapq.heappop(ropes)
        cost+=a+b
        if ropes:
            heapq.heappush(ropes,a+b)
    return cost

ropes=[8,4,6,12]
print(minCostToConnectRopes(ropes))


"""empty message

Revision ID: 5fe110ca29e7
Revises: 04e6148ab996
Create Date: 2018-06-18 17:42:59.740765

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = '5fe110ca29e7'
down_revision = '04e6148ab996'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('Request', sa.Column('type_id', postgresql.UUID(as_uuid=True), nullable=False))
    op.drop_constraint('Request_request_id_fkey', 'Request', type_='foreignkey')
    op.create_foreign_key(None, 'Request', 'Request_type', ['type_id'], ['id'])
    op.drop_column('Request', 'request_id')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('Request', sa.Column('request_id', postgresql.UUID(), autoincrement=False, nullable=False))
    op.drop_constraint(None, 'Request', type_='foreignkey')
    op.create_foreign_key('Request_request_id_fkey', 'Request', 'Request_type', ['request_id'], ['id'])
    op.drop_column('Request', 'type_id')
    # ### end Alembic commands ###


from django.shortcuts import render, HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import transaction
from django.db.models import F
from django.views import View
from Personalwebsite import settings as sys
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth.models import User
import json
from APP_Comment.models import *
from App_Blog.models import Article

class AddComment(LoginRequiredMixin, View):
    def get(self, request):
        return HttpResponse(json.dumps('fuck you!'))

    def post(self, request):
        if request.is_ajax():
            userId = request.POST['userId']
            articleId = request.POST['articleId']
            content = request.POST['content'][:-2]
            browserId = request.POST['browserId']
            article_obj = Article.objects.filter(id=articleId)
            response = {}
            try:
                with transaction.atomic():
                    Comment.objects.create(user_id=userId, articleId_id=articleId, body=content, browserId=browserId)
                    article_obj.update(commentCount=F('commentCount') + 1)
                response['successComment'] = True
            except Exception:
                response['successComment'] = False
            subject = '文章《%s》有新的评论' % Article.objects.get(id=articleId).title
            username = User.objects.get(id=userId).username
            send_content = """

%s说:%s

去看看

                            """ % (username, content, articleId)
            msg = EmailMultiAlternatives(subject, send_content, sys.EMAIL_HOST_USER, [sys.EMAIL_SELF_ATTR, ])
            msg.content_subtype = "html"
            msg.send()
            return HttpResponse(json.dumps(response))
        else:
            cnm = '您的本次请求存在违法信息，已被系统标记！'
            return HttpResponse(json.dumps(cnm))

class AddReply(LoginRequiredMixin, View):
    def post(self, request):
        if request.is_ajax():
            replyPk = request.POST['replyPk']
            userId = request.user.pk
            articleId = request.POST['articleId']
            content = request.POST['content'][:-2]
            browserId = request.POST['browserId']
            status = {}
            if all([replyPk, userId, articleId, content, browserId]):
                article_obj = Article.objects.filter(id=articleId)
                # 查询到当前被评论的这条评论
                replyObj = Comment.objects.filter(id=replyPk).first()
                # 获取到他的根评论id
                try:
                    rootId = replyObj.root.id
                except:
                    rootId = replyPk
                parentId = replyPk
                # 获取到该条评论的用户名
                rootUser = replyObj.user.username
                rootUserPk = replyObj.user.id
                # 开启事物，同步数据
                try:
                    with transaction.atomic():
                        Comment.objects.create(user_id=userId,
                                               replayTo_id=rootUserPk,
                                               root_id=rootId,
                                               parentId_id=parentId,
                                               articleId_id=articleId,
                                               body=content,
                                               browserId=browserId)
                        article_obj.update(commentCount=F('commentCount') + 1)
                    status['success'] = True
                except:
                    status['success'] = False
                    return HttpResponse(json.dumps(status))
                # 构建出返回前端的数据
                status['replyToUser'] = rootUser
                status['rootId'] = rootId
            else:
                status['success'] = False
            return HttpResponse(json.dumps(status))
        else:
            cnm = '您的本次操作属于违规操作，已被系统标记。'
            return HttpResponse(json.dumps(cnm))


import sqlalchemy as sql
import pandas as pd
from datetime import datetime
engine = sql.create_engine('mysql+pymysql://simplon:simplon@localhost/ASSURAUTO')

CL_ID = pd.read_sql_query('SELECT max(CL_ID) as max FROM CLIENTS;' , engine)['max'].values
CL_ID = CL_ID[0]+1
CO_CLIENTS_FK = CL_ID
CL_PRENOM = input('Entrez le prenom : ')
CL_NOM = input('Entrez le nom : ').upper()
CL_ADRESSE = input("Entrez l'adresse : ")
CL_POSTALE =''
while len(CL_POSTALE) == 0 :
    CL_POSTALE = input('Entrez le code postale : ')

    if (CL_POSTALE.isdigit()):
        CL_POSTALE = CL_POSTALE

    else:
        print("ERRROR")
        CL_POSTALE = ''

CL_VILLE = input('Entrez la ville : ')
CL_COORDONNEES = input('Entrez les coordonnees : ')

engine.execute('INSERT INTO CLIENTS (CL_ID, CL_PRENOM, CL_NOM, CL_ADRESSE, CL_POSTALE, CL_VILLE, CL_COORDONNEES) values (%s,"%s","%s","%s",%s,"%s",%s);' %(CL_ID, CL_PRENOM, CL_NOM, CL_ADRESSE, CL_POSTALE, CL_VILLE, CL_COORDONNEES))

CO_CATEGORIE = input('Entrez la categorie : ')
CO_BONUS_MALUS = input('Entrez le bonus/malus : ')

engine.execute('INSERT INTO CONTRAT (CO_NUM, CO_DATE, CO_CATEGORIE, CO_BONUS_MALUS, CO_CLIENTS_FK) values ((SELECT max(CO_NUM)+1 from CONTRAT as CO), CURDATE(),"%s",%s,%s);' %( CO_CATEGORIE, CO_BONUS_MALUS,CO_CLIENTS_FK))


from tkinter import messagebox
import sqlite3
from tkinter import simpledialog
from tkinter.constants import END
from FuncionesCRUD_POO import *

def conectarBBDD():

    nombre_BBDD=simpledialog.askstring("BBDD", "Introduce el nombre de la BBDD")

    almacena(nombre_BBDD)

    miConexion=sqlite3.connect(nombre_BBDD)

    miCursor=miConexion.cursor()

    try:
        miCursor.execute('''

            CREATE TABLE DATOSUSUARIOS(
                ID INTEGER PRIMARY KEY AUTOINCREMENT,
                NOMBRE VARCHAR(50),
                PASSWORD VARCHAR(50),
                APELLIDO VARCHAR(50),
                DIRECCION VARCHAR (70),
                COMENTARIOS VARCHAR (200)
            )
        ''')

        messagebox.showinfo("BBDD", "Base de Datos creada con exito")

    except:

        messagebox.showwarning("Cuidao", "La Base de Datos ya existe")

def salirAplicacion(raiz):

    valor_salir=messagebox.askquestion("Salir", "Deseas salir de la aplicacion?")

    if valor_salir=="yes":
        raiz.destroy()

# def limpiarCampos(campo1, campo2, campo3, campo4, campo5):
#     campo1.set("")
#     campo2.set("")
#     campo3.set("")
#     campo4.set("")
#     campo5.set("")

def limpiarCampos(*args):

    for campo in args:

        campo.delete(1.0, END)

    else:

        campo.set("")

    # cuadroTexto.delete(1.0, END)