import FWCore.ParameterSet.Config as cms
process = cms.Process('myprocess')
process.TFileService=cms.Service("TFileService",fileName=cms.string('flatTree.root'))
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff')
process.GlobalTag.globaltag = '80X_dataRun2_Prompt_ICHEP16JEC_v0'
##-------------------- Define the source  ----------------------------
process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(-1))
process.source = cms.Source("PoolSource",
  fileNames = cms.untracked.vstring(
    "/store/data/Run2016D/SingleMuon/MINIAOD/23Sep2016-v1/010000/249B6517-C79B-E611-A51E-7845C4F91621.root"
    )
)
#############   Format MessageLogger #################
process.load('FWCore.MessageService.MessageLogger_cfi')
process.MessageLogger.cerr.FwkReport.reportEvery = 1000

#############   JEC #################
#process.load("CondCore.DBCommon.CondDBCommon_cfi")
#from CondCore.DBCommon.CondDBSetup_cfi import *
#process.jec = cms.ESSource("PoolDBESSource",
#      DBParameters = cms.PSet(
#        messageLevel = cms.untracked.int32(0)
#        ),
#      timetype = cms.string('runnumber'),
#      toGet = cms.VPSet(
#        cms.PSet(
#            record = cms.string('JetCorrectionsRecord'),
#            tag    = cms.string('JetCorrectorParametersCollection_Spring16_25nsV3_DATA_AK4PFchs'),
#            label  = cms.untracked.string('AK4PFchs')
#        ),
#        cms.PSet(
#            record = cms.string('JetCorrectionsRecord'),
#            tag    = cms.string('JetCorrectorParametersCollection_Spring16_25nsV3_DATA_AK8PFchs'),
#            label  = cms.untracked.string('AK8PFchs')
#        )
#      ),
#      connect = cms.string('sqlite:Spring16_25nsV3_DATA.db')
#)
## add an es_prefer statement to resolve a possible conflict from simultaneous connection to a global tag
#process.es_prefer_jec = cms.ESPrefer('PoolDBESSource','jec')

process.load("PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff")
process.patJetCorrFactorsReapplyJEC = process.updatedPatJetCorrFactors.clone(
  src = cms.InputTag("slimmedJets"),
  levels = ['L1FastJet','L2Relative','L3Absolute','L2L3Residual'],
  payload = 'AK4PFchs'
)

process.load("PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff")
process.patJetsReapplyJEC = process.updatedPatJets.clone(
  jetSource = cms.InputTag("slimmedJets"),
  jetCorrFactorsSource = cms.VInputTag(cms.InputTag("patJetCorrFactorsReapplyJEC"))
)

process.patJetCorrFactorsReapplyJECAK8 = process.updatedPatJetCorrFactors.clone(
  src = cms.InputTag("slimmedJetsAK8"),
  levels = ['L1FastJet','L2Relative','L3Absolute','L2L3Residual'],
  payload = 'AK8PFchs'
)

process.load("PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff")
process.patJetsReapplyJECAK8 = process.updatedPatJets.clone(
  jetSource = cms.InputTag("slimmedJetsAK8"),
  jetCorrFactorsSource = cms.VInputTag(cms.InputTag("patJetCorrFactorsReapplyJECAK8"))
)

from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
process.goodJets = selectedPatJets.clone(src='patJetsReapplyJEC',cut='pt>30 & abs(eta)<2.4')

##-------------------- User analyzer  --------------------------------
process.vv = cms.EDAnalyzer('VVFlatTreeProducer',
  jets             = cms.InputTag('patJetsReapplyJEC'),
  muons            = cms.InputTag('slimmedMuons'),
  electrons        = cms.InputTag('slimmedElectrons'),
  met              = cms.InputTag('slimmedMETs'),
  candidates       = cms.InputTag('packedPFCandidates'),
  vertices         = cms.InputTag('offlineSlimmedPrimaryVertices'),
  rho              = cms.InputTag('fixedGridRhoFastjetAll'),
  ptMin            = cms.double(40),
  etaMax           = cms.double(2.4),
  minMuPt          = cms.double(20),
  minElPt          = cms.double(20),
  btagMin          = cms.double(0.8),
  btagger          = cms.string('pfCombinedInclusiveSecondaryVertexV2BJetTags'),
  triggerNames     = cms.vstring(
    'HLT_IsoMu22_v*'
  ),
  triggerResults   = cms.InputTag('TriggerResults','','HLT'),
  triggerPrescales = cms.InputTag('patTrigger')
)

process.p = cms.Path(
   process.patJetCorrFactorsReapplyJEC +
   process.patJetsReapplyJEC +
   process.vv
)


import os
import tools.binary as BIN

pf = '../../content/CoCo/Daggorath/rompatch.txt'

dr = os.path.dirname(pf)

lines = []
with open('../../content/CoCo/Daggorath/rompatch.txt') as f:
    for g in f:
        if ';' in g:
            g = g[0:g.index(';')]
        g = g.strip()
        if g:
            lines.append(g)

first = lines[0].split(' ')

with open(os.path.join(dr,first[0]),'rb') as f:
    data = list(f.read())

for line in lines[1:]:
    org,dat = BIN.line_to_data(line)
    if dat:
        p = org - int(first[2],16)
        print(p,len(dat))
        for b in dat:
            data[p] = b
            p+=1

with open(os.path.join(dr,first[1]),'wb') as f:
    f.write(bytes(data))


import time
import sys
import math

n=int(sys.argv[1])

T1 = time.perf_counter()

document=open(sys.argv[2],'w')

nietpriem = set()
priem = []
for i in range(2, n):
    if i in nietpriem:
        continue
    for j in range(i*i, n+1, i):
        nietpriem.add(j)
    priem.append(i)

document.write("\n".join(map(str, priem)))
document.close()

T2 = time.perf_counter()

print(str(len(priem)), 'priemgetallen gevonden in ', T2 - T1, 'seconden')


names_to_ages = {"Bill": 21, "Jane": 34, "Sven": 56}

# d = {name: age for name, age in names_to_ages.items() if name[0] == "S"}
#
# print(d)
# # for name in names_to_ages:
# #     names_to_ages[name] += 1
# #     print(name, names_to_ages[name])
# #
# #
# # for name, age in names_to_ages.items():
# #     print(name, age)
#
#
# # words = ["a", "b", "a"]
# # word_to_count = {}
# # for word in words:
# #     if word in word_to_count:
# #         word_to_count[word] += 1
# #     else:
# #         word_to_count[word] = 1
# #
# #
# # word_to_count = {}
# # for word in words:
# #     try:
# #         word_to_count[word] += 1
# #     except KeyError:
# #         word_to_count[word] = 1

def find_older(people, threshold_age):
    old_people = []
    for name, age in people.items():
        if age >= threshold_age:
            old_people.append(name)
    # return old_people
    return [name for name, age in people.items() if age >= threshold_age]

# print(find_older(names_to_ages, 50))

class LindsayList(list):
    def whatever(self):
        print("whatever")

my_list = list()
print(my_list)
my_list.append('a')

my_lindsay_list = LindsayList()
print(my_lindsay_list)
my_lindsay_list.append('b')
my_lindsay_list.whatever()


import numpy as np, time, h5py, copy, argparse, os, mpi4py.MPI, sys, pipes, shutil
from enlib import enmap, utils, pmat, fft, config, array_ops, map_equation, nmat, errors
from enlib import log, bench, scan
from enlib.cg import CG
from enact import data, nmat_measure, filedb, todinfo

config.default("filedb", "filedb.txt", "File describing the location of the TOD and their metadata")
config.default("todinfo", "todinfo.txt", "File describing location of the TOD id lists")
config.default("map_bits", 32, "Bit-depth to use for maps and TOD")
config.default("downsample", 1, "Factor with which to downsample the TOD")
config.default("map_precon", "bin", "Preconditioner to use for map-making")
config.default("map_cg_nmax", 1000, "Max number of CG steps to perform in map-making")
config.default("verbosity", 1, "Verbosity for output. Higher means more verbose. 0 outputs only errors etc. 1 outputs INFO-level and 2 outputs DEBUG-level messages.")
config.default("task_dist", "size", "How to assign scans to each mpi task. Can be 'plain' for myid:n:nproc-type assignment, 'size' for equal-total-size assignment. The optimal would be 'time', for equal total time for each, but that's not implemented currently.")

parser = config.ArgumentParser(os.environ["HOME"] + "/.enkirc")
parser.add_argument("filelist")
parser.add_argument("area")
parser.add_argument("odir")
parser.add_argument("prefix",nargs="?")
parser.add_argument("-d", "--dump", type=int, default=10)
parser.add_argument("--ncomp",      type=int, default=3)
parser.add_argument("--ndet",       type=int, default=0)
args = parser.parse_args()

precon= config.get("map_precon")
dtype = np.float32 if config.get("map_bits") == 32 else np.float64
comm  = mpi4py.MPI.COMM_WORLD
myid  = comm.rank
nproc = comm.size
nmax  = config.get("map_cg_nmax")

db       = filedb.ACTFiles(config.get("filedb"))
filelist = todinfo.get_tods(args.filelist, config.get("todinfo"))

area = enmap.read_map(args.area)
area = enmap.zeros((args.ncomp,)+area.shape[-2:], area.wcs, dtype)
utils.mkdir(args.odir)
root = args.odir + "/" + (args.prefix + "_" if args.prefix else "")

# Dump our settings
if myid == 0:
	config.save(root + "config.txt")
	with open(root + "args.txt","w") as f:
		f.write(" ".join([pipes.quote(a) for a in sys.argv[1:]]) + "\n")
	with open(root + "env.txt","w") as f:
		for k,v in os.environ.items():
			f.write("%s: %s\n" %(k,v))
	with open(root + "ids.txt","w") as f:
		for id in filelist:
			f.write("%s\n" % id)
	shutil.copyfile(config.get("filedb"), root + "filedb.txt")
# Set up logging
utils.mkdir(root + "log")
logfile   = root + "log/log%03d.txt" % myid
log_level = log.verbosity2level(config.get("verbosity"))
L = log.init(level=log_level, file=logfile, rank=myid)
# And benchmarking
utils.mkdir(root + "bench")
benchfile = root + "bench/bench%03d.txt" % myid

# Read in all our scans
L.info("Reading scans")
tmpinds    = np.arange(len(filelist))[myid::nproc]
myscans, myinds  = [], []
for ind in tmpinds:
	try:
		d = scan.read_scan(filelist[ind])
	except IOError:
		try:
			d = data.ACTScan(db[filelist[ind]])
		except errors.DataMissing as e:
			L.debug("Skipped %s (%s)" % (filelist[ind], e.message))
			continue
	d = d[:,::config.get("downsample")]
	if args.ndet > 0: d = d[:args.ndet]
	myscans.append(d)
	myinds.append(ind)
	L.debug("Read %s" % filelist[ind])

nread = comm.allreduce(len(myscans))
L.info("Found %d tods" % nread)
if nread == 0:
	L.info("Giving up")
	sys.exit(1)

if config.get("task_dist") == "size":
	# Try to get about the same amount of data for each mpi task.
	mycosts = [s.nsamp*s.ndet for s in myscans]
	all_costs = comm.allreduce(mycosts)
	all_inds  = comm.allreduce(myinds)
	myinds_old = myinds
	myinds = [all_inds[i] for i in utils.equal_split(all_costs, nproc)[myid]]
	# And reread the correct files this time. Ideally we would
	# transfer this with an mpi all-to-all, but then we would
	# need to serialize and unserialize lots of data, which
	# would require lots of code.
	if sorted(myinds_old) != sorted(myinds):
		L.info("Rereading shuffled scans")
		myscans = []
		for ind in myinds:
			d = data.ACTScan(db[filelist[ind]])[:,::config.get("downsample")]
			if args.ndet > 0: d = d[:args.ndet]
			myscans.append(d)
			L.debug("Read %s" % filelist[ind])
	else:
		myinds = myinds_old

L.info("Building equation system")
eq  = map_equation.LinearSystemMap(myscans, area, precon=precon)
eq.write(root)
bench.stats.write(benchfile)

L.info("Computing approximate map")
x  = eq.M(eq.b)
bmap = eq.dof.unzip(x)[0]
if myid == 0: enmap.write_map(root + "bin.fits", bmap)

