# The sum of the squares of the first ten natural numbers is,
# 1(2) + 2(2) + ... + 10(2) = 385
# The square of the sum of the first ten natural numbers is,
# (1 + 2 + ... + 10)2 = 55(2) = 3025
# Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

sum = 0
sumsquare = 0
for num in range(1,101):
    sum += num
    sumsquare += num*num
print(sum*sum - sumsquare)


import re
import pickle
import time
import datetime
import threading
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.config import Config
from kivy.uix.listview import ListItemButton
from kivy.properties import ObjectProperty, ListProperty
from kivy.core.clipboard import Clipboard
from kivy.clock import Clock
from functools import partial
from pyautogui import typewrite, press

Config.set("graphics", "width", "600")
Config.set("graphics", "height", "360")

class CtrlButton(ListItemButton):
    pass

class MyWidget(BoxLayout):
    carousel = ObjectProperty()
    ctrlc = ObjectProperty()
    tlacitka = ObjectProperty()
    last = ""
    event1 = None
    event2 = None
    ob = datetime.datetime(2018, 1, 1, 0, 0, 0)
    pr = datetime.datetime(2018, 1, 1, 0, 0, 0)
    pa = datetime.datetime(2018, 1, 1, 0, 0, 0)

    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)

    def clipboard_cleaner(self):
        self.ctrlc.cb_list.adapter.data = []

    def clipboard_starter(self, button):
        threading.Thread(target=self.clipboard_checker, args=button).start()

    def clipboard_checker(self, *args):
        button = "".join(args)
        try:
            Clock.unschedule(self.event2)
        except:
            pass
        self.event2 = Clock.schedule_interval(partial(self.clipboard_paster, button), 1.0)

    def clipboard_paster(self, button, dt=None):
        text = Clipboard.paste()

        if text != self.last and button == "automat":
            text = Clipboard.paste().strip()
            Clipboard.copy(text)
        elif button == "automat bez mezer":
            self.zkratit()
            text = Clipboard.paste()

        if text != self.last:
            self.ctrlc.cb_list.adapter.data.extend([text])
            self.last = text

    def time_counter(self, *button):
        button = button[0]
        if button == "prace":
            self.pr += datetime.timedelta(seconds=1)
            self.tlacitka.prace = self.pr.strftime("%H:%M:%S")
        elif button == "obed":
            self.ob += datetime.timedelta(seconds=1)
            self.tlacitka.obed = self.ob.strftime("%H:%M:%S")
        else:
            self.pa += datetime.timedelta(seconds=1)
            self.tlacitka.pauza = self.pa.strftime("%H:%M:%S")

    def time_starter(self, button):
        threading.Thread(target=self.time_checker, args=button.text).start()

    def time_checker(self, *args):
        button = "".join(args)
        try:
            Clock.unschedule(self.event1)
        except:
            pass
        self.event1 = Clock.schedule_interval(partial(self.time_counter, button), 1.0)

    def zkrat_ref(self):
        b = Clipboard.paste()
        ref = re.compile("\d{10}")
        c = ref.search(b)
        if c:
            Clipboard.copy(c.group()[5:])
        else:
            pass

    def low(self):
        b = Clipboard.paste()
        Clipboard.copy(b.lower())

    @staticmethod
    def zvetsit():
        b = Clipboard.paste()
        try:
            o = re.compile("(\d{12})")
            mo = o.findall(b)
            if mo:
                if mo[0][:3] == "420":
                    i = 0
                    e = []
                    for j in mo[0]:
                        e.append(j)
                        i += 1
                        if i % 3 == 0:
                            e.append(" ")
                    Clipboard.copy("".join(e[:-1]))

            c = re.compile("(\d{9})")
            mo1 = c.findall(b)
            if mo1:
                if mo1[0][:3] != "420":
                    i = 0
                    e = []
                    for j in mo1[0]:
                        e.append(j)
                        i += 1
                        if i % 3 == 0:
                            e.append(" ")
                    Clipboard.copy("".join(e[:-1]))

        except IndexError:
            pass

    @staticmethod
    def zkratit():
        d = []
        b = Clipboard.paste()
        c = re.compile(
            """
        (\d{3})
        (\s|-|\.)?
        (\d{3})
        (\s|-|\.)?
        (\d{3})
        (\s|-|\.)?
        (\d{3})
        """,
            re.VERBOSE,
        )
        mo = c.findall(b)
        for i in mo:
            if i[0] == "420":
                num = "".join([i[2], i[4], i[6]])
                d.append(num)
        e = re.compile(
            """
        (\d{3})
        (\s|-|\.)?
        (\d{3})
        (\s|-|\.)?
        (\d{3})
        """,
            re.VERBOSE,
        )
        mo1 = e.findall(b)
        for j in mo1:
            if j[0] != "420":
                num = "".join([j[0], j[2], j[4]])
                d.append(num)

        Clipboard.copy("\r\n".join(d))

    def save_pass(self):
        with open("qwerqwr.dat", "wb") as target:
            login = self.tlacitka.log.text
            heslo = self.tlacitka.pas.text
            a = (login, heslo)
            self.tlacitka.log.text = ""
            self.tlacitka.pas.text = ""
            pickle.dump(a, target)

    def log_in_starter(self):
        threading.Thread(target=self.log_in).start()

    def log_in(self):
        time.sleep(2)
        with open("qwerqwr.dat", "rb") as source:
            a = pickle.load(source)
            login = a[0]
            heslo = a[1]

        typewrite("\t")
        typewrite(login)
        typewrite("\t")
        typewrite(heslo)
        press("enter")

class WidgetApp(App):
    def build(self):
        self.title = "Pomocnik"
        return MyWidget()

if __name__ == "__main__":
    WidgetApp().run()


from pyspark.sql.functions import *
import re
import sys
from operator import add
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType

spark = SparkSession \
    .builder \
    .appName("task_1") \
    .getOrCreate()

def printfunc(x,y):
	a = x.rdd.cache()
	b = a.collect()
	print(b[0].hashtag)

# Read all the csv files written atomically in a directory
userSchema =StructType().add("ID","string").add("language","string").add("date","string").add("source","string").add("len","string").add("likes","string").add("RTs","string").add("Hashtags","string").add("Usernames","string").add("Userid","string").add("name","string").add("Place","string").add("followers","integer").add("freinds","integer")

csvDF = spark \
    .readStream \
    .option("sep", ";") \
    .schema(userSchema) \
    .csv("hdfs://localhost:9000/test1")  # Equivalent to format("csv").load("/path/to/directory")

temp = csvDF.select(explode(split(csvDF.Hashtags,",")).alias("Hashtags"))
temp = temp.groupBy('Hashtags').count().orderBy(desc('count'))
temp = temp.limit(5)

temp \
    .writeStream \
    .outputMode("complete") \
    .format("console") \
    .start() \
    .awaitTermination(60)
#.foreachBatch(printfunc) \
#    .outputMode("complete") \


from openpyxl import load_workbook
import numpy as np

def myPrint(name,var):
    try:
        print(name+":"+var)
    except :
        print(name+":"+str(var))

def intergrate(arr,padding):
    ret = []
    for x in range(padding,arr.shape[0]-padding):
        temp = []
        temp = np.array(temp)
        for y in range(x-padding,x+padding+1):
            temp = np.append(temp,arr[y])
        ret.append(temp)
    return np.array(ret)

def readXlsx(path):
    workbook = load_workbook(path, data_only=True)    #找到需要xlsx文件的位置
    booksheet = workbook.active                 #获取当前活跃的sheet,默认是第一个sheet

    #如果想获取别的sheet页采取下面这种方式，先获取所有sheet页名，在通过指定那一页。
    # sheets = workbook.get_sheet_names()  # 从名称获取sheet
    # booksheet = workbook.get_sheet_by_name(sheets[0])

    #获取sheet页的行数据
    rows = booksheet.rows
    #获取sheet页的列数据
    # columns = booksheet.columns
    # myPrint("rows",str(rows))
    # myPrint('col',str(columns))
    i = 0
    # 迭代所有的行
    retdata = []
    for row in rows:
        i = i + 1
        line = [col.value for col in row]
        retdata.append(line)
        # cell_data_1 = booksheet.cell(row=i, column=3).value               #获取第i行1 列的数据
        # cell_data_2 = booksheet.cell(row=i, column=4).value               #获取第i行 2 列的数据
        # cell_data_3 = booksheet.cell(row=i, column=8).value                   #获取第i行 3 列的数据
        # cell_data_4 = booksheet.cell(row=i, column=18).value                   #获取第i行 4 列的数据
        # print (cell_data_1, cell_data_2, cell_data_3, cell_data_4)
    return retdata

def isset(v):
    try:
        type (eval(v))
    except:
        return 0
    else:
        return 1

