""" Lab 1 - Exercise 2 """

import numpy as np
import matplotlib.pyplot as plt

from cmcpack import integrate
import farms_pylog as pylog

def ode(x, _=None, A=np.eye(2)):
    """ System x_dot = A*x """
    return np.dot(A, x)

def integration(x0, time, A, name, **kwargs):
    """ System integration """
    labels = kwargs.pop("label", ["State {}".format(i) for i in range(2)])
    sys_int = integrate(ode, x0, time, args=(A,))
    sys_int.plot_state("{}_state".format(name), labels)
    sys_int.plot_phase("{}_phase".format(name))

def exercise2(clargs):
    """ Exercise 2 """
    pylog.info("Running exercise 2")

    # System definition
    pylog.warning("Proper matrix A must be implemented")
    A = np.array([[1, 0], [0, 1]])
    time_total = 10
    time_step = 0.01
    x0, time = [0, 1], np.arange(0, time_total, time_step)

    # Normal run
    pylog.warning("System integration must be implemented")
    # integration(x0, time, A, "example")

    # Stable point (Optional)
    pylog.warning("Stable point integration must be implemented")

    # Periodic
    pylog.warning("Periodic system must be implemented")

    # Plot
    if not clargs.save_figures:
        plt.show()

if __name__ == "__main__":
    from cmcpack import parse_args
    CLARGS = parse_args()
    exercise2(CLARGS)


def getMinimumUniqueSum(arr):
    res = list(arr)
    for i in range(len(arr)):
        elem = arr[i]
        new_arr = list(res)
        new_arr.remove(elem)
        while elem in new_arr:
            elem += 1
        res[i] = elem
    return sum(res)

arr = [3, 2, 1, 2, 7, 3, 2, 4, 8, 1, 7]
ans = getMinimumUniqueSum(arr)
to_match = sum([3, 2, 1, 4, 7, 5, 6, 8, 9, 10, 11])
if ans != to_match:
    print("Error: getMinimumUniqueSum!")
else:
    print("Succes: getMinimumUniqueSum! Answer is: {}".format(ans))

def isPossible(a, b, c, d):
    f1 = a
    f2 = b

    ans = False
    while 1:
        f1 = f1 + f2 if f1 < c else f1
        if f1 >= c and f2 > d:
            if f1 == c and ((abs(d - f2)) % a == 0 or (abs(d - f2)) % b == 0):
                ans = True
            break
        elif f1 == c:
            f2 = f2 + f1
        elif f1 > c:
            f1 = a
            f2 = f2 + f1
        if f1 == c and f2 == d:
            ans = True
            break
    return ans

ans1 = isPossible(3, 7, 748, 2016)
to_match1 = True
ans2 = isPossible(3, 8, 748, 2016)
to_match2 = False
if ans1 != to_match1 and ans2 != to_match2:
    print("Error: isPossible!")
else:
    print("Succes: isPossible! Answers are: {} and {}".format(ans1, ans2))

def get_direction(arr):
    len_arr = len(arr)
    first_half = arr[0:int(len_arr / 2)]
    sec_half = arr[int(len_arr / 2): len_arr]
    return False if sum(sec_half) > sum(first_half) else True

def separatingStudents(arr):
    itr = 0
    ind = 0
    count = 0
    steps = 0
    rev = get_direction(arr)
    sorted_arr = sorted(arr, reverse=rev)
    new_arr = list(arr)
    mover = 1 if rev else 0
    anti_mover = 0 if rev else 1
    while new_arr != sorted_arr:
        if new_arr[itr] == mover and count != 0:
            steps += count
            count = 0
            temp = new_arr[ind]
            new_arr[ind] = new_arr[itr]
            new_arr[itr] = temp
            itr = ind
        elif new_arr[itr] == mover:
            ind += 1
            itr += 1
        elif new_arr[itr] == anti_mover:
            count += 1
            itr += 1
    return steps

arr1 = [0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1]
arr2 = [1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1]
ans1 = separatingStudents(arr1)
ans2 = separatingStudents(arr2)
to_match1 = 16
to_match2 = 3
if ans1 != to_match1 or ans2 != to_match2:
    print("Error: separatingStudents!")
else:
    print("Succes: separatingStudents! Answers are: {} and {}".format(ans1, ans2))


import serial
import  time

# ser = serial.Serial()
# ser.baudrate = 115200
# ser.port = 'COM5'
# ser.open()
# joystick_data = 0
# init_msg = 'ml0'
# init_msg = init_msg.encode()
# ser.write(init_msg)
# while True:
#     print(ser.readline())
#     # ser.write(joystick_data)
#     message = 'mr150'
#     ser.write(message.encode())
#     message = 'ml-150'
#     ser.write(message.encode())
#     time.sleep(0.001)

class SerialComms:

    def __init__(self, baud, port):
        self.ser = serial.Serial()
        self.ser.baudrate = baud
        self.ser.port = port
        self.ser.open()

    def send_data(self, leftData, rightData):
        left = 'ml' + str(leftData)
        right = 'mr' + str(rightData)
        self.ser.write(left.encode())
        self.ser.write(right.encode())


# https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_canny/py_canny.html#canny
import cv2
from matplotlib import pyplot as plt

INPUT_FILE_NAME = 'flash.jpg'

img = cv2.imread(INPUT_FILE_NAME, 0)
edges = cv2.Canny(img, 200, 400)

plt.subplot(121)
plt.imshow(img, cmap='gray')
plt.title('Original image')
plt.xticks([])
plt.yticks([])

plt.subplot(122)
plt.imshow(edges, cmap='gray')
plt.title('Edge image')
plt.xticks([])
plt.yticks([])

plt.show()


import datetime
import discord
from discord.ext import commands

from utils.data import birthdays, congratulated

class Birthday:

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

    @commands.command(pass_context=True)
    async def birthday(self, ctx, birthday_string=None):
        """<dd-mm-yyyy> None for know the current value"""
        # Get the author
        user = ctx.message.author
        if birthday_string is not None:
            birth_date = datetime.datetime.strptime(birthday_string, '%d-%m-%Y')
            birthdays[user.id] = [user, birth_date]
            if user.id in congratulated:
                print('Removing')
                congratulated.remove(user.id)
        if user.id in birthdays:
            birth_date = birthdays[user.id][1]
            await self.bot.say('Your birthday is {}'.format(birth_date.strftime('%d-%m-%Y')))
        else:
            await self.bot.say('Hey, I don\'t know your birthday yet!Try this command again with a valid date'
                               ' so I can remember it forever!')

def setup(bot):
    bot.add_cog(Birthday(bot))


#########################################################################################################
#                                          AVRRead                                                      #
# A utility to read the XML files (probably .atdf in fact) in a Studio 6/7 installation and use         #
# the data within to define one big structure to overlay the SFR area of any AVR. Just use:             #
#                                                                                #
# python avrread.py -i ATmgea16.atdf                                                                    #
#                                                                                #
# or any other .atdf to generat an ATmega16.h (or whatever) header file for use in programming the      #
# AVR. In this case don't use "#include <avr/io.h>" but instead just do something like this:            #
#                                                                                #
#        #include "ATmega16.h"                                                                          #
#                                                                                #
#        USE_SFRS(pSFR);                                                                                #
#                                                                                #
#        int main(void)                                                                                #
#        {                                                                                #
#            pSFR->_DDRB.byte = 0xFF;                                                                   #
#            pSFR->_UCSRB.bit._TXEN = 1;                                                                #
#            while (1)                                                                                #
#            {                                                                                #
#                pSFR->_PORTB.byte ^= (1 << 3);                                                         #
#            }                                                                                #
#        }                                                                                #
#                                                                                #
# Use the USE_SFR() macro to name a struct pointer variable (like "pSFR") that you then want to         #
# use to access the registers in the code.                                                              #
#                                                                                #
#                        by Cliff Lawson                                                                #
#                                                                                #
# Licence: I need beer - see what you can do!                                                           #
#########################################################################################################

# following ("from...") line is useful if you are trying to make Python 3 code run in Python 2
# (however things like "argparse" here means this program is 3.2+ anyway.
# from __future__ import print_function
import sys
import os
import argparse
import xml.etree.ElementTree as et
from collections import namedtuple

# found this on StackOverflow - it simply returns the lowest bit that is set in a byte
def lowestSet(int_type):
    low = (int_type & -int_type)
    lowBit = -1
    while (low):
        low >>= 1
        lowBit += 1
    return(lowBit)

# often find this useful to check the raw command line args
# for n in range(0, len(sys.argv)):
#	print(n, sys.argv[n])

# I like argparse - it makes for very clean command line interfaces
parser = argparse.ArgumentParser(description='Read Atmel XML (version 1.3)')
parser.add_argument("-i", "--input", dest='in_fname', help="name of .XML file to read as input")
parser.add_argument("-o", "--output", dest='out_name', help="Name of output file (overides default)")
parser.add_argument("-q", "--quiet", dest='quiet', action="store_true", help="Don't print to console")
parser.add_argument("-v", "--verbose", dest='verbose', action="store_true", help="Show developer info")
parser.add_argument("-a", "--anonymous", dest='anon', action="store_true", help="Use anonymous structs (GCC only)")
parser.add_argument("-n", "--no_union", dest='nounion', action="store_true", help="No unions - just one entry per register")
parser.add_argument("-m", "--multiple", dest='multiple', action="store_true", help="process multiple files")

# my one argument with argparse is that if you run the app without args it doesn't show help info, so
# this will achieve that...
if len(sys.argv) == 1:
    parser.print_help()
    sys.exit(1)

# this actually runs the argument parser on sys.argv
args = parser.parse_args()

flist = []

if args.in_fname is not None and os.path.isfile(args.in_fname):
    flist.append(args.in_fname)
elif args.multiple is True and args.in_fname is None:
    for f in os.listdir("."):
        if ".atdf" in f:
            flist.append(f)