def solve_cg(eq, nmax=1000, ofmt=None, dump_interval=10):
	cg = CG(eq.A, eq.b, M=eq.M, dot=eq.dof.dot)
	while cg.i < nmax:
		with bench.mark("cg_step"):
			cg.step()
		dt = bench.stats["cg_step"]["time"].last
		L.info("CG step %5d %15.7e %6.1f %6.3f" % (cg.i, cg.err, dt, dt/len(eq.scans)))
		xmap, xjunk = eq.dof.unzip(cg.x)
		if ofmt and cg.i % dump_interval == 0 and myid == 0:
			enmap.write_map(ofmt % cg.i, eq.dof.unzip(cg.x)[0])
		# Output benchmarking information
		bench.stats.write(benchfile)
	return cg.x

if nmax > 0:
	L.info("Solving equation")
	x = solve_cg(eq, nmax=nmax, ofmt=root + "map%04d.fits", dump_interval=args.dump)


from tkinter import *
from tkinter.colorchooser import askcolor
from tkinter.filedialog import *
from graph import *
from canvas_gui import *
import random
import pickle
import re

class Window:

    def __init__(self, g = None):
        self.root = Tk()
        self.g = g
        self.default_col_v_fill = StringVar()
        self.default_col_v_outline = StringVar()
        self.default_col_r = StringVar()
        # self.creating = 0
        self.names = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

        self._make_widgets()
        mainloop()

    def _make_widgets(self):
        self.menubar = Menu(self.root)
        self.file_menu = Menu(self.menubar, tearoff=0)
        self.file_menu.add_command(label = 'open', command = self.download)
        self.file_menu.add_command(label = 'save as', command = self.save)
        self.menubar.add_cascade(label = 'file', menu = self.file_menu)

        self.edit_menu = Menu(self.menubar, tearoff=0)
        self.edit_menu.add_command(label = 'new graph', command = self.create_graph)
        self.edit_menu.add_command(label = 'new random graph', command = self.random_graph)
        self.menubar.add_cascade(label = 'edit', menu = self.edit_menu)
        self.root.config(menu=self.menubar)

        self.top_frame = Frame(self.root)
        self.top_frame.grid(row = 0, column = 0,  sticky=(W))

        self.create_button = Button(self.top_frame, text = 'create graph', command = self.create_graph)
        self.create_button.grid(row = 0, column = 0)
        self.random_button = Button(self.top_frame, text = 'random graph', command = self.random_graph)
        self.random_button.grid(row = 0, column = 1)
        self.save_button = Button(self.top_frame, text = 'save', command = self.save)
        self.save_button.grid(row = 0, column = 2)
        self.download_button = Button(self.top_frame, text = 'download', command = self.download)
        self.download_button.grid(row = 0, column = 3)

        self.col_frame = Frame(self.top_frame)
        self.col_frame.grid(row = 0, column = 4)
        c1 = random_color()
        self.default_col_v_fill.set(c1)
        c2 = random_color()
        self.default_col_v_outline.set(c2)
        self.default_col_r.set(c2)
        self.vertex_color_button = Canvas(self.col_frame, width=20, height=20, bg = self.default_col_v_fill.get())
        self.outline_color_button = Canvas(self.col_frame, width=20, height=20, bg = self.default_col_v_outline.get())
        self.vertex_color_button.grid(row = 0, column = 0)
        self.outline_color_button.grid(row = 0, column = 1)

        self.vertex_color_button.bind('<Button-1>', self.set_vertex_color)
        self.outline_color_button.bind('<Button-1>', self.set_outline_color)

        self.canvas = GraphCanvas(self.root, width=600, height=400)
        self.canvas.grid(row = 1, column = 0)
        self.y_scrollbar = Scrollbar(self.root, command = self.canvas.yview, orient=VERTICAL)
        self.x_scrollbar = Scrollbar(self.root, command = self.canvas.xview, orient=HORIZONTAL)
        self.canvas.configure(yscrollcommand = self.y_scrollbar.set, xscrollcommand = self.x_scrollbar.set)

        self.y_scrollbar.grid(row = 1, column = 1,  columnspan=1,  sticky='ns')
        self.x_scrollbar.grid(row = 2, column = 0,  columnspan=1,  sticky='ew')

        self.root.rowconfigure(1, weight = 1)
        self.root.columnconfigure(0, weight = 1)

        if self.g:
            self.canvas.view_graph(self.g)

        ###
        self.vertex_popup_menu = Menu(self.root, tearoff = 0)
        self.vertex_popup_menu.add_command(label = 'delete', command = self.delete_vertex)
        self.vertex_popup_menu.add_command(label = 'rename', command = self.rename_vertex)
        self.vertex_popup_menu.add_command(label = 'colour', command = self.vertex_color_configure)
    def vertex_popup(self, ev):
        self.event = ev
        self.vertex_popup_menu.post(ev.x_root, ev.y_root)
    def set_vertex_color(self, ev):
        col = askcolor()
        if col[1]:
            self.default_col_v_fill.set(col[1])
            # if self.creating: #
            #     self.g.default_ver = col[1] #
                # self.g.ver_colours = {n: col[1] for n, c in self.g.items()}
            self.vertex_color_button.configure(bg = self.default_col_v_fill.get())
    def set_outline_color(self, ev):
        col = askcolor()
        if col[1]:
            self.default_col_v_outline.set(col[1])
            self.default_col_r.set(col[1])
            # if self.creating: #
            #     self.g.outline_colour = col[1] #
            self.outline_color_button.configure(bg = self.default_col_v_outline.get())
    def vertex_color_configure(self, ev = 0):
        if not ev:
            ev = self.event
            self.event = None
        n = self.find_vertex(ev)

        col = askcolor()[1]
        if col:
            cort = self.g.ver_colours.get(n) #
            self.g.ver_colours[n] = (col, cort[1]) #
            self.canvas.view_vertex(self.g, n)

    def find_vertex(self, ev):
        n = 0
        for name, coor in self.g.form.items():
            x, y = coor[0], coor[1]
            if x - 20 <= ev.x <= x + 20 and y-20 <= ev.y <= y+20:
                n = name
                break
        return n

    def create_graph(self):
        # self.creating = 1 #
        self.canvas.delete('all')
        self.g = DictGraph()
        self.notice = Message(self.top_frame, text = 'set vertices')
        self.notice.grid(row = 0, column = 5)
        self.step_button = Button(self.top_frame, text = 'ready', command = self.step_function)
        self.step_button.grid(row = 0, column = 6)
        self.cancel_button = Button(self.top_frame, text = 'cancel', command = self.delete_vertex_name)
        self.cancel_button.grid(row = 0, column = 7)
        self.canvas.bind('<Button-1>', self.set_vertex)
        self.next_name = (name for name in self.names)
        self.cancel_tag = None
    def set_vertex(self, ev):
        if not self.find_vertex(ev):
            name = next(self.next_name)
            self.g.set_vertices(name)
            x = ev.x
            y = ev.y
            self.g.form[name] = (x,y)
            self.g.ver_colours[name] = (self.default_col_v_fill.get(), self.default_col_v_outline.get())
            self.canvas.view_vertex(self.g, name)
            # self.canvas.tag_bind(name, '<Button-1>', self.rename_vertex)
            self.cancel_tag = name
    def set_rib(self, ev):
        n = self.find_vertex(ev)
        if n:
            if self.next and self.next != n:
                self.g.set_rib(self.next, n)
                self.g.rib_colours[self.next + n] = self.default_col_r.get()
                self.g.rib_colours[n + self.next] = self.default_col_r.get()
                self.canvas.view_rib(self.g, self.next, n)
                self.canvas.view_vertex(self.g, self.next)
                self.canvas.view_vertex(self.g, n)

                self.canvas.tag_bind(self.next+n, '<Button-1>', self.set_outline_color)
                self.cancel_tag = (self.next, n)
                self.next = None
            else:
                self.next = n
    def step_function(self):
        self.next = None
        self.cancel_tag = None
        self.notice['text'] = 'set ribs'
        self.canvas.bind('<Button-1>', lambda ev: None)
        for e in self.g.vertices.keys():
            self.canvas.tag_bind(e, '<B1-Motion>', self.set_rib)
            self.canvas.tag_bind(e, '<Button-1>', self.set_rib)
        # self.step_button['command'] = 'self.finish_function'
        self.step_button.configure(command = self.finish_function)
        self.cancel_button.configure(command = self.delete_rib_by_names)
    def finish_function(self):
        self.notice.destroy()
        self.step_button.destroy()
        self.cancel_button.destroy()
        for e in self.g.vertices.keys():
            self.canvas.tag_bind(e, '<B1-Motion>', self.move_vertex_start)
            self.canvas.tag_bind(e, '<Button-3>', self.vertex_popup)
        # self.creating = 0 #

    def random_graph(self):
        self.ask = Toplevel()
        self.ver = IntVar()
        self.rib = IntVar()
        self.ver.set(random.choice(range(4,8)))
        self.rib.set(random.choice(range(4,8)))

        Label(self.ask, text = 'vertices').grid(row = 0, column = 0)
        Label(self.ask, text = 'ribs').grid(row = 1, column = 0)
        ver = Entry(self.ask, textvariable = self.ver)
        ver.grid(row = 0, column = 1)
        rib = Entry(self.ask, textvariable = self.rib)
        rib.grid(row = 1, column = 1)
        ok_b = Button(self.ask, text = 'ok', command = self.start_command)
        ok_b.grid(row = 3, column = 0, columnspan = 2)
        self.ask.bind('<Return>', self.start_command)
        self.ask.focus()
    def start_command(self, ev = 0):
        self.g = random_graph(self.ver.get(), self.rib.get())
        c1 = random_color()
        self.default_col_v_fill.set(c1)
        c2 = random_color()
        self.default_col_v_outline.set(c2)
        self.default_col_r.set(c2)

        self.vertex_color_button.configure(bg = self.default_col_v_fill.get())
        self.outline_color_button.configure(bg = self.default_col_v_outline.get())

        self.g.ver_colours = {e: (c1, c2) for e in self.g.vertices.keys()}
        ribs = self.g.get_ribs() #
        for e in ribs: #
            ab = list(e[0])
            a, b = ab[0], ab[1]
            if not self.g.rib_colours.get(a+b):
                self.g.rib_colours[a+b] = self.default_col_r.get()
                self.g.rib_colours[b+a] = self.default_col_r.get()

        self.canvas.view_graph(self.g)
        for e in self.g.vertices.keys():
            # self.canvas.tag_bind(e, '<Button-1>', self.vertex_color_configure)
            self.canvas.tag_bind(e, '<Button-3>', self.vertex_popup)
            self.canvas.tag_bind(e, '<B1-Motion>', self.move_vertex_start)

        self.ask.destroy()

    def save(self):
        filename = asksaveasfilename()
        f = open(filename, 'wb')
        pickle.dump(self.g, f)

    def download(self):
        filename = askopenfilename()
        f = open(filename, 'rb')
        self.g = pickle.load(f)
        self.canvas.view_graph(self.g)

    def find_rib_tags(self, name):
        ln = len(name)
        pat1 = r'\w+'+name+'$'
        pat2 = r'^'+name+'\w+'
        s1 = []
        s2 = []
        for e in self.g.rib_colours.keys():
            s1 += re.findall(pat1, e)
            s2 += re.findall(pat2, e)

        s1 = [str[0:-ln] for str in s1]
        s2 = [str[ln:] for str in s2]
        s = [e for e in s1 if e in s2]
        tags = [name + e for e in s] + [e + name for e in s]
        return tags

    def delete_rib_by_names(self, a = 0, b = 0):
        if a and b or self.cancel_tag:
            if a == 0 or b == 0:
                a, b = self.cancel_tag[0], self.cancel_tag[1]
                self.cancel_tag = None
                self.next = None
            self.g.del_rib(a, b)
            del self.g.rib_colours[a+b]
            del self.g.rib_colours[b+a]
            self.canvas.delete_rib(a, b)

    def delete_vertex_name(self, name = 0):
        if name or self.cancel_tag:
            if not name:
                name = self.cancel_tag
                self.cancel_tag = None

            self.canvas.delete_ribs(self.g, name) #
            self.canvas.delete_vertex(name) #
            self.g.del_vertex(name)
            del self.g.ver_colours[name]
            rib_tags = self.find_rib_tags(name)
            for e in rib_tags:
                del self.g.rib_colours[e]

    def delete_vertex(self, ev = 0):
        if not ev:
            ev = self.event
            self.event = None
        name = self.find_vertex(ev)
        if name:
            self.delete_vertex_name(name)

    def move_vertex_start(self, ev):
        self.next = self.find_vertex(ev)
        if self.next:
            self.g.form[self.next] = (ev.x, ev.y)
            self.canvas.bind('<ButtonRelease-1>', self.move_vertex_stop)

    def move_vertex_stop(self, ev):
        if self.next:
            ver = self.next
            # print(0, ver)
            self.g.form[ver] = (ev.x, ev.y)
            self.canvas.delete_ribs(self.g, ver)
            self.canvas.delete_vertex(ver)
            r = self.g.vertices.get(ver)
            for e in r.keys():
                self.canvas.view_rib(self.g, ver, e)
                self.canvas.delete_vertex(e)
                self.canvas.view_vertex(self.g, e)
            self.canvas.view_vertex(self.g, ver)
            self.next = None
            self.canvas.unbind('<ButtonRelease-1>')

    def rename_vertex(self, ev = 0):
        if not ev:
            ev = self.event
            self.event = None
        # self.renaming = StringVar()
        self.entry_name= Entry(self.canvas, width=4) #, textvariable = self.renaming
        self.entry_name.grid()
        self.entry_name.focus()
        ver = self.find_vertex(ev)
        self.next = ver
        x, y = self.g.form.get(ver)[0], self.g.form.get(ver)[1]
        self.canvas.create_window((x, y), window= self.entry_name)
        self.root.bind('<Return>', self.rename_ok)
    def rename_ok(self, ev):
        new = self.entry_name.get()
        if new not in self.g.vertices.keys():
            old, self.next = self.next, None

            form = self.g.form.get(old)
            del self.g.form[old]
            self.g.form[new] = form

            # ribs = self.find_rib_tags(old)
            dict = self.g.vertices.get(old)
            for e in dict.keys():
                col = self.g.rib_colours.get(old+e)
                self.canvas.delete_rib(old, e)
                del self.g.rib_colours[old+e]
                del self.g.rib_colours[e+old]
                self.g.rib_colours[new+e] = col
                self.g.rib_colours[e+new] = col
                self.canvas.view_rib(self.g, new, e)
                self.canvas.view_vertex(self.g, e)
                w = dict.get(e)
                self.g.vertices.get(e)[new] = w
                del self.g.vertices.get(e)[old]

            col = self.g.ver_colours.get(old)
            del self.g.ver_colours[old]
            self.g.ver_colours[new] = col

            del self.g.vertices[old]
            self.g.vertices[new] = dict

            self.canvas.delete_vertex(old)
            self.canvas.view_vertex(self.g, new)

            self.entry_name.destroy()
            self.canvas.tag_bind(new, '<Button-3>', self.vertex_popup)
            self.canvas.tag_bind(new, '<B1-Motion>', self.move_vertex_start)