if __name__ == '__main__':
    arr = [[0,0,0],[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
    arr = np.array(arr)
    x  = intergrate(arr,1)
    print(x)


#Given a rectangular matrix of characters, add a border of asterisks(*) to it.

#Example

#For

#picture = ["abc",
#           "ded"]
#the output should be

#addBorder(picture) = ["*****",
#                      "*abc*",
#                      "*ded*",
#                      "*****"]

def addBorder(picture):

	long = len(picture)

	for i in range( long):
		#First element as example
		lista = list(picture[i])
		elemLen = len( lista )

		#Add last
		lista.append("*")
		#Add first
		lista.insert(0,"*")

		picture[i] = ''.join(lista)

	#Add first and last rows
	leng = len(lista)

	asterisks = '*' * leng

	picture.append(asterisks)
	picture.insert(0,asterisks)
	return picture


from LCODEplot import *
from shutil import copyfile
from IPython.display import Markdown, display
def printmd(string):
    display(Markdown(string))

config = """
# Simulation area:
geometry = c
window-width = 10;		r-step = 0.01
window-length = 1500;		xi-step = 0.01
time-limit = 50000.1;		time-step = 200

# Particle beams:
beam-current = 0.00281
rigid-beam = n
beam-substepping-energy = 810000
beam-particles-in-layer = 160
beam-profile = \"\"\"
xishape=b, ampl=1.0, length=1500, rshape=g, radius=1.0, angshape=l, angspread=4.5e-5, energy=7.83e5, m/q=1836, eshape=g, espread=2740.0
\"\"\"

# Plasma:
plasma-model = P # Plasma model (fluid/particles/newparticles, f/p/P)
plasma-particles-number = 5000
plasma-profile = 2 # Initial profile (uniform/stepwise/gaussian/arbitrary/channel)
plasma-width = 2
plasma-temperature = 0
ion-model = Y # Model of plasma ions (mobile/background/absent/equilibrium, Y/y/n/N)
ion-mass = 157000
substepping-depth = 3
substepping-sensivity = 0.2

# Every-time-step diagnostics:
indication-line-format = 1 # On-screen indication line format (eacht/eachxi)
output-Ez-minmax = y;		output-Ez-local = y
output-Phi-minmax = y;		output-Phi-local = y
output-lost-particles = y

# Periodical diagnostics:
output-time-period = 5000

#  Colored maps: (Er,Ef,Ez,Phi,Bf,Bz,pr,pf,pz,pri,pfi,pzi
#                 nb,ne,ni,Wf,dW,SEB,Sf,Sf2,Sr,Sr2,dS,dS2):
colormaps-full = ""
colormaps-subwindow = ""
colormaps-type = F
drawn-portion = 1 # Drawn portion of the simulation window
subwindow-xi-from = -0;		subwindow-xi-to = -100
subwindow-r-from = 0;		subwindow-r-to = 10
output-reference-energy = 1000
output-merging-r = 2;		output-merging-z = 50
output-skipping-r = 20;          output-skipping-xi = 20
palette = d # Colormaps palette (default/greyscale/hue/bluewhitered, d/g/h/b)
                E-step = 0.059;	               nb-step = 0.00056
              Phi-step = 0.059;	               ne-step = 0.1
               Bf-step = 0.059;	               ni-step = 0.01
               Bz-step = 0.059;	             flux-step = 0.02
 electron-momenta-step = 0.1;	 r-corrected-flux-step = 0.02
      ion-momenta-step = 0.1;	           energy-step = 10

#  Output of various quantities as functions of xi:
#   (ne,nb,Ez,<Ez>,Bz,Phi,pz,emitt,dW,Wf,ni,pzi)
#   (nb2,Er,Ez2,Bf,Bz2,Fr,pr,pf,<rb>,dS,Sf,SEB,pri,pfi,Ef)
f(xi) = Ez,Phi,emitt,nb2,Ez2,<rb>,dS,Sf,SEB
f(xi)-type = n
axis-radius = 0;		auxillary-radius = 1
               E-scale = 0.59;	              nb-scale = 0.02
             Phi-scale = 0.59;	              ne-scale = 2
              Bz-scale = 0.59;	              ni-scale = 0.1
electron-momenta-scale = 0.5;	            flux-scale = 0.5
     ion-momenta-scale = 0.5;	          energy-scale = 1
     beam-radius-scale = 5;	       emittance-scale = 300

#  Beam particle information as pictures (r,pr,pz,M):
output-beam-particles = ""
draw-each = 1
beam-picture-height = 900
beam-pr-scale = 1000
beam-a-m-scale = 1000;		beam-pz-scale = 15000

# Output of beam characteristics in histogram form (r,z,M,a):
histogram-output = ""
histogram-output-accel = ""
histogram-type = y
histogram-bins = 300;		beam-angle-scale = 0.02

#  Trajectories of plasma particles:
trajectories-draw = n
trajectories-each = 50;	trajectories-spacing = 100
trajectories-min-energy = 1;	trajectories-energy-step = 0.5

# Saving run state periodically:
saving-period = 50000
save-beam = n
save-plasma = n
"""

### Making directory module

def makedir(path, name, cfg=config):
    path = os.path.join(path, name)
    print('Making directory... ', end='')
    try:
        os.makedirs(path)
        print('done.')
    except:
        print('seems like the directory already exists.')

    with open(os.path.join(path, 'lcode.cfg'), "w") as text_file:
        print('Writing lcode.cfg... ', end='')
        text_file.write(cfg)
    print('done')
    return path

### Simulation setting up module

def setup_simulation(lcode, time_step, window_width, window_length):
    lcode.set_parameter('time-step', time_step)
    print(type(window_width))
    window_width = round(window_width, 2)
    lcode.set_parameter('window-width', window_width)
    window_length = float(window_length)
    lcode.set_parameter('window-length', window_length)
    print('')

### Making plasma module

def plasma_zshape(x, n, form='L'):
    zshape = ''
    dxs = x[1:] - x[:-1]
    arr = np.array([dxs, n[:-1], n[1:]]).T
    zshape += 'plasma-zshape = """\n'
    for dx, n_start, n_end in arr:
        zshape += '%f %f %s %f\n' % (dx, n_start, form, n_end)
    zshape +='"""'
    return zshape

def make_plasma(lcode, n_plasma, plasma_length, plasma_radius, n_profile):
    print("# PLASMA")
    plasma_length = round(plasma_length)
    lcode.set_parameter('time-limit', plasma_length + 0.1)

    plasma_radius = round(plasma_radius, 2)
    lcode.set_parameter('plasma-width', plasma_radius)

    # z-shape
    n0 = n_plasma
    z = np.arange(0, plasma_length, lcode.get_parameter('time-step'))
    nz = np.array([n0*n_profile(x) for x in z])
    plt.title('density profile')
    plt.plot(z*lcode.cwp/100, lcode.n*nz)
    plt.xlabel(r'$z$ [m]')
    plt.ylabel(r'$n$ [cm-3]')
    print('Writing pzshape.txt... ', end='')
    with open(os.path.join(lcode.path, 'pzshape.txt'), 'w') as f:
        f.write(plasma_zshape(z, nz))
    print('done\n')

### Beamfile construction module

def Q2I(Q, sigma_z): # SI (return Amps)
    return c/100. * Q / np.sqrt(2*np.pi) / sigma_z
def make_beam(lcode, sigma_z, pos_xi, sigma_r, gamma, enspread, emittance, N_particles):
    print("# BEAM")
    q_m = m_MeV/M_MeV
    # xi
    xi_shape = Gauss(pos_xi, sigma_z)
    # r
    r_shape = rGauss(sigma_r)
    # pz
    pz_shape = Gauss(gamma, enspread)
    # angle
    angspread = emittance / (gamma / (M_MeV/m_MeV) * sigma_r)
    #print('%e' % angspread)
    ang_shape = Gauss(0, angspread)
    # current
    Ipeak_A = Q2I(N_particles*1.6e-19, sigma_z*lcode.cwp/100)
    Ipeak_kA = Ipeak_A/1000
    lcode.beam = lcode.make_beam(xi_shape, r_shape, pz_shape, ang_shape, Ipeak_kA, q_m, saveto=lcode.path)
    print('Writing beamfile.bit...', end='')
    with open(os.path.join(lcode.path, 'beamfile.bit'), 'w') as f:
        f.write('0.0')
    print('done.\n')

### Making task module

def make_task(lcode, name, N_nodes, cluster='matrosov'):
    if cluster == 'matrosov':
        task = """#!/bin/bash
#
#PBS -N {}
#PBS -l nodes={}:intel:ppn=36,pvmem=30000mb,walltime=100:00:00
cd $PBS_O_WORKDIR
/share/apps/bin/mpiexec -perhost 36 lcode lcode.cfg pzshape.txt""".format(name, N_nodes)
        print('Making task.sh... ', end='')
        with open(os.path.join(lcode.path, 'task.sh'), 'w') as f:
            f.write(task)
        print('done.\n')
    elif cluster == 'matrosov2':
        task = """#!/bin/bash
#
#PBS -N {}
#PBS -l nodes={}:amd:ppn=32,pvmem=30000mb,walltime=100:00:00
cd $PBS_O_WORKDIR
/share/apps/bin/mpiexec -perhost 32 lcode2 lcode.cfg pzshape.txt""".format(name, N_nodes)
        print('Making task.sh... ', end='')
        with open(os.path.join(lcode.path, 'task.sh'), 'w') as f:
            f.write(task)
        print('done.\n')
    elif cluster == 'condor':
        print('Making condor directory... ', end='')
        try:
            os.makedirs(os.path.join(lcode.path, 'condor'))
            print('done.')
        except:
            print('seems like the directory already exists.')
        print('Copying condor files... ', end='')
        copyfile('../condor/job.py', os.path.join(lcode.path, 'condor/job.py'))
        copyfile('../condor/job_start.sh', os.path.join(lcode.path, 'condor/job_%s.sh' % name))
        copyfile('../condor/job.submit', os.path.join(lcode.path, 'condor/job.submit'))
        with open('../condor/job.sub') as f:
            lines = f.readlines()
        lines[0] = 'executable            = job_%s.sh\n' % name
        with open(os.path.join(lcode.path, 'condor/job.sub'), "w") as f:
            f.writelines(lines)
        print('done.')


def readInputs():
    """
    -----------------------------------------------------------
    Lê a primeira linha ("linha de problema"), e extrai dela a
    quantidade de variáveis e cláusulas a serem lidas;
    -----------------------------------------------------------
    """
    pblm_ln = input()
    var_qtd = int(pblm_ln.split()[2])
    clauses_qtd = int(pblm_ln.split()[3])
    return [var_qtd, clauses_qtd]

def readClauses(clauses_qtd):
    """
    -----------------------------------------------------------
    Recebe a quantidade de cláusulas a serem lidas e cria uma
    lista com as cláusulas;
    -----------------------------------------------------------
    """
    clauses = []
    for i in range(clauses_qtd):
        clause = []
        clause.append(input().split())
        clause[0].remove('0')
        clauses.append(clause[0])
    return clauses

def readVariables(var_qtd):
    """
    -----------------------------------------------------------
    Recebe a quantidade de variáveis e cria uma lista,
    inicializando todas com o valor False (0);
    -----------------------------------------------------------
    """
    var_values = []
    for i in range(var_qtd):
        var_values.append(0)
    return var_values

def unitary_bin(var_qtd):
    """
    -----------------------------------------------------------
    Cria uma lista do mesmo tamanho da lista de variáveis, onde
    o último elemento é 1 e os outros são 0. Criando um número
    binário de valor 1;
    -----------------------------------------------------------
    """
    unb = []
    for i in range(var_qtd):
        if i == var_qtd-1:
            unb.append(1)
        else:
            unb.append(0)
    return unb

def soma_binaria(bin_1, bin_2):
    """
    -----------------------------------------------------------
    Recebe duas listas, cada uma com um valor binário e realiza a soma de ambos;
    -----------------------------------------------------------
    """
    bin_result = []
    sobra = 0
    digits = 0
    bin_1.reverse()
    bin_2.reverse()
    if len(bin_1) > len(bin_2):
        digits = len(bin_1)
        for i in range(len(bin_1) - len(bin_2)):
            bin_2.append(0)
    elif len(bin_1) < len(bin_2):
        digits = len(bin_2)
        for i in range(len(bin_2) - len(bin_1)):
            bin_1.append(0)
    else:
        digits = len(bin_1)

    for i in range(digits):
        if bin_1[i] + bin_2[i] + sobra == 0:
            bin_result.append(0)
            sobra = 0
        elif bin_1[i] + bin_2[i] + sobra == 1:
            bin_result.append(1)
            sobra = 0
        elif bin_1[i] + bin_2[i] + sobra == 2:
            bin_result.append(0)
            sobra = 1
        elif bin_1[i] + bin_2[i] + sobra == 3:
            bin_result.append(1)
            sobra = 1

    if sobra == 1:
        bin_result.append(1)
        sobra = 0

    bin_1.reverse()
    bin_2.reverse()
    bin_result.reverse()
    return bin_result

def or_ver(values):
    """
    -----------------------------------------------------------
    Verifica a satisfatibilidade das cláusulas, em que as
    variáveis são ligadas por conectivos "ou";
    -----------------------------------------------------------
    """
    if 1 in values:
        return 1
    else:
        return 0

def and_ver(values):
    """
    -----------------------------------------------------------
    Verifica a satisfatibilidade da sentença, em que as
    cláusulas sao ligadas por conectivos "e";
    -----------------------------------------------------------
    """
    result = all(elem == 1 for elem in values)
    return result

def sat_test(clauses, values):
    """
    -----------------------------------------------------------
    Recebe as cáusulas e os valores Falso ou Verdadeiro (0 ou 1)
    das variáveis e verifica se o problema é satisfatível;
    -----------------------------------------------------------
    """
    ver = []
    for i in range(len(clauses)):
        logic = []
        for k in range(len(clauses[i])):
            if int(clauses[i][k]) < 0:
                if values[int(clauses[i][k])*(-1)-1] == 0:
                    logic.append(1)
                else:
                    logic.append(0)
            else:
                logic.append(values[int(clauses[i][k])-1])

        ver.append(or_ver(logic))
    return ver

def solve():
    """
    -----------------------------------------------------------
    Agrupa todas as funções em prol do resultado e retorna uma
    lista composta por 0s e/ou 1s se o problema é satisfatível
    (onde 0 é Falso e 1 é Verdadeiro para as respectivas
    variáveis), ou retorna nada caso o problema não seja
    satisfatível.
    -----------------------------------------------------------
    """
    var_cl = readInputs()
    clauses = readClauses(var_cl[1])
    variables = readVariables(var_cl[0])
    one = unitary_bin(var_cl[0])
    for i in range(2**var_cl[0]):
        vvv = sat_test(clauses, variables)
        if and_ver(vvv):
            print(variables)
            break

        variables = soma_binaria(variables, one)

if __name__=="__main__":
    solve()


# 自定义一个人类
class Person(object):

    # 国籍
    # 私有类属性
    __country = "中国"

    # 取值
    # 定义一个类方法
    # 定义类方法或者静态方法需要加修饰器
    # cls -> class -> Person
    @classmethod
    def get_country(cls):
        return cls.__country

    # 赋值
    @classmethod
    def set_country(cls, new_country):
        cls.__country = new_country

# 因为是私有的
# print(Person.__country)

# 类方法的调用方式:
# 01: 类名.类方法名() ***
# 02: 对象名.类方法名()
# 01: 取值
print(Person.get_country())
# 02: 赋值
Person().set_country("荷兰")
print(Person.get_country())


import os

from .count_nout import count_nout

def port(path_in,path_out):
    files_list=[]
    for dirpath, _, files in os.walk(path_in):
        files_list.extend(files)
        dirpath_prune = dirpath.replace(path_in,'').replace("@","at_").replace("-","_")
        depth = 2
        for s in dirpath_prune:
            if s == '\\' or s == '/':
                depth += 1
        dots = '.'*depth
        # print(dirpath_prune)
        # print(dots)

        for f in files:
            if f[-2:] == '.m':
                if os.path.basename(os.path.normpath(dirpath)+".m") in files_list:
                    print(os.path.basename(os.path.normpath(dirpath)))
                    current_folder = os.path.join(path_out,"_"+dirpath_prune[1:])
                else:
                    current_folder = os.path.join(path_out,dirpath_prune[1:])
                # print(path_out)
                # print(dirpath_prune)
                # print(current_folder)

                if not os.path.isdir(current_folder):
                    os.makedirs(current_folder)
                if not os.path.isfile(os.path.join(current_folder,'__init__.py')):
                    with open(os.path.join(current_folder,'__init__.py'),'w') as fout:
                        pass

                nout = count_nout(os.path.join(dirpath,f))
                # print(os.path.join(dirpath,f))

                with open(os.path.join(current_folder,f[:-2]+'.py'),'w') as fout:
                    fout.write(f'def {f[:-2]}(*args,nout={nout},oc=None):\n')
                    fout.write('\tif oc == None:\n')
                    fout.write(f'\t\tfrom {dots}oc_api import oc_matpower\n')
                    fout.write('\toc = oc_matpower()\n')
                    fout.write(f'\treturn oc.{f[:-2]}(*args,nout=nout)\n')


#written may 16 2015
#takes in twitter txt data of "," dlm USER_ID's, and returns a
#list of the usernames.

'''
heres an idea:
since we have so much tweeter data, just do calls for the followers/following
information of like 1 user for instance, and then check to see out of the
total number of tweets we have collected (over 10,000) related to hockey
key words, how many of the total are followers/following the other person.
we can do this for all users, and then calculate the average.
'''
#CLEANNEDHOCKEY2.txt

#cleannedhockey2MM_DLM.txt
#cleannedhockey3.txt

from string import *

def clean_data1(txtfilename):
     rtxt = open( txtfilename, 'r')
     wtxt = open( "test.txt" , "w")

     listt = []
     for line in rtxt:
          if line != ".":
               print(line)
               listt.append(line)
               wtxt.write(line)
     '''
          listt2 = (line).split(",")
          listt.append(listt2)
     #seperate the string by a delimiter into nodes of a list
     '''
     rtxt.close()
     wtxt.close()
     return listt

#mylist = cleandata1("cleannedhockey4.txt")

def make_list(txtfilename):
     rtxt = open( txtfilename, 'r')
     mylist = []
     for line in rtxt:
          dlm = line.split(",")
          try:
               mylist.append(int(dlm[0]))
               #print (dlm[0])
          except:
               print("error occured with INT type. ")
     rtxt.close()
     return mylist

dataL = make_list("final_clean.txt")
print(len(dataL))

# remember that when text file data is read,
#its automatically assumed to be string data.


from scipy.special import comb
import numpy as np
import matplotlib.pyplot as plt
import math

def ensemble_error(n_classifier, error):
    k_start = int(math.ceil(n_classifier/2.))
    probs = [comb(n_classifier, k)*
             error**k *
             (1 - error)**(n_classifier - k)
             for k in range(k_start, n_classifier+1)]
    return sum(probs)

error_range = np.arange(0.0, 1.01, 0.01)

ens_errors = [ensemble_error(n_classifier=11, error=error)
             for error in error_range]

plt.plot(error_range, ens_errors,
         label='Ensemble error',
         linewidth=2)
plt.plot(error_range, error_range,
         label='Base error',
         linestyle='--',
         linewidth=2)
plt.xlabel("Base Error")
plt.ylabel("Base/Ensemble Error")
plt.legend(loc="upper left")
plt.grid(alpha=0.5)
plt.show()

np.argmax(np.bincount([0, 0, 1],
          weights=[0.2,0.2,0.6]))

ex1 = np.array([[0.2, 0.1],
                [0.8, 0.2]])
# (0.2 * 0.2) + (0.8 * 0.8)
# (0.1 * 0.2) + (0.2 * 0.8)
np.average(ex1, axis=0, weights=[0.2, 0.8])

ex2 = np.array([[0.9, 0.1],
                [0.8, 0.2],
                [0.4, 0.6]])

p = np.average(ex2, axis=0, weights=[0.2, 0.2, 0.6])
np.argmax(p)

from sklearn import datasets
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline

iris = datasets.load_iris()

X, y = iris.data[50:, [1,2]], iris.target[50:]
le = LabelEncoder()
y = le.fit_transform(y)

X_train, X_test, y_train, y_test = \
        train_test_split(X, y,
                         test_size=0.4,
                         random_state=1,
                         stratify=y)

clf1 = LogisticRegression(solver='liblinear',
                          penalty='l2',
                          C=0.001, random_state=0)

clf2 = DecisionTreeClassifier(max_depth=1,
                              criterion='entropy',
                              random_state=0)

clf3 = KNeighborsClassifier(n_neighbors=1,
                            p=2, metric='minkowski')

pipe1 = Pipeline([['sc', StandardScaler()],
                  ['clf', clf1]])

pipe3 = Pipeline([['sc', StandardScaler()],
                  ['clf', clf3]])

clf_labels = ['Logistic Regression', 'Decision Tree', 'KNN']
print('10-겹 교차 검증: \n')
for clf, label in zip([pipe1, clf2, pipe3], clf_labels):
    scores = cross_val_score(estimator=clf,
                             X=X_train,
                             y=y_train,
                             cv=10, scoring='roc_auc')
    print("ROC AUC: %0.2f (+/- %0.2f) [%s]" %
            (scores.mean(), scores.std(), label))

from model.vote_classifier import MajorityVoteClassifier

mv_clf = MajorityVoteClassifier(classifiers=[pipe1, clf2, pipe3])
clf_labels += ['Majority voting']
all_clf = [pipe1, clf2, pipe3, mv_clf]

for clf, label in zip(all_clf, clf_labels):
    scores = cross_val_score(estimator=clf,
                             X=X_train,
                             y=y_train,
                             cv=10, scoring='roc_auc')
    print('ROC AUC : %0.2f (+/- %0.2f) [%s]'
            % (scores.mean(), scores.std(), label))

from sklearn.metrics import roc_curve, auc
colors = ['black', 'orange', 'blue', 'green']
linestyle = [':', '--', '-', '-']
for clf, label, clr, ls \
                in zip(all_clf, clf_labels, colors, linestyle):
    y_pred = clf.fit(X_train, y_train).predict_proba(X_test)[:,1]
    fpr, tpr, thresholds = roc_curve(y_true=y_test,
                                     y_score=y_pred)
    roc_auc = auc(x=fpr, y=tpr)
    plt.plot(fpr, tpr,
             color=clr,
             linestyle=ls,
             label='%s (auc= %0.2f)' % (label, roc_auc))

plt.legend(loc='lower right')
plt.plot([0, 1], [0, 1],
         linestyle='--',
         color='gray',
         linewidth=2)
plt.xlim([-0.1, 1.1])
plt.ylim([-0.1, 1.1])
plt.grid(alpha=0.5)
plt.xlabel('False positive rate (FPR)')
plt.ylabel('True positive rate (TPR)')
plt.show()

sc = StandardScaler()
X_train_std = sc.fit_transform(X_train)

x1_min, x1_max = X_train_std[:, 0].min() - 1, X_train_std[:, 0].max() + 1
x2_min, x2_max = X_train_std[:, 1].min() - 1, X_train_std[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, 0.1),
                       np.arange(x2_min, x2_max, 0.1))

f, axarr = plt.subplots(nrows=2, ncols=2,
                        sharex='col',
                        sharey='row',
                        figsize=(7, 5))

for idx, clf, tt in zip(product([0, 1], [0, 1]), all_clf, clf_labels):
    clf.fit(X_train_std, y_train)
    Z = clf.predict(np.c_[xx1.ravel(), xx2.ravel()])
    Z = Z.reshape(xx1.shape)
    axarr[idx[0], idx[1]].contourf(xx1, xx2, Z, alpha=0.3)
    axarr[idx[0], idx[1]].scatter(x=X_train_std[y_train == 0, 0],
                                  y=X_train_std[y_train == 0, 1],
                                  c='blue',
                                  marker='^',
                                  s=50)
    axarr[idx[0], idx[1]].scatter(x=X_train_std[y_train == 1, 0],
                                  y=X_train_std[y_train == 1, 1],
                                  c='green',
                                  marker='o',
                                  s=50)
    axarr[idx[0], idx[1]].set_title(tt)
plt.text(-3.5, -4.5,
         s='Sepal width [Standardized]',
         ha='center', va='center',
         fontsize=12)
plt.text(-13, 4.5,
         s='Sepal length [Standardized]',
         ha='center', va='center',
         fontsize=12, rotation=90)
plt.show()
#'pipeline-1__clf__C': 0.001
#'decisiontreeclassifier__max_depth'
mv_clf.get_params()

from sklearn.model_selection import GridSearchCV
params = {'decisiontreeclassifier__max_depth':[1, 2],
          'pipeline-1__clf__C': [0.001, 0.1, 100.0]}
grid = GridSearchCV(estimator=mv_clf,
                    param_grid=params,
                    cv=15,
                    scoring='roc_auc',
                    iid=False)
grid.fit(X_train_std, y_train)

print('최적의 매개변수: %s' % grid.best_params_)
print('최적의 정확도: %s' % grid.best_score_)

###############################################################################
###### Bagging and Bootstrap                                             ######
###############################################################################
import pandas as pd
from sklearn.ensemble import BaggingClassifier

df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/'
                      'machine-learning-databases/wine/wine.data',
                      header=None)