if len(flist) >= 1:
    for fname in flist:

        # The following creates an empty list. As the XML is parsed this will be appened()'d too to build a complete
        # picture of the AVR layout as a list of dictionaries
        mainlist = []

        # Assuming the user has given a name then do our thing!
        if fname is not None and os.path.isfile(fname):
            # the user has the opportunity to use -o to set an output filename but if they haven't used that this
            # takes the input .atdf/.xml filename and replaces the extension with ".h" to create the output name
            if args.out_name is None:
                out_name = os.path.splitext(fname)[0]+".h"

            if args.multiple is True or args.quiet is not True:
                print("Creating:", out_name)
            # ===================================== PART 1 (process the XML) ======================================
            # following two lines are the classic way to invoke ElementTree to read an XML then get access to the
            # root from which access to all other data then occurs
            tree = et.parse(fname)
            root = tree.getroot()

            # So the first thing I search for is the "memory-segment" entry with attribute name='MAPPED_IO'
            # this has the start/length of the SFRs (start is bound to be 0x20, it's the length I need to
            # later build the struct that covers the entire SFR region)
            io_node = root.find(".//memory-segment[@name='MAPPED_IO']")
            sfr_start = io_node.attrib['start']
            sfr_size = io_node.attrib['size']

            # The "interesting stuff" (as far as this program is concerned) is then the "modules" which are things
            # like "UART", "TIMER_COUNTER_1" and so on.
            modules = root.find("modules")

            # this then iterates over each module found...
            for mod in modules.findall("module"):
                # rather curiously there are two "modules" called "FUSE" and "LOCKBIT" - I want to ignore them...
                if mod.attrib['name'] in ['FUSE', 'LOCKBIT']:
                    continue

                # To keep the user entertained with some output - print the name of each module as I find it...
                if not args.quiet:
                    print("===============", mod.attrib['name'], "===============")

                # Now there's a load of data for each "module" that I'm not interested in. All I want are the registers
                # and bits and these appear under one or more "register-groups"
                rg = mod.find("register-group")

                # then in each register group iterate through the individual registers..
                for reg in rg.findall("register"):
                    # for each register pick out the useful bits of information
                    addr = int(reg.attrib['offset'], 0)
                    name = reg.attrib['name']
                    capt = reg.attrib['caption']
                    if capt is None:
                        capt = "missing caption"
                    sz = int(reg.attrib['size'])
                    # only used for whole registers - some are not full 8 or 16 bits
                    try:
                        main_mask = int(reg.attrib['mask'], 0)
                    except KeyError:
                        if sz == 1:
                            main_mask = 0xFF
                        elif sz == 2:
                            main_mask = 0xFFFF

                    # use the following to add extra detail if more than one byte involved
                    xtra = ""
                    if sz != 1:
                        xtra = str(sz) + " bytes"
                    if not args.quiet:
                        print(name, "addr=", hex(addr), xtra, "// ", capt)

                    # Have a look to see if there is a "bitfield" defined for this register
                    bits = reg.findall("bitfield")

                    # going to create a list of tuples (eventually sorted and duplicates removed) for any groups of bits
                    bitlist = []
                    if len(bits) != 0:
                        # if there is/are bitfields then work through each entry in turn
                        for bit in bits:
                            # int(x, 0) converts "0xNN" into an integer value - unfortunately the XML only holds these
                            # as a "mask" so if it's bits 3,4,5,6 the mask will be 0x78 and so on - need to process this
                            # later to get the lowest bit (3 in this example) and the starting bit position. For the
                            # lowest bit set I found something useful on StackOverflow which is at the start of this file
                            # for the number of bits set in a mask I found a very clever technique in another answer
                            # on StackOverflow - you use bit() to convert the mask to a "10101.." string then use count('1')
                            # on this to find out how many bits there are (as it happens they're always adjacent in fact)
                            mask = int(bit.attrib['mask'], 0)
                            try:
                                captn = bit.attrib['caption']
                            except KeyError:
                                captn = "caption missing"
                            try:
                                lsb = int(bit.attrib['lsb'])
                            except KeyError:
                                lsb = 0
                            numbits = bin(mask).count('1')
                            # @@@ need to consider non-adjacent bits in a mask such as 0xB0 (10110000) - e.g. mega16 SM bits
                            # <thinks> - split the bits in a "multi-mask" at this stage and make multiple 1 bit appends
                            # rather than trying to unwind this later.
                            # OK change of plan - because entries like the SM bits have a mask of 0xB0 (10110000) with non-
                            # adjacent bits then don't just store the low bit and numbits, but iterate through the bitmask now
                            # and add individual :1 entries for multiple bits (adding the lsb suffix and an incrementing count)
                            if numbits == 1:
                                bitinfo = namedtuple("bitinfo", "bitpos name caption")
                                bitinfo.bitpos = lowestSet(mask)
                                bitinfo.name = bit.attrib['name']
                                bitinfo.caption = captn
                                bitlist.append(bitinfo)
                            else:
                                suffix = lsb  # this starts at 0 if there is no lsb=
                                bitpos = 0
                                while numbits:
                                    while mask & (1 << bitpos) == 0:
                                        bitpos += 1
                                    bitinfo = namedtuple("bitinfo", "bitpos name caption")
                                    bitinfo.bitpos = bitpos
                                    bitpos += 1
                                    bitinfo.name = bit.attrib['name'] + str(suffix)
                                    suffix += 1
                                    bitinfo.caption = captn
                                    bitlist.append(bitinfo)
                                    numbits -= 1

                        if not args.quiet:
                            for n in sorted(bitlist, key=lambda x: x.bitpos):
                                print(n.name, "bit=" + str(n.bitpos), n.caption)

                    # now we assume we are going to this register/bits as a whole new entry in mainlist[]. However it turns
                    # out the XML may have several different register/bit definitions in different places for the same
                    # register - but you can spot this because you have already seen the address used. (BTW this all occurs
                    # with a register like TIMSK that may have some TMR_0 bits defined under the section for "TIMER 0" but
                    # then has some more bits defined later under "TIMER 1" and so on)
                    do_add = 1

                    # so now we check to see if the address of the register we're currently looking at was already seen
                    # and recorded in mainlist[]. If it has been then what we need to do is extract the existing "bitlist"
                    # (which is a list of tuples), then append each new tuple we've just found to this. However that may
                    # lead to duplicates.
                    for n in mainlist:
                        if n['addr'] == addr:

                            # so pull the "bits" from the existing entry that was found to have the same address
                            updated_bits = n['bits']

                            # then append each new bit entry tuple to this..
                            for entry in bitlist:
                                do_add = 1
                                for eb in updated_bits:
                                    if entry.bitpos == eb.bitpos:
                                        do_add = 0
                                if do_add:
                                    updated_bits.append(entry)

                            # I'll leave this (one of my development print()s as I found it MOST useful!)
                            # print("YOIKS!", "now=", sorted(nodups))
                            # now search the entrie mainlist[] again to find the index (i) of the one where we found the
                            # existing entry for the same address
                            for i in range(0, len(mainlist)):

                                # and when we stumble upon it..
                                if mainlist[i]['addr'] == addr:

                                    # replace what was there with new details including the sorted, duplicate removed list of bits
                                    mainlist[i] = {'addr': addr, 'name': name, 'size': sz, 'main_mask': main_mask, 'caption': capt, 'bits': sorted(updated_bits, key=lambda x: x.bitpos)}

                            # as we've updated an existing entry we don't want to add the data as a new one so..
                            do_add = 0

                    # if the address has not occurred before then just add the details including the sorted list of bits -
                    # it sort by default on the first item in the tuple which is the bit position
                    if do_add:
                        mainlist.append({'addr': addr, 'name': name, 'size': sz, 'main_mask': main_mask, 'caption': capt, 'bits': sorted(bitlist, key=lambda x: x.bitpos)})

            # The order of the "modules" in the XML is arbitrary and does not follow address order so now we sort the mainlist
            # of dictionaries using the 'addr' field in each one. Again this clever technique came from Stack Overflow
            mainlist = sorted(mainlist, key=lambda k: k['addr'])

            # finally entertain the user with something interesting looking (good for debugging too!)
            if args.verbose:
                print("\n++++++++++ All of that data from XML now stored as.... +++++++++++\n")
                for ent in mainlist:
                    print(hex(ent['addr']), ent)

            # ===================================== PART 2 (generate the output) ======================================
            # So we arrive here with mainlist[] fully populated with the complete info of all registers/bits stripped
            #  from the XMLso and the list now ordered by address. Now it's time to generate some output
            regidx = 0

            # remember the "MAPPED_IO" which was the first thing taken from the XML - this is where we use the sfr_start/size
            # we pulled from it at that time
            addr = int(sfr_start, 0)

            # this is just standard Python file IO - open xxx.h as a writable text file..
            hdr = open(out_name, "wt")

            # the preamble is a fixed text so write that now...
            hdr.write("#include <stdint.h>\n\ntypedef struct {\n")

            # now we build a struct that will span sfr_start to sfr_start+sfr_size (remember int(x,0) converts "0xNN" to int)
            # Oh and if you are wondering why this is a while() loop and not a for() loop it's because in Python (I found
            # out the hard way!) you cannot use "for x in range(start,end)" and the modify x within the loop to skip some values
            # the range() builds a list at the very start and x will be set to every member in that list for each iteration
            # of the loop - updates to the iteration variable are over-written!
            while addr < (int(sfr_start, 0) + int(sfr_size,0)):

                # now for each address in the SFR range we see if the next mainlist[] entry has something for it
                # first pull the mainlist entries into more readable varaible names:
                main_addr = mainlist[regidx]['addr']
                byts = int(mainlist[regidx]['size'])
                uint_sz = byts * 8
                main_mask = int(mainlist[regidx]['main_mask'])
                regbits = bin(main_mask).count('1')
                name = mainlist[regidx]['name']  # .lower()
                caption = mainlist[regidx]['caption']
                if main_addr == addr:

                    # if here then this address has an entry in mainlist[] so now the question is "is it a whole register or
                    # is it a group of bits?". Whole registers are things like PORTB, ADC, OCR0 and so on, while registers with
                    # (named) bits are things like UCSRA, TWCR and so on. For a whole register with anonymous bits then
                    # just generate something like:
                    #
                    # union {
                    # 	uint8_t reg; // (@ 0x32) Port D Data Register
                    # 	struct {
                    # 		unsigned int b0:1;
                    # 		unsigned int b1:1;
                    # 		unsigned int b2:1;
                    # 		unsigned int b3:1;
                    # 		unsigned int b4:1;
                    # 		unsigned int b5:1;
                    # 		unsigned int b6:1;
                    # 		unsigned int b7:1;
                    # 	} bit;
                    # } _PORTD;
                    #
                    # while for a register with named bits generate something like:
                    #
                    # union {
                    #     uint8_t reg; // (@ 0x2e) SPI Status Register
                    #     struct {
                    #         int _SPI2X:1; // b0 Double SPI Speed Bit
                    #         int :5; // b1 - unused
                    #         int _WCOL:1; // b6 Write Collision Flag
                    #         int _SPIF:1; // b7 SPI Interrupt Flag
                    #     } bit;
                    # } _SPSR;
                    #
                    #
                    # If it is a whole register then it might be more than one byte so need to decide to uint8_t, uint16_t
                    # and so on (I'm hoping they haven't got one defined as 'size':3 because that would lead to uint24_t
                    # as I just multiply by 8!!)
                    whole_reg = len(mainlist[regidx]['bits']) == 0
                    if args.nounion:
                        if whole_reg:
                            if regbits == 8 or regbits == 16:
                                hdr.write("\tuint" + str(uint_sz) + "_t " + name + "; // (@ " + str(hex(addr)) + ") " + caption)
                            else:
                                hdr.write("\tunsigned int " + name + ":" + str(regbits) + "; // (@ " + str(hex(addr)) + ") " + caption)
                        else:
                            hdr.write("\tstruct { // (@ " + str(hex(addr)) + ") " + caption + "\n")
                    else:
                        if regbits == 8 or regbits == 16:
                            hdr.write("\tunion {\n\t\tuint" + str(uint_sz) + "_t reg; // (@ " + str(hex(addr)) + ") " + caption + "\n\t\tstruct {\n")
                        else:
                            hdr.write("\tunion {\n\t\tunsigned int reg:" + str(regbits) + "; // (@ " + str(hex(addr)) + ") " + caption + " (range: 0.." + str((1 << regbits) - 1) + ") \n\t\tstruct {\n")

                    # now for a whole register just write bN fields for the number of bits there are
                    if whole_reg and not args.nounion:
                        for b in range(0,  bin(main_mask).count('1')):
                            hdr.write("\t\t\tunsigned int b" + str(b) + ":1;\n")
                    else:
                        # So this is the complicated bit when there are named bits defined
                        bitpos = 0
                        for b in mainlist[regidx]['bits']:

                            # We have tuples like (2, 5, 'FOO') which means FOO is at bit position 2 and spans 5 bits but
                            # some of the structs have "gaps" that are unused and we need to fill these with padding
                            # the gap is padded using the following...
                            if b.bitpos > bitpos:
                                nskip = b.bitpos - bitpos
                                hdr.write("\t\t\tunsigned int       :" + str(b.bitpos - bitpos) + "; // b" + str(bitpos))
                                if nskip > 1:
                                    hdr.write("...b" + str(b.bitpos - 1))
                                hdr.write(" - unused\n")

                                # and step bitpos on to the bit position of the enrty we're about to write
                                bitpos = b.bitpos

                            # then the actual named "FOO:5" entry is created by this...
                            hdr.write("\t\t\tunsigned int _" + b.name + ":1; // b" + str(b.bitpos) + " " + b.caption + "\n")

                            bitpos += 1  # b.numbits
                    if args.nounion:
                        if not whole_reg:
                            hdr.write("\t} " + name + ";\n")
                        else:
                            hdr.write("\n")
                    else:
                        if args.anon:
                            hdr.write("\t\t};\n\t} _" + name + ";\n")
                        else:
                            if uint_sz == 8:
                                hdr.write("\t\t} bit;\n\t} _" + name + ";\n")
                            else:
                                # just assume/handle uint16_t for now..
                                hdr.write("\t\t} bit;\n")
                                hdr.write("\t\tstruct {\n")
                                hdr.write("\t\t\tuint8_t low;\n")
                                if regbits == 16:
                                    hdr.write("\t\t\tuint8_t high;\n")
                                else:
                                    hdr.write("\t\t\tunsigned int high:" + str(regbits - 8) + ";\n")
                                hdr.write("\t\t} halves;\n")
                                hdr.write("\t} _" + name + ";\n")

                    # following adds 0 for size:1 entries but is mainly here for multi-byte entries so that addr can be
                    # stepped on for uint16_t registers and so on
                    addr += byts - 1

                    # now step the mainlist[] index on to the next entry
                    regidx += 1

                    # this may look "odd" but it prevents regidx trying to index beyond the end of mainlist and setting it
                    # to 1 is benign as "addr" has already moved on so there's no chance of it matching as it's now "behind"
                    # (hope that makes sense!)
                    if regidx >= len(mainlist):
                        regidx = 1
                else:
                    # this just writes an unused0xNN entry for each byte that has nothing in mainlist[]
                    hdr.write("\tuint8_t unused" + str(hex(addr)) + ";\n")
                addr += 1

            # then just finish with the closing part of the struct{} definition and we're all done! :-)
            # BTW I wanted to call the whole thing "AVR" not "SFRS" but the compiler alredy defines "AVR"
            hdr.write("} SFRS_t;\n\n#define USE_SFRS() volatile SFRS_t * const pSFR = (SFRS_t *)" + sfr_start + "\n\n")

            # now to make some easier to type/read symbols that actually hide some of that implementation
            for entry in mainlist:
                name = entry['name']
                hdr.write("/* ================= (" + name + ") " + entry['caption'] + " ================ */\n")
                hdr.write("#define " + name.lower() + " pSFR->_" + name + ".reg\n")
                if len(entry['bits']) == 0:
                    for n in range(0, bin(entry['main_mask']).count('1')):
                        hdr.write("#define " + name.lower() + "_b" + str(n) + " pSFR->_" + name + ".bit.b" + str(n) + "\n")
                    # assume it's uint16_t so there are two "halves" too:
                    if int(entry['size']) > 1:
                        hdr.write("#define " + name.lower() + "l pSFR->_" + name + ".halves.low\n")
                        hdr.write("#define " + name.lower() + "h pSFR->_" + name + ".halves.high\n")

                else:
                    for bit in entry['bits']:
                        bitname = bit.name.lower()
                        hdr.write("#define " + name.lower() + "_" + bitname + " pSFR->_" + name + ".bit._" + bitname.upper() + "\n")
                    for bit in entry['bits']:
                        bitname = bit.name.lower()
                        suffix = ""
                        if name == "SREG":
                            suffix = "_flag"
                        hdr.write("#define " + bitname + suffix + " (1 << " + str(bit.bitpos) + ")\n")
                    for bit in entry['bits']:
                        bitname = bit.name.lower()
                        hdr.write("#define " + bitname + "_bp " + str(bit.bitpos) + "\n")
                hdr.write("\n")
            hdr.close()
        else:
            print("No valid input file")