def random_color():
    l = ['00','11','22','33','44','55','66','77','88','99','aa','bb','cc','dd','ee','ff']
    cs = '#'+'00'*3
    while cs == '#000000' or cs == '#ffffff':
        cs = [random.choice(l),random.choice(l),random.choice(l)]
        cs = '#'+cs[0]+cs[1]+cs[2]
    return cs

if __name__ == '__main__':
    root = Window()


import io
import json
from datetime import date, datetime, timedelta, timezone

import cv2
import numpy as np
from discord import Embed, File, Game
from discord.ext import commands as c
from PIL import Image, ImageDraw, ImageFont

from module import db, item

with open('../assets/login_bonus.json', encoding='utf-8') as f:
    df = json.load(f)

class Cog(c.Cog):
    def __init__(self, bot):
        self.bot = bot

    @c.Cog.listener()
    async def on_command(self, ctx):
        def overlay(cv_background_image, cv_overlay_image, point,):
            """
            [summary]
                OpenCV形式の画像に指定画像を重ねる
            Parameters
            ----------
            cv_background_image : [OpenCV Image]
            cv_overlay_image : [OpenCV Image]
            point : [(x, y)]
            Returns : [OpenCV Image]
            """
            overlay_height, overlay_width = cv_overlay_image.shape[:2]

            # OpenCV形式の画像をPIL形式に変換(α値含む)
            # 背景画像
            cv_rgb_bg_image = cv2.cvtColor(cv_background_image, cv2.COLOR_BGR2RGB)
            pil_rgb_bg_image = Image.fromarray(cv_rgb_bg_image)
            pil_rgba_bg_image = pil_rgb_bg_image.convert('RGBA')
            # オーバーレイ画像
            cv_rgb_ol_image = cv2.cvtColor(cv_overlay_image, cv2.COLOR_BGRA2RGBA)
            pil_rgb_ol_image = Image.fromarray(cv_rgb_ol_image)
            pil_rgba_ol_image = pil_rgb_ol_image.convert('RGBA')

            # composite()は同サイズ画像同士が必須のため、合成用画像を用意
            pil_rgba_bg_temp = Image.new('RGBA', pil_rgba_bg_image.size,
                                            (255, 255, 255, 0))
            # 座標を指定し重ね合わせる
            pil_rgba_bg_temp.paste(pil_rgba_ol_image, point, pil_rgba_ol_image)
            result_image = Image.alpha_composite(pil_rgba_bg_image, pil_rgba_bg_temp)

            # OpenCV形式画像へ変換
            cv_bgr_result_image = cv2.cvtColor(
                np.asarray(result_image), cv2.COLOR_RGBA2BGRA)

            return cv_bgr_result_image
        login_timezone = timezone(timedelta(hours=+0), 'UTC')
        # timezone = timezone(timedelta(hours=+9), 'JST')
        now = datetime.now(login_timezone)
        login_data = db.player.login.get(ctx.author.id)
        login_datetime = datetime.fromtimestamp(login_data[1],login_timezone)
        next_login_datetime=datetime(login_datetime.year,login_datetime.month,login_datetime.day,tzinfo=login_timezone)+timedelta(1)
        #if now.timestamp()-login_data[1] >= 86400:  # 最終ログインから24時間
        login_const = 15
        if next_login_datetime <= now:# or True:
            count=login_data[0]%login_const+1
            image = cv2.imread("../assets/back.jpg")
            for y in range(3):
                for x in range(5):
                    cv_overlay_image = cv2.imread(df[x+5*y]["img"], cv2.IMREAD_UNCHANGED)  # IMREAD_UNCHANGEDを指定しα込みで読み込む
                    cv_overlay_image = cv2.resize(cv_overlay_image, (140, 140))
                    image = overlay(image, cv_overlay_image, (215+255*x, 270+255*y))
                    if count>x+5*y:
                        cv_overlay_image = cv2.imread("../assets/received.png", cv2.IMREAD_UNCHANGED)  # IMREAD_UNCHANGEDを指定しα込みで読み込む
                        cv_overlay_image = cv2.resize(cv_overlay_image, (200, 200))
                        image = overlay(image, cv_overlay_image, (188+254*x, 240+255*y))
                    img_pil = Image.fromarray(image)
                    draw = ImageDraw.Draw(img_pil)
                    draw.text((350+255*x, 400+255*y), str(df[x+5*y]["reward"]), font=ImageFont.truetype('../assets/HGRPP1.TTC', 64), fill = (256-150*(count>x+5*y),)*3+(0,))
                    image = np.array(img_pil)
            _,img=cv2.imencode(".jpg",image,[int(cv2.IMWRITE_JPEG_QUALITY), 100])
            db.player.login.do(ctx.author.id, now.timestamp())
            f = File(fp=io.BytesIO(img),filename="login_image.jpg")
            login_bonus = df[login_data[0]%login_const]
            if login_bonus["item_id"]=="FG":
                db.player.money.add(ctx.author.id,login_bonus["reward"])
                e = Embed(title="【ログインボーナス】",description="{0}は{1}FG手に入れた。".format(ctx.author.mention,login_bonus["reward"]))
            else:
                item.obtain_an_item(ctx.author.id, login_bonus["item_id"], login_bonus["reward"])
                e = Embed(title="【ログインボーナス】",description="{0}は{1}を{2}個手に入れた。".format(ctx.author.mention,item.items.get(str(login_bonus["item_id"]),{"name": "unknown"})["name"],login_bonus["reward"]))
            e.set_image(url="attachment://login_image.jpg")
            await ctx.send(file=f, embed=e)

    @c.command(pass_context=True, description='仮実装のloginコマンド。実行はしないほうがいいかもな')
    async def login(self, ctx):
        login_timezone = timezone(timedelta(hours=+0), 'UTC')
        # login_timezone = timezone(timedelta(hours=+9), 'JST')
        now = datetime.now(login_timezone)
        login_data = db.player.login.get(ctx.author.id)
        login_datetime = datetime.fromtimestamp(login_data[1], login_timezone)
        next_login_datetime=datetime(login_datetime.year,login_datetime.month,login_datetime.day,tzinfo=login_timezone)+timedelta(1)
        #if now.timestamp()-login_data[1] >= 86400:  # 最終ログインから24時間
        if next_login_datetime > now:
            await ctx.send("あなたはすでにログインしています\n最終ログイン："+login_datetime.isoformat(sep=' ')+"\n次回ログイン可能："+next_login_datetime.isoformat(sep=' '))

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


import sys,datetime
import sqlite3
import tsp_ga

tour=sqlite3.connect('stadiumTour.db')
tr=tour.cursor()
dict1={0:"Brighton",1:"Bristol",2:"Cambridge",3:"Glasgow",4:"Liverpool",5:"London",6:"Manchester",7:"Oxford"}
#stadium starts
def displaycities():
      sql="SELECT * from stadium;"
      tr.execute(sql)
      result=tr.fetchall();
      #print(result)
      #for record in result:
            #print (record)
      print("Sno\tStadium Name\tCity\tZipcode\tCapacity")
      for record in result:
            print(record[0],"\t",record[1],"\t",record[2],"\t",record[3],"\t",
                  record[4],"\t")

def searchcities():
      name=input('Enter the name')
      sql="SELECT sname,city from stadium WHERE city='"+name+"';"
      tr.execute(sql)
      result=tr.fetchone()
      if result==None:
            print("no record found")
      else:
            print(result[0],",",result[1],"\n")

def shrtst_path():
      print('shortest path is:')
      testList=tsp_ga.ga()
      cost=testList[0][0]
      s=testList[0][5]
      s=s.replace(',','')
      s=s.replace(' ','')
      s=s.replace('[','')
      s=s.replace(']','')
      l1=[int(y) for y in list(s)]

      for i in range(len(l1)):
            print(dict1[l1[i]],"->",end=" ")
      print('\ncost of the shortest path is: ',cost)

#stadium ends

#staff starts
def displaystaff():
      sql="SELECT * from staff;"
      tr.execute(sql)
      result=tr.fetchall();
      #print(result)
      #for record in result:
            #print (record)
      print("Stid\tStaff name\tJob")
      for record in result:
            print(record[0],"\t",record[1],"\t",record[2])

def searchstaff():
      name=input('Enter the name: ')
      sql="SELECT stid,sname,job from staff WHERE Sname='"+name+"';"
      tr.execute(sql)
      result=tr.fetchone()
      if result==None:
            print("no record found")
      else:
            print(result[0],",",result[1],",",result[2],"\n")

def updatestaff():
      print("""
                  1.Insert
                  2.Delete
                  3.Update
            """)
      c=int(input("enter c hoice"))
      if c==1:
            try:
                  x=int(input('Enter stid:'))
                  y=input('Enter sname')
                  z=input('enter job')
                  tr.execute("insert into staff values(?,?,?)",(x,y,z))
                  tour.commit()
                  print ("One record added successfully.")
            except:
                  print ("Error in operation.")

                  tour.rollback()

      elif c==2:
            try:
                  x=input('Enter the staff name to be deleted:')
                  tr.execute("delete from staff where sname='"+x+"';")
                  print('delete sucessfull')
                  tour.commit()
            except:
                  print('error in Operation')

                  tour.rollback()

      elif c==3:
            try:
                  w=input('Enter the staff name to be update')
                  x=int(input('Enter stid:'))
                  y=input('Enter sname')
                  z=input('enter job')
                  tr.execute('update staff set stid=?,sname=?,job=? where sname=?;',(w,x,y,z))
                  tour.commit()
                  print("record updated sucessfully")
            except:
                  print ("Error in operation.")

                  tour.rollback()

#staff ends

#equpments starts