df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash',
                   'Alcalinity of ash', 'Magnesium', 'Total phenols',
                   'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins',
                   'Color intensity', 'Hue',
                   'OD280/OD315 of diluted wines', 'Proline']

# 클래스 1 제외하기
df_wine = df_wine[df_wine['Class label'] != 1]

X, y = df_wine[['Alcohol', 'OD280/OD315 of diluted wines']].values, df_wine['Class label'].values

from sklearn.preprocessing import LabelEncoder

le = LabelEncoder()
y = le.fit_transform(y)

X_train, X_test, y_train, y_test =\
            train_test_split(X, y,
                             test_size=0.2,
                             random_state=1,
                             stratify=y)

tree = DecisionTreeClassifier(criterion='entropy',
                              max_depth=None,
                              random_state=1)

bag = BaggingClassifier(base_estimator=tree,
                        n_estimators=500,
                        max_samples=1.0,
                        max_features=1.0,
                        bootstrap=True,
                        bootstrap_features=False,
                        n_jobs=1,
                        random_state=1)

from sklearn.metrics import accuracy_score

tree = tree.fit(X_train, y_train)
y_train_pred = tree.predict(X_train)
y_test_pred = tree.predict(X_test)

tree_train = accuracy_score(y_train, y_train_pred)
tree_test = accuracy_score(y_test, y_test_pred)
print('결정 트리의 훈련 정확도/테스트 정확도 %.3f/%.3f'
      % (tree_train, tree_test))