# coding: utf-8

from os import listdir

def recupere_cartes():
    # Récupère les cartes dans le répertoire cartes.
    liste_fichiers = listdir("cartes")
    # ne conserve que les fichiers .txt
    les_cartes = ["cartes/" + x for x in liste_fichiers if x.endswith(".txt")]

    return les_cartes

def choix_labyrinthe(cartes):
    # Choix de la carte par l'utilisateur
    dic_numero_labyrinthe = {}
    i = 0
    print("Labyrinthes existants : ")
    for carte in cartes:
        i += 1
        dic_numero_labyrinthe[i] = carte
        print(" {} - {}.".format(i, dic_numero_labyrinthe[i].split("/")[1]\
            .split(".txt")[0]))
    lab_nb = 0
    while lab_nb not in range(1, i+1):
        lab_nb = input(\
            "\nEntrez un numéro de labyrinthe pour commencer à jouer : "\
                       )
        try: # si ce n'est pas un entier on fixe la valeur à 0
            lab_nb = int(lab_nb)
        except:
            lab_nb = 0
    return dic_numero_labyrinthe[lab_nb]

def demande_mouvement():
    # Récupère le choix de mouvement de l'utilisateur

    usage = "\nMouvements :\nhaut : N\nbas : S\ndroite : E\ngauche : O\n"\
            "-----\nplusieurs mouvements : direction + 4\nquitter : Q\n"\
            "percer : P + direction\nmurer : M + direction\n"

    while True:
        mouvement = input("> ").upper()
        try:
            mouvement[0]
        except IndexError: # champs vide
            print(usage)
            continue
        if mouvement[0] in "ENOQS":
            if mouvement[1:] == "":
                dir_dist = mouvement[0], 1 # seule la lettre est fournie
                return dir_dist
            else:
                try:
                    dir_dist = mouvement[0], int(mouvement[1:])
                    return dir_dist
                except ValueError: # la distance n'est pas un int
                    pass
        elif mouvement[0] in "MP":
            if mouvement[1:] == "":
                pass
            elif mouvement[1] in "ENOS":
                dir_dist = mouvement[0], mouvement[1]
                return dir_dist
        print(usage)


'''
JC added 3D uvw in no surface case
 Question why deleting only u,v,w and not u2,v2,w2

Compute pu,pv,pw corresponsing to u,v,w at particles positions for 2d surf

- add w_sed0 to pw

Input:
    simul, dx, dy, dz, nx, ny, nz
    px, py, pz
    ...

Outputs:
    pu, pv, pw

'''

###################################################################################
#Load u,v

if simul.simul[-4:]=='surf':
    [u,v] = part.get_vel_io_surf(simul, x_periodic=x_periodic,
                                 y_periodic=y_periodic, ng=ng, coord=coord)
    if not meanflow and alpha_time != 0:
        simul.update(np.ceil(time))
        [u2,v2] = part.get_vel_io_surf(simul, x_periodic=x_periodic,
                                       y_periodic=y_periodic, ng=ng, coord=coord)
        simul.update(np.floor(time))
        u = linear(u,u2,alpha_time)
        v = linear(v,v2,alpha_time)
else:
    [u, v, w] = part.get_vel_io(simul, x_periodic=x_periodic,
                                y_periodic=y_periodic, ng=ng, coord=coord)
    if not meanflow and alpha_time != 0:
        simul.update(np.ceil(time))
        [u2,v2,w2] = part.get_vel_io(simul,x_periodic=x_periodic,
                y_periodic=y_periodic,ng=ng,coord=coord)
        simul.update(np.floor(time))
        u = linear(u,u2,alpha_time)
        v = linear(v,v2,alpha_time)
        w = linear(w,w2,alpha_time)
###############################################################################
# Get u,v at particles positions

pu[:]=partF.interp_3d_u(px,py,pz,u,ng,nq,i0,j0,k0)
pv[:]=partF.interp_3d_v(px,py,pz,v,ng,nq,i0,j0,k0)
pw[:]=partF.interp_3d_w(px,py,pz,w,ng,nq,i0,j0,k0) + w_sed0

###################################################################################

del u,v,w


#!/usr/bin/env python3

import zlib
import struct

from PyQt5 import QtCore, QtWidgets

from dsrlib.domain.hidenum import HIDDeviceWorker
from dsrlib.domain.mixins import WorkspaceMixin

from .utils import LayoutBuilder

class ConfigurationUploader(WorkspaceMixin, QtWidgets.QDialog):
    def __init__(self, parent, *, device, **kwargs):
        super().__init__(parent, **kwargs)
        self._progress = QtWidgets.QProgressBar(self)
        self._bytecode = self.workspace().bytecode()
        self._offset = 0
        self._worker = HIDDeviceWorker(device)
        self._crc = zlib.crc32(self._bytecode)

        self._progress.setMinimum(0)
        self._progress.setMaximum(len(self._bytecode))
        self._progress.setValue(0)

        bld = LayoutBuilder(self)
        with bld.vbox() as layout:
            self._label = QtWidgets.QLabel(_('Uploading to {name}...').format(name=device.name), self)
            layout.addWidget(self._label)
            layout.addWidget(self._progress)
            layout.setContentsMargins(5, 5, 5, 5)

    def exec_(self): # pylint: disable=C0103
        self._worker.start()
        QtCore.QTimer.singleShot(0, self._next)
        return super().exec_()

    def _next(self):
        length = min(59, len(self._bytecode))
        data = struct.pack('<BHH', 0x88, self._offset, length) + self._bytecode[:length]
        self._bytecode = self._bytecode[length:]
        if len(data) < 64:
            data += b'\x00' * (64 - len(data))
        self._worker.write(data)

        self._offset += length
        self._progress.setValue(self._offset)

        if self._bytecode:
            QtCore.QTimer.singleShot(1000, self._next)
        else:
            QtCore.QTimer.singleShot(1000, self._check)

    def _check(self):
        self._worker.reportReceived.connect(self._gotReport)
        self._label.setText(_('CRC check...'))
        self._worker.getReport(0x84, 5)

    def _gotReport(self, data):
        unused, crc = struct.unpack('<BI', data[:5])
        if crc == self._crc:
            self.accept()
        else:
            QtWidgets.QMessageBox.warning(self, _('Warning'), _('The CRC check failed. You will probably want to retry.'))
            self.reject()
        self._worker.cancel()


#Ray Tso
#5/11/18
#warmup16.py

file = open('engmix.txt')
for word in file:
    word=word.strip()
    if len(word)<0 and word[0]=='r'and word[-1]=='t':
        print(word.strip())


import sqlite3
from flask_restful import Resource
from flask import Flask, request

class Cliente (Resource):

    def __init__(self):
        self.conn = sqlite3.connect('base.bd')
        self.cursor = self.conn.cursor()

    def post(self):
        try:
            cursor = self.conn.cursor()
            print('####')
            dados_requisicao = request.json
            dados_requisicao = tuple( list(dados_requisicao.values()))

            lista = [dados_requisicao]

            self.conn.executemany('INSERT INTO Cliente \
            (cpf, nome)\
            VALUES (?, ?)', lista)

            self.conn.commit()
            cursor.close()

            return {'Status':'Dados inseridos'}

        except Exception as exception:

            return {'Error': f"Não foi possivél inserir um novo cliente: {exception}"}


# Ω*
#               ■          ■■■■■
#               ■         ■■   ■■
#               ■        ■■     ■
#               ■        ■■
#     ■■■■■     ■        ■■■
#    ■■   ■■    ■         ■■■
#   ■■     ■■   ■          ■■■■
#   ■■     ■■   ■            ■■■■
#   ■■■■■■■■■   ■              ■■■
#   ■■          ■               ■■
#   ■■          ■               ■■
#   ■■     ■    ■        ■■     ■■
#    ■■   ■■    ■   ■■■  ■■■   ■■
#     ■■■■■     ■   ■■■    ■■■■■

"""
Copyright (c) 2020.5.28 [el.ideal-ideas]
This software is released under the MIT License.
see LICENSE.txt or following URL.
https://www.el-ideal-ideas.com/MocaSystem/LICENSE/
"""

# -- Imports --------------------------------------------------------------------------

from .MocaBliveAPIServer import MocaBliveAPIServer
from ssl import SSLContext
from src.core import moca_config, LOG_DIR, VERSION, TOP_DIR
from src.moca_modules.moca_utils import *
from subprocess import call
from sanic import Blueprint
from sanic.request import Request
from sanic.response import HTTPResponse, text, json
from sanic.websocket import WebSocketConnection
from sanic.exceptions import InvalidUsage
from src.blive_api import RawBLiveClient, InitError
from ujson import loads
from sys import executable
from asyncio import sleep
from src.database import get_comments, get_gifts

# -------------------------------------------------------------------------- Imports --

# -- Variables --------------------------------------------------------------------------

allowed_origin: str = moca_config.get('origin')

blive_api: Blueprint = Blueprint('blive_api', 'blive')

# -------------------------------------------------------------------------- Variables --

# -- Server --------------------------------------------------------------------------

ssl: Optional[SSLContext]
if isinstance(moca_config.get('certfile'), str) and \
        isinstance(moca_config.get('keyfile'), str) and \
        Path(moca_config.get('certfile')).is_file() and \
        Path(moca_config.get('keyfile')).is_file():
    ssl = MocaBliveAPIServer.create_ssl_context(moca_config.get('certfile'),
                                                moca_config.get('keyfile'))