def displayequipments():
      sql="SELECT * from equipments;"
      tr.execute(sql)
      result=tr.fetchall();
      #print(result)
      #for record in result:
            #print (record)
      print("equipID\tEName\tQty")
      for record in result:
            print(record[0],"\t",record[1],"\t",record[2])

def searchequipments():
      name=input('Enter the equipment: ')
      sql="SELECT equipID,Ename,Qty from Equipments WHERE Ename='"+name+"';"
      tr.execute(sql)
      result=tr.fetchone()
      if result==None:
            print("no record found")
      else:
            #
            print(result[0],",",result[1],",",result[2],"\n")

def updateequipments():
      print("""
                  1.Insert
                  2.Delete
                  3.Update
            """)
      c=int(input("enter c hoice"))
      if c==1:
            try:
                  x=int(input('Enter equipid:'))
                  y=input('Enter ename')
                  z=input('enter qty')
                  tr.execute("insert into equipments values(?,?,?)",(x,y,z))
                  tour.commit()
                  print ("One record added successfully.")
            except:
                  print ("Error in operation.")

                  tour.rollback()

      elif c==2:
            try:
                  x=input('Enter the ename name to be deleted:')
                  tr.execute("delete from equipments where Ename='"+x+"';")
                  print('delete sucessfull')
                  tour.commit()
            except:
                  print('error in Operation')

                  tour.rollback()

      elif c==3:
            try:
                  w=input('Enter the ename name to be update')
                  x=int(input('Enter equipid:'))
                  y=input('Enter ename')
                  z=input('enter qty')
                  tr.execute('update equipments set equipID=?,Ename=?,Qty=? where Ename=?;',(w,x,y,z))
                  tour.commit()
                  print("record updated sucessfully")
            except:
                  print ("Error in operation.")

                  tour.rollback()

#equipment ends

#merchandise starts
def displaymerchandise():
      sql="SELECT * from merchandise;"
      tr.execute(sql)
      result=tr.fetchall();
      #print(result)
      #for record in result:
            #print (record)
      print("Type\tHoodie\tQty\tprice")
      for record in result:
            print(record[0],"\t",record[1],"\t",record[2],"\t",record[3])

def searchmerchandise():
      name=input('Enter the type of merchandise: ')
      sql="SELECT * from merchandise WHERE Type='"+name+"';"
      tr.execute(sql)
      result=tr.fetchone()
      if result==None:
            print("no record found")
      else:
            #
            print(result[0],",",result[1],",",result[2],",",result[3],"\n")

def updatemerchandise():
      print("""
                  1.Insert
                  2.Delete
                  3.Update
            """)
      c=int(input("enter c hoice"))
      if c==1:
            try:
                  x=int(input('Enter type:'))
                  y=input('Enter merch_id')
                  z=input('enter quantity')
                  v=input('enter price')
                  tr.execute("insert into merchandise values(?,?,?)",(x,y,z,v))
                  tour.commit()
                  print ("One record added successfully.")
            except:
                  print ("Error in operation.")

                  tour.rollback()

      elif c==2:
            try:
                  x=input('Enter the type of merch to be deleted:')
                  tr.execute("delete from merchandise where type='"+x+"';")
                  print('delete sucessfull')
                  tour.commit()
            except:
                  print('error in Operation')

                  tour.rollback()

      elif c==3:
            try:
                  w=input('Enter the ename name to be update')
                  x=int(input('Enter type:'))
                  y=input('Enter merch_id')
                  z=input('enter quantity')
                  v=input('enter price')

                  tr.execute('update merchandise set type=?,merch_id=?,quantity=?,price=? where =?;',(w,x,y,z,v))
                  tour.commit()
                  print("record updated sucessfully")
            except:
                  print ("Error in operation.")

                  tour.rollback()

#merchandise ends

def cities():
      done=False
      while done==False:
            print("""==========Touring Cities=========
                  1.Display the cities
                  2.Search a city
                  3.Generate shortest path
                  4.Go to main menu
                  """)
            choice=int(input("Enter Choice:"))
            if choice==1:
                  displaycities()
            elif choice==2:
                  searchcities()
            elif choice==3:
                  shrtst_path()
            elif choice==4:
                  main()

def staff():
      done=False
      while done==False:
            print("""==========Staff module==========
                  1.Display Staff
                  2.Search a Staff
                  3.Update staff table
                  4.Go to main menu
                  """)
            choice=int(input("Enter Choice:"))
            if choice==1:
                  displaystaff()
            elif choice==2:
                  searchstaff()
            elif choice==3:
                  updatestaff()
            elif choice==4:
                  main()

def equipments():
      done=False
      while done==False:
            print("""==========Staff module==========
                  1.Display Equpments
                  2.Search a Equipment
                  3.Update Equipment table
                  4.Go to main menu
                  """)
            choice=int(input("Enter Choice:"))
            if choice==1:
                  displayequipments()
            elif choice==2:
                  searchequipments()
            elif choice==3:
                  updateequipments()
            elif choice==4:
                  main()

def merchandise():
      done=False
      while done==False:
            print("""==========Staff module==========
                  1.Display Merchandise
                  2.Search a Merchandise
                  3.Update Merchandise table
                  4.Go to main menu
                  """)
            choice=int(input("Enter Choice:"))
            if choice==1:
                  displaymerchandise()
            elif choice==2:
                  searchmerchandise()
            elif choice==3:
                  updatemerchandise()
            elif choice==4:
                  main()

def main():
      done=False
      while done==False:
            print(""" ======STADIUM TOUR MANAGEMENT MENU=======
                  1. Touring cities
                  2. Staff
                  3. Equipments
                  4.Merchandise
                  5. Exit
                  """)
            choice=int(input("Enter Choice:"))
            if choice==1:
                        cities()
            elif choice==2:
                        staff()
            elif choice==3:
                        equipments()
            elif choice==4:
                        merchandise()
            elif choice==5:
                  sys.exit()
            else:
                  print('invalid choice')

main()


from utils.dates_functions import add_months_datetime, get_calendario, get_date_to_db
from controllers.DefaultValues import DefaultValues
from django.conf import settings
from django.apps import apps

from django.db import transaction
from calendario.models import Calendario

from utils.validators import validate_string, validate_number_int
from utils.permissions import current_date, fecha_periodo
from datetime import datetime

# conexion directa a la base de datos
from django.db import connection