bag = bag.fit(X_train, y_train)
y_train_pred = bag.predict(X_train)
y_test_pred = bag.predict(X_test)

bag_train = accuracy_score(y_train, y_train_pred)
bag_test = accuracy_score(y_test, y_test_pred)
print('배깅의 훈련 정확도/테스트 정확도 %.3f/%.3f'
      % (bag_train, bag_test))

import numpy as np
import matplotlib.pyplot as plt

x_min = X_train[:, 0].min() - 1
x_max = X_train[:, 0].max() + 1
y_min = X_train[:, 1].min() - 1
y_max = X_train[:, 1].max() + 1

xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),
                     np.arange(y_min, y_max, 0.1))

f, axarr = plt.subplots(nrows=1, ncols=2,
                        sharex='col',
                        sharey='row',
                        figsize=(8, 3))

for idx, clf, tt in zip([0, 1],
                        [tree, bag],
                        ['Decision tree', 'Bagging']):
    clf.fit(X_train, y_train)

    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    axarr[idx].contourf(xx, yy, Z, alpha=0.3)
    axarr[idx].scatter(X_train[y_train == 0, 0],
                       X_train[y_train == 0, 1],
                       c='blue', marker='^')

    axarr[idx].scatter(X_train[y_train == 1, 0],
                       X_train[y_train == 1, 1],
                       c='green', marker='o')

    axarr[idx].set_title(tt)

axarr[0].set_ylabel('Alcohol', fontsize=12)
plt.text(10.2, -0.5,
         s='OD280/OD315 of diluted wines',
         ha='center', va='center', fontsize=12)

plt.tight_layout()
plt.show()

from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier

tree = DecisionTreeClassifier(criterion='entropy',
                              max_depth=1,
                              random_state=1)

ada = AdaBoostClassifier(base_estimator=tree,
                         n_estimators=500,
                         learning_rate=0.1,
                         random_state=1)

gbrt = GradientBoostingClassifier(n_estimators=20, random_state=42)

tree = tree.fit(X_train, y_train)
y_train_pred = tree.predict(X_train)
y_test_pred = tree.predict(X_test)

tree_train = accuracy_score(y_train, y_train_pred)
tree_test = accuracy_score(y_test, y_test_pred)
print('결정 트리의 훈련 정확도/테스트 정확도 %.3f/%.3f'
      % (tree_train, tree_test))

ada = ada.fit(X_train, y_train)
y_train_pred = ada.predict(X_train)
y_test_pred = ada.predict(X_test)

ada_train = accuracy_score(y_train, y_train_pred)
ada_test = accuracy_score(y_test, y_test_pred)

print('에이다부스트의 훈련 정확도/테스트 정확도 %.3f/%.3f'
      % (ada_train, ada_test))

gbrt.fit(X_train, y_train)
gbrt_train_score = gbrt.score(X_train, y_train)
gbrt_test_score = gbrt.score(X_test, y_test)

print('앙상블에 사용한 트리 개수 %d' % gbrt.n_estimators_)
print('그래디언트 부스팅 train/test 정확도 %.3f/%.3f'
      % (gbrt_train_score, gbrt_test_score))

f, axarr = plt.subplots(nrows=1, ncols=3,
                        sharex='col',
                        sharey='row',
                        figsize=(12, 4))

for idx, clf, tt in zip([0, 1, 2],
                        [tree, ada, gbrt],
                        ['Decision tree', 'AdaBoost', 'GradientBoost']):
    clf.fit(X_train, y_train)

    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    axarr[idx].contourf(xx, yy, Z, alpha=0.3)
    axarr[idx].scatter(X_train[y_train == 0, 0],
                       X_train[y_train == 0, 1],
                       c='blue', marker='^')
    axarr[idx].scatter(X_train[y_train == 1, 0],
                       X_train[y_train == 1, 1],
                       c='green', marker='o')
    axarr[idx].set_title(tt)

axarr[0].set_ylabel('Alcohol', fontsize=12)
plt.text(10.2, -0.5,
         s='OD280/OD315 of diluted wines',
         ha='center', va='center', fontsize=12)

plt.tight_layout()
plt.show()


"""
Earcu spider created on the top of ATSSpider

scrapy crawl earcu -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url="https://ea1.earcu.com/nuh/jobs"

Seed URL:
    https://ea1.earcu.com/nationalexpress/jobs
    https://ea1.earcu.com/nuh/jobs
    https://smithandwilliamson.earcu.com/smithandwilliamson/jobs/
"""

from re import compile, M
from scrapy.http import Request
from scrapy.selector import Selector
from urlparse import urljoin, urlparse

from brightcorp.base.atsspiders import ATSSpider
from brightcorp.items import BrightcorpItemLoader
from brightcorp.processors import ConvertDateString, NormalizedJoin, Prefix

pattern = {
    'href': compile(r'var\s*url\s*=\s*\'([^\']*)\';', M),
    'ref_number': compile(r'\/(\d+)\/'),
}

class Earcu(ATSSpider):

    name = 'earcu'
    company = ''
    handle_httpstatus_list = [302]
    headers = {
        'X-Requested-With': 'XMLHttpRequest'
    }

    def __init__(self, *args, **kwargs):
        super(Earcu, self).__init__(*args, **kwargs)
        if 'url' in kwargs:
            url_parsed = urlparse(kwargs['url']).path
            company = url_parsed.split('/')
            if company:
                self.company = company[1]

    def parse(self, response):
        """
        Parse each category/location and get vacancy count.
        Parse category/location urls.
        """
        sel = Selector(response)
        for div in sel.xpath(
            '//div[contains(@class, "listContainer")]/div[contains(@class, "listItemContainer")]'
        ):
            count = div.xpath(
                './div/div[@class="codeListBlockLower"]//a/span[@class="listItemCount"]/text() |'
                './div//*[@class="listItemCount"]/text()'
            ).extract()
            if count and int(count[0]) > 0:
                href = div.xpath(
                    './div/div[@class="codeListBlockLower"]//a/@href |'
                    './div/div[@class="listItemTitle"]/a/@href'
                ).extract()
                if href:
                    yield Request(
                        callback=self.parse_ajax,
                        headers=self.headers,
                        dont_filter=True,
                        url=urljoin(response.url, href[0])
                    )

    def parse_ajax(self, response):
        """
        Made GET request to ajax url for getting SERP pages
        """
        sel = Selector(response)
        ajax_url = sel.xpath(
            '//div[@class="scriptContainerTag"]/script/text()'
        ).extract()
        if ajax_url:
            match = pattern['href'].search(''.join(ajax_url))
            if match:
                href = '%s&availableWidthInput=700&gadgetsWidthInput=0' % match.group(1)
                yield Request(
                    callback=self.parse_jobs_list,
                    headers=self.headers,
                    dont_filter=True,
                    url=urljoin(response.url, href)
                )

    def parse_jobs_list(self, response):
        """
        Parse SERP page jobs list
        """
        sel = Selector(response)
        for div in sel.xpath(
            '//div[@class="gridContent"]/div/div[contains(@class, "rowContainerHolder")]'
        ):
            href = div.xpath(
                './div/div/div/a[@class="rcMenu"]/@href'
            ).extract()
            if href:
                yield Request(
                    callback=self.parse_job_callback(),
                    url=urljoin(response.url, href[0])
                )
        # pagination
        next_page = sel.xpath(
            '//div[@class="pagingButtons"]/a[contains(@class, "scroller_movenext")]/@href'
        ).extract()
        if next_page:
            yield Request(
                callback=self.parse_jobs_list,
                headers=self.headers,
                url=urljoin(response.url, next_page[0])
            )

    def parse_job(self, response):
        """
        Extract required information
        """
        sel = Selector(response)

        loader = BrightcorpItemLoader(selector=sel)

        loader.add_xpath(
            'title',
            '//div[@class="JobTitle"]/h1/text() |'
            '//div[@class="posDescriptionContainer"]/h1/text()'
        )
        loader.add_xpath(
            'location',
            '//li/div[contains(text(), "Location:")]/following-sibling::div[1]/text() |'
            '//li/div[contains(text(), "Region:")]/following-sibling::div[1]/text() |'
            '//p//strong[contains(text(), "Office:")]/../text()'
        )
        loader.add_xpath(
            'baseSalary',
            '//li/div[contains(text(), "Salary:")]/following-sibling::div[1]/text()'
        )
        loader.add_xpath(
            'jobtype',
            [
                '//li/div[contains(text(), "Working Pattern:")]/following-sibling::div[1]/text()',
                '//li/div[contains(text(), "Job (Contract) Type:")]/following-sibling::div[1]/text()',
                '//li/div[contains(text(), "Job Type:")]/following-sibling::div[1]/text()',
            ],
            NormalizedJoin(', ')
        )
        loader.add_xpath(
            'jobcategory',
            '//li/div[contains(text(), "ESR Main Staff Group:")]/following-sibling::div[1]/text() |'
            '//li/div[contains(text(), "Discipline:")]/following-sibling::div[1]/text()'
        )
        loader.add_xpath(
            'description',
            '//div[@class="earcu_posdescription"]/div[@class="earcu_posdescriptionnote"]'
        )
        loader.add_xpath(
            'expiration_date',
            '//li/div[contains(text(), "Closing Date:")]/following-sibling::div[1]/text()',
            ConvertDateString('%d %B %Y')
        )
        loader.add_xpath(
            'company',
            '//li/div[contains(text(), "Group:")]/following-sibling::div[1]/text()'
        )
        loader.add_value(
            'referencenumber',
            response.url,
            Prefix('%s-%s-' % (self.name, self.company)),
            re=pattern['ref_number']
        )
        loader.add_value('url', response.url)
        loader.add_value('apply_url', response.url)

        yield loader.load_item()


import json
from redbot.core.data_manager import cog_data_path
import random
import discord
import asyncio
import time
from redbot.core.utils.predicates import MessagePredicate
from redbot.core.utils.menus import start_adding_reactions
from redbot.core.utils.predicates import ReactionPredicate
from .custompredicate import CustomPredicate
from redbot.core.commands.context import Context
from redbot.core import commands, bank, checks
from .adventure import Adventure
from .treasure import Treasure
from .classes import Classes

BaseCog = getattr(commands, "Cog", object)
users = {}