else:
    ssl = None

server: MocaBliveAPIServer = MocaBliveAPIServer(
    'MocaBliveAPIServer',
    moca_config.get('host'),
    moca_config.get('port'),
    ssl,
    LOG_DIR,
    None,
    moca_config.get('access_log'),
    moca_config.get('use_ipv6'),
    0,
    moca_config.get('headers')
)

server.add_blueprint(blive_api)

app = server.app

# -------------------------------------------------------------------------- Server --

# -- Blueprint --------------------------------------------------------------------------

@blive_api.route('/version')
async def version(request: Request) -> HTTPResponse:
    return text(VERSION)

@blive_api.route('/listen')
async def listen(request: Request) -> HTTPResponse:
    res = await app.redis.execute('KEYS', 'mr-moca-blive-api-pid-*')
    return json([item.decode()[22:] for item in res])

@blive_api.route('/select-comments')
async def select_comments(request: Request) -> HTTPResponse:
    try:
        json_data = request.json if isinstance(request.json, dict) else {}
    except InvalidUsage:
        json_data = {}
    room_id = json_data.get(
        'room_id', request.args.get('room_id', request.form.get('room_id', request.headers.get('ROOM-ID')))
    )
    start = json_data.get(
        'start', request.args.get('start', request.form.get('start', request.headers.get('Start')))
    )
    limit = json_data.get(
        'limit', request.args.get('limit', request.form.get('limit', request.headers.get('Limit')))
    )
    try:
        start = int(start)
    except (ValueError, TypeError):
        pass
    try:
        limit = int(limit)
    except (ValueError, TypeError):
        pass
    if room_id is None:
        return text('ROOM_ID_IS_REQUIRED')
    elif not isinstance(room_id, str):
        return text('ROOM_ID_FORMAT_ERROR')
    elif len(room_id) > 32:
        return text('ROOM_ID_LENGTH_ERROR')
    if start is None:
        start = 0
    elif (not isinstance(start, int)) or (start < 0):
        return text('START_INDEX_FORMAT_ERROR')
    if limit is None:
        limit = 1024
    elif (not isinstance(limit, int)) or (limit < 0):
        return text('LIMIT_FORMAT_ERROR')

    pool = await app.mysql.get_aio_pool()
    data = await get_comments(pool, room_id, start, limit)
    return json(data)

@blive_api.route('/select-gifts')
async def select_gifts(request: Request) -> HTTPResponse:
    try:
        json_data = request.json if isinstance(request.json, dict) else {}
    except InvalidUsage:
        json_data = {}
    room_id = json_data.get(
        'room_id', request.args.get('room_id', request.form.get('room_id', request.headers.get('ROOM-ID')))
    )
    start = json_data.get(
        'start', request.args.get('start', request.form.get('start', request.headers.get('Start')))
    )
    limit = json_data.get(
        'limit', request.args.get('limit', request.form.get('limit', request.headers.get('Limit')))
    )
    try:
        start = int(start)
    except (ValueError, TypeError):
        pass
    try:
        limit = int(limit)
    except (ValueError, TypeError):
        pass
    if room_id is None:
        return text('ROOM_ID_IS_REQUIRED')
    elif not isinstance(room_id, str):
        return text('ROOM_ID_FORMAT_ERROR')
    elif len(room_id) > 32:
        return text('ROOM_ID_LENGTH_ERROR')
    if start is None:
        start = 0
    elif (not isinstance(start, int)) or (start < 0):
        return text('START_INDEX_FORMAT_ERROR')
    if limit is None:
        limit = 1024
    elif (not isinstance(limit, int)) or (limit < 0):
        return text('LIMIT_FORMAT_ERROR')

    pool = await app.mysql.get_aio_pool()
    data = await get_gifts(pool, room_id, start, limit)
    return json(data)

@blive_api.websocket('/raw')
async def raw(request: Request, ws: WebSocketConnection):
    info = loads(await ws.recv())
    origin: str = request.headers.get('origin', 'None')
    if (info.get('room_id') is None) or (info.get('secret_key') is None):
        await app.moca_log.save(
            f'IP: 连接失败。类型: RawBLiveClient, 状态: 数据格式错误, 房间号: {info.get("room_id")}', 1
        )
        await ws.send('DENIED')
    elif (allowed_origin != '*') and not origin.startswith(allowed_origin):
        await app.moca_log.save(
            f'IP: 连接失败。类型: RawBLiveClient, 状态: origin认证失败, 房间号: {info.get("room_id")}', 1
        )
        await ws.send('DENIED')
    elif info.get('secret_key', '') != app.moca_config.get('secret_key', ''):
        await app.moca_log.save(
            f'IP: 连接失败。类型: RawBLiveClient, 状态: secret_key认证失败, 房间号: {info.get("room_id")}', 1
        )
        await ws.send('DENIED')
    else:
        await app.moca_log.save(
            f'IP: 开始连接。类型: RawBLiveClient, 状态: 成功, 房间号: {info.get("room_id")}', 1
        )
        client = RawBLiveClient(info['room_id'], ws, app, app.moca_config)
        try:
            await client.start()
        except InitError:
            await ws.send('ROOM_ID_ERROR')
        finally:
            await client.close()
        await app.moca_log.save(
            f'IP: 停止连接。类型: RawBLiveClient, 状态: 成功, 房间号: {info.get("room_id")}', 1
        )

@blive_api.websocket('/live')
async def live(request: Request, ws: WebSocketConnection):
    info = loads(await ws.recv())
    origin: str = request.headers.get('origin', 'None')
    if (info.get('room_id') is None) or (info.get('secret_key') is None):
        await app.moca_log.save(
            f'IP: 连接失败。类型: DefaultBLiveClient, 状态: 数据格式错误, 房间号: {info.get("room_id")}', 1
        )
        await ws.send('DENIED')
    elif (allowed_origin != '*') and not origin.startswith(allowed_origin):
        await app.moca_log.save(
            f'IP: 连接失败。类型: DefaultBLiveClient, 状态: origin认证失败, 房间号: {info.get("room_id")}', 1
        )
        await ws.send('DENIED')
    elif info.get('secret_key', '') != app.moca_config.get('secret_key', ''):
        await app.moca_log.save(
            f'IP: 连接失败。类型: DefaultBLiveClient, 状态: secret_key认证失败, 房间号: {info.get("room_id")}', 1
        )
        await ws.send('DENIED')
    else:
        await app.moca_log.save(
            f'IP: 开始连接。类型: DefaultBLiveClient, 状态: 成功, 房间号: {info.get("room_id")}', 1
        )
        count = await app.redis.increment('moca-blive-api-client-count' + info['room_id'])
        if count == 1:
            call(
                f'nohup {executable} "{str(TOP_DIR.joinpath("moca.py"))}"'
                f' run-listener {info["room_id"]} &> /dev/null &',
                shell=True
            )
        try:
            index = await app.redis.llen('moca-blive-api-' + info['room_id'])
            while True:
                data = await app.redis.lrange('moca-blive-api-' + info['room_id'], index, -1)
                index += len(data)
                await sleep(0.1)
                for item in data:
                    await ws.send(dumps(item))
        finally:
            await app.moca_log.save(
                f'IP: 停止连接。类型: DefaultBLiveClient, 状态: 成功, 房间号: {info.get("room_id")}', 1
            )
            count = await app.redis.decrement('moca-blive-api-client-count' + info['room_id'])
            if count == 0:
                pid = await app.redis.get('moca-blive-api-pid-' + info['room_id'])
                call(f'kill {pid}', shell=True)
                await app.redis.delete('moca-blive-api-pid-' + info['room_id'])

# -------------------------------------------------------------------------- Blueprint --


# -*- coding=utf-8 -*-
'''
Created on 2016年2月22日

@author: YANG
'''

'''
DATA INFO
0~3：时间戳、小区名等无效信息

  9: 小区下行速率
 17：RRC建立成功率
 25：E-RAB建立成功率
 26：E-RAB掉话率
 27：同频切换成功率
 18,19,23,37,45,51,56经过之前的检测，都是完全无变化项，即给分类带来零帮助
 28,29,30有大量的NIL数据

'''

from Beta_1.RCA_Predict import RCA_Predict
from Beta_1.RCA_Train import RCA_Train
from Beta_1.FileInput import FileInput
import time
import xlrd
import pickle
def RCA(IGLIMIT=0.1, ratio=3, labelIndex=1, fileName="1", filteredFea=[]):

    #===========================================================================
    # 参数获取，包括 path, fileName, ratio, IGLIMIT, label
    # path 训练数据的文件路径
    # fileName 训练数据文件名
    # ratio 模型的正负样本比例
    # IGLIMIT information gain的下限，用于控制决策树的生长。越小，决策树越复杂，得到的根因个数越多，可能包含的随机噪声越大
    # label 需要分析的KPI, 用几个简写代替
    # {Download Average Rate: 1,
    #  RRC Setup Success Rate:2,
    #  ERAB Setup Success Rate:3,
    #  ERAB Call Drop Rate:4,
    #  Intra-Frequency Handover Success Rate:5}
    #===========================================================================

    labelDic = [9,17,25,26,27]

    trainer = RCA_Train(fileName, labelDic[labelIndex-1], IGLIMIT, ratio)
    predictor = RCA_Predict(fileName, labelDic[labelIndex-1])

    trainer.Train(filteredFea)
    return predictor.Predict(filteredFea)

def showTime():
    print(time.strftime("%Y-%m-%d  %H:%M:%S",time.localtime()))

def intersection(prediction1, prediction2):
    #===========================================================================
    # 用来衡量prediction1(dic类型)与prediction2之间的相近程度
    # 现有策略：
    # 每个prediction最多采用前十个元素，求交集，并给出各个元素的熵增益之和，用以进一步判断模型训练得出结果的稳定性
    # 至少有三个相同的才算stable
    #===========================================================================
    result = {}
    for item in prediction1:
        if(prediction2.__contains__(item)):
            result[item] = prediction1[item]+prediction2[item]

    return result

def getParameters():
    #===========================================================================
    # IGLIMIT=0.1, ratio=3, path="tempdata", labelIndex=1, fileName="1", filteredFea
    #===========================================================================

    reader = open("settings\\parameters.txt","r")
    IGLIMIT = float(reader.readline().strip()[len("IGLIMIT : ")+1:-1])
    ratio = float(reader.readline().strip()[len("ratio : ")+1:-1])
    path = reader.readline().strip()[len("path : ")+1:-1]
    fileName = reader.readline().strip()[len("fileName : ")+1:-1]
    labelIndex = int(reader.readline().strip()[len("KPI : ")+1:-1])
    filteredFea = []
    items = reader.readline().strip()[len("filteredFea : ")+2:-2].split(",")
    for item in items:
        try:
            filteredFea.append(int(item))
        except:
            break
    return IGLIMIT, ratio, path, fileName, labelIndex, filteredFea

def IsFormatSame(path="", fileName=""):
    '''
    dic = []
    book = xlrd.open_workbook("tempdata\\data.xls")
    sheet = book.sheet_by_index(0)
    for i in range(sheet.ncols):
        dic.append(sheet.cell_value(0,i))

    writer = open("settings\\names",'wb')
    pickle.dump(dic,writer)
    writer.close()
    '''

    reader = open("settings\\names",'rb')
    dic = pickle.load(reader)

    book = xlrd.open_workbook("%s\\%s.xls"%(path, fileName))
    sheet = book.sheet_by_index(0)

    for colIndex in range(sheet.ncols):
        if(sheet.cell_value(0,colIndex)!=dic[colIndex]):
            print("the format is wrong")
            return False
    return True