class CalendarioController(DefaultValues):
    def __init__(self):
        DefaultValues.__init__(self)
        self.modelo_name = 'Calendario'
        self.modelo_id = 'calendario_id'
        self.modelo_app = 'calendario'
        self.modulo_id = settings.MOD_CALENDARIO

        # variables de session
        self.modulo_session = "calendario"
        self.columnas.append('departamento')

        self.variables_filtros.append('search_departamento')
        self.variables_filtros.append('search_periodo')
        self.variables_filtros.append('search_actividad')

        self.variables_filtros_defecto['search_departamento'] = ''
        self.variables_filtros_defecto['search_actividad'] = '0'

        anio = '20' + str(datetime.now().year) if len(str(datetime.now().year)) == 2 else str(datetime.now().year)
        mes = '0' + str(datetime.now().month) if len(str(datetime.now().month)) == 1 else str(datetime.now().month)
        self.variables_filtros_defecto['search_periodo'] = anio + mes

        self.variable_page = "page"
        self.variable_page_defecto = "1"
        self.variable_order = "search_order"
        self.variable_order_value = self.columnas[0]
        self.variable_order_type = "search_order_type"
        self.variable_order_type_value = 'ASC'

        # tablas donde se debe verificar para eliminar
        self.modelos_eliminar = {}

        # control del formulario
        self.control_form = ""

    def index(self, request):
        DefaultValues.index(self, request)
        self.filtros_modulo.clear()
        #sql_add = f"AND c.status_id in ('{self.activo}','{self.inactivo}', '{self.anulado}') "
        sql_add = f"AND c.status_id in ('{self.activo}','{self.inactivo}') "
        # status
        self.filtros_modulo['status_id_id__in'] = [self.activo, self.inactivo]

        user_perfil = apps.get_model('permisos', 'UsersPerfiles').objects.get(user_id=request.user)

        # actividad
        actividad_search = self.variables_filtros_values['search_actividad'].strip()
        if actividad_search != '0':
            sql_add = f"AND c.actividad_id='{actividad_search}' "

        # periodo del calendario
        calendario = []
        # if self.variables_filtros_values['search_periodo'].strip() != "":
        periodo = self.variables_filtros_values['search_periodo'].strip()
        anio = periodo[0:4]
        mes = periodo[4:6]
        calendario = get_calendario(mes, anio)

        fecha_ini = fecha_periodo(periodo, '01')
        fecha_ini = get_date_to_db(fecha=fecha_ini, formato_ori='yyyy-mm-dd', formato='yyyy-mm-dd HH:ii:ss', tiempo='00:00:00')
        fecha_fin = add_months_datetime(fecha=fecha_ini, formato_ori='yyyy-mm-dd HH:ii:ss', meses=1, formato='yyyy-mm-dd HH:ii:ss')
        sql_add += f"AND c.fecha_actividad_ini>='{fecha_ini}' AND c.fecha_actividad_ini<'{fecha_fin}' "
        #print('sql_add: ', sql_add)

        # departamento
        depa = self.variables_filtros_values['search_departamento'].strip()
        if depa != "":
            sql_add += f"AND d.departamento LIKE '%{depa}%' "

        # lista de todos los usuarios
        users_perfiles_lista = apps.get_model('permisos', 'UsersPerfiles').objects.filter(status_id=self.status_activo)

        # lista del calendario
        sql = "SELECT c.calendario_id, c.fecha_actividad_ini, c.fecha_actividad_fin, c.fecha_reserva, c.user_perfil_id_reserva, "
        sql += "c.fecha_confirma, c.user_perfil_id_confirma, c.fecha_anula, c.user_perfil_id_anula, c.motivo_anula, "
        sql += "c.detalle, c.observacion, c.status_id, a.actividad, a.codigo, a.color_hex, d.departamento, d.codigo AS departamento_codigo, "
        sql += "d.departamento_id, a.color_txt "
        sql += "FROM calendario c INNER JOIN actividades a ON c.actividad_id=a.actividad_id "
        sql += "LEFT JOIN departamentos d ON c.departamento_id=d.departamento_id "
        sql += "WHERE c.calendario_id>0 "
        sql += sql_add

        sql += "ORDER BY a.actividad, c.fecha_actividad_ini, c.fecha_reserva "
        #print('sql: ', sql)

        retorno = []
        with connection.cursor() as cursor:
            cursor.execute(sql)
            rows = cursor.fetchall()

            # recorremos todos los dias del calendario
            semana_add = []

            for semana in calendario:
                for dia_semana in semana:
                    objeto_dia = {}
                    objeto_dia['posicion'] = dia_semana['posicion']
                    objeto_dia['dia'] = dia_semana['dia']
                    objeto_dia['nombre'] = dia_semana['nombre']
                    objeto_dia['existe'] = dia_semana['existe']

                    if objeto_dia['existe'] == 1:
                        #print('dia: ', objeto_dia['dia'])
                        # dia valido, vemos las actividades
                        para_dia = str(objeto_dia['dia'])
                        if len(para_dia) == 1:
                            para_dia = '0' + para_dia

                        fecha_dia = anio + '-' + mes + '-' + para_dia
                        lista_actividades = []
                        #print('fecha dia: ', fecha_dia)

                        for row in rows:
                            aux_fecha = get_date_to_db(fecha=row[1], formato_ori='yyyy-mm-dd HH:ii:ss', formato='yyyy-mm-dd HH:ii:ss')  # fecha actividad ini
                            div_aux = aux_fecha.split(' ')
                            fecha_calendario = div_aux[0]
                            hora_calendario = div_aux[1]
                            #print('hora calendario: ', hora_calendario)
                            # fecha fin calendario
                            aux_fecha = get_date_to_db(fecha=row[2], formato_ori='yyyy-mm-dd HH:ii:ss', formato='yyyy-mm-dd HH:ii:ss')  # fecha actividad ini
                            div_aux = aux_fecha.split(' ')
                            fecha_calendario_fin = div_aux[0]
                            hora_calendario_fin = div_aux[1]
                            #print('fecha calendario: ', fecha_calendario, ' ..fecha dia: ', fecha_dia)

                            if fecha_dia == fecha_calendario:
                                # actividad para el dia
                                actividad = {}
                                actividad['calendario_id'] = row[0]
                                actividad['hora_ini'] = hora_calendario[0:5]
                                actividad['hora_fin'] = hora_calendario_fin[0:5]
                                actividad['fecha_reserva'] = row[3]
                                actividad['user_perfil_id_reserva'] = row[4]
                                actividad['fecha_confirma'] = row[5]
                                actividad['user_perfil_id_confirma'] = row[6]
                                actividad['fecha_anula'] = row[7]
                                actividad['user_perfil_id_anula'] = row[8]
                                actividad['motivo_anula'] = row[9]
                                actividad['detalle'] = row[10]
                                actividad['observacion'] = row[11]
                                actividad['status_id'] = row[12]
                                actividad['actividad'] = row[13]
                                actividad['actividad_codigo'] = row[14]
                                actividad['color_hex'] = row[15]
                                actividad['departamento'] = row[16]
                                actividad['departamento_codigo'] = row[17]
                                actividad['departamento_id'] = row[18]
                                actividad['color_txt'] = row[19]

                                # user id del departamento
                                user_id_dpto = 0
                                for us_perfil in users_perfiles_lista:
                                    if actividad['departamento'] == us_perfil.user_id.username:
                                        user_id_dpto = us_perfil.user_id.id
                                        break
                                actividad['user_id_dpto'] = user_id_dpto

                                #print('actividad: ', actividad)
                                lista_actividades.append(actividad)

                        objeto_dia['lista_actividades'] = lista_actividades
                        semana_add.append(objeto_dia)
                    else:
                        objeto_dia['lista_actividades'] = []
                        semana_add.append(objeto_dia)

                # termina el for de semana
                retorno.append(semana_add)
                semana_add = []
            # termina el for calendario
            # retorno.append(semana_add)

        # return calendario
        #print('retorno: ', retorno)
        return retorno

    def registrar_actividad(self, periodo, request, user):
        # armamos los datos
        try:
            hora_ini = validate_string('hora inicio', request.POST['hora_ini'])
            minuto_ini = validate_string('minutos inicio', request.POST['minuto_ini'])
            hora_fin = validate_string('hora fin', request.POST['hora_fin'])
            minuto_fin = validate_string('minutos fin', request.POST['minuto_fin'])
            actividad_id = validate_number_int('actividad', request.POST['actividad'])
            aux_dia = validate_number_int('dia', request.POST['dia'])
            #departamento_id = validate_number_int('departamento', request.POST['departamento'], len_zero='yes')
            # registro directo por un usuario que no es departamento
            departamento_id = 0
            detalle = validate_string('detalle', request.POST['detalle'], len_zero='yes')

            dia = str(aux_dia)
            if len(dia) == 1:
                dia = "0" + dia

            actividad = apps.get_model('calendario', 'Actividades').objects.get(pk=actividad_id)
            # if departamento_id > 0:
            #     departamento = apps.get_model('departamentos', 'Departamento').objects.get(pk=departamento_id)

            user_perfil = apps.get_model('permisos', 'UsersPerfiles').objects.get(user_id=user)

            fecha_inicio = periodo[0:4] + '-' + periodo[4:6] + '-' + dia + ' ' + hora_ini + ':' + minuto_ini + ':00'
            fecha_fin = periodo[0:4] + '-' + periodo[4:6] + '-' + dia + ' ' + hora_fin + ':' + minuto_fin + ':00'
            # verificamos que no exista actividad confirmada en este rango
            sql = f"SELECT COUNT(*) AS cant FROM calendario WHERE fecha_actividad_ini>='{fecha_inicio}' AND fecha_actividad_ini<'{fecha_fin}' AND actividad_id='{actividad_id}' AND status_id='{self.activo}' "
            cant = 0
            with connection.cursor() as cursor:
                cursor.execute(sql)
                row = cursor.fetchone()
                cant = row[0]
                if cant == 0:
                    sql = f"SELECT COUNT(*) AS cant FROM calendario WHERE fecha_actividad_fin>'{fecha_inicio}' AND fecha_actividad_fin<='{fecha_fin}' AND actividad_id='{actividad_id}' AND status_id='{self.activo}' "
                    with connection.cursor() as cursor2:
                        cursor2.execute(sql)
                        row2 = cursor2.fetchone()
                        cant = row2[0]

            if cant > 0:
                self.error_operation = "Ya existen actividades en este rango de fecha para la actividad : " + actividad.actividad
                return False

            # guardamos en la base de datos
            calendario_add = apps.get_model('calendario', 'Calendario').objects.create(
                fecha_actividad_ini=fecha_inicio, fecha_actividad_fin=fecha_fin, departamento_id=departamento_id,
                user_perfil_id_reserva=user_perfil.user_perfil_id, fecha_reserva='now', detalle=detalle,
                user_perfil_id_confirma=user_perfil.user_perfil_id, fecha_confirma='now',
                actividad_id=actividad, status_id=self.status_activo,
                created_at='now', updated_at='now'
            )
            calendario_add.save()

            self.error_operation = ''
            return True

        except Exception as ex:
            self.error_operation = 'Error de datos, ' + str(ex)
            return False

    def solicitar_actividad(self, periodo, request, user):
        # armamos los datos
        try:
            hora_ini = validate_string('hora inicio', request.POST['hora_ini'])
            minuto_ini = validate_string('minutos inicio', request.POST['minuto_ini'])
            hora_fin = validate_string('hora fin', request.POST['hora_fin'])
            minuto_fin = validate_string('minutos fin', request.POST['minuto_fin'])
            actividad_id = validate_number_int('actividad', request.POST['actividad'])
            aux_dia = validate_number_int('dia', request.POST['dia'])
            detalle = validate_string('detalle', request.POST['detalle'], len_zero='yes')

            user_perfil = apps.get_model('permisos', 'UsersPerfiles').objects.get(user_id=user)
            departamento = apps.get_model('departamentos', 'Departamentos').objects.get(departamento=user_perfil.user_id.username)
            departamento_id = departamento.departamento_id
            actividad = apps.get_model('calendario', 'Actividades').objects.get(pk=actividad_id)

            dia = str(aux_dia)
            if len(dia) == 1:
                dia = "0" + dia

            fecha_inicio = periodo[0:4] + '-' + periodo[4:6] + '-' + dia + ' ' + hora_ini + ':' + minuto_ini + ':00'
            fecha_fin = periodo[0:4] + '-' + periodo[4:6] + '-' + dia + ' ' + hora_fin + ':' + minuto_fin + ':00'
            # verificamos que no exista actividad confirmada en este rango
            sql = f"SELECT COUNT(*) AS cant FROM calendario WHERE fecha_actividad_ini>='{fecha_inicio}' AND fecha_actividad_ini<'{fecha_fin}' AND actividad_id='{actividad_id}' AND status_id='{self.activo}' "
            cant = 0
            with connection.cursor() as cursor:
                cursor.execute(sql)
                row = cursor.fetchone()
                cant = row[0]
                if cant == 0:
                    sql = f"SELECT COUNT(*) AS cant FROM calendario WHERE fecha_actividad_fin>'{fecha_inicio}' AND fecha_actividad_fin<='{fecha_fin}' AND actividad_id='{actividad_id}' AND status_id='{self.activo}' "
                    with connection.cursor() as cursor2:
                        cursor2.execute(sql)
                        row2 = cursor2.fetchone()
                        cant = row2[0]

            if cant > 0:
                self.error_operation = "Ya existen actividades en este rango de fecha para la actividad : " + actividad.actividad
                return False

            # guardamos en la base de datos
            calendario_add = apps.get_model('calendario', 'Calendario').objects.create(
                fecha_actividad_ini=fecha_inicio, fecha_actividad_fin=fecha_fin, departamento_id=departamento_id,
                user_perfil_id_reserva=user_perfil.user_perfil_id, fecha_reserva='now', detalle=detalle,
                actividad_id=actividad, status_id=self.status_inactivo,
                created_at='now', updated_at='now'
            )
            calendario_add.save()

            self.error_operation = ''
            return True

        except Exception as ex:
            self.error_operation = 'Error de datos, ' + str(ex)
            return False

    def confirmar_actividad(self, id, user):
        # armamos los datos
        try:
            calendario_id = validate_number_int('calendario id', id)
            calendario = apps.get_model('calendario', 'Calendario').objects.get(pk=calendario_id)
            fecha_inicio = get_date_to_db(fecha=calendario.fecha_actividad_ini, formato_ori='yyyy-mm-dd HH:ii:ss', formato='yyyy-mm-dd HH:ii:ss')
            fecha_fin = get_date_to_db(fecha=calendario.fecha_actividad_fin, formato_ori='yyyy-mm-dd HH:ii:ss', formato='yyyy-mm-dd HH:ii:ss')

            user_perfil = apps.get_model('permisos', 'UsersPerfiles').objects.get(user_id=user)

            # verificamos que no exista actividad confirmada en este rango
            sql = f"SELECT COUNT(*) AS cant FROM calendario WHERE fecha_actividad_ini>='{fecha_inicio}' AND fecha_actividad_ini<'{fecha_fin}' AND actividad_id='{calendario.actividad_id.actividad_id}' AND status_id='{self.activo}' "
            cant = 0
            with connection.cursor() as cursor:
                cursor.execute(sql)
                row = cursor.fetchone()
                cant = row[0]
                if cant == 0:
                    sql = f"SELECT COUNT(*) AS cant FROM calendario WHERE fecha_actividad_fin>'{fecha_inicio}' AND fecha_actividad_fin<='{fecha_fin}' AND actividad_id='{calendario.actividad_id.actividad_id}' AND status_id='{self.activo}' "
                    with connection.cursor() as cursor2:
                        cursor2.execute(sql)
                        row2 = cursor2.fetchone()
                        cant = row2[0]

            if cant > 0:
                self.error_operation = "Ya existen actividades en este rango de fecha para la actividad : " + calendario.actividad_id.actividad
                return False

            # actualizamos en la base de datos
            calendario.user_perfil_id_confirma = user_perfil.user_perfil_id
            calendario.fecha_confirma = 'now'
            calendario.updated_at = 'now'
            calendario.status_id = self.status_activo
            calendario.save()

            self.error_operation = ''
            return True

        except Exception as ex:
            self.error_operation = 'Error de datos, ' + str(ex)
            return False

    def anular_actividad(self, id, user):
        # armamos los datos
        try:
            calendario_id = validate_number_int('calendario id', id)
            calendario = apps.get_model('calendario', 'Calendario').objects.get(pk=calendario_id)
            fecha_inicio = get_date_to_db(fecha=calendario.fecha_actividad_ini, formato_ori='yyyy-mm-dd HH:ii:ss', formato='yyyy-mm-dd HH:ii:ss')
            fecha_fin = get_date_to_db(fecha=calendario.fecha_actividad_fin, formato_ori='yyyy-mm-dd HH:ii:ss', formato='yyyy-mm-dd HH:ii:ss')

            user_perfil = apps.get_model('permisos', 'UsersPerfiles').objects.get(user_id=user)
            #self.error_operation = 'asdfa'
            # return False

            # verificamos si es usuario departamento, solo puede eliminar sus actividades
            if user_perfil.perfil_id.perfil_id == settings.PERFIL_DEPARTAMENTO:
                departamento = apps.get_model('departamentos', 'Departamentos').objects.get(pk=calendario.departamento_id)
                if user_perfil.user_id.username != departamento.departamento:
                    self.error_operation = 'Solo puede eliminar sus actividades'
                    return False

            # actualizamos en la base de datos
            calendario.user_perfil_id_anula = user_perfil.user_perfil_id
            calendario.fecha_anula = 'now'
            calendario.deleted_at = 'now'
            calendario.status_id = self.status_anulado
            calendario.motivo_anula = ''
            calendario.save()

            self.error_operation = ''
            return True

        except Exception as ex:
            self.error_operation = 'Error de datos, ' + str(ex)
            return False


import cv2
import numpy as np

#Basic image processing methods

#Method for filling holes in connected components of the mask
#In other words, brings all the connected components to simply connected

def fill_holes (img):
    (h, w) = img.shape

    before_area = img.sum ()

    img_enlarged = np.zeros ((h + 2, w + 2), np.uint8)
    img_enlarged [1:h+1, 1:w+1] = img

    img_enl_not = cv2.bitwise_not (img_enlarged)
    th, im_th = cv2.threshold (img_enl_not, 220, 255, cv2.THRESH_BINARY_INV);

    im_floodfill = im_th.copy()

    h, w = im_th.shape[:2]
    mask = np.zeros((h+2, w+2), np.uint8)

    cv2.floodFill(im_floodfill, mask, (0,0), 255);
    im_floodfill_inv = cv2.bitwise_not(im_floodfill)
    im_out = im_th | im_floodfill_inv

    result = im_out [1:h-1, 1:w-1]

    return result