class GobCog(BaseCog):

    fp = cog_data_path(None, "gobcog") / 'users.json'  # this looks for users.json inside your RedBot/cogs/gobcog folder. Needs to be setup once: create the folder, make a users.json with just an empty {} inside.
    global users
    with fp.open('r') as f:
        users = json.load(f)
    last_trade = 0
    bot = None

    """Goblins Adventure bot"""

    @commands.command()
    @commands.guild_only()
    async def cp(self, ctx, user: discord.Member=None):
        """This shows the bank balance of you or an optionally specified member.
            !cp @locastan
            will bring up locastans balance.
            !cp without user will display your balance.
        """
        if user is None:
            user = ctx.author
        bal = await bank.get_balance(user)
        currency = await bank.get_currency_name(ctx.guild)
        await ctx.send(
            "```css\n{} owns {} {}```".format(
                user.display_name, bal, currency
            )
        )

    @commands.command()
    @commands.guild_only()
    async def unequip(self, ctx, item: str="None"):
        """This stashes a specifed equipped item
            into your backpack.

            !unequip "name of item"
        """
        await GobCog.sub_unequip(ctx,item)

    @staticmethod
    async def sub_unequip(ctx, item: str="None"):
        global users
        user = ctx.author
        equipped = {}
        for slot in users[str(user.id)]['items']:
            if users[str(user.id)]['items'][slot] and slot != "backpack":
                equipped.update(users[str(user.id)]['items'][slot])
        if item == "None" or not any([x for x in equipped if item in x.lower()]):
            if item == "{.:'":
                return
            else:
                return await ctx.send("You do not have an item matching {} equipped.".format(item))
        else:
            lookup = list(x for x in equipped if item in x.lower())
            for olditem in lookup:
                for slot in equipped[olditem].get('slot'):
                    users[str(user.id)]['items'][slot] = {}
                    users[str(user.id)]['att'] -= int(equipped[olditem].get('att'))     # keep in mind that double handed items grant their bonus twice so they remove twice
                    users[str(user.id)]['cha'] -= int(equipped[olditem].get('cha'))
                users[str(user.id)]['items']['backpack'].update({olditem: equipped[olditem]}) # TODO: Change data structure of items dict so you can have duplicate items because of key duplicate overwrite in dicts.
                await ctx.send("You removed {} and put it into your backpack.".format(olditem))
            await ctx.send("Your new stats: **Attack**: {} [+{}], **Diplomacy**: {} [+{}].".format(users[str(user.id)]['att'],users[str(user.id)]['skill']['att'],users[str(user.id)]['cha'],users[str(user.id)]['skill']['cha']))

    @commands.command()
    @checks.admin_or_permissions(administrator=True)
    async def give_loot(self, ctx, type: str="normal", user: discord.Member=None):
        """[Admin] This rewards a treasure chest to a specified member.
            !give_loot normal @locastan
            will give locastan a normal chest.
            (Adding "rare" or "epic" to command, creates rare and epic chests.)
        """
        global users
        if user is None:
            user = ctx.author
        if not 'treasure' in users[str(user.id)].keys():
            users[str(user.id)]['treasure'] = [0,0,0]
        if type == "rare":
            users[str(user.id)]['treasure'][1] += 1
        elif type == "epic":
            users[str(user.id)]['treasure'][2] += 1
        else:
            users[str(user.id)]['treasure'][0] += 1
        await ctx.send(
            "```{} now owns {} normal, {} rare and {} epic chests.```".format(
                user.display_name, str(users[str(user.id)]['treasure'][0]),str(users[str(user.id)]['treasure'][1]),str(users[str(user.id)]['treasure'][2])))
        with GobCog.fp.open('w') as f:
            json.dump(users, f)

    @commands.command()
    @checks.admin_or_permissions(administrator=True)
    async def clean_stats(self, ctx):
        """[Admin] This recalulates each members stats based on equipped items.
            (Meant for stat cleanup after a messup error appeared.)
        """
        global users
        deadsies = []
        for user in users:
            member = discord.utils.find(lambda m: m.id == int(user), ctx.guild.members)
            if member == None: #member left the discord.
                deadsies.append(str(user))
                continue
            i = iter(users[str(user)]['items'])
            attack = 0
            diplomacy = 0
            for slot in i:
                if users[str(user)]['items'][slot] and slot != "backpack":
                    item = list(users[str(user)]['items'][slot].keys())[0]
                    attack += users[str(user)]['items'][slot][item]['att']
                    diplomacy += users[str(user)]['items'][slot][item]['cha']
            users[str(user)]['att'] = attack
            users[str(user)]['cha'] = diplomacy
            users[str(user)]['name'] = {}
            users[str(user)]['name'] = member.display_name
            if 'class' not in users[str(user)]:
                users[str(user)]['class'] = {}
            if users[str(user)]['class'] == {}:
                users[str(user)]['class'] = {'name': "Hero", 'ability': False, 'desc': "Your basic adventuring hero."}
            if 'skill' not in users[str(user)]:
                users[str(user)]['skill'] = {}
                users[str(user)]['skill'] = {'pool': 0, 'att': 0, 'cha': 0}
            print(users[str(user)]['name']+": "+str(int(users[str(user)]['lvl'] / 5)) + "-" + str(users[str(user)]['skill']['att']+users[str(user)]['skill']['cha']))
            users[str(user)]['skill']['pool'] = int(users[str(user)]['lvl'] / 5) - (users[str(user)]['skill']['att']+users[str(user)]['skill']['cha'])
        for userID in deadsies:
            users.pop(userID)
        with GobCog.fp.open('w') as f:
            json.dump(users, f)

    @commands.command()
    @commands.guild_only()
    @commands.cooldown(rate=1, per=43200, type=commands.BucketType.user)
    async def pet(self,ctx, switch:str=None):
        """This allows a Ranger to tame or set free a pet or send it foraging (once per day).
            !pet
            !pet forage
            !pet free
        """
        global users
        user = ctx.author.id
        if 'name' in users[str(user)]['class'] and users[str(user)]['class']['name'] != "Ranger":
            ctx.command.reset_cooldown(ctx)
            return await ctx.send("You need to be a Ranger to do this.")
        else:
            if switch == None or users[str(user)]['class']['ability'] == False:
                pet = await Classes.pet(ctx, users, None)
                if pet != None:
                    ctx.command.reset_cooldown(ctx) #reset cooldown so ppl can forage right after taming a new pet.
                    users[str(user)]['class']['ability'] = {'active': True, 'pet': pet}
                    with GobCog.fp.open('w') as f:
                        json.dump(users, f)
            elif switch == 'forage':
                item = await Classes.pet(ctx, users, switch)
                if item != None:
                    if item['equip'] == "sell":
                        price = random.randint(10,1000)*max(item['item']['att']+item['item']['cha'],1)
                        await bank.deposit_credits(ctx.author, price)
                        await ctx.send("{} sold the {} for {} copperpieces.".format(ctx.author.display_name,item['itemname'],price))
                    elif item['equip'] == "equip":
                        equip = {"itemname": item['itemname'],"item": item['item']}
                        await self.equip_item(ctx, equip, False)
                    else:
                        users[str(user)]['items']['backpack'].update({item['itemname']: item['item']})
                        await ctx.send("{} put the {} into the backpack.".format(ctx.author.display_name,item['itemname']))
                        with GobCog.fp.open('w') as f:
                            json.dump(users, f)
            elif switch == 'free':
                await Classes.pet(ctx, users, switch)
                with GobCog.fp.open('w') as f:
                    json.dump(users, f)

    @commands.command()
    @commands.guild_only()
    @commands.cooldown(rate=1, per=3600, type=commands.BucketType.user)
    async def rage(self,ctx):
        """This allows a Berserker to add substantial attack bonuses for one battle.
        """
        global users
        user = ctx.author.id
        if 'name' in users[str(user)]['class'] and users[str(user)]['class']['name'] != "Berserker":
            ctx.command.reset_cooldown(ctx)
            return await ctx.send("You need to be a Berserker to do this.")
        else:
            users = await Classes.rage(ctx, users)

    @commands.command()
    @commands.guild_only()
    @commands.cooldown(rate=1, per=3600, type=commands.BucketType.user)
    async def bless(self,ctx):
        """This allows a praying Cleric to add substantial bonuses for heroes fighting the battle.
        """
        global users
        user = ctx.author.id
        if 'name' in users[str(user)]['class'] and users[str(user)]['class']['name'] != "Cleric":
            ctx.command.reset_cooldown(ctx)
            return await ctx.send("You need to be a Cleric to do this.")
        else:
            users = await Classes.bless(ctx, users)

    @commands.command()
    @commands.guild_only()
    @commands.cooldown(rate=1, per=3600, type=commands.BucketType.user)
    async def sing(self,ctx):
        """This allows a Bard to add substantial diplomacy bonuses for one battle.
        """
        global users
        user = ctx.author.id
        if 'name' in users[str(user)]['class'] and users[str(user)]['class']['name'] != "Bard":
            ctx.command.reset_cooldown(ctx)
            return await ctx.send("You need to be a Bard to do this.")
        else:
            users = await Classes.sing(ctx, users)

    @commands.command()
    @commands.guild_only()
    @commands.cooldown(rate=1, per=43200, type=commands.BucketType.user)
    async def forge(self,ctx):
        """This allows a Tinkerer to forge two items into a device.
        """
        global users
        user = ctx.author.id
        if 'name' in users[str(user)]['class'] and users[str(user)]['class']['name'] != "Tinkerer":
            ctx.command.reset_cooldown(ctx)
            return await ctx.send("You need to be a Tinkerer to do this.")
        else:
            bkpk = ""
            consumed = []
            forgeables = len(users[str(user)]['items']['backpack']) - sum("{.:'" in x for x in users[str(user)]['items']['backpack'])
            if forgeables <= 1:
                ctx.command.reset_cooldown(ctx)
                return await ctx.send("You need at least two forgeable items in your backpack to forge.")
            for item in users[str(user)]['items']['backpack']:
                if "{.:'" not in item:
                    if len(users[str(user)]['items']['backpack'][item]['slot']) == 1:
                        bkpk += " - " + item + " - (ATT: "+ str(users[str(user)]['items']['backpack'][item]['att']) + " | DPL: "+ str(users[str(user)]['items']['backpack'][item]['cha']) +" ["+ users[str(user)]['items']['backpack'][item]['slot'][0] + " slot])\n"
                    else:
                        bkpk += " - " + item + " -(ATT: "+ str(users[str(user)]['items']['backpack'][item]['att']*2) + " | DPL: "+ str(users[str(user)]['items']['backpack'][item]['cha']*2) +" [two handed])\n"
            await ctx.send(
                "```css\n[{}'s forgeables] \n\n```".format(
                    ctx.author.display_name
                ) + "```css\n" + bkpk + "\n (Reply with the full or partial name of item 1 to select for forging. Try to be specific.)```"
            )
            try:
                reply = await ctx.bot.wait_for("message", check=MessagePredicate.same_context(ctx), timeout=30)
            except asyncio.TimeoutError:
                ctx.command.reset_cooldown(ctx)
                return await ctx.send("I don't have all day, you know.")
            item1 = {}
            for item in users[str(user)]['items']['backpack']:
                if reply.content.lower() in item:
                    if  "{.:'" not in item:
                        item1 = users[str(user)]['items']['backpack'].get(item)
                        consumed.append(item)
                        break
                    else:
                        ctx.command.reset_cooldown(ctx)
                        return await ctx.send("Tinkered devices cannot be reforged.")
            if item1 == {}:
                ctx.command.reset_cooldown(ctx)
                return await ctx.send("I could not find that item, check your spelling.")
            bkpk = ""
            for item in users[str(user)]['items']['backpack']:
                if item not in consumed and "{.:'" not in item:
                    if len(users[str(user)]['items']['backpack'][item]['slot']) == 1:
                        bkpk += " - " + item + " - (ATT: "+ str(users[str(user)]['items']['backpack'][item]['att']) + " | DPL: "+ str(users[str(user)]['items']['backpack'][item]['cha']) +" ["+ users[str(user)]['items']['backpack'][item]['slot'][0] + " slot])\n"
                    else:
                        bkpk += " - " + item + " -(ATT: "+ str(users[str(user)]['items']['backpack'][item]['att']*2) + " | DPL: "+ str(users[str(user)]['items']['backpack'][item]['cha']*2) +" [two handed])\n"
            await ctx.send(
                "```css\n[{}'s forgeables] \n\n```".format(
                    ctx.author.display_name
                ) + "```css\n" + bkpk + "\n (Reply with the full or partial name of item 2 to select for forging. Try to be specific.)```"
            )
            try:
                reply = await ctx.bot.wait_for("message", check=MessagePredicate.same_context(ctx), timeout=30)
            except asyncio.TimeoutError:
                ctx.command.reset_cooldown(ctx)
                return await ctx.send("I don't have all day, you know.")
            item2 = {}
            for item in users[str(user)]['items']['backpack']:
                if reply.content.lower() in item and reply.content.lower() not in consumed:
                    if  "{.:'" not in item:
                        item2 = users[str(user)]['items']['backpack'].get(item)
                        consumed.append(item)
                        break
                    else:
                        ctx.command.reset_cooldown(ctx)
                        return await ctx.send("Tinkered devices cannot be reforged.")
            if item2 == {}:
                    ctx.command.reset_cooldown(ctx)
                    return await ctx.send("I could not find that item, check your spelling.")
            newitem = await Classes.forge(ctx, item1, item2)
            for item in consumed:
                users[str(user)]['items']['backpack'].pop(item)
            await GobCog.sub_unequip(ctx,"{.:'")
            lookup = list(x for x in users[str(user)]['items']['backpack'] if "{.:'" in x.lower())
            if len(lookup) > 0:
                msg = await ctx.send("```css\n You already have a device. Do you want to replace {}? ```".format(', '.join(lookup)))
                start_adding_reactions(msg, ReactionPredicate.YES_OR_NO_EMOJIS)
                pred = ReactionPredicate.yes_or_no(msg, ctx.author)
                await ctx.bot.wait_for("reaction_add", check=pred)
                try:
                    await msg.delete()
                except discord.Forbidden:  # cannot remove message try remove emojis
                    for key in ReactionPredicate.YES_OR_NO_EMOJIS:
                        await msg.remove_reaction(key, ctx.bot.user)
                if pred.result: #user reacted with Yes.
                    for item in lookup:
                        del users[str(user)]['items']['backpack'][item]
                        users[str(user)]['items']['backpack'].update({newitem['itemname']: newitem['item']})
                        await ctx.send('```css\n Your new {} consumed {} and is now lurking in your backpack. ```'.format(newitem['itemname'], ', '.join(lookup)))
                else:
                    with GobCog.fp.open('w') as f:
                        json.dump(users, f)
                    return await ctx.send('```css\n {} got mad at your rejection and blew itself up. ```'.format(newitem['itemname']))
            else:
                users[str(user)]['items']['backpack'].update({newitem['itemname']: newitem['item']})
                await ctx.send('```css\n Your new {} is lurking in your backpack. ```'.format(newitem['itemname']))
                with GobCog.fp.open('w') as f:
                    json.dump(users, f)

    @commands.command()
    @commands.guild_only()
    @commands.cooldown(rate=1, per=300, type=commands.BucketType.user)
    async def heroclass(self, ctx, clz:str=None, action:str=None):
        """This allows you to select a class.
            You need to be level 10 to select one.
            For information on class use: !heroclass "classname" info
        """
        global users
        classes = {'Tinkerer': {'name': "Tinkerer", 'ability': False, 'desc': "Tinkerers can forge two different items into a device bound to their very soul.\n Use !forge."},
                    'Berserker':{'name': "Berserker", 'ability': False, 'desc': "Berserker have the option to rage and add big bonuses to attacks, but fumbles hurt.\n Use !rage when attacking in an adventure."},
                    'Cleric': {'name': "Cleric", 'ability': False, 'desc': "Clerics can bless the entire group when praying.\n Use !bless when fighting in an adventure."},
                    'Ranger': {'name': "Ranger", 'ability': False, 'desc': "Rangers can gain a special pet, which can find items and give reward bonuses.\n Use !pet."},
                    'Bard': {'name': "Bard", 'ability': False, 'desc': "Bards can perform to aid their comrades in diplomacy.\n Use !sing when being diplomatic in an adventure."}}
        user = ctx.author
        if clz == None:
            ctx.command.reset_cooldown(ctx)
            await ctx.send("So you feel like taking on a class, **{}**?\nAvailable classes are: Tinkerer, Berserker, Cleric, Ranger and Bard.\n Use !heroclass \"name-of-class\" to choose one.".format(user.display_name))
        else:
            clz = clz[:1].upper() + clz[1:]
            if clz in classes and action == None:
                if users[str(user.id)]['lvl'] >= 10:
                    if 'name' in users[str(user.id)]['class']:
                        if users[str(user.id)]['class']['name'] == 'Tinkerer' or users[str(user.id)]['class']['name'] == 'Ranger':
                            curclass = users[str(user.id)]['class']['name']
                            if curclass == 'Tinkerer':
                                msg = await ctx.send("```css\n You will loose your forged device if you change your class.\nShall I proceed? ```")
                            else:
                                msg = await ctx.send("```css\n You will loose your pet if you change your class.\nShall I proceed? ```")
                            start_adding_reactions(msg, ReactionPredicate.YES_OR_NO_EMOJIS)
                            pred = ReactionPredicate.yes_or_no(msg, ctx.author)
                            await ctx.bot.wait_for("reaction_add", check=pred)
                            try:
                                await msg.delete()
                            except discord.Forbidden:  # cannot remove message try remove emojis
                                for key in ReactionPredicate.YES_OR_NO_EMOJIS:
                                    await msg.remove_reaction(key, ctx.bot.user)
                            if pred.result: #user reacted with Yes.
                                if curclass == 'Tinkerer':
                                    await GobCog.sub_unequip(ctx,"{.:'")
                                    if any([x for x in users[str(user.id)]['items']['backpack'] if "{.:'" in x.lower()]):
                                        lookup = list(x for x in users[str(user.id)]['items']['backpack'] if "{.:'" in x.lower())
                                        for item in lookup:
                                            del users[str(user.id)]['items']['backpack'][item]
                                            await ctx.send('```css\n {} has run off to find a new master. ```'.format(', '.join(lookup)))
                            else:
                                ctx.command.reset_cooldown(ctx)
                                return
                    users[str(user.id)]['class'] = {}
                    users[str(user.id)]['class'] = classes[clz]
                    await ctx.send("Congratulations. You are now a {}.".format(classes[clz]['name']))
                    with GobCog.fp.open('w') as f:
                        json.dump(users, f)
                else:
                    ctx.command.reset_cooldown(ctx)
                    await ctx.send("You need to be at least level 10 to choose a class.")
            elif clz in classes and action == "info":
                ctx.command.reset_cooldown(ctx)
                await ctx.send("{}".format(classes[clz]['desc']))
            else:
                ctx.command.reset_cooldown(ctx)
                await ctx.send("{} may be a class somewhere, but not on my watch.".format(clz))

    @commands.command()
    @commands.guild_only()
    async def skill(self, ctx, spend:str=None):
        """This allows you to spend skillpoints.
            !skill attack/diplomacy
        """
        global users
        user = ctx.author
        if users[str(user.id)]['skill']['pool'] == 0:
            return await ctx.send("You do not have unspent skillpoints.")
        if spend == None:
            await ctx.send("You currently have **{}** unspent skillpoints.\nIf you want to put them towards a permanent attack or diplomacy bonus,\nuse !skill attack or !skill diplomacy".format(str(users[str(user.id)]['skill']['pool'])))
        else:
            if spend not in ['attack','diplomacy']:
                return await ctx.send("Don't try to fool me! There is no such thing as {}.".format(spend))
            elif spend == "attack":
                users[str(user.id)]['skill']['pool'] -= 1
                users[str(user.id)]['skill']['att'] += 1
            elif spend == "diplomacy":
                users[str(user.id)]['skill']['pool'] -= 1
                users[str(user.id)]['skill']['cha'] += 1
            await ctx.send("You permanently raised your {} value by one.".format(spend))
            with GobCog.fp.open('w') as f:
                json.dump(users, f)

    @commands.command()
    @commands.guild_only()
    async def loot(self, ctx, type: str="normal"):
        """This opens one of your precious treasure chests.
            (If you have rare or epic chests, type "rare" or
            "epic" after the command to open those.)
        """
        if type == "normal":
            redux = [1,0,0]
        elif type == "rare":
            redux = [0,1,0]
        elif type == "epic":
            redux = [0,0,1]
        else:
            await ctx.send("There is talk of a {} treasure chest but nobody ever saw one.".format(type))
            return
        global users
        user = ctx.author
        if not 'treasure' in users[str(user.id)].keys():
            users[str(user.id)]['treasure'] = [0,0,0]
        treasure = users[str(user.id)]['treasure'][redux.index(1)]
        if treasure == 0:
            await ctx.send("You have no {} treasure chest to open.".format(type))
        else:
            item = await Treasure.open_chest(ctx, user, type)
            users[str(user.id)]['treasure'] = [x-y for x,y in zip(users[str(user.id)]['treasure'], redux)]
            if item['equip'] == "sell":
                price = random.randint(10,1000)*max(item['item']['att']+item['item']['cha'],1)
                await bank.deposit_credits(user, price)
                await ctx.send("{} sold the {} for {} copperpieces.".format(user.display_name,item['itemname'],price))
            elif item['equip'] == "equip":
                equip = {"itemname": item['itemname'],"item": item['item']}
                await self.equip_item(ctx, equip, False)
            else:
                users[str(user.id)]['items']['backpack'].update({item['itemname']: item['item']})
                await ctx.send("{} put the {} into the backpack.".format(user.display_name,item['itemname']))

    @commands.command()
    @commands.guild_only()
    async def stats(self, ctx, user: discord.Member=None):
        """This draws up a charsheet of you or an optionally specified member.
            !stats @locastan
            will bring up locastans stats.
            !stats without user will open your stats.
        """
        if user is None:
            user = ctx.author
        if user.bot:
            return
        bal = await bank.get_balance(user)
        currency = await bank.get_currency_name(ctx.guild)
        global users
        xp = round(users[str(user.id)]['exp'])
        lvl = users[str(user.id)]['lvl']
        att = users[str(user.id)]['att']
        satt = users[str(user.id)]['skill']['att']
        cha = users[str(user.id)]['cha']
        scha = users[str(user.id)]['skill']['cha']
        pool = users[str(user.id)]['skill']['pool']
        equip = "Equipped Items: \n"
        i = iter(users[str(user.id)]['items'])
        for slot in i:
            if users[str(user.id)]['items'][slot] and slot != "backpack":
                item = list(users[str(user.id)]['items'][slot].keys())[0]
                if len(users[str(user.id)]['items'][slot][item]['slot']) == 1:
                    equip += " - " + item + " - (ATT: "+ str(users[str(user.id)]['items'][slot][item]['att']) + " | CHA: "+ str(users[str(user.id)]['items'][slot][item]['cha']) +" ["+ users[str(user.id)]['items'][slot][item]['slot'][0] + " slot])\n"
                else:
                    equip += " - " + item + " -(ATT: "+ str(users[str(user.id)]['items'][slot][item]['att']*2) + " | CHA: "+ str(users[str(user.id)]['items'][slot][item]['cha']*2) +" [two handed])\n"
                    next(i, None)
        next_lvl = int((lvl+1) ** 4)
        if users[str(user.id)]['class'] != {} and 'name' in users[str(user.id)]['class']:
            clazz = users[str(user.id)]['class']['name'] + "\n" + users[str(user.id)]['class']['desc']
        else:
            clazz = "Hero."
        await ctx.send(
            "```css\n[{}'s Character Sheet] \n\n```".format(user.display_name) + "```css\nA level {} {} \n\n- ATTACK: {} [+{}] - DIPLOMACY: {} [+{}] -\n\n- Credits: {} {} \n- Experience: {}/{} \n- Unspent skillpoints: {} \n```".format(
                lvl, clazz, att, satt, cha, scha, bal, currency, xp, next_lvl, pool
            ) + "```css\n" + equip + "```" +
            "```css\n" + "You own {} normal, {} rare and {} epic chests.```".format(
                str(users[str(user.id)]['treasure'][0]),str(users[str(user.id)]['treasure'][1]),str(users[str(user.id)]['treasure'][2]))
        )

    @commands.command()
    @commands.guild_only()
    async def backpack(self, ctx, switch: str="None", item: str="None", asking: int=10, buyer: discord.Member=None):
        """This draws up the contents of your backpack.
            Selling: !backpack sell "(partial) name of item"
            Trading: !backpack trade "name of item" cp @buyer
            Equip:   !backpack equip "(partial) name of item"
            or respond with "name of item" to backpack.
        """
        user = ctx.author
        if user.bot:
            return
        global users
        bkpk = "Items in Backpack: \n"
        if switch == "None":
            for item in users[str(user.id)]['items']['backpack']: # added second if level for two handed weapons so their slots show properly.
                if len(users[str(user.id)]['items']['backpack'][item]['slot']) == 1:
                    bkpk += " - " + item + " - (ATT: "+ str(users[str(user.id)]['items']['backpack'][item]['att']) + " | DPL: "+ str(users[str(user.id)]['items']['backpack'][item]['cha']) +" ["+ users[str(user.id)]['items']['backpack'][item]['slot'][0] + " slot])\n"
                else:
                    bkpk += " - " + item + " -(ATT: "+ str(users[str(user.id)]['items']['backpack'][item]['att']*2) + " | DPL: "+ str(users[str(user.id)]['items']['backpack'][item]['cha']*2) +" [two handed])\n"
            await ctx.send(
                "```css\n[{}'s baggage] \n\n```".format(
                    user.display_name
                ) + "```css\n" + bkpk + "\n (Reply with the name of an item or use !backpack equip \"name of item\" to equip it.)```"
            )
            try:
                reply = await ctx.bot.wait_for("message", check=MessagePredicate.same_context(ctx), timeout=30)
            except asyncio.TimeoutError:
                return
            if not reply:
                return
            else:
                if not " sell " in reply.content.lower() and not " trade " in reply.content.lower():
                    equip = {}
                    for item in users[str(user.id)]['items']['backpack']:
                        if reply.content.lower() in item:
                            equip = {"itemname": item,"item": users[str(user.id)]['items']['backpack'][item]}
                            break
                    if equip != {}: #not good to change dict size during iteration so I moved this outside the for loop.
                        await self.equip_item(ctx, equip, True)
        elif switch == "equip":
            if item == "None" or not any([x for x in users[str(user.id)]['items']['backpack'] if item in x.lower()]):
                await ctx.send("You have to specify an item from your backpack to equip.")
                return
            lookup = list(x for x in users[str(user.id)]['items']['backpack'] if item in x.lower())
            if len(lookup) > 1:
                await ctx.send("I found multiple items ({}) matching that name in your backpack.\nPlease be more specific.".format(" and ".join([", ".join(lookup[:-1]),lookup[-1]] if len(lookup) > 2 else lookup)))
                return
            else:
                item = lookup[0]
                equip = {"itemname": item,"item": users[str(user.id)]['items']['backpack'][item]}
                await self.equip_item(ctx, equip, True)
        elif switch == "sell": #new logic allows for bulk sales. It also always confirms the sale by yes/no query to avoid accidents.
            if item == "None" or not any([x for x in users[str(user.id)]['items']['backpack'] if item in x.lower()]):
                await ctx.send("You have to specify an item (or partial name) from your backpack to sell.")
                return
            lookup = list(x for x in users[str(user.id)]['items']['backpack'] if item in x.lower())
            if any([x for x in lookup if "{.:'" in x.lower()]):
                device = [x for x in lookup if "{.:'" in x.lower()]
                await ctx.send("```css\n Your {} is refusing to be sold and bit your finger for trying. ```".format(device))
                return
            msg = await ctx.send("Do you want to sell these items {}?".format(str(lookup)))
            start_adding_reactions(msg, ReactionPredicate.YES_OR_NO_EMOJIS)
            pred = ReactionPredicate.yes_or_no(msg, buyer)
            await ctx.bot.wait_for("reaction_add", check=pred)
            try:
                await msg.delete()
            except discord.Forbidden:  # cannot remove message try remove emojis
                for key in ReactionPredicate.YES_OR_NO_EMOJIS:
                    await msg.remove_reaction(key, ctx.bot.user)
            if pred.result: #user reacted with Yes.
                for item in lookup:
                    price = random.randint(10,1000)*max(users[str(user.id)]['items']['backpack'][item]['att']+users[str(user.id)]['items']['backpack'][item]['cha'],1)
                    await bank.deposit_credits(user, price)
                    del users[str(user.id)]['items']['backpack'][item]
                    await ctx.send("You sold your {} for {} copperpieces.".format(item,price))
                    with GobCog.fp.open('w') as f:
                        json.dump(users, f)
        elif switch == "trade":
            if item == "None" or not any([x for x in users[str(user.id)]['items']['backpack'] if item in x.lower()]):
                await ctx.send("You have to specify an item from your backpack to trade.")
                return
            lookup = list(x for x in users[str(user.id)]['items']['backpack'] if item in x.lower())
            if len(lookup) > 1:
                await ctx.send("I found multiple items ({}) matching that name in your backpack.\nPlease be more specific.".format(" and ".join([", ".join(lookup[:-1]),lookup[-1]] if len(lookup) > 2 else lookup)))
                return
            if any([x for x in lookup if "{.:'" in x.lower()]):
                device = [x for x in lookup if "{.:'" in x.lower()]
                await ctx.send("```css\n Your {} does not want to leave you. ```".format(device))
                return
            else:
                item = lookup[0]
                if len(users[str(user.id)]['items']['backpack'][item]["slot"]) == 2: # two handed weapons add their bonuses twice
                    hand = "two handed"
                    att = users[str(user.id)]['items']['backpack'][item]["att"]*2
                    cha = users[str(user.id)]['items']['backpack'][item]["cha"]*2
                else:
                    if users[str(user.id)]['items']['backpack'][item]["slot"][0] == "right" or users[str(user.id)]['items']['backpack'][item]["slot"][0] == "left":
                        hand = users[str(user.id)]['items']['backpack'][item]["slot"][0] + " handed"
                    else:
                        hand = users[str(user.id)]['items']['backpack'][item]["slot"][0] + " slot"
                    att = users[str(user.id)]['items']['backpack'][item]["att"]
                    cha = users[str(user.id)]['items']['backpack'][item]["cha"]
                await ctx.send("{} wants to sell his {}. (Attack: {}, Charisma: {} [{}])".format(user.display_name,item,str(att),str(cha),hand))
                msg = await ctx.send("Do you want to buy this item for {} cp?".format(str(asking)))
                start_adding_reactions(msg, ReactionPredicate.YES_OR_NO_EMOJIS)
                pred = ReactionPredicate.yes_or_no(msg, buyer)
                await ctx.bot.wait_for("reaction_add", check=pred)
                try:
                    await msg.delete()
                except discord.Forbidden:  # cannot remove message try remove emojis
                    for key in ReactionPredicate.YES_OR_NO_EMOJIS:
                        await msg.remove_reaction(key, ctx.bot.user)
                if pred.result: #buyer reacted with Yes.
                    spender = buyer
                    to = user
                    if await bank.can_spend(spender,asking):
                        bal = await bank.transfer_credits(spender, to, asking)
                        currency = await bank.get_currency_name(ctx.guild)
                        tradeitem = users[str(user.id)]['items']['backpack'].pop(item)
                        users[str(buyer.id)]['items']['backpack'].update({item: tradeitem})
                        with GobCog.fp.open('w') as f:
                            json.dump(users, f)
                        await ctx.send(
                            "```css\n" + "{} traded to {} for {} {}```".format(
                                item, buyer.display_name, asking, currency
                            ))
                    else:
                        await ctx.send("You do not have enough copperpieces.")

    @commands.command()
    @commands.guild_only()
    async def give(self, ctx, amount: int=1, to: discord.Member=None):
        """This will transfer cp from you to a specified member.
            !give 10 @Elder Aramis
            will transfer 10 cp to Elder Aramis.
        """
        if to is None:
            await ctx.send("You need to specify who you want me to give your money to, " + ctx.author.name + ".")
        spender = ctx.author
        if await bank.can_spend(spender,amount):
            bal = await bank.transfer_credits(spender, to, amount)
        currency = await bank.get_currency_name(ctx.guild)
        await ctx.send(
            "```You transferred {3} {2}. {0} now has {1} {2}```".format(
                to.display_name, bal, currency, amount
            )
        )

    @commands.command()
    @checks.admin_or_permissions(administrator=True)
    async def fund(self, ctx, amount: int=1, to: discord.Member=None):
        """This will create cp for a specified member.
            !fund 10 @Elder Aramis
            will create 10 cp and add to Elder Aramis.
        """
        if to is None:
            return await ctx.send("You need to specify a receiving member, " + ctx.author.name + ".")
        member = discord.utils.find(lambda m: m.name == to, ctx.guild.members)
        if member == None:
            return await ctx.send("I could not find that user, " + ctx.author.name + ".")
        bal = await bank.deposit_credits(to, amount)
        currency = await bank.get_currency_name(ctx.guild)
        await ctx.send(
            "```You funded {3} {2}. {0} now has {1} {2}```".format(
                to.display_name, bal, currency, amount
            )
        )

    @commands.command(name="adventure", aliases=['a'])
    @commands.guild_only()
    @commands.cooldown(rate=1, per=120, type=commands.BucketType.guild)
    async def _adventure(self, ctx):
        """This will send you on an adventure!
            You play by reacting with the offered emojis.
        """
        global users
        await ctx.send("You feel adventurous, " + ctx.author.display_name + "?")
        reward, participants = await Adventure.simple(ctx, users) #Adventure class doesn't change any user info, so no need to return the users object in rewards.
        if reward is not None:
            print(reward, participants)
            for user in reward.keys():
                member = discord.utils.find(lambda m: m.display_name == user, ctx.guild.members)
                await self.add_rewards(ctx, member, reward[user]["xp"], reward[user]["cp"], reward[user]["special"])
            for user in participants: #reset activated abilities
                member = discord.utils.find(lambda m: m.display_name == user, ctx.guild.members)
                if 'name' in users[str(member.id)]['class']:
                    if users[str(member.id)]['class']['name'] != "Ranger" and users[str(member.id)]['class']['ability']:
                        users[str(member.id)]['class']['ability'] = False
            with GobCog.fp.open('w') as f:
                json.dump(users, f)

    @commands.command(name="negaverse", aliases=['nv'])
    @commands.guild_only()
    @commands.cooldown(rate=1, per=60, type=commands.BucketType.user)
    async def _negaverse(self, ctx, amount: int = None):
        """This will send you to fight a nega-member!
            !nv amount_of_cp
        """
        spender = ctx.message.author
        if amount == None:
            return await ctx.send("You need to specify some cp to convert into energy before entering.")
        if await bank.can_spend(spender,amount):
            await bank.withdraw_credits(spender, amount)
        else:
            return await ctx.send("You don't have enough copperpieces.")
        negachar = "**Nega-" + random.choice(ctx.message.guild.members).name + "**"
        await ctx.send("You enter the negaverse and meet " + negachar + ".")
        roll = random.randint(1,20)
        versus = random.randint(1,20)
        if roll== 1:
            await ctx.send("**" + ctx.author.name + "**" + " fumbled and died to " + negachar + "'s savagery.")
        elif roll == 20:
            await ctx.send("**" + ctx.author.name + "**" + " decapitated " + negachar + ". You gain {} xp and {} cp.".format(amount*2, amount))
            await self.add_rewards(ctx, ctx.message.author, amount*2, amount, False)
        elif roll > versus:
            await ctx.send("**" + ctx.author.name + "** 🎲({})".format(roll) + " bravely defeated " + negachar + " 🎲({}). You gain {} xp.".format(versus, amount))
            await self.add_rewards(ctx, ctx.message.author, amount, 0, False)
        elif roll == versus:
            await ctx.send("**" + ctx.author.name + "** 🎲({})".format(roll) + " almost killed " + negachar + " 🎲({}).".format(versus))
        else:
            await ctx.send("**" + ctx.author.name + "** 🎲({})".format(roll) + " was killed by " + negachar + " 🎲({}).".format(versus))

    async def __error(self, ctx: commands.Context, error):
        if isinstance(error, commands.CommandOnCooldown):
            m, s = divmod(error.retry_after, 60)
            h, m = divmod(m, 60)
            s = int(s)
            m = int(m)
            h = int(h)
            if h == 0 and m == 0:
                out = "{:02d}s".format(s)
            elif h == 0:
                out = "{:02d}:{:02d}s".format(m, s)
            else:
                out = "{:01d}:{:02d}:{:02d}s".format(h, m, s)
            if h == 0 and m < 3:
                await Adventure.countdown(ctx, error.retry_after, "I feel a little tired now. !{} is available again in: ".format(ctx.command.qualified_name))
            else:
                await ctx.send("⏳ " + "Don't be hasty, {}. You can use !{} again in: ".format(ctx.author.display_name, ctx.command.qualified_name) + out)
        else:
            pass

    async def on_message(self, message):
        global users
        if not message.author.bot:
            await self.update_data(users, message.author)
            if GobCog.last_trade == 0: #this shuts hawls bro up for 3 hours after a cog reload
                GobCog.last_trade = time.time()
            roll = random.randint(1,20)
            if roll == 20:
                ctx = await self.bot.get_context(message)
                await self.trader(ctx)

    async def on_member_join(self, member):
        global users
        await self.update_data(users, member)

        with GobCog.fp.open('w') as f:
            json.dump(users, f)

    @staticmethod
    async def equip_item(ctx, item, from_backpack):
        global users
        user = ctx.author
        if not 'items' in users[str(user.id)].keys(): # if the user has an older account or something went wrong, create empty items slot.
            users[str(user.id)]['items'] = {"left":{},"right":{},"ring":{},"charm":{},"backpack": {}}
        for slot in item['item']["slot"]:
            if users[str(user.id)]['items'][slot] == {}:
                users[str(user.id)]['items'][slot][item['itemname']] = item['item']
                users[str(user.id)]['att'] += item['item']['att']
                users[str(user.id)]['cha'] += item['item']['cha']
                await ctx.send("You equipped {}.".format(item['itemname']))
            else:
                olditem = users[str(user.id)]['items'][slot]
                for oslot in olditem[list(olditem.keys())[0]]['slot']:
                    users[str(user.id)]['items'][oslot] = {}
                    users[str(user.id)]['att'] -= olditem[list(olditem.keys())[0]]['att']     # keep in mind that double handed items grant their bonus twice so they remove twice
                    users[str(user.id)]['cha'] -= olditem[list(olditem.keys())[0]]['cha']
                users[str(user.id)]['items']['backpack'].update(olditem)
                users[str(user.id)]['items'][slot][item['itemname']] = item['item']
                users[str(user.id)]['att'] += item['item']['att']
                users[str(user.id)]['cha'] += item['item']['cha']
                await ctx.send("You equipped {} and put {} into your backpack.".format(item['itemname'],list(olditem.keys())[0]))
        if from_backpack:
            del users[str(user.id)]['items']['backpack'][item['itemname']]
        await ctx.send("Your new stats: **Attack**: {} [+{}], **Diplomacy**: {} [+{}].".format(users[str(user.id)]['att'],users[str(user.id)]['skill']['att'],users[str(user.id)]['cha'],users[str(user.id)]['skill']['cha']))
        with GobCog.fp.open('w') as f:
            json.dump(users, f)

    @staticmethod
    async def update_data(users, user):
        if str(user.id) not in users:
            print('Setting up account for', user.display_name + '.')
            users[str(user.id)] = {}
            users[str(user.id)]['exp'] = 0
            users[str(user.id)]['lvl'] = 1
            users[str(user.id)]['att'] = 0
            users[str(user.id)]['cha'] = 0
            users[str(user.id)]['treasure'] = [0,0,0]
            users[str(user.id)]['items'] = {"left":{},"right":{},"ring":{},"charm":{},"backpack": {}}
            users[str(user.id)]['name'] = {}
            users[str(user.id)]['name'] = user.display_name
            users[str(user.id)]['class'] = {}
            users[str(user.id)]['class'] = {'name': "Hero", 'ability': False, 'desc': "Your basic adventuring hero."}
            users[str(user.id)]['skill'] = {}
            users[str(user.id)]['skill'] = {'pool': 0, 'att': 0, 'cha': 0}
            with GobCog.fp.open('w') as f:
                json.dump(users, f)

    @staticmethod
    async def add_rewards(ctx, user, exp, cp, special):
        global users
        users[str(user.id)]['exp'] += exp
        await bank.deposit_credits(user, cp)
        await GobCog.level_up(ctx, users, user)
        if special != False:
            if not 'treasure' in users[str(user.id)].keys():
                users[str(user.id)]['treasure'] = [0,0,0]
            users[str(user.id)]['treasure'] = [sum(x) for x in zip(users[str(user.id)]['treasure'], special)]

        with GobCog.fp.open('w') as f:
            json.dump(users, f)

    @staticmethod
    async def level_up(ctx, users, user):
        exp = users[str(user.id)]['exp']
        lvl_start = users[str(user.id)]['lvl']
        lvl_end = int(exp ** (1/4))

        if lvl_start < lvl_end: #recalculate free skillpoint pool based on new level and already spent points.
            await ctx.send('{} is now level {}!'.format(user.mention,lvl_end))
            users[str(user.id)]['lvl'] = lvl_end
            users[str(user.id)]['skill']['pool'] = int(lvl_end / 5) - (users[str(user.id)]['skill']['att']+users[str(user.id)]['skill']['cha'])
            if users[str(user.id)]['skill']['pool'] > 0:
                await ctx.send('You have skillpoints available.')

    @staticmethod
    async def trader(ctx):

        async def handle_buy(itemindex, user, stock, msg):
            global users
            item = stock[itemindex]
            spender = user
            react = None
            if await bank.can_spend(spender,int(item['price'])):
                await bank.withdraw_credits(spender, int(item['price']))
                if 'chest' in item['itemname']:
                    if item['itemname'] == ".rare_chest":
                        users[str(user.id)]['treasure'][1] += 1
                    elif item['itemname'] == "[epic chest]":
                        users[str(user.id)]['treasure'][2] += 1
                    else:
                        users[str(user.id)]['treasure'][0] += 1
                else:
                    users[str(user.id)]['items']['backpack'].update({item['itemname']: item['item']})
                with GobCog.fp.open('w') as f:
                    json.dump(users, f)
                await ctx.send("{} bought the {} for {} cp and put it into the backpack.".format(user.display_name,item['itemname'],str(item['price'])))
            else:
                await ctx.send("You do not have enough copperpieces.")
            try:
                timeout = GobCog.last_trade+1200-time.time()
                if timeout <= 0:
                    timeout = 0
                react, user = await ctx.bot.wait_for(
                    "reaction_add",
                    check=CustomPredicate.with_emojis(tuple(controls.keys()), msg),
                    timeout=timeout
                )
            except asyncio.TimeoutError:  #the timeout only applies if no reactions are made!
                try:
                    await msg.delete()
                except discord.Forbidden:  # cannot remove all reactions
                    for key in controls.keys():
                        await message.remove_reaction(key, ctx.bot.user)
            if react != None and user:
                await handle_buy(controls[react.emoji], user, stock, msg)

        em_list = ReactionPredicate.NUMBER_EMOJIS[:5]
        react = False
        controls = {em_list[1]: 0, em_list[2]: 1, em_list[3]: 2, em_list[4]: 3}
        modRole = discord.utils.get(ctx.guild.roles, name='Goblin Adventurer!')
        if modRole is not None:
            text = modRole.mention + "\n" + "```css\n [Hawls brother is bringing the cart around!]```"
        else:
            text = "```css\n [Hawls brother is bringing the cart around!]```"
        if GobCog.last_trade == 0:
            GobCog.last_trade = time.time()
        elif GobCog.last_trade >= time.time()-10800: #trader can return after 3 hours have passed since last visit.
            print("Last Trade Visit: {}, current time: {}".format(str(GobCog.last_trade), str(time.time())))
            return #silent return.
        GobCog.last_trade = time.time()
        stock = await Treasure.trader_get_items()
        for index, item in enumerate(stock):
            item = stock[index]
            if "chest" not in item['itemname']:
                if len(item['item']["slot"]) == 2: # two handed weapons add their bonuses twice
                    hand = "two handed"
                    att = item['item']["att"]*2
                    cha = item['item']["cha"]*2
                else:
                    if item['item']["slot"][0] == "right" or item['item']["slot"][0] == "left":
                        hand = item['item']["slot"][0] + " handed"
                    else:
                        hand = item['item']["slot"][0] + " slot"
                    att = item['item']["att"]
                    cha = item['item']["cha"]
                text += "```css\n" + "[{}] {} (Attack: {}, Charisma: {} [{}]) for {} cp.".format(str(index+1),item['itemname'],str(att),str(cha),hand,item['price'])+ " ```"
            else:
                text += "```css\n" + "[{}] {} for {} cp.".format(str(index+1),item['itemname'],item['price'])+ " ```"
        text += "Do you want to buy any of these fine items? Tell me which one below:"
        msg = await ctx.send(text)
        Adventure.start_adding_reactions(msg, controls.keys(), ctx.bot.loop)
        try:
            timeout = GobCog.last_trade+1200-time.time()
            if timeout <= 0:
                timeout = 0
            Treasure.countdown(ctx, timeout, "The cart will leave in: ") #need unique countdown or else adventure countdown will overwrite the ticker...
            react, user = await ctx.bot.wait_for(
                "reaction_add",
                check=CustomPredicate.with_emojis(tuple(controls.keys()), msg),
                timeout=timeout
            )
        except asyncio.TimeoutError:  #the timeout only applies if no reactions are made!
            try:
                await msg.delete()
            except discord.Forbidden:  # cannot remove all reactions
                for key in controls.keys():
                    await message.remove_reaction(key, ctx.bot.user)
        if react and user:
            await handle_buy(controls[react.emoji], user, stock, msg)


#Copyright 2015 Phoenix Bioinformatics Corporation. All rights reserved.

from django.conf.urls import patterns, include, url
from django.contrib import admin
from rest_framework import routers

router = routers.DefaultRouter()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include(router.urls)),
    url(r'^meters/', include('metering.urls')),
    url(r'^parties/', include('party.urls')),
    url(r'^subscriptions/', include('subscription.urls')),
    url(r'^authorizations/', include('authorization.urls')),
    url(r'^partners/', include('partner.urls')),
    url(r'^session-logs/', include('loggingapp.urls')),
    url(r'^credentials/', include('authentication.urls', namespace="authentication")),
    url(r'^apikeys/', include('apikey.urls')),
    url(r'^cookies/', include('cookies.urls')),
)