def main():
    #===========================================================================
    # 此处的处理逻辑存在较大的安全隐患，即对训练结果出现极端情况时丧失处理能力
    # 极端情况指： 当训练参数调至ratio很大，IGLIMIT很小，决策树既无法长大，root cause亦应该很稳定时，
    # 依旧不能满足 5组数据有3个共同的情况！
    #===========================================================================
    paras = getParameters()

    IGLIMIT = paras[0]
    ratio = paras[1]
    path = paras[2]
    fileName = paras[3]
    labelIndex = paras[4]
    filteredFea = paras[5]
    Found = False
    prediction1 = {}

    if(not IsFormatSame(path, fileName)):
        return

    if(not FileInput().DataPreprocess(path, fileName)):
        return

    print("\n\n=============================================================\n\nparameters information\nIGLIMIT : %f\nratio : %f\npath : %s\nfileName : %s\nlabelIndex : %d"%(IGLIMIT,ratio,path,fileName,labelIndex))
    print("filteredFea :",filteredFea)
    while(not Found):
        print("\n\n=============================================================\n\ntraining information")
        showTime()
        print("IGLIMIT:%f, ratio:%f"%(IGLIMIT,ratio))
        rootCause = RCA(IGLIMIT, ratio, labelIndex, fileName, filteredFea)
        prediction1 = {}
        for item in rootCause[:]:
            prediction1[item[0]] = item[1]
        for i in range(1):
            rootCause = RCA(IGLIMIT,ratio, labelIndex, fileName, filteredFea)
            prediction2 = {}
            for item in rootCause[:]:
                prediction2[item[0]] = item[1]
            prediction1 = intersection(prediction1, prediction2)
            if(len(prediction1)<1):
                IGLIMIT -= 0.01
                if(IGLIMIT<0.04):
                    print("the model cannot work")
                    return
                break
            if(i==0):
                Found = True
    showTime()
    labelDic = FileInput().InputGetDicForDel(fileName)
    result = sorted(prediction1.items(), key = lambda x:x[1], reverse=True)
    print("\n\n=============================================================\n\n\nthe final result for root cause recommendation")
    for item in result:
        print([item[0], item[1], labelDic[item[0]]])

    return

if __name__=="__main__":
    main()
    l= "\"nihao\"\n"
    print(l[1:-1])


import time
import unittest
import os
import logging
from app import app

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class IsAppUp(unittest.TestCase):

    def setUp(self):
        self.app = app.test_client()
        print("In setUp")
        caps = {'browserName': 'chrome'}
        self.browser = webdriver.Remote(
            command_executor='http://localhost:4444/wd/hub',
            desired_capabilities=caps)
        self.logger = logging
        self.logger.info("About to call a test")

    def test_simple(self):
        print("In simple")
        self.logger.info("In simple")
        browser = self.browser
        browser.get('http://localhost:5004/interviews')
        time.sleep(3)
        """ self.assertIn("Home", browser.title)
        search_box = browser.find_element_by_name('employeeName')
        search_box.send_keys('John')
        search_box.send_keys(Keys.RETURN)
        time.sleep(3) # simulate long running test
        self.assertIn('John', browser.page_source) """

    def test_page(self):
        response = self.app.get('/interviews', follow_redirects=True)
        self.assertEqual(response.status_code, 200)

    def tearDown(self):
        print("In tearDown")
        self.browser.quit() # quit vs close?

if __name__ == '__main__':
    logging.basicConfig(filename='selenium-plugin.log',level=logging.INFO)
    logging.info("About to call main")
    unittest.main()


import matplotlib.pyplot as plt
import numpy as np
import string

#thermo counts
letterCounter = dict(zip(string.ascii_lowercase,[0]*26))
total = 0
with open("Thermo.txt") as f:
    for line in f:
        for word in line.split():
            for letter in list(word.lower()):
                letterCounter[letter]+=1
                total+=1

for i in letterCounter:
    if letterCounter.values() == 0:
        pass
    else:
        letterCounter[i] = letterCounter[i] / total

print("thermo")
print(letterCounter)
print(total)

f.close()

#ecoli counts
letterCounter2 = dict(zip(string.ascii_lowercase,[0]*26))
total2 = 0

with open("Ecoli.txt") as f2:
    for line in f2:
        for word in line.split():
            for letter in list(word.lower()):
                letterCounter2[letter]+=1
                total2+=1

for i in letterCounter2:
    if letterCounter2.values() == 0:
        pass
    else:
        letterCounter2[i] = letterCounter2[i] / total2

print("ecoli")
print(letterCounter2)
print(total2)

f2.close()

#graph for Thermophile
objects = ('G', 'C', 'T', 'A')
y_pos = np.arange(len(objects))
performance = [31.89546112193373,31.751577379199064,18.207584001246127,18.145]