#Method for bringing 3-channel image to RG-chromaticity color space
#Essentially it is a kind of normalization such that the absolute
#values of the intensity are neglected; the components ratios are not

def to_RG_chromaticity (img):
    (h, w, d) = img.shape

    norm = np.zeros ((h, w), np.float)
    norm = img [:, :, 0].astype ('float') +\
           img [:, :, 1].astype ('float') +\
           img [:, :, 2].astype ('float')

    norm [norm == 0] = 5

    turned = np.zeros (img.shape, np.uint8)
    turned [:, :, 0] = ((img [:, :, 0].astype ('float')) / norm * 255).astype ('uint8')
    turned [:, :, 1] = ((img [:, :, 1].astype ('float')) / norm * 255).astype ('uint8')
    turned [:, :, 2] = ((img [:, :, 2].astype ('float')) / norm * 255).astype ('uint8')

    return turned

#Method for finding the bounding box of the connected component having the biggest value
#of the given criterion, i.e. height, width, area.
#Not implemented yet.

#def find_bounding_box (mask, criterion):
#    result = np.array (mask)
#    output = cv2.connectedComponentsWithStats (mask, 8, cv2.CV_32S)
#    labels_num = output      [0]
#    labels     = output      [1]
#    stats      = output      [2]
#    sz         = stats.shape [0]
#
#    max_crit_val = 0
#    max_label    = 0
#
#    for label_num in range (1, sz - 1):
#        if (stats [label_num, cv2.CC_STAT_AREA] > max_w):
#            max_w = stats [label_num, cv2.CC_STAT_AREA]
#            max_label = label_num
#
#    top    = stats [max_label, cv2.CC_STAT_TOP]
#    left   = stats [max_label, cv2.CC_STAT_LEFT]
#    width  = stats [max_label, cv2.CC_STAT_WIDTH]
#    height = stats [max_label, cv2.CC_STAT_HEIGHT]
#
#    return (left, top), (left + width, top + height)

def find_max_bounding_box (mask):
    result = np.array (mask)
    output = cv2.connectedComponentsWithStats (mask, 8, cv2.CV_32S)
    labels_num = output      [0]
    labels     = output      [1]
    stats      = output      [2]
    sz         = stats.shape [0]

    max_area  = 0
    max_label = 0

    for label_num in range (1, sz):
        if (stats [label_num, cv2.CC_STAT_AREA] > max_area):
            max_area = stats [label_num, cv2.CC_STAT_AREA]
            max_label = label_num

    top    = stats [max_label, cv2.CC_STAT_TOP]
    left   = stats [max_label, cv2.CC_STAT_LEFT]
    width  = stats [max_label, cv2.CC_STAT_WIDTH]
    height = stats [max_label, cv2.CC_STAT_HEIGHT]

    return (left, top), (left + width, top + height)


import torch
import torch.nn.init
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import cv2
import numpy as np

# resize image to size 32x32
cv2_scale = lambda x: cv2.resize(x, dsize=(32, 32),
                                 interpolation=cv2.INTER_LINEAR)
# reshape image
np_reshape = lambda x: np.reshape(x, (32, 32, 1))

def zeros_like(x):
    assert x.__class__.__name__.find('Variable') != -1 or x.__class__.__name__.find('Tensor') != -1, "Object is neither a Tensor nor a Variable"
    y = torch.zeros(x.size())
    if x.is_cuda:
       y = y.cuda()
    if x.__class__.__name__ == 'Variable':
        return torch.autograd.Variable(y, requires_grad=x.requires_grad)
    elif x.__class__.__name__.find('Tensor') != -1:
        return torch.zeros(y)

def ones_like(x):
    assert x.__class__.__name__.find('Variable') != -1 or x.__class__.__name__.find('Tensor') != -1, "Object is neither a Tensor nor a Variable"
    y = torch.ones(x.size())
    if x.is_cuda:
       y = y.cuda()
    if x.__class__.__name__ == 'Variable':
        return torch.autograd.Variable(y, requires_grad=x.requires_grad)
    elif x.__class__.__name__.find('Tensor') != -1:
        return torch.ones(y)

def batched_forward(model, data, batch_size, **kwargs):
    n_patches = len(data)
    if n_patches > batch_size:
        bs = batch_size
        n_batches = n_patches / bs + 1
        for batch_idx in range(n_batches):
            st = batch_idx * bs
            if batch_idx == n_batches - 1:
                if (batch_idx + 1) * bs > n_patches:
                    end = n_patches
                else:
                    end = (batch_idx + 1) * bs
            else:
                end = (batch_idx + 1) * bs
            if st >= end:
                continue
            if batch_idx == 0:
                try:
                    first_batch_out = model(data[st:end])#, kwargs)
                except:
                    first_batch_out = model(data[st:end])# kwargs)
                out_size = torch.Size([n_patches] + list(first_batch_out.size()[1:]))
                #out_size[0] = n_patches
                out = torch.zeros(out_size);
                if data.is_cuda:
                    out = out.cuda()
                out = Variable(out)
                out[st:end] = first_batch_out
            else:
                try:
                    out[st:end] = model(data[st:end])#, kwargs)
                except:
                    out[st:end] = model(data[st:end])#, kwargs)
        return out
    else:
        return model(data)#, kwargs)

class L2Norm(nn.Module):
    def __init__(self):
        super(L2Norm,self).__init__()
        self.eps = 1e-10
    def forward(self, x):
        norm = torch.sqrt(torch.sum(x * x, dim = 1) + self.eps)
        x= x / norm.unsqueeze(-1).expand_as(x)
        return x

class L1Norm(nn.Module):
    def __init__(self):
        super(L1Norm,self).__init__()
        self.eps = 1e-10
    def forward(self, x):
        norm = torch.sum(torch.abs(x), dim = 1) + self.eps
        x= x / norm.expand_as(x)
        return x

def str2bool(v):
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False

def CircularGaussKernel(kernlen=None, circ_zeros = False, sigma = None, norm = True):
    assert ((kernlen is not None) or sigma is not None)
    if kernlen is None:
        kernlen = int(2.0 * 3.0 * sigma + 1.0)
        if (kernlen % 2 == 0):
            kernlen = kernlen + 1;
        halfSize = kernlen / 2;
    halfSize = kernlen / 2;
    r2 = float(halfSize*halfSize)
    if sigma is None:
        sigma2 = 0.9 * r2;
        sigma = np.sqrt(sigma2)
    else:
        sigma2 = 2.0 * sigma * sigma
    x = np.linspace(-halfSize,halfSize,kernlen)
    xv, yv = np.meshgrid(x, x, sparse=False, indexing='xy')
    distsq = (xv)**2 + (yv)**2
    kernel = np.exp(-( distsq/ (sigma2)))
    if circ_zeros:
        kernel *= (distsq <= r2).astype(np.float32)
    if norm:
        kernel /= np.sum(kernel)
    return kernel

def generate_2dgrid(h,w, centered = True):
    if centered:
        x = torch.linspace(-w/2+1, w/2, w)
        y = torch.linspace(-h/2+1, h/2, h)
    else:
        x = torch.linspace(0, w-1, w)
        y = torch.linspace(0, h-1, h)
    grid2d = torch.stack([y.repeat(w,1).t().contiguous().view(-1), x.repeat(h)],1)
    return grid2d

def generate_3dgrid(d, h, w, centered = True):
    if type(d) is not list:
        if centered:
            z = torch.linspace(-d/2+1, d/2, d)
        else:
            z = torch.linspace(0, d-1, d)
        dl = d
    else:
        z = torch.FloatTensor(d)
        dl = len(d)
    grid2d = generate_2dgrid(h,w, centered = centered)
    grid3d = torch.cat([z.repeat(w*h,1).t().contiguous().view(-1,1), grid2d.repeat(dl,1)],dim = 1)
    return grid3d

def zero_response_at_border(x, b):
    if (b < x.size(3)) and (b < x.size(2)):
        x[:, :,  0:b, :] =  0
        x[:, :,  x.size(2) - b: , :] =  0
        x[:, :, :,  0:b] =  0
        x[:, :, :,   x.size(3) - b: ] =  0
    else:
        return x * 0
    return x

class GaussianBlur(nn.Module):
    def __init__(self, sigma=1.6):
        super(GaussianBlur, self).__init__()
        weight = self.calculate_weights(sigma)
        self.register_buffer('buf', weight)
        return
    def calculate_weights(self,  sigma):
        kernel = CircularGaussKernel(sigma = sigma, circ_zeros = False)
        h,w = kernel.shape
        halfSize = float(h) / 2.;
        self.pad = int(np.floor(halfSize))
        return torch.from_numpy(kernel.astype(np.float32)).view(1,1,h,w);
    def forward(self, x):
        w = Variable(self.buf)
        if x.is_cuda:
            w = w.cuda()
        return F.conv2d(F.pad(x, (self.pad,self.pad,self.pad,self.pad), 'replicate'), w, padding = 0)

def batch_eig2x2(A):
    trace = A[:,0,0] + A[:,1,1]
    delta1 = (trace*trace - 4 * ( A[:,0,0]*  A[:,1,1] -  A[:,1,0]* A[:,0,1]))
    mask = delta1 > 0
    delta = torch.sqrt(torch.abs(delta1))
    l1 = mask.float() * (trace + delta) / 2.0 +  1000.  * (1.0 - mask.float())
    l2 = mask.float() * (trace - delta) / 2.0 +  0.0001  * (1.0 - mask.float())
    return l1,l2

def line_prepender(filename, line):
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip('\r\n') + '\n' + content)
    return


from histologieverwaltung.views import HistoMethods
from django.conf.urls import patterns, url

urlpatterns = patterns('histologieverwaltung.views',

    url(r'^$', 'index', name='index'),
    url(r'^detail/(?P<patient_id>[a-z A-Z 0-9]+)/(?P<histo_id>[\d\-H]+)/$', HistoMethods.showHistoDetail, name='histoDetail'),
    url(r'^showPatientHisto/(?P<patient_id>[a-z A-Z 0-9]+)/$', HistoMethods.showPatientHisto, name='showPatientProbe'),
    url(r'^anzeigeHistologiebefunde_admin/$', HistoMethods.showHistoBefunde_admin,name='showHistoBefunde_admin'),
    url(r'^erstelleHistologiebefund/(?P<patient_id>[a-z A-Z 0-9]+)/$', HistoMethods.createHistoBefund, name='createHistoBefund'),
    url(r'^editHistologiebefund/(?P<histo_ID>[\d\-H]+)$', HistoMethods.editHistoBefund,name='editHistoBefundForm'),
    url(r'^anzeigeHistologiebefunde_admin/deleteToggleHistologiebefund/(?P<histo_ID>[\d\-H]+)$', HistoMethods.toggleHisto, name='toggleHisto'),

)


from flask import Flask, request, Response
from kik import KikApi, Configuration
from kik.messages import messages_from_json, TextMessage, PictureMessage, SuggestedResponseKeyboard, TextResponse, StartChattingMessage
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='db_kik')
curs = conn.cursor()