plt.bar(y_pos, performance, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Percentages')
plt.title('Thermophile Genome Makeup')

plt.show()

"""
#graph for Ecoli
objects1 = ('C', 'G', 'T', 'A')
y_pos = np.arange(len(objects1))
performance = [25.441712775434777,25.188812774889185,24.661890684223203,24.707583765452834]

plt.bar(y_pos, performance, align='center', alpha=0.5)
plt.xticks(y_pos, objects1)
plt.ylabel('Percentages')
plt.xlabel('Ecoli Genome Makeup')

plt.show()
"""


# Retain only sentences. from paragraphs that end with punctuation.

import csv
from localdefs import *

SOURCE_FILE = str(DATA_DIR / 'sentences.csv')
TARGET_FILE = str(DATA_DIR / 'sjabloon.txt')

SOURCE_HEADER = ['TOKEN', 'POSTAG']

def main():
    print('Reading {}'.format(SOURCE_FILE))
    print('Writing {}'.format(TARGET_FILE))
    with open(SOURCE_FILE, encoding='utf-8') as source:
        reader = csv.reader(source, dialect='local')
        assert next(reader) == SOURCE_HEADER
        sjabloon = []
        with open(TARGET_FILE, 'w', encoding='utf-8') as target:
            for token, postag in reader:
                if token or postag:
                    sjabloon.append(token if postag == 'LET()' else postag)
                else:
                    if sjabloon:
                        target.write(' '.join(sjabloon))
                        target.write('\n')
                    sjabloon = []
            assert not sjabloon

if __name__ == '__main__':
    main()


from app import mongo
from app.utils import jsonify_stix

class Bundle(object):
    """ Bundle model for access bundle collection in mongodb """

    def __init__(self):
        self.collection = mongo.db.bundle

    def get_all(self, limit, offset, sort, filt):
        query = self.collection.find().skip(offset).limit(limit)
        query_size = self.collection.find()
        if filt is not None:
            query = self.collection.find({filt['id']: {'$regex': filt['value']}}).skip(offset).limit(limit)
            query_size = self.collection.find({filt['id']: {'$regex': filt['value']}})
        if sort is not None:
            query.sort(sort['id'], -1 if sort['desc'] else 1 )

        bundle_list = list(query)
        size = query_size.count()
        result = jsonify_stix(bundle_list)
        return result, size

    def find(self, id):
        result = jsonify_stix(self.collection.find_one({'id': id}))
        return result

    def count(self):
        result = self.collection.count()
        return result


import argparse
from crawler import Crawler

# init parameters
parser = argparse.ArgumentParser(description="Simple and unlimited sitemap generator")
parser.add_argument('--url', action="store", default="", help="e.g. http://kkabardi.me")
parser.add_argument('--exclude', action="store", default="", help="Exclude urls" )
parser.add_argument('--no-verbose', action="store_true", default="", help="Prints verbose output")
parser.add_argument('--output', action="store", default="sitemap.xml", help="Shows the output for the file path")

# parse parameters
args = parser.parse_args()
url = args.url.rstrip("/")
links_fetched = []

# initializeing crawler
crawler = Crawler(url, exclude=args.exclude, no_verbose=args.no_verbose);

# fetch links
links = crawler.start()

# write into file
with open(args.output, "w") as file:

	file.write('<?xml version="1.0" encoding="UTF-8"?>\n\t<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">')

	for link in links:
		file.write("\n\<url>\n<loc>\n{0}{1}/\n</loc>\n</url>".format(url, link))

	file.write('</urlset>')


import os

from yacs.config import CfgNode as CN
# -----------------------------------------------------------------------------
# Convention about Training / Test specific parameters
# -----------------------------------------------------------------------------
# Config definition
# -----------------------------------------------------------------------------
_C = CN()

_C.MODEL = CN()
_C.MODEL.DEVICE = "cuda"
_C.MODEL.CUDNN = True
_C.MODEL.ARCHITECTURE = ""
_C.MODEL.WEIGHT = ""

# -----------------------------------------------------------------------------
# INPUT
# -----------------------------------------------------------------------------
_C.INPUT = CN()
_C.INPUT.NUM_SEGMENTS = 256
_C.INPUT.UPSAMPLE = True
_C.INPUT.MAX_NUM_WORDS = 30
_C.INPUT.FIX_NUM_WORDS = False
_C.INPUT.PRE_QUERY_SIZE = 300
_C.INPUT.WORD2VEC = 'GloVe'

# -----------------------------------------------------------------------------
# Dataset
# -----------------------------------------------------------------------------
_C.DATASETS = CN()
# List of the dataset names for training, as present in paths_catalog.py
_C.DATASETS.TRAIN = ()
_C.DATASETS.RESAMPLE = False
_C.DATASETS.RESAMPLE_WEIGHT = 0.0 # class balanced sampling
# List of the dataset names for testing, as present in paths_catalog.py
_C.DATASETS.TEST = ()
_C.DATASETS.VISUAL_DIM = 1024
_C.DATASETS.IN_MEMORY = False
_C.DATASETS.DEP_GRAPH = False
_C.DATASETS.CONSTI_MASK = False
_C.DATASETS.TREE_DEPTH = 3
_C.DATASETS.PROPOSAL_METHOD = ''
_C.DATASETS.NUM_CLIPS = -1 # for method 2dtan
_C.DATASETS.ANCHOR_WIDTHS = []
_C.DATASETS.WINDOW_WIDTHS = []
_C.DATASETS.WINDOW_OVERLAP = 0.0

# -----------------------------------------------------------------------------
# DataLoader
# -----------------------------------------------------------------------------
_C.DATALOADER = CN()
# Number of data loading threads
_C.DATALOADER.NUM_WORKERS = 4

# -----------------------------------------------------------------------------
# Models
# -----------------------------------------------------------------------------
# Causality
_C.MODEL.CAUSAL = CN()
_C.MODEL.CAUSAL.USE_CAUSALITY = False
_C.MODEL.CAUSAL.TAU = 16.0
_C.MODEL.CAUSAL.GAMMA = 1.0/32.0
_C.MODEL.CAUSAL.ALPHA = 0.5

# 2DTAN
_C.MODEL.TAN = CN()

_C.MODEL.TAN.FEATPOOL = CN()
_C.MODEL.TAN.FEATPOOL.INPUT_SIZE = 4096
_C.MODEL.TAN.FEATPOOL.HIDDEN_SIZE = 512
_C.MODEL.TAN.FEATPOOL.KERNEL_SIZE = 2
_C.MODEL.TAN.FEATPOOL.FREEZE = False

_C.MODEL.TAN.FEAT2D = CN()
_C.MODEL.TAN.FEAT2D.POOLING_COUNTS = [15,8,8,8]

_C.MODEL.TAN.INTEGRATOR = CN()
_C.MODEL.TAN.INTEGRATOR.QUERY_HIDDEN_SIZE = 512
_C.MODEL.TAN.INTEGRATOR.LSTM = CN()
_C.MODEL.TAN.INTEGRATOR.LSTM.NUM_LAYERS = 3
_C.MODEL.TAN.INTEGRATOR.LSTM.BIDIRECTIONAL = False
_C.MODEL.TAN.INTEGRATOR.FREEZE = False

_C.MODEL.TAN.PREDICTOR = CN()
_C.MODEL.TAN.PREDICTOR.HIDDEN_SIZE = 512
_C.MODEL.TAN.PREDICTOR.KERNEL_SIZE = 5
_C.MODEL.TAN.PREDICTOR.NUM_STACK_LAYERS = 8
_C.MODEL.TAN.PREDICTOR.FREEZE = False

_C.MODEL.TAN.LOSS = CN()
_C.MODEL.TAN.LOSS.MIN_IOU = 0.3
_C.MODEL.TAN.LOSS.MAX_IOU = 0.7

# TCR
_C.MODEL.TCR = CN()
_C.MODEL.TCR.ENCODER_LAYERS = 1
_C.MODEL.TCR.DECODER_LAYERS = 1
_C.MODEL.TCR.LAMBDA_IOU = 2
_C.MODEL.TCR.LAMBDA_L1 = 2

_C.MODEL.TCR.VIDEOENCODER = CN()
_C.MODEL.TCR.VIDEOENCODER.METHOD = 'conv'
_C.MODEL.TCR.VIDEOENCODER.HIDDEN_DIM = 512
_C.MODEL.TCR.VIDEOENCODER.DROPOUT = 0.2
_C.MODEL.TCR.VIDEOENCODER.KERNEL_SIZE = -1 # conv
_C.MODEL.TCR.VIDEOENCODER.NUM_LAYERS = -1 # transformer
_C.MODEL.TCR.VIDEOENCODER.NUM_HEADS = -1 # transformer

_C.MODEL.TCR.QUERYENCODER = CN()
_C.MODEL.TCR.QUERYENCODER.HIDDEN_DIM = 512

_C.MODEL.TCR.MMENCODER = CN()
_C.MODEL.TCR.MMENCODER.FUSION_METHOD = 'mean'
_C.MODEL.TCR.MMENCODER.HIDDEN_DIM = 512
_C.MODEL.TCR.MMENCODER.TRANSFORMER = CN()
_C.MODEL.TCR.MMENCODER.TRANSFORMER.NUM_LAYERS = 3
_C.MODEL.TCR.MMENCODER.TRANSFORMER.FEEDFORWARD_DIM = 2048
_C.MODEL.TCR.MMENCODER.TRANSFORMER.NUM_HEADS = 8
_C.MODEL.TCR.MMENCODER.TRANSFORMER.DROPOUT = 0.1

_C.MODEL.TCR.PREDICTOR = CN()
_C.MODEL.TCR.PREDICTOR.METHOD = 'fian'

_C.MODEL.TCR.LOSS = CN()
_C.MODEL.TCR.LOSS.METHOD = 'standard'
_C.MODEL.TCR.LOSS.TAU = 0.55
_C.MODEL.TCR.LOSS.ALPHA = 0.001
_C.MODEL.TCR.LOSS.NEG_THR = 0.0
_C.MODEL.TCR.LOSS.POS_THR = 1.0

# LGI
_C.MODEL.LGI = CN()

_C.MODEL.LGI.QUERYENCODER = CN()
_C.MODEL.LGI.QUERYENCODER.NUM_SEMANTIC_ENTITY = 3
_C.MODEL.LGI.QUERYENCODER.SQAN_DROPOUT = 0.0
_C.MODEL.LGI.QUERYENCODER.RNN = CN()
_C.MODEL.LGI.QUERYENCODER.RNN.TYPE = 'LSTM'
_C.MODEL.LGI.QUERYENCODER.RNN.HIDDEN_SIZE = 512
_C.MODEL.LGI.QUERYENCODER.RNN.NUM_LAYERS = 2
_C.MODEL.LGI.QUERYENCODER.RNN.DROPOUT = 0.5
_C.MODEL.LGI.QUERYENCODER.RNN.BIDIRECTIONAL = True

_C.MODEL.LGI.VIDEOENCODER = CN()
_C.MODEL.LGI.VIDEOENCODER.HIDDEN_SIZE = 512
_C.MODEL.LGI.VIDEOENCODER.USE_POSITION = True

_C.MODEL.LGI.MMENCODER = CN()
_C.MODEL.LGI.MMENCODER.FUSION = CN()
_C.MODEL.LGI.MMENCODER.FUSION.METHOD = 'mul'
_C.MODEL.LGI.MMENCODER.LOCAL_CONTEXT = CN()
_C.MODEL.LGI.MMENCODER.LOCAL_CONTEXT.METHOD = 'res_block'
_C.MODEL.LGI.MMENCODER.LOCAL_CONTEXT.RESBLOCK_KSIZE = 15
_C.MODEL.LGI.MMENCODER.LOCAL_CONTEXT.RESBLOCK_NUM = 1
_C.MODEL.LGI.MMENCODER.LOCAL_CONTEXT.DOWNSAMPLE = False
_C.MODEL.LGI.MMENCODER.GLOBAL_CONTEXT = CN()
_C.MODEL.LGI.MMENCODER.GLOBAL_CONTEXT.METHOD = 'nl'
_C.MODEL.LGI.MMENCODER.GLOBAL_CONTEXT.SATT_NUM = 1
_C.MODEL.LGI.MMENCODER.GLOBAL_CONTEXT.SATT_USE_EMBEDDING = True
_C.MODEL.LGI.MMENCODER.GLOBAL_CONTEXT.NL_NUM = 2
_C.MODEL.LGI.MMENCODER.GLOBAL_CONTEXT.NL_HEADS_NUM = 4
_C.MODEL.LGI.MMENCODER.GLOBAL_CONTEXT.NL_DROPOUT = 0.0
_C.MODEL.LGI.MMENCODER.GLOBAL_CONTEXT.NL_USE_BIAS = True
_C.MODEL.LGI.MMENCODER.GLOBAL_CONTEXT.NL_USE_LOCAL_MASK = False

_C.MODEL.LGI.PREDICTOR = CN()
_C.MODEL.LGI.PREDICTOR.ATT_HDIM = 256
_C.MODEL.LGI.PREDICTOR.GROUNDING_HDIM = 512
_C.MODEL.LGI.PREDICTOR.LOGIC_HEAD = 'ReLU'

_C.MODEL.LGI.LOSS = CN()
_C.MODEL.LGI.LOSS.USE_TAG_LOSS = True
_C.MODEL.LGI.LOSS.TAG_WEIGHT = 1.0
_C.MODEL.LGI.LOSS.USE_DQA_LOSS = True
_C.MODEL.LGI.LOSS.DQA_WEIGHT = 1.0
_C.MODEL.LGI.LOSS.DQA_LAMBDA = 0.3

# CMIN
_C.MODEL.CMIN = CN()
_C.MODEL.CMIN.HIDDEN_DIM = 512
_C.MODEL.CMIN.DROPOUT = 0.2

_C.MODEL.CMIN.QUERYENCODER = CN()
_C.MODEL.CMIN.QUERYENCODER.MAX_NUM_WORDS = 20
_C.MODEL.CMIN.QUERYENCODER.NUM_GCN_LAYERS = 2

_C.MODEL.CMIN.VIDEOENCODER = CN()
_C.MODEL.CMIN.VIDEOENCODER.NUM_HEADS = 8
_C.MODEL.CMIN.VIDEOENCODER.NUM_ATT_LAYERS = 2
_C.MODEL.CMIN.VIDEOENCODER.ATT_WIDTH = 3

_C.MODEL.CMIN.LOSS = CN()
_C.MODEL.CMIN.LOSS.ALPHA = 0.001

# TCR
_C.MODEL.FIAN = CN()

_C.MODEL.FIAN.VIDEOENCODER = CN()
_C.MODEL.FIAN.VIDEOENCODER.NUM_HEADS = 8
_C.MODEL.FIAN.VIDEOENCODER.HIDDEN_DIM = 512
_C.MODEL.FIAN.VIDEOENCODER.NUM_ATT_LAYERS = 2
_C.MODEL.FIAN.VIDEOENCODER.ATT_WIDTH = 3
_C.MODEL.FIAN.VIDEOENCODER.DROPOUT = 0.2

_C.MODEL.FIAN.QUERYENCODER = CN()
_C.MODEL.FIAN.QUERYENCODER.HIDDEN_DIM = 512

_C.MODEL.FIAN.MMENCODER = CN()
_C.MODEL.FIAN.MMENCODER.HIDDEN_DIM = 512
_C.MODEL.FIAN.MMENCODER.TRANSFORMER = CN()
_C.MODEL.FIAN.MMENCODER.TRANSFORMER.FEEDFORWARD_DIM = 2048
_C.MODEL.FIAN.MMENCODER.TRANSFORMER.NUM_HEADS = 8
_C.MODEL.FIAN.MMENCODER.TRANSFORMER.DROPOUT = 0.1

_C.MODEL.FIAN.LOSS = CN()
_C.MODEL.FIAN.LOSS.TAU = 0.55
_C.MODEL.FIAN.LOSS.ALPHA = 0.001

# CSMGAN
_C.MODEL.CSMGAN = CN()
_C.MODEL.CSMGAN.HIDDEN_DIM = 512
_C.MODEL.CSMGAN.DROPOUT = 0.2

_C.MODEL.CSMGAN.VIDEOENCODER = CN()
_C.MODEL.CSMGAN.VIDEOENCODER.NUM_HEADS = 8
_C.MODEL.CSMGAN.VIDEOENCODER.NUM_ATT_LAYERS = 2
_C.MODEL.CSMGAN.VIDEOENCODER.ATT_WIDTH = 3

_C.MODEL.CSMGAN.LOSS = CN()
_C.MODEL.CSMGAN.LOSS.ALPHA = 0.001
_C.MODEL.CSMGAN.LOSS.HIGH_SCORE_THR = 0.45

# ---------------------------------------------------------------------------- #
# Solver
# ---------------------------------------------------------------------------- #
_C.SOLVER = CN()
_C.SOLVER.OPTIMIZER = 'Adam'
_C.SOLVER.MAX_EPOCH = 12
_C.SOLVER.LR = 0.01
_C.SOLVER.WEIGHT_DECAY = 0.0
_C.SOLVER.BATCH_SIZE = 32
_C.SOLVER.SCHEDULER = 'MultiStepLR'
_C.SOLVER.MILESTONES = (8, 11)
_C.SOLVER.CHECKPOINT_PERIOD = 1
_C.SOLVER.TEST_PERIOD = 1

# ---------------------------------------------------------------------------- #
# Specific test options
# ---------------------------------------------------------------------------- #
_C.TEST = CN()
_C.TEST.BATCH_SIZE = 64
_C.TEST.NMS_THRESH = 0.4

# ---------------------------------------------------------------------------- #
# Misc options
# ---------------------------------------------------------------------------- #
_C.OUTPUT_DIR = "."
_C.PATHS_CATALOG = os.path.join(os.path.dirname(__file__), "paths_catalog.py")


def fzt1(f, modulo=0):
    n = len(f)
    bin_top = 1
    depth = 0
    while bin_top < n:
        depth += 1
        bin_top <<= 1
    res = [0]*bin_top
    for i in range(n):
        res[i] = f[i]
    for i in range(depth):
        offset = 1 << (i+1)
        for j in range(0, bin_top, offset):
            for k in range(1<<i):
                res[j+k] += res[j+k+(1<<i)]
                if modulo:
                    if res[j+k] >= modulo:
                        res[j+k] -= modulo
    return res
def fmt1(f, modulo=0):
    n = len(f)
    bin_top = 1
    depth = 0
    while bin_top < n:
        depth += 1
        bin_top <<= 1
    res = [0]*bin_top
    for i in range(n):
        res[i] = f[i]
    for i in range(depth):
        offset = 1 << (i+1)
        for j in range(0, bin_top, offset):
            for k in range(1<<i):
                res[j+k] -= res[j+k+(1<<i)]
                if modulo:
                    if res[j+k] < 0:
                        res[j+k] += modulo
    return res
def convolution_and(f, g, modulo=0):
    n, m = len(f), len(g)
    S = max(n, m)
    flg = False
    while S & (S - 1):
        S = S & (S - 1)
        flg = True
    if flg:
        S <<= 1
    x = [0]*S
    y = [0]*S
    for i in range(n):
        x[i] = f[i]
    for i in range(m):
        y[i] = g[i]
    x = fzt1(x, modulo)
    y = fzt1(y, modulo)
    for i in range(S):
        x[i] *= y[i]
        if modulo:
            x[i] %= modulo
    x = fmt1(x, modulo)
    return x


#!/usr/bin/env python

import sys
import os

try:
    from setuptools import setup, find_packages, Command
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages, Command

import restclient

def read_file(name):
    return open(os.path.join(os.path.dirname(__file__), name)).read()

readme = read_file('README.rst')
changes = read_file('CHANGES.rst')

install_requires = [
    'httplib2>=0.7.1',
]
tests_require = [
    'nose',
]

if sys.version_info[:2] < (2, 5):
    install_requires.append('simplejson>=2.2.1')

setup(
    name='restclient',
    version='.'.join(map(str, restclient.__version__)),
    description='RestClient allows you to interact with resources as if they were objects.',
    long_description='\n\n'.join([readme, changes]),
    author='Joeri Bekker',
    author_email='joeri@maykinmedia.nl',
    license='MIT',
    platforms=['any'],
    url='http://github.com/joeribekker/restclient',
    install_requires=install_requires,
    tests_require=tests_require,
    extras_require={'test': tests_require},
    #test_suite='runtests.runtests',
    include_package_data=True,
    packages=find_packages(exclude=('tests', 'examples')),
    zip_safe=False,
    test_suite='runtests.runtests',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development',
    ],
)


from django.contrib import admin
from django.urls import path, include
from .views import index, trabajos, registrarse, iniciarSesion, mantencion1, mantencion2, mantencion3, mantencion4, mantencion5, mantencion6, repuestos

urlpatterns = [
    path('', index, name="INDEX"),
    path('trabajos/', trabajos, name="TRABAJOS"),
    path('registrarse/', registrarse, name="REGISTRO"),
    path('iniciarSesion/', iniciarSesion, name="INICIAR"),
    path('mantencion1/', mantencion1, name="MANTENCION1"),
    path('mantencion2/', mantencion2, name="MANTENCION2"),
    path('mantencion3/', mantencion3, name="MANTENCION3"),
    path('mantencion4/', mantencion4, name="MANTENCION4"),
    path('mantencion5/', mantencion5, name="MANTENCION5"),
    path('mantencion6/', mantencion6, name="MANTENCION6"),
    path('repuestos/', repuestos, name="REPU"),
]


"""
2D Roguelike game
Author: Gordon Stirling
Python/Pygame project
http://www1.ayrshire.ac.uk

Sprites created by: DawnBringer
https://opengameart.org/content/dawnlike-16x16-universal-rogue-like-tileset-v181

Tutorial 15 -  In-game message console
Continuing on from the previous tutorial we are going to finish off creating the
in-game message console.  By the end of this tutorial the messages which previously
were printed to the console will now display on-screen.  We will limit the number of
messages on-screen to 4, with older messages disappearing.

"""

# 3rd party modules
import pygame
import libtcodpy as libtcod

# game modules
import settings

# struct definition
class struct_Tile:
    def __init__(self, block_path):
        self.block_path = block_path
        self.explored = False

# object definitions
class obj_Actor:
    def __init__(self, x, y, name_object, sprite, creature = None, ai = None):
        self.x = x # map address
        self.y = y # map address
        self.sprite = sprite
        self.creature = creature
        self.ai = ai

        if creature:
            creature.owner = self

        if ai:
            ai.owner = self

    def draw(self):
        is_visible = libtcod.map_is_in_fov(FOV_MAP, self.x, self.y)

        if is_visible:
            SURFACE_MAIN.blit(self.sprite, (self.x * settings.CELL_WIDTH,
                                            self.y * settings.CELL_HEIGHT))

# component definitions
class com_Creature:
    ''' Creatures have health, can attack and damage other objects '''
    def __init__(self, name_instance, hp = 10, has_died = None):
        self.name_instance = name_instance
        self.maxhp = hp
        self.hp = hp
        self.has_died = has_died

    def move(self, dx, dy):
        tile_is_wall = GAME_MAP[self.owner.x + dx][self.owner.y + dy].block_path == True

        target = map_check_for_creature(self.owner.x + dx, self.owner.y + dy, self.owner)

        if target:
            self.attack(target, settings.ATT_DAMAGE)

        if not tile_is_wall and target is None:
            self.owner.x += dx
            self.owner.y += dy

    def attack(self, target, damage):
        game_message (self.name_instance + " attacks " + target.creature.name_instance + " for " + str(damage) + " damage!", settings.WHITE)

        target.creature.take_damage(damage)

    def take_damage(self, damage):
        self.hp -= damage
        game_message (self.name_instance + "'s health is " + str(self.hp) + "/" + str(self.maxhp), settings.RED)

        if self.hp <= 0:
            if self.has_died is not None:
                self.has_died(self.owner)

#TODO define Item component - consumables etc.
class com_Item:
    pass

#TODO define Container component - loot chests etc.
class com_Container:
    pass

#TODO define AI component - turns, attacking, moving etc.
class com_AI_Test:
    '''Once per turn, execute'''

    def take_turn(self):
        self.owner.creature.move(libtcod.random_get_int(0, -1, 1), libtcod.random_get_int(0, -1, 1))

def death(enemy):
    '''On death, enemy stops moving'''
    game_message (enemy.creature.name_instance + " is dead!", settings.GREY)

    enemy.creature = None
    enemy.ai = None

# map definition
def create_map():
    new_map = [[ struct_Tile(False) for y in range(0, settings.MAP_HEIGHT) ] for x in range(0, settings.MAP_WIDTH)]

    new_map[10][10].block_path = True
    new_map[10][15].block_path = True

    for x in range(settings.MAP_WIDTH):
        new_map[x][0].block_path = True
        new_map[x][settings.MAP_HEIGHT-1].block_path = True

    for y in range(settings.MAP_HEIGHT):
        new_map[0][y].block_path = True
        new_map[settings.MAP_WIDTH-1][y].block_path = True

    map_make_fov(new_map)

    return new_map

def map_check_for_creature(x, y, exclude_obj = None):
    target = None

    if exclude_obj:
        # check object list to find creature at that location that isn't excluded
        for obj in GAME_OBJECTS:
            if (obj is not exclude_obj and
                obj.x == x and
                obj.y == y and
                obj.creature):
                target = obj

            if target:
                return target

    else:
        # check object list to find any creature at that location
        for obj in GAME_OBJECTS:
            if (obj.x == x and
                obj.y == y and
                obj.creature):
                target = obj

            if target:
                return target

def map_make_fov(incoming_map):
    global FOV_MAP

    FOV_MAP = libtcod.map_new(settings.MAP_WIDTH, settings.MAP_HEIGHT)

    for y in range(settings.MAP_HEIGHT):
        for x in range(settings.MAP_WIDTH):
            libtcod.map_set_properties(FOV_MAP, x, y,
                                       not incoming_map[x][y].block_path,
                                       not incoming_map[x][y].block_path)

def map_calculate_fov():
    global FOV_CALCULATE

    if FOV_CALCULATE:
        FOV_CALCULATE = False
        libtcod.map_compute_fov(FOV_MAP,
                                PLAYER.x,
                                PLAYER.y,
                                settings.FOV_RADIUS,
                                settings.FOV_LIGHT_WALLS,
                                settings.FOV_ALGO)

def draw_map(map_to_draw):

    for x in range(0, settings.MAP_WIDTH):
        for y in range(0, settings.MAP_HEIGHT):

            is_visible = libtcod.map_is_in_fov(FOV_MAP, x, y)

            if is_visible:

                map_to_draw[x][y].explored = True

                if map_to_draw[x][y].block_path == True:
                    # draw wall
                    SURFACE_MAIN.blit(settings.S_WALL, (x * settings.CELL_WIDTH, y * settings.CELL_HEIGHT))
                else:
                    # draw floor
                    SURFACE_MAIN.blit(settings.S_FLOOR, (x * settings.CELL_WIDTH, y * settings.CELL_HEIGHT))

            elif map_to_draw[x][y].explored:

                if map_to_draw[x][y].block_path == True:
                    # draw wall
                    SURFACE_MAIN.blit(settings.S_WALL_EXPLORED, (x * settings.CELL_WIDTH, y * settings.CELL_HEIGHT))
                else:
                    # draw floor
                    SURFACE_MAIN.blit(settings.S_FLOOR_EXPLORED, (x * settings.CELL_WIDTH, y * settings.CELL_HEIGHT))

# function definitions
def draw_text(display_surface, text_to_display, T_coords, text_colour, back_colour = None):
    '''This function takes in some text, and displays it on the reference surface'''

    text_surf, text_rect = get_text_objs(text_to_display, text_colour, back_colour)

    text_rect.topleft = T_coords

    display_surface.blit(text_surf, text_rect)

# helper functions
def get_text_objs(incoming_text, incoming_colour, incoming_bg):
    if incoming_bg:
        text_surface = settings.FONT_DEBUG_MESSAGE.render(incoming_text, False, incoming_colour, incoming_bg)
    else:
        text_surface = settings.FONT_DEBUG_MESSAGE.render(incoming_text, False, incoming_colour)
    return text_surface, text_surface.get_rect()

def get_text_height(font):
    font_obj = font.render('a', False, (0, 0, 0))
    font_rect = font_obj.get_rect()

    return font_rect.height

def draw_game():
    '''We will use this function to draw objects to the surface'''

    # clear (reset) the surface
    SURFACE_MAIN.fill(settings.DEFAULT_BG_COLOUR)

    # draw the map
    draw_map(GAME_MAP)

    # draw the character
    for obj in GAME_OBJECTS:
        obj.draw()

    draw_debug()
    draw_messages()

    # update the display
    pygame.display.flip()

def draw_messages():
    if len(GAME_MESSAGES) <= settings.NUM_MESSAGES:
        to_draw = GAME_MESSAGES
    else:
        to_draw = GAME_MESSAGES[-settings.NUM_MESSAGES:]

    text_height = get_text_height(settings.FONT_MESSAGE_TEXT)

    start_y = (settings.MAP_HEIGHT * settings.CELL_HEIGHT - (settings.NUM_MESSAGES * text_height)) - 10

    i = 0

    for message, colour in to_draw:
        draw_text(SURFACE_MAIN, message, (0, start_y + (i * text_height)), colour, settings.BLACK)
        i += 1

def draw_debug():
    draw_text(SURFACE_MAIN, "FPS: " + str(int(CLOCK.get_fps())), (0,0), settings.WHITE, settings.BLACK)

def game_player_input():
    global FOV_CALCULATE

    # get player input
    events = pygame.event.get()

    #  process input - more events to come
    for event in events:
        if event.type == pygame.QUIT:
            return "QUIT"

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                PLAYER.creature.move(0, -1)
                FOV_CALCULATE = True
                return "player_moved"

            if event.key == pygame.K_DOWN:
                PLAYER.creature.move(0, 1)
                FOV_CALCULATE = True
                return "player_moved"

            if event.key == pygame.K_LEFT:
                PLAYER.creature.move(-1, 0)
                FOV_CALCULATE = True
                return "player_moved"

            if event.key == pygame.K_RIGHT:
                PLAYER.creature.move(1, 0)
                FOV_CALCULATE = True
                return "player_moved"

    return "no action"

def game_message(game_msg, msg_colour):
    GAME_MESSAGES.append((game_msg, msg_colour))

def game_init():
    '''This function initialises the main window and pygame'''

    # make a global (available to all modules) variable to hold the game window (surface)
    global SURFACE_MAIN, GAME_MAP, PLAYER, ENEMY, GAME_OBJECTS, FOV_CALCULATE, CLOCK, GAME_MESSAGES

    # initialise pygame
    pygame.init()

    CLOCK = pygame.time.Clock()

    #create window (surface)
    SURFACE_MAIN = pygame.display.set_mode((settings.MAP_WIDTH * settings.CELL_WIDTH, settings.MAP_HEIGHT * settings.CELL_HEIGHT))

    GAME_MAP = create_map()

    GAME_MESSAGES = []

    FOV_CALCULATE = True

    creature_com1 = com_Creature("Del")
    creature_com2 = com_Creature("Rodney", has_died = death)

    ai_com = com_AI_Test()

    PLAYER = obj_Actor(1, 1, "hero", settings.S_PLAYER, creature = creature_com1)
    ENEMY = obj_Actor(15, 10,
                      "dark guard",
                      settings.S_ENEMY,
                      creature = creature_com2,
                      ai = ai_com)

    GAME_OBJECTS = [PLAYER, ENEMY]

def game_main_loop():
    '''This function loops the main game'''

    game_quit = False

    # player action definition
    player_action = "no action"

    while not game_quit:

        # handle player input
        player_action = game_player_input()

        map_calculate_fov()

        if player_action == "QUIT":
            game_quit = True

        if player_action != "no action":
            for obj in GAME_OBJECTS:
                if obj.ai:
                    obj.ai.take_turn()

        # draw the game
        draw_game()

        CLOCK.tick(settings.G_FPS)

    # quit the game
    pygame.quit()
    exit()