class KikBot(Flask):

    """ Flask kik bot application class"""

    def __init__(self, kik_api, import_name, static_path=None, static_url_path=None, static_folder="static",
                 template_folder="templates", instance_path=None, instance_relative_config=False,
                 root_path=None):

        self.kik_api = kik_api

        super(KikBot, self).__init__(import_name, static_path, static_url_path, static_folder, template_folder,
                                     instance_path, instance_relative_config, root_path)

        self.route("/incoming", methods=["POST"])(self.incoming)

    def incoming(self):
        """Handle incoming messages to the bot. All requests are authenticated using the signature in
        the 'X-Kik-Signature' header, which is built using the bot's api key (set in main() below).
        :return: Response
        """
        # verify that this is a valid request
        if not self.kik_api.verify_signature(
                request.headers.get("X-Kik-Signature"), request.get_data()):
            return Response(status=403)

        messages = messages_from_json(request.json["messages"])

        response_messages = []

        for message in messages:
            user = self.kik_api.get_user(message.from_user)
            # Check if its the user's first message. Start Chatting messages are sent only once.
            if isinstance(message, StartChattingMessage):

                response_messages.append(TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body="haloo {}, pilihlah salah satu?".format(user.first_name),
                    # keyboards are a great way to provide a menu of options for a user to respond with!
                    keyboards=[SuggestedResponseKeyboard(responses=[TextResponse("Good"), TextResponse("ga")])]))

            # Check if the user has sent a text message.
            elif isinstance(message, TextMessage):
                user = self.kik_api.get_user(message.from_user)
                message_body = message.body.lower()
                print(message_body)
                sql = """insert into tb_inbox(user, message)
                        values ('%s','%s')""" % (user.first_name, message_body)
                print("Berhasil Menginputkan")

                curs.execute(sql)

                conn.commit()

                if message_body.split()[0] in ["hi", "hello", "hallo"]:
                    query = "SELECT in_message FROM tb_perintah"
                    curs.execute(query)
                    menu = curs.fetchall()
                    print(message_body)
                    print(menu)
                    msg = "List Menu !!\n"
                    iterasi = 1
                    for x in menu:
                        for y in x:
                            print(y)
                            msg = msg + ""+str(iterasi)+". "+y+"\n"
                        iterasi+=1
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body=msg.format(user.first_name),
                        keyboards=[SuggestedResponseKeyboard(responses=[TextResponse("1"), TextResponse("2"), TextResponse("3"), TextResponse("4")])]))

                    query = "INSERT INTO tb_outbox (user,message,status) VALUES('%s','%s','1')" % (user.first_name, message_body)
                    curs.execute(query)
                    conn.commit()

                elif message_body.startswith("#"):

                    msg = message_body.split()

                    print(msg[0])

                    query = "SELECT query FROM tb_perintah WHERE marker = '%s' " % (msg[0])

                    print(query)

                    try:

                        curs.execute(query)

                    except:

                        print("ERROR")

                    menu = curs.fetchone()

                    print(menu[0])

                    if menu != None:

                        try:

                            msgProdi = msg[6] + " " + msg[7]

                            print(msgProdi)

                            qry = menu[0] % ("%" + msg[3] + "%", "%" + msgProdi + "%")

                        except:

                            print("INDEX MESSAGE TIDAK DITEMUKAN")

                            qry = menu[0]

                        print(qry)

                        curs.execute(qry)

                        data = curs.fetchall()

                        iterasi = 0

                        teks = ""

                        msgNew = ""

                        for row in data:

                            for i in curs.description:
                                print(i[0])

                                print(row[iterasi])

                                msgNew = msgNew + (i[0] + " = " + str(row[iterasi]) + "\n")

                                iterasi += 1

                                # if iterasi == i*4:

                                #     msgNew = "\n"

                                # else:

                                #     msgNew = ""

                            iterasi = 0

                    query = "INSERT INTO tb_outbox (user,message,status) VALUES('%s','%s','0')" % (

                        user.first_name, message_body)

                    print(query)

                    curs.execute(query)

                    conn.commit()

                    response_messages.append(TextMessage(

                        to=message.from_user,

                        chat_id=message.chat_id,

                        body=msgNew))

                else:
                    print(int(message_body))
                    query = "SELECT * FROM tb_perintah WHERE id_perintah = %i " %(int(message_body))
                    curs.execute(query)
                    menu = curs.fetchone()
                    print(message.from_user)
                    print(message.chat_id)
                    print(menu[2])
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body=menu[2].format(user.first_name)))

                query = "INSERT INTO tb_outbox (user,message,status) VALUES('%s','%s','1')" % (user.first_name, message_body, )
                curs.execute(query)
                conn.commit()

                #query = "INSERT INTO tb_outbox (user,message) VALUES('%s','%s')" % (user.first_name, message_body)
                #curs.execute(query)
                #conn.commit()

                # elif message_body == "1":
                #     response_messages.append(TextMessage(
                #         to=message.from_user,
                #         chat_id=message.chat_id,
                #         body="masukan nama mahasiswa :",
                #         keyboards=[SuggestedResponseKeyboard(
                #             responses=[TextResponse("miftah")])]))
                #
                #
                #
                # elif message_body == "2":
                #     response_messages.append(TextMessage(
                #         to=message.from_user,
                #         chat_id=message.chat_id,
                #         body="Masukan nama dosen :",
                #         keyboards=[SuggestedResponseKeyboard(
                #             responses=[TextResponse("boleh"), TextResponse("tidak")])]))
                #
                # elif message_body == "3":
                #     response_messages.append(TextMessage(
                #         to=message.from_user,
                #         chat_id=message.chat_id,
                #         body="masukan semua mahasiswa :",
                #         keyboards=[SuggestedResponseKeyboard(
                #             responses=[TextResponse("boleh"), TextResponse("tidak")])]))
                #
                # elif message_body == "4":
                #     response_messages.append(TextMessage(
                #         to=message.from_user,
                #         chat_id=message.chat_id,
                #         body="masukan semua dosen :",
                #         keyboards=[SuggestedResponseKeyboard(
                #             responses=[TextResponse("boleh"), TextResponse("tidak")])]))
                #

                    # Send the user a response along with their profile picture (function definition is below)

            #
            #     elif message_body in ["Engga","tidak", "Gak mau"]:
            #         response_messages.append(TextMessage(
            #             to=message.from_user,
            #             chat_id=message.chat_id,
            #             body="Okedeh, {}. Semangat yaa, jangan lupa chat aku lagi :)".format(user.first_name)))
            #     else:
            #         response_messages.append(TextMessage(
            #             to=message.from_user,
            #             chat_id=message.chat_id,
            #             body="maaf om {}, saya ga ngerti yang di maksud".format(user.first_name),
            #             keyboards=[SuggestedResponseKeyboard(responses=[TextResponse("boleh"), TextResponse("Engga")])]))

            # If its not a text message, give them another chance to use the suggested responses
            else:

                response_messages.append(TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body="maaf itu apa ya {}?".format(user.first_name),
                    keyboards=[SuggestedResponseKeyboard(responses=[TextResponse("Good"), TextResponse("Bad")])]))

            # We're sending a batch of messages. We can send up to 25 messages at a time (with a limit of
            # 5 messages per user).

            self.kik_api.send_messages(response_messages)

        return Response(status=200)

    @staticmethod
    def profile_pic_check_messages(user, message):
        """Function to check if user has a profile picture and returns appropriate messages.
        :param user: Kik User Object (used to acquire the URL the profile picture)
        :param message: Kik message received by the bot
        :return: Message
        """

        messages_to_send = []
        profile_picture = user.profile_pic_url

        if profile_picture is not None:
            messages_to_send.append(
                # Another type of message is the PictureMessage - your bot can send a pic to the user!
                PictureMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    pic_url=profile_picture
                ))

            profile_picture_response = "ini dia foto kamuu!"
        else:
            profile_picture_response = "ga mirip loh, yaudh lah yaa"

        messages_to_send.append(
            TextMessage(to=message.from_user, chat_id=message.chat_id, body=profile_picture_response))

        return messages_to_send

if __name__ == "__main__":
    """ Main program """
    kik = KikApi('botmca', 'fffa79e9-afe9-45e4-b2bd-6ec78732b3de')
    # For simplicity, we're going to set_configuration on startup. However, this really only needs to happen once
    # or if the configuration changes. In a production setting, you would only issue this call if you need to change
    # the configuration, and not every time the bot starts.
    kik.set_configuration(Configuration(webhook='https://c6aaa154.ngrok.io/incoming'))
    app = KikBot(kik, __name__)
    app.run(port=8080, host='127.0.0.1', debug=True)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- Python -*-

from __future__ import print_function
import sys
sys.path.append(".")

import RTC
import OpenRTM_aist

import tkmotor
import time

mod_spec = ["implementation_id", "TkMotorPosComp",
            "type_name", "TkMotorPosComp",
            "description", "Tk Motor component (position control)",
            "version", "1.0",
            "vendor", "Noriaki Ando and Shinji Kurihara",
            "category", "Generic",
            "activity_type", "DataFlowComponent",
            "max_instance", "10",
            "language", "Python",
            "lang_type""SCRIPT",
            ""]

tkm = tkmotor.TkMotor(6, 40)
#thread.start_new_thread(tkm.mainloop, ())

class TkMotorPosComp(OpenRTM_aist.DataFlowComponentBase):
  def __init__(self, manager):
    OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)
    self._cnt = 0
    self._num = 6
    return

  def onInitialize(self):
    self._tk_data = RTC.TimedFloatSeq(RTC.Time(0,0), [])
    self._tkIn = OpenRTM_aist.InPort("pos", self._tk_data)

    self.addInPort("pos", self._tkIn)
    return RTC.RTC_OK

  def onActivated(self, ec_id):
    val = [self._cnt] * self._num
    tkm.set_angle(val)
    time.sleep(0.01)
    self._cnt += 1
    self._v = [0] * 6
    return RTC.RTC_OK

  def onExecute(self, ec_id):
    try:
      indata = self._tkIn.read()
      val = indata.data
      print(val)
      if len(val) == 6:
        for i in range(6):
          self._v[i] = val[i] * 10
        tkm.set_angle(self._v)
    except:
      print("Exception cought in onExecute()")

    time.sleep(0.01)
    return RTC.RTC_OK

  def onShutdown(self, ec_id):
    tkm.quit()
    return RTC.RTC_OK

def TkMotorPosCompInit(manager):
  profile = OpenRTM_aist.Properties(defaults_str=mod_spec)
  manager.registerFactory(profile,
                          TkMotorPosComp,
                          OpenRTM_aist.Delete)

def MyModuleInit(manager):
  TkMotorPosCompInit(manager)

  # Create a component
  comp = manager.createComponent("TkMotorPosComp")

  print("Componet created")

def main():
  # Initialize manager
  mgr = OpenRTM_aist.Manager.init(sys.argv)

  # Set module initialization proceduer
  # This procedure will be invoked in activateManager() function.
  mgr.setModuleInitProc(MyModuleInit)

  # Activate manager and register to naming service
  mgr.activateManager()

  # run the manager in blocking mode
  # runManager(False) is the default
  #mgr.runManager()

  # If you want to run the manager in non-blocking mode, do like this
  mgr.runManager(True)
  tkm.mainloop()

if __name__ == "__main__":
  main()


# test our installation of h5py

import sys
import os
import numpy as np
import h5py

fname = 'run_test_helloworld.h5'
f = h5py.File(fname,'w')
f['data'] = 'hello world!'
f['data2'] = np.zeros((3,5), np.int32)
del f
h5 = h5py.File(fname,'r')
assert h5['data'].value == 'hello world!'
assert h5['data2'].shape[0]==3
assert h5['data2'].shape[1]==5
assert np.sum(h5['data2'][:])==0

del h5
os.unlink(fname)

from mpi4py import MPI
sys.stdout.write("mpi version: %r\n" % (MPI.get_vendor(),))


#__author: liutengyu
#__Date:2018/6/25
import re
path_rwfile='C:/Users/Administrator/Desktop/01上线工作目录lty/'
#a系统名 b表名 c主键 line[3]算法
def write(query,switcher,writer):
    for line in query:
        print(len(query))
        line=line.replace('\n','')
        line=line.split('\t')
        print(line)
        a=line[0]
        ah=a[:1]+"H"+a[1:]
        b=line[1]
        c=line[2]
        sh_py=ah+'_'+b+'0200.py'
        sh_py=sh_py.lower()
        print(a,b,c)
        if line[3] in switcher:
            PK=switcher[line[3]]
            for i in range(2):
                PK=PK.replace('$a$',a)
                PK=PK.replace('$ah$',ah)
                PK=PK.replace('$b$',b)
                PK=PK.replace('$c$',c)
                PK=PK.replace('$sh_py$',sh_py)
            ####################################
                lis_c=c.split(',')
                Ac_Bc=[]
                for i_c,j in zip(lis_c,range(len(lis_c))):
                    lis_c[j]='A.'+i_c
                    lis_b='B.'+i_c
                    Ac_Bc.append('A.'+i_c+'='+lis_b)
                Ac=','.join(lis_c)
                Ac_Bc=','.join(Ac_Bc)
                PK=PK.replace('$A.c$',Ac)
                PK=PK.replace('$A.c=B.c$',Ac_Bc)
            ######################################
                print(PK)
                writer.write(PK+'\n')
                if line[3]+'_H' in  switcher:
                    PK=switcher[line[3]+'_H']
                else:
                    break