# call the initialisation functions to make the game run
if __name__ == '__main__':
    game_init()
    game_main_loop()


# -*- coding: utf-8 -*-
"""
Utils functions GEE
"""

from qgis.core import QgsRasterLayer, QgsProject
from qgis.utils import iface
import qgis

import ee

def get_ee_image_url(image):
    map_id = ee.data.getMapId({'image': image})
    url = map_id['tile_fetcher'].url_format
    return url

def update_ee_layer_properties(layer, image, shown, opacity):
    layer.setCustomProperty('ee-layer', True)

    if not (opacity is None):
        layer.renderer().setOpacity(opacity)

    # serialize EE code
    ee_script = image.serialize()
    layer.setCustomProperty('ee-script', ee_script)

def add_ee_image_layer(image, name, shown, opacity):
    check_version()

    url = "type=xyz&url=" + get_ee_image_url(image)
    layer = QgsRasterLayer(url, name, "wms")
    update_ee_layer_properties(layer, image, shown, opacity)
    QgsProject.instance().addMapLayer(layer)

    if not (shown is None):
        QgsProject.instance().layerTreeRoot().findLayer(
            layer.id()).setItemVisibilityChecked(shown)

def update_ee_image_layer(image, layer, shown=True, opacity=1.0):
    check_version()

    url = "type=xyz&url=" + get_ee_image_url(image)
    layer.dataProvider().setDataSourceUri(url)
    layer.dataProvider().reloadData()
    update_ee_layer_properties(layer, image, shown, opacity)
    layer.triggerRepaint()
    layer.reload()
    iface.mapCanvas().refresh()

    item = QgsProject.instance().layerTreeRoot().findLayer(layer.id())
    if not (shown is None):
        item.setItemVisibilityChecked(shown)

def get_layer_by_name(name):
    layers = QgsProject.instance().mapLayers().values()

    for l in layers:
        if l.name() == name:
            return l

    return None

def add_or_update_ee_image_layer(image, name, shown=True, opacity=1.0):
    layer = get_layer_by_name(name)

    if layer:
        if not layer.customProperty('ee-layer'):
            raise Exception('Layer is not an EE layer: ' + name)

        update_ee_image_layer(image, layer, shown, opacity)
    else:
        add_ee_image_layer(image, name, shown, opacity)

def add_ee_catalog_image(name, asset_name, visParams, collection_props):
    image = None

    if collection_props:
        raise Exception('Not supported yet')
    else:
        image = ee.Image(asset_name).visualize(visParams)

    add_or_update_ee_image_layer(image, name)

def check_version():
    # check if we have the latest version only once plugin is used, not once it is loaded
    qgis.utils.plugins['ee_plugin'].check_version()


from flask import Flask
import flask
from flask.globals import request
app = Flask(__name__)

# ruta
@app.route('/almacenar gastos', methods = ['POST','GET'])
# Ahora cuando alguien entre a esa ruta
def crud_entrada_gasto():
    if request.method == 'POST':
        # Almacenar informacion
        request.data = request.form
    elif request.method == 'GET':
        print("Llego un get")

    return 'Gasto almacenado'


def translate_text(target_text):
    """Translating Text."""

    from google.cloud import translate

    client = translate.TranslationServiceClient()
    parent = client.location_path("beaming-edition-325211", "global")
    text = target_text

    response = client.translate_text(
        parent=parent,
        contents=[text],
        mime_type="text/plain",
        source_language_code="en-US",
        target_language_code="ja",
    )

    # Display the translation for each input text provided
    for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))
        translate_text = translation.translated_text

    return translate_text


# Project 2 - Contestant
import socket
import sys
import traceback

class Contestant:
    def __init__(self):
        self.contestantSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def try_connect(self, addr):
        try:
            self.contestantSocket.connect(addr)
            print('Successful connection!')
        except ConnectionRefusedError as connRefE:
            print('Error: unable to connect', str(connRefE), file=sys.stderr)
            print(traceback.format_exc())
            sys.exit(-1)
        except Exception as connE:
            print('Connection error:', str(connE), file=sys.stderr)
            print(traceback.format_exc())
            sys.exit(-1)

    def play_contest(self):
        pass

if len(sys.argv) != 3:
    print('Program error: wrong number of arguments', file=sys.stderr)
    sys.exit(-1)

host = sys.argv[1]
port = 0
try:
    port = int(sys.argv[2])
except TypeError as nan:
    print('Program error: port number is invalid', str(nan), file=sys.stderr)
    sys.exit(-1)

contestant = Contestant()
contestant.try_connect((host, port))
contestant.play_contest()


# @File : 特殊成员2.py
# @Author: 我叫八进制
# @Date : 2018/10/9
# @Desc :

# class Foo:
#     def __init__(self, name, age):
#         self.name = name
#         self.age = age
#     def __add__(self, other):
#         # self = obj1
#         # other = obj2
#         # return 123
#         # return self.age + other.age
#         return obj2
#     def __del__(self):
#         print('析构方法')   # 对象被销毁时，自动执行
#
# obj1 = Foo('alex', 18)
# obj2 = Foo('dddd', 16)
#
# # 两个对象相加时候，自动执行第一个对象的__add__方法，并且将第二个对象当成参数传递进入
# print(obj1 + obj2)

# ------------------------------------------------------
# class Foo:
#     '''注释'''
#     def __init__(self, name, age):
#         self.name = name
#         self.age = age
#
# obj = Foo('alex', 18)
# d = obj.__dict__
# print(d)
#
#
# ret = Foo.__dict__
# print(ret)

# -------------------------------------------------------

# li = [11, 22, 33, 44]
#
# rl = li[3]
# print(rl)
#
# li[3] = 666
#
# del li[2]

# ------------------------------------------------------------------

class Foo:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 得到值
    def __getitem__(self, item):
        # return item+10
        # 如果item是基本类型，int，str，索引获取
        # slice对象的话,切片
        if type(item) == slice:
            print('调用者希望切片')
        else:
            print('调用者希望对象处理')

li = Foo('alex', 18)

li[123]
li[1:3:2]


#
# Copyright 2016 University of Oxford
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Main interface for the htsget library.
"""
from __future__ import division
from __future__ import print_function

import logging

import htsget.protocol as protocol
import htsget.exceptions as exceptions

import requests

CONTENT_LENGTH = "Content-Length"

def get(
        url, output, reference_name=None, reference_md5=None,
        start=None, end=None, fields=None, tags=None, notags=None,
        data_format=None, max_retries=5, retry_wait=5, timeout=10):
    """
    Runs a request to the specified URL and write the resulting data to
    the specified file-like object.

    :param str url: The URL of the data to retrieve. This may be composed of a prefix
        such as ``http://example.com/reads/`` and an ID suffix such as
        ``NA12878``. The full URL must be supplied here, i.e., in this example
        ``http://example.com/reads/NA12878``.
    :param file output: A file-like object to write the downloaded data to. To support
       retrying of failed transfers, this file must be seekable. For this reason,
       retry will fail if ``stdout`` is provided.
    :param str reference_name: The reference sequence name, for example "chr1",
        "1", or "chrX". If unspecified, all data is returned.
    :param str reference_md5: The MD5 checksum uniquely representing the reference
        sequence as a lower-case hexadecimal string, calculated as the MD5 of the
        upper-case sequence excluding all whitespace characters (this is equivalent to
        SQ:M5 in SAM).
    :param int start: The start position of the range on the reference, 0-based,
        inclusive. If specified, ``reference_name`` or ``reference_md5`` must also
        be specified.
    :param int end: The end position of the range on the reference, 0-based exclusive.
        If specified, ``reference_name`` or ``reference_md5`` must also be specified.
    :param str data_format: The requested format of the returned data.
    :param int max_retries: The maximum number of times that an individual transfer
        will be retried.
    :param float retry_wait: The amount of time in seconds to wait before retrying
        a failed transfer.
    :param float timeout: The socket timeout for I/O operations.
    """
    manager = SynchronousDownloadManager(
        url, output, reference_name=reference_name,
        reference_md5=reference_md5, start=start, end=end, fields=fields, tags=tags,
        notags=notags, data_format=data_format, max_retries=max_retries, timeout=timeout,
        retry_wait=retry_wait)
    manager.run()

class SynchronousDownloadManager(protocol.DownloadManager):
    """
    Class implementing the GA4GH streaming API synchronously using the
    requests library.
    """
    def __get(self, *args, **kwargs):
        try:
            response = requests.get(*args, **kwargs)
        except requests.RequestException as re:
            raise exceptions.RetryableIOError(re)
        try:
            response.raise_for_status()
        except requests.HTTPError as he:
            # TODO classify other errors that we consider unrecoverable.
            if response.status_code == 404:
                raise exceptions.ExceptionWrapper(he)
            else:
                raise exceptions.RetryableIOError(he)
        return response

    def _handle_ticket_request(self):
        logging.debug("handle_ticket_request(url={})".format(self.ticket_request_url))
        response = self.__get(self.ticket_request_url, timeout=self.timeout)
        self.ticket = protocol.parse_ticket(response.text)

    def _handle_http_url(self, url, headers):
        logging.debug("handle_http_url(url={}, headers={})".format(url, headers))
        response = self.__get(url, headers=headers, stream=True, timeout=self.timeout)
        length = 0
        piece_size = 65536
        try:
            for piece in response.iter_content(piece_size):
                length += len(piece)
                self.output.write(piece)
        except requests.RequestException as re:
            raise exceptions.RetryableIOError(re)
        if CONTENT_LENGTH in response.headers:
            content_length = int(response.headers[CONTENT_LENGTH])
            if content_length != length:
                raise exceptions.ContentLengthMismatch(
                    "Length mismatch {} != {}".format(content_length, length))


from bandits.bandit import Bandit
from distributions.betadistribution import BetaDistribution
import numpy as np
import copy

class Oracle_ucb():
    def __init__(self, bandit, agency, C):
        self.bandit = bandit
        self.agency = agency
        self.q_tilde = []
        self.C = C
        self.goog = 0
        self.reports = []
        super().__init__()

    def reset(self):
        self.bandit.reset()

    def __compute_trust_posterior(self, t):
        self.q_tilde = []
        for (arm_index, arm) in enumerate(self.bandit.arms):
            # arm.influence_reward_dist = copy.deepcopy(arm.reward_dist)
            initial = 0
            if t <= self.bandit.K:
                initial = 0.5
            else:
                initial = 0.5
            reports = [initial]
            reports = []
            num_reports = 0
            #iterate through each agent and process their report
            for agent_index, agent in enumerate(self.agency.agents):
                if agent.trustworthy == True:
                    num_reports += 1 * agent.num_reports
                    reports.append(self.agency.agent_reports[agent][arm_index])

            self.q_tilde.append(np.mean(reports))
            self.reports.append(num_reports)

    def select_arm(self, t, influence_limit = True):
        self.__compute_trust_posterior(t)
        # print("predictions", self.q_tilde)
        W = 0

        for agent_index, agent in enumerate(self.agency.agents):
            if agent.trustworthy == True:
                 W += 1

        selected_arm = self.bandit.select_arm(t, self.q_tilde, self.reports, W)
        return selected_arm, 0
        # selected_arm, prediction = self.bandit.select_arm(t, self.q_tilde, W, self.C)
        # self.goog = prediction
        # return selected_arm, 0
        # return self.bandit.select_arm(t, self.q_tilde, W, self.C), 0

    def update(self, arm, reward):
        # self.bandit.update(arm, reward)
        self.bandit.arms[self.goog].real_pulls += 1
        self.bandit.update(arm, reward)

        # self._compute_T_posterior(arm, reward)

        # self.bandit.arms[arm].real_pulls += 1
        # # print("STATUS:", self.goog)
        # should_explore = np.random.rand()
        # if should_explore < self.goog or self.goog == -1:
        # # if self.goog == False:
        #     # self._update_reputations(arm, reward)
        #     self.bandit.update(arm, reward)


'''
	Test1
	Test ROT13 with an arbitrary letter that which when added 13 will be beyond Z or z
'''

import pytest

from rot13 import rot13

def  test_rot13():
	result =  rot13("U")
	return result

result = test_rot13()

assert result=="H"