def PCheckSA():#主键检测
    switch_P_SA={
    'I':"UNION ALL SELECT '$a$_$b$','主键重复',TAB.CNT FROM (SELECT $c$,COUNT(*) AS CNT FROM SDATA.$a$_$b$ WHERE DT=\'$bizDate$\' GROUP BY $c$ HAVING CNT>1) TAB",
    'F3':"UNION ALL SELECT '$a$_$b$',\'主键重复\',TAB.CNT FROM (SELECT $c$,COUNT(*) AS CNT FROM SDATA.$a$_$b$ WHERE DT=\'$bizDate$\' GROUP BY $c$ HAVING CNT>1) TAB",
    'F5':"UNION ALL SELECT '$a$_$b$',\'主键重复\',TAB.CNT FROM (SELECT $c$,COUNT(*) AS CNT FROM SDATA.$a$_$b$ WHERE DT=\'$bizDate$\' GROUP BY $c$ HAVING CNT>1) TAB"
    }
    checkcode_sdatapk2 = open(path_rwfile+'config.conf', "a", encoding="utf-8")
    checkcode_sdatapk2.write('PrimaryCheckSA.conf:\n')
    write(query,switch_P_SA,checkcode_sdatapk2)
    checkcode_sdatapk2.close()

def PCheckSH():
    switch_P_SH={
    'I':"UNION ALL SELECT '$ah$_$b$' ,'主键重复',TAB.CNT FROM (SELECT COUNT(*) AS CNT FROM SHDATA.$ah$_$b$  GROUP BY $c$ HAVING CNT>1) TAB",
    'F3':"UNION ALL SELECT '$ah$_$b$' ,'主键重复',TAB.CNT FROM (SELECT COUNT(*) AS CNT FROM SHDATA.$ah$_$b$  GROUP BY $c$ HAVING CNT>1) TAB",
    'F5':"UNION ALL SELECT '$ah$_$b$' ,'主键重复',TAB.CNT FROM (SELECT COUNT(*) AS CNT FROM SHDATA.$ah$_$b$  GROUP BY $c$ HAVING CNT>1) TAB",
    'F3_H':"UNION ALL SELECT '$ah$_$b$_H' ,'主键重复',TAB.CNT FROM (SELECT COUNT(*) AS CNT FROM SHDATA.$ah$_$b$_H GROUP BY $c$,start_dt HAVING CNT>1) TAB",
    'F5_H':"UNION ALL SELECT '$ah$_$b$_H' ,'主键重复',TAB.CNT FROM (SELECT COUNT(*) AS CNT FROM SHDATA.$ah$_$b$_H GROUP BY $c$,start_dt HAVING CNT>1) TAB"
    }
    checkcode_sdatapk2 = open(path_rwfile+'config.conf', "a", encoding="utf-8")
    checkcode_sdatapk2.write('PrimaryCheckSH.conf:\n')
    write(query,switch_P_SH,checkcode_sdatapk2)
    checkcode_sdatapk2.close()

def CheckSASH():
    switch_SASH={
    'I':"UNION ALL SELECT sa.name,\'数据sa与sh比对\',1 FROM (SELECT count(*) num,'$b$' name  FROM SDATA.$a$_$b$  ) AS sa JOIN (SELECT count(*) num,'$b$' name  FROM SHDATA.$ah$_$b$ ) AS sh ON sa.name=sh.name WHERE sa.num <> sh.num",
    'F3':"UNION ALL SELECT sa.name,\'数据sa与sh比对\',1 FROM (SELECT count(*) num,'$b$' name  FROM SDATA.$a$_$b$  where dt =\'$bizDate$\') AS sa JOIN(SELECT count(*) num,'$b$' name  FROM SHDATA.$ah$_$b$ ) AS sh ON sa.name=sh.name JOIN (SELECT count(*) num,'$b$' name  FROM SHDATA.$ah$_$b$_H where end_dt=\'3000-12-31\' and start_dt=\'$bizDate10$\' ) AS sh_h ON sh.name = sh_h.name WHERE sa.num <> sh.num or   sh.num <> sh_h.num OR   sa.num <> sh_h.num",
    'F5':"UNION ALL SELECT sa.name,\'数据sa与sh比对\',1 FROM (SELECT count(*) num,'$b$' name  FROM SDATA.$a$_$b$  where dt =\'$bizDate$\') AS sa JOIN(SELECT count(*) num,'$b$'  name  FROM SHDATA.$ah$_$b$ ) AS sh ON sa.name=sh.name JOIN (SELECT count(*) num,'$b$'  name  FROM SHDATA.$ah$_$b$_H where end_dt=\'3000-12-31\' ) AS sh_h ON sh.name = sh_h.name WHERE sa.num <> sh.num or   sh.num <> sh_h.num OR   sa.num <> sh_h.num"
    }
    checkcode_sdatapk2 = open(path_rwfile+'config.conf', "a", encoding="utf-8")
    checkcode_sdatapk2.write('sash.conf:\n')
    write(query,switch_SASH,checkcode_sdatapk2)
    checkcode_sdatapk2.close()

def CheckCross():
    switch_Cross={
    'F3':"UNION ALL SELECT '$ah$_$b$_H',\'交叉链\',TAB.CNT FROM (SELECT $A.c$,COUNT(*) AS CNT FROM shdata.$ah$_$b$_H A LEFT JOIN SHDATA.$ah$_$b$_H B ON $A.c=B.c$ AND A.START_DT = B.END_DT WHERE B.END_DT IS NULL GROUP BY $A.c$ HAVING COUNT(*)>1) TAB",
    'F5':"UNION ALL SELECT '$ah$_$b$_H',\'交叉链\',TAB.CNT FROM (SELECT $A.c$,COUNT(*) AS CNT FROM shdata.$ah$_$b$_H A LEFT JOIN SHDATA.$ah$_$b$_H B ON $A.c=B.c$ AND A.START_DT = B.END_DT WHERE B.END_DT IS NULL GROUP BY $A.c$ HAVING COUNT(*)>1) TAB"
    }
    checkcode_sdatapk2 = open(path_rwfile+'config.conf', "a", encoding="utf-8")
    checkcode_sdatapk2.write('CrossChainSH.conf:\n')
    write(query,switch_Cross,checkcode_sdatapk2)
    checkcode_sdatapk2.close()

def CheckEff():
    switch_Eff={
    'F3':"UNION ALL SELECT  T.NAME,\'有效数据检测\',T.NUM FROM (SELECT \'$ah$_$b$_H\' AS NAME,COUNT(*) AS NUM FROM SHDATA.$ah$_$b$_H WHERE  START_DT>END_DT) T WHERE T.NUM!=0",
    'F5':"UNION ALL SELECT  T.NAME,\'有效数据检测\',T.NUM FROM (SELECT \'$ah$_$b$_H\' AS NAME,COUNT(*) AS NUM FROM SHDATA.$ah$_$b$_H WHERE  START_DT>END_DT) T WHERE T.NUM!=0"
    }
    checkcode_sdatapk2 = open(path_rwfile+'config.conf', "a", encoding="utf-8")
    checkcode_sdatapk2.write('ShEffective.conf:\n')
    write(query,switch_Eff,checkcode_sdatapk2)
    checkcode_sdatapk2.close()
def CheckEdepen():
    switch_dep={
    'I' :"INSERT INTO etl.ETL_JOB_DEPENDENCE_CONTROL VALUES ('SHDATA.$ah$_$b$','SDATA.$a$_$b$','SHDATA','$a$','$ah$_$b$','SHDATA.$ah$_$b$','$sh_py$','','','')",
    'F3':"INSERT INTO etl.ETL_JOB_DEPENDENCE_CONTROL VALUES ('SHDATA.$ah$_$b$','SDATA.$a$_$b$','SHDATA','$a$','$ah$_$b$','SHDATA.$ah$_$b$','$sh_py$','','','')",
    'F5':"INSERT INTO etl.ETL_JOB_DEPENDENCE_CONTROL VALUES ('SHDATA.$ah$_$b$','SDATA.$a$_$b$','SHDATA','$a$','$ah$_$b$','SHDATA.$ah$_$b$','$sh_py$','','','')"
    }
    #INSERT INTO etl.ETL_JOB_DEPENDENCE_CONTROL VALUES ('SHDATA.SH001_OUT_DATA_WC_GJJ','SDATA.S001_OUT_DATA_WC_GJJ','SHDATA','S001','SH001_OUT_DATA_WC_GJJ','SHDATA.SH001_OUT_DATA_WC_GJJ','sh001_out_data_wc_gjj0200.py','','','')
    checkcode_sdatapk2 = open(path_rwfile+'config.conf', "a", encoding="utf-8")
    checkcode_sdatapk2.write('dependence.conf:\n')
    write(query,switch_dep,checkcode_sdatapk2)
    checkcode_sdatapk2.close()

def CheckStrategy():
    checkcode_sdatapk2 = open(path_rwfile+'config.conf', "a", encoding="utf-8")
    checkcode_sdatapk2.write('TableStrategy:\n')
    for line in query:
        line=line.split('\t')
        checkcode_sdatapk2.write(line[1]+':'+line[3]+'\n')
        checkcode_sdatapk2.write(line[0]+'_'+line[1]+r"_FIELDS_TERMINATE='\001'")
    checkcode_sdatapk2.write('\n\n')
    checkcode_sdatapk2.close()

def TaskctlSet():
    checkcode_sdatapk2 = open(path_rwfile+'config.conf', "a", encoding="utf-8")
    checkcode_sdatapk2.write('\n\n\nTaskctlSet:\n')
    JobMOdSH='''
        <python>
            <name>SH$sys$_$tablenameE$$tablenameC$</name>
            <progname>$(sh$sys$Path)sh$sys$_$tablenameS$0200.py</progname>
            <para>$(bizDate)</para>
        </python>
        '''
    JobMOdSHH='''
        <python>
            <name>SH$sys$_$tablenameE$_H$tablenameC$</name>
            <progname>$(sh$sys$Path)sh$sys$_$tablenameS$_h0200.py</progname>
            <para>$(bizDate)</para>
        </python>
        '''
    JobMOdSA='''
        <python>
            <name>S$sys$_$tablenameE$$tablenameC$</name>
            <progname>$(filePath)</progname>
            <para>S$sys$ $tablenameE$ $(bizDate) $para$</para>
        </python>
        '''
    def repl(ss):
        ss=ss.replace('$sys$',sys)
        ss=ss.replace('$tablenameE$',tablenameE)
        ss=ss.replace('$tablenameC$',tablenameC)
        ss=ss.replace('$tablenameS$',tablenameS)
        ss=ss.replace('$para$',para)
        return ss

    def SetSA():
        nonlocal para
        #global para
        ss=JobMOdSA
        if line[3]=='I' or line[3]=='F3':
            para='1 "'+line[5]+'" null $(bizDate)'
            checkcode_sdatapk2.write(repl(ss))
        else:
            para='0 null null null'
            checkcode_sdatapk2.write(repl(ss))

    def SetSH():
        ss=JobMOdSH
        seriel_name="\n        <name>"+line[0]+"_"+line[1]+"</name>"
        if line[3]=='I':
            tmp='<serial>'+seriel_name+repl(ss)+'</serial>\n'
            checkcode_sdatapk2.write(tmp)
        else:
            tmp=repl(ss)+repl(JobMOdSHH)
            tmp='<serial>'+seriel_name+tmp+'</serial>\n'
            checkcode_sdatapk2.write(tmp)

    for i in range(2):
        if i==0:
            for line in query:
                print (line)
                line=line.replace('\n','')
                line=line.split('\t')
                sys=re.search('[0-9]{3}',line[0], flags=0).group()
                tablenameE=line[1].upper()
                tablenameC=line[4]
                tablenameS=line[1].lower()
                para=''
                SetSA()
        else:
            for line in query:
                line=line.replace('\n','')
                line=line.split('\t')
                sys=re.search('[0-9]{3}',line[0], flags=0).group()
                tablenameE=line[1].upper()
                tablenameC=line[4]
                tablenameS=line[1].lower()
                para=''
                SetSH()
    checkcode_sdatapk2.close()
checkcode_sdatapk2 = open(path_rwfile+'onlinetable.txt', "r",encoding='utf-8')
query=checkcode_sdatapk2.readlines()
print(query)
function=[CheckStrategy,PCheckSA,PCheckSH,CheckSASH,CheckCross,CheckEff,CheckEdepen,TaskctlSet]
for fun in function[:]:
    fun()