import dataset
import sys
import copy
import numpy as np
import random
import pickle

import torch.nn.functional as functional
import torch
from torch.utils.data import Dataset,DataLoader
from torch.autograd import Variable
import torch.nn as nn
from model import Encoder
from model import Decoder

train_file = sys.argv[1]
batch_size = 16
enco_input_size = 10
enco_hidden_size = 500
embed_size = 1500
deco_hidden_size = 1000
deco_input_size = 0
sent_limit = 12
learning_rate = 1e-3
epochs = 100
times = '9'
model_name = 'model'+times+'.th'

online = 0
post = sys.stdout
if online == 1:
    post = open('/home/piepie01/public_html/123/output1','w')

def count_parameters(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

class clr_conv(Dataset):
    def __init__(self,train_X,train_Y,word2index):
        self.X = copy.copy(train_X)
        self.Y = copy.copy(train_Y)
        self.word2index = word2index
    def __len__(self):
        return len(self.Y)
    def __getitem__(self,index):
        x = [0 for i in range(sent_limit)]
        y = [0 for i in range(sent_limit)]
        x[0] = 1
        y[0] = 1
        for i,txt in enumerate(self.X[index].split()):
            if txt in self.word2index.keys():
                x[i+1] = self.word2index[txt]
            else:
                x[i+1] = 3
            x[i+2] = 2
        for i,txt in enumerate(self.Y[index].split()):
            if txt in self.word2index.keys():
                y[i+1] = self.word2index[txt]
            else:
                y[i+1] = 3
            y[i+2] = 2
        x = torch.LongTensor(x).cuda()
        y = torch.LongTensor(y).cuda()
        return x,y

def index2sent(sent,index2word):
    l = [index2word[i] for i in sent]
    return ' '.join(l)
def get_weight(length):
    w = np.array([1 for _ in range(length)])

def main(argv):
    train_X, train_Y = dataset.read_data(train_file,post)
    word2index, index2word = dataset.word2vec(train_X,post)
    #print(word2index[:10])
    with open('save/word'+times+'.pickle','wb') as f:
        pickle.dump(word2index,f)
    with open('save/index'+times+'.pickle1','wb') as f:
        pickle.dump(index2word,f)
    #exit()
    conv = clr_conv(train_X,train_Y,word2index)
    data_loader = DataLoader(conv, shuffle = True, batch_size = batch_size)

    encoder = Encoder(enco_input_size, enco_hidden_size, len(word2index),embed_size).cuda()
    decoder = Decoder(deco_input_size, deco_hidden_size, len(word2index), sent_limit,embed_size).cuda()

    print("Encoder's parameters :",count_parameters(encoder))
    print("Decoder's parameters :",count_parameters(decoder))
    weight = get_weight(len(word2index))
    #criterion = nn.CrossEntropyLoss().cuda()
    criterion = nn.NLLLoss().cuda()
    enco_opt = torch.optim.Adam(encoder.parameters(), lr = learning_rate)
    deco_opt = torch.optim.Adam(decoder.parameters(), lr = learning_rate)

    for epoch in range(epochs):
        total = 0
        step_count = 0
        max_step = 10000
        for x,y in data_loader:
            if step_count > max_step:
                break
                #continue
            enco_opt.zero_grad()
            deco_opt.zero_grad()
            inp = Variable(x)
            oup = Variable(y)
            x_size = x.size()
            y_size = y.size()
            #print('x_size :',x_size)
            #print('y_size :',y_size)
            deco_padding = Variable(torch.zeros(1,x_size[0],deco_hidden_size).cuda())
            #enco_hid = Variable(torch.zeros(1,batch_size,enco_hidden_size).cuda()), Variable(torch.zeros(1,batch_size,enco_hidden_size).cuda())
            deco_hid = Variable(torch.zeros(1,batch_size,deco_hidden_size).cuda())
            enco_hid = None
            #deco_hid = None

            enco_out1, enco_hid = encoder(inp, enco_hid)
            #print(deco_padding.size())
            #print('enco_out1 :',enco_out1.size())
            #print('deco_hid :',deco_hid.size())
            #print('enco_hid :',enco_hid[0].size())
            #deco_out, deco_emb, deco_hid = decoder(enco_out1,deco_padding,deco_hid)
            #print('deco_out :',deco_out.size())
            #print('deco_emb :',deco_emb.size())
            #print('deco_hid :',deco_hid[0].size())
            embed = Variable(torch.zeros(x_size[0],1,embed_size).cuda())

            loss = 0.0
            #enco_padding = Variable(torch.zeros(x_size[0],enco_input_size).long().cuda())
            enco_padding = Variable(torch.zeros(x_size[0],sent_limit).long().cuda())
            sentence = []
            sent_ind = random.randint(0,batch_size-1)
            if random.random() < 0.5:
                for i in range(y_size[1]):
                    #enco_out2, enco_hid = encoder(enco_padding, enco_hid)
                    #print('enco_out2 :',enco_out2.size())
                    #print('embed :',embed.size())
                    #exit()
                    #print(enco_out1.size())
                    #print('embed_size',embed.size())
                    deco_out2, embed, deco_hid = decoder(enco_out1,embed.view(1,x_size[0],embed_size),deco_hid)

                    embed = decoder.embed(oup[:,i]).view(1,-1,deco_hidden_size)
                    sentence.append(torch.max(deco_out2[sent_ind].view(1,-1),1)[1].data[0])
                    loss+=criterion(deco_out2,oup[:,i])
            else:
                for i in range(y_size[1]):
                    #enco_out2, enco_hid = encoder(enco_padding, enco_hid)
                    #print('enco_out2 :',enco_out2.size())
                    #print('embed :',embed.size())
                    #exit()
                    deco_out2, embed, deco_hid = decoder(enco_out1,embed.view(1,x_size[0],embed_size),deco_hid)
                    sentence.append(torch.max(deco_out2[sent_ind].view(1,-1),1)[1].data[0])
                    loss+=criterion(deco_out2,oup[:,i])
            #print(sentence)
            #exit()
            total+=loss.data[0]
            if step_count % 100 == 0:
                print('[epoch:{}], [step:{}] : {}'.format(epoch, step_count,loss.data[0]/y_size[1]),file = post)
                print("Q mao's output :",index2sent(sentence, index2word),file = post)
                print("Sample input :",index2sent(inp.cpu().data[sent_ind].numpy(), index2word),file = post)
                print("Sample output :",index2sent(oup.cpu().data[sent_ind].numpy(), index2word),file = post)
                post.flush()
            step_count+=1
            loss.backward()
            torch.nn.utils.clip_grad_norm(encoder.parameters(), 0.25)
            torch.nn.utils.clip_grad_norm(encoder.parameters(), 0.25)
            enco_opt.step()
            deco_opt.step()
            #exit()
        if (epoch+1) % 1 == 0:
            torch.save({'encoder': encoder.state_dict(),'decoder': decoder.state_dict()},'save/'+model_name)
if __name__ == "__main__":
    main(sys.argv)


import os
import sys
from .Configuration import Configuration
try:
	import pty, select
except Exception as e:
	print(e)

_b = sys.version_info[0] < 3 and (lambda x:x) or (lambda x:x.encode('utf-8'))

class ConnectionSSH():

	@staticmethod
	def ssh_exec(args, capture_output=False):
		log = []
		# [
		#	0. "sftp",
		#	***. Connection.usuario + "@" + Connection.host, Antes se mandaba este parametro
		#	1. "cd " + currentPath + " && ls -lrt | sed '/ \.$/d' | sed '/ \.\.$/d'"
		#]
		#args = [arguments[0], "-p " + Configuration.puerto, Configuration.usuario + "@" + Configuration.host, arguments[1]]
		program = args[0] # sftp or ssh
		port = '-P ' + Configuration.puerto
		user_host = Configuration.usuario + "@" + Configuration.host
		command_remote = "cd '{}'".format(Configuration.currentPath) + args[1]
		log.append("\n".join(args))
		# create pipe for stdout
		stdout_fd, w1_fd = os.pipe()
		stderr_fd, w2_fd = os.pipe()

		pid, pty_fd = pty.fork()
		if not pid:
			log.append("if Not pid")
			os.close(stdout_fd)
			os.close(stderr_fd)
			os.dup2(w1_fd, 1)
			os.dup2(w2_fd, 2)
			os.close(w1_fd)
			os.close(w2_fd)

			if program == 'sftp':
				os.execvp(program, [program, "-o", 'PubkeyAuthentication=no', port, user_host])
			elif program == 'ssh':
				os.execvp(program, [program, "-o", 'PubkeyAuthentication=no', user_host, command_remote])

		os.close(w1_fd)
		os.close(w2_fd)

		output = bytearray()
		rd_fds = [stdout_fd, stderr_fd, pty_fd]

		def _read(fd):
			if fd not in rd_ready:
				return

			try:
				data = os.read(fd, 128*1024)
			except (OSError, IOError, Exception):
				data = None

			if not data:
				rd_fds.remove(fd)

			return data

		try:
			time_out = 1.76
			log.append(str(rd_fds))
			while rd_fds:

				rd_ready, _, _ = select.select(rd_fds, [], [], time_out)

				log.append("1. Status rd_ready:" + str(rd_ready))
				if rd_ready == [] and command_remote.find("ls -lrt") != -1:
					limit = 0
					while limit <= 10 and rd_ready == []:
						rd_ready, _, _ = select.select(rd_fds, [], [], 1)
						limit = limit + 1
					log.append("2. Status rd_ready:" + str(rd_ready))

				if rd_ready:
					# Deal with prompts from pty
					data = _read(pty_fd)
					if data is not None:
						if b'assword:' in data:
							os.write(pty_fd, _b(Configuration.password + '\n'))
							log.append("Se escribio la contraseña")
						elif b're you sure you want to continue connecting' in data:
							os.write(pty_fd, b'yes\n')
							log.append("Se dijo que si se quería continuar")

					# Deal with stdout
					data = _read(stdout_fd)
					if data is not None:
						if capture_output:
							output.extend(data)
							log.append("Data is not none y se agrega a la salida")
							time_out = 1.28
						else:
							log.append("Data is not none no se agrega a la salida")
							sys.stdout.write(data.decode('utf-8', 'ignore'))

					# Mensajes del promp
					data = _read(stderr_fd)
					if data is not None:
						if rd_ready[0] == stderr_fd and b'onnected to' in data:
							os.write(pty_fd, _b(command_remote + '\n'))
							log.append("Se logro la conexion")
						elif rd_ready[0] == stderr_fd and b'Permission denied, please try again.' in data:
							log.append("Error al ingresar la contraseña")
							output.extend(b'Usuario o password incorrectos')
							break
						elif rd_ready[0] == stderr_fd and (
								b'Could not resolve hostname' in data
							or b'No route to host' in data
							or b'Network is unreachable' in data
							or b': Permission denied' in data
							or b'No such file or directory' in data
							or b'not found.' in data
							or b'Couldn\'t delete file: Failure' in data):
							log.append("La terminal regresa error.")
							output.extend(data)
						else:
							sys.stderr.write(data.decode('utf-8', 'ignore'))
							log.append("Error no identificado, se describe data a continuación")
							log.append( str( data.decode('utf-8', 'ignore') ) )
							log.append(str(stderr_fd))
							log.append(str(rd_ready[0]))
							output.extend(data)
				else:
					log.append("Se hizo un break")
					break
		finally:
			log.append("Crasheo")
			os.close(pty_fd)

		pid, retval = os.waitpid(pid, 0)
		return retval, output, log


#!/usr/bin/python3

import cmd
import re
from shlex import split
from models import storage
from models.base_model import BaseModel
from models.user import User
from models.state import State
from models.city import City
from models.place import Place
from models.amenity import Amenity
from models.review import Review

def parse(arg):
    curly_braces = re.search(r"\{(.*?)\}", arg)
    brackets = re.search(r"\[(.*?)\]", arg)
    if curly_braces is None:
        if brackets is None:
            return [i.strip(",") for i in split(arg)]
        else:
            lexer = split(arg[:brackets.span()[0]])
            retl = [i.strip(",") for i in lexer]
            retl.append(brackets.group())
            return retl
    else:
        lexer = split(arg[:curly_braces.span()[0]])
        retl = [i.strip(",") for i in lexer]
        retl.append(curly_braces.group())
        return retl

class HBNBCommand(cmd.Cmd):
    prompt = "(hbnb) "
    __classes = {
        "BaseModel",
        "User",
        "State",
        "City",
        "Place",
        "Amenity",
        "Review"
    }

    def emptyline(self):
        pass

    def default(self, arg):
        argdict = {
            "all": self.do_all,
            "show": self.do_show,
            "destroy": self.do_destroy,
            "count": self.do_count,
            "update": self.do_update
        }
        match = re.search(r"\.", arg)
        if match is not None:
            argl = [arg[:match.span()[0]], arg[match.span()[1]:]]
            match = re.search(r"\((.*?)\)", argl[1])
            if match is not None:
                command = [argl[1][:match.span()[0]], match.group()[1:-1]]
                if command[0] in argdict.keys():
                    call = "{} {}".format(argl[0], command[1])
                    return argdict[command[0]](call)
        print("*** Unknown syntax: {}".format(arg))
        return False

    def do_quit(self, arg):
        return True

    def do_EOF(self, arg):
        print("")
        return True

    def do_create(self, arg):
        argl = parse(arg)
        if len(argl) == 0:
            print("** class name missing **")
        elif argl[0] not in HBNBCommand.__classes:
            print("** class doesn't exist **")
        else:
            new_instance = eval(argl[0])()
            print(new_instance.id)
            storage.save()

    # ... (other methods)

if __name__ == "__main__":
    HBNBCommand().cmdloop()


# flake8: noqa

import os
from fastapi import FastAPI, HTTPException, Request, Response
import uuid
from fastapi.responses import RedirectResponse
from prometheus_fastapi_instrumentator import Instrumentator
import logging
import datetime
from redis_om import (
    Field,
    HashModel,
    Migrator
)
from redis_om import get_redis_connection
import csv
from fastapi.testclient import TestClient

from .main import app

client = TestClient(app)

def test_get_load():
    response = client.get("/api/v1/load")
    assert response.status_code == 200
    assert response.json()['rows_loaded'] > 100

def test_get_employee_100():
    response = client.get("/api/v1/employee/100")
    assert response.status_code == 200
    assert response.json()['data'][0]['employee_id'] == 100

def test_get_employee_9999():
    response = client.get("/api/v1/employee/9999")
    assert response.status_code == 200
    assert response.json()['data'] == []

def test_get_employee_xxxx():
    response = client.get("/api/v1/employee/xxxx")
    assert response.status_code != 200

def test_get_first_name():
    response = client.get("/api/v1/employee/first_name/Karma")
    assert response.status_code == 200
    assert response.json()['data'][0]['first_name'] == 'Karma'

def test_get_first_name_empty():
    response = client.get("/api/v1/employee/first_name/xxxx")
    assert response.status_code == 200
    assert response.json()['data'] == []

def test_get_healthz():
    response = client.get("/healthz")
    assert response.status_code == 200


from torch.utils.data import Dataset, DataLoader, Subset
from torchvision.datasets.folder import DatasetFolder
from argparse import ArgumentParser
from PIL import Image
from dl_toolbox.torch_datasets.utils import *
import matplotlib.pyplot as plt
import os
import torch

from dl_toolbox.utils import MergeLabels, OneHot
from dl_toolbox.torch_collate import CustomCollate

cls_names = [
    'airplane',
    'bridge',
    'commercial_area',
    'golf_course',
    'island',
    'mountain',
    'railway_station',
    'sea_ice',
    'storage_tank',
    'airport',
    'chaparral',
    'dense_residential',
    'ground_track_field',
    'lake',
    'overpass',
    'rectangular_farmland',
    'ship',
    'tennis_court',
    'baseball_diamond',
    'church',
    'desert',
    'harbor',
    'meadow',
    'palace',
    'river',
    'snowberg',
    'terrace',
    'basketball_court',
    'circular_farmland',
    'forest',
    'industrial_area',
    'medium_residential',
    'parking_lot',
    'roundabout',
    'sparse_residential',
    'thermal_power_station',
    'beach',
    'cloud',
    'freeway',
    'intersection',
    'mobile_home_park',
    'railway',
    'runway',
    'stadium',
    'wetland'
]

resisc_labels = {
    'base': {key: {} for key in cls_names},
    'small': {key: {} for key in ['stadium', 'wetland']}
}

def pil_to_torch_loader(path: str):

    with open(path, "rb") as f:
        img = np.array(Image.open(f))
        img = torch.from_numpy(img).permute(2,0,1).float() / 255.
        return img

class ResiscDs(DatasetFolder):

    def __init__(
        self,
        data_path,
        img_aug,
    ):
        super().__init__(
            root=data_path,
            loader=pil_to_torch_loader,
            extensions=('jpg',)
        )
        self.img_aug = get_transforms(img_aug)
        self.class_names = self.classes

    @classmethod
    def add_model_specific_args(cls, parent_parser):

        parser = ArgumentParser(parents=[parent_parser], add_help=False)
        parser.add_argument("--data_path", type=str)
        parser.add_argument("--img_aug", type=str)

        return parser

    def __getitem__(self, idx):

        path, label = self.samples[idx]
        image = self.loader(path)
        end_image, _ = self.img_aug(img=image)

        return {
            'orig_image': image,
            'image': end_image,
            'mask': torch.tensor(label),
            'path': path
        }

#class ResiscDs2(Dataset):
#
#    def __init__(
#        self,
#        data_path,
#        idxs,
#        img_aug,
#        labels,
#        *args,
#        **kwargs
#    ):
#
#        self.data_path = data_path
#        self.idxs = idxs
#        self.img_aug = get_transforms(img_aug)
#        self.labels = resisc_labels[labels]
#        self.cls_names = list(self.labels.keys())
#
#    @classmethod
#    def add_model_specific_args(cls, parent_parser):
#
#        parser = ArgumentParser(parents=[parent_parser], add_help=False)
#        parser.add_argument("--data_path", type=str)
#        parser.add_argument("--img_aug", type=str)
#        parser.add_argument("--labels", type=str)
#
#        return parser
#
#    def __len__(self):
#
#        return len(self.cls_names) * len(self.idxs)
#
#    def __getitem__(self, idx):
#
#        cls_idx = idx // len(self.idxs)
#        cls_name = self.cls_names[cls_idx]
#        img_idx = self.idxs[idx % len(self.idxs)]
#        path = os.path.join(self.data_path, cls_name, f'{cls_name}_{img_idx:03}.jpg')
#        img_array = np.asarray(Image.open(path))
#        image = torch.from_numpy(img_array).permute(2,0,1).float() / 255.
#        label = torch.tensor(cls_idx)
#        if self.img_aug is not None:
#            end_image, _ = self.img_aug(img=image)
#        else:
#            end_image = image
#
#        return {
#            'orig_image': image,
#            'image': end_image,
#            'mask': label,
#            'path': path
#        }

def main():

    dataset = ResiscDs(
        data_path='/d/pfournie/ai4geo/data/NWPU-RESISC45',
        img_aug='d4'
    )
    train_set = Subset(
        dataset=dataset,
        indices=[700*i+j for i in range(45) for j in range(50)]
    )
    print(len(train_set))

    dataloader = DataLoader(
        dataset=train_set,
        shuffle=True,
        collate_fn=CustomCollate(),
        batch_size=4,
        num_workers=1,
        drop_last=True
    )
    #for i, batch in enumerate(dataloader):
    #    f, ax = plt.subplots(4, 2, figsize=(20, 10))
    #    for j in range(4):
    #        ax[j, 0].imshow(batch['orig_image'][j].numpy().transpose(1,2,0))
    #        ax[j, 1].imshow(batch['image'][j].numpy().transpose(1,2,0))
    #        ax[j,0].set_title(batch['path'][j])
    #        ax[j, 1].set_title(int(batch['mask'][j]))
    #    plt.show()

if __name__ == '__main__':
    main()


from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from jinja2.ext import loopcontrols
from jinja2 import Environment

import pprint
import xml.etree.ElementTree as ET
import json
import urllib2

from time import strftime
from datetime import datetime, timedelta

conf_file = open("conf.json")
conf = json.load(conf_file)
conf_file.close()

locations = conf["locations"]
exclusions = conf["exclusions"]

pp = pprint.PrettyPrinter(indent = 4)

app = None

def create_app(configfile=None):

	app = Flask(__name__)
	app.jinja_env.add_extension('jinja2.ext.loopcontrols')
	Bootstrap(app)

	@app.context_processor
	def utility_processor():
		def format_time2(unit):
			return u'{:.2f}'.format(unit)
		def format_time(unit):
			sec = timedelta(seconds=int(unit))
			d = datetime(1,1,1) + sec
			retS = ""
			if d.hour:
				retS += str(d.hour)+":"
			if d.minute:
				retS += str(d.minute)+":"
			if d.second:
				retS += str(d.second)
			return retS
		def hasany(item, needle, iterable):
			return any(d[item] == needle for d in iterable)
		def hasnext(item,item2,needle,iterable):
			return next((home[item] for home in iterable if home[item2] == needle), None)
		def getTime(format):
			return strftime(format)
		def hasexclusions(busNumber,direction):
			res = False
			for exclude in exclusions:
				if str(exclude['busNumber']) == busNumber:
					if direction in exclude['directions']:
						return True
			return False
		return dict(format_time=format_time,hasany=hasany,hasnext=hasnext,getTime=getTime,hasexclusions=hasexclusions)

	@app.route("/")
	def index():
		return render_template('index.html',data=get(), location=locations["home"], directions=["inbound","outbound","silver line"])

	@app.route("/<location>")
	def location(location):
		return render_template('index.html',data=get(), location=locations[location],directions=["ruggles station","wentworth campus"])

	return app

def get():
	baseUrl = conf["baseurl"]
	service = conf["a"]

	routes = conf["routes"]

	routelist = []

	for route in routes:
		stopId = route["stopId"]
		routeTitles = route["routeTitles"]

		req = urllib2.Request(str(baseUrl) + "&a=" + str(service) + "&stopId=" + str(stopId))
		response = urllib2.urlopen(req)

		tree = ET.parse(response)
		root = tree.getroot()

		for predictions in root.iter('predictions'):
			title = ""
			seconds = 0
			routeTitle = predictions.attrib['routeTitle']
			#pp.pprint("routeTitle: "+routeTitle)
			if routeTitle not in routeTitles:
				pass
			else:
				busses = []
				seconds = []
				stopTitle = predictions.attrib["stopTitle"]
				#pp.pprint("stop Title: " +stopTitle)
				for prediction in predictions.iter('direction'):
					title = prediction.attrib['title']
					for direction in prediction.iter('prediction'):
						seconds.append(int(direction.attrib['seconds']))
					busses += [{"busNumber": routeTitle, "route": title,"seconds": seconds}]
				if seconds:
					routelist += [{"stopId": stopId,"stopTitle": stopTitle,  "busses": busses}]
	with open('data.json','w') as out:
		json.dump(routelist,out)
	return routelist

theApp = create_app()
if __name__ == "__main__":
    create_app().run(debug = True, host='0.0.0.0')


from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
import time

# pip3 install selenium webdriver-manager
# download chrome driver - https://sites.google.com/chromium.org/driver/downloads

driverPath = Service("/path/chromedriver")
driver = webdriver.Chrome(service = driverPath)

# headless
#options = webdriver.ChromeOptions()
#options.add_argument("headless")
#driver = webdriver.Chrome(service = driverPath, options = options)

url = "https://rhost"
driver.get(url)

# send keystrokes by getting element by id
textField = driver.find_element_by_id("id")
textField.send_keys("text")
time.sleep(1)
textField.send_keys(Keys.RETURN)
time.sleep(1)
driver.find_element_by_id("id").click()

# read inner html
element = driver.find_element_by_id("id")
innerHtml = element.get_attribute("innerHTML")

# scroll to bottom
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")

# get attribute of element by class
elements = driver.find_elements_by_class_name("class")
for e in elements:
    print(e.get_attribute("href"))

# get all elements by tag
elements = driver.find_elements_by_xpath("//a[@href]")
for e in elements:
    print(e.get_attribute("href"))

# write content to file
with open('file.txt', 'w') as f:
    f.write(driver.page_source)

driver.close()


import pygame as pg
import time,os
import CA_func as c
import pgset
k = input("File name:")
if k != "0":
    ktemp = k + '.txt'
    f = open(ktemp,'r').readlines()
    inmax = 0
    for i in f:
        if len(i)>inmax:
            inmax = len(i)
    print("x:",inmax,"y:",len(f),)
initial_pos=[int(input("Initial x:")),int(input("Initial y:"))]
csize = int(input("cell size"))
x = int(input("width:"))
y = int(input("height:"))
if csize <3:
    csize = 3
elif csize>50:
    csize = 20
if csize*x >= 1920:
    x = int(1920/csize)
if csize*y >= 1000:
    y = int(1000/csize)
if(csize*x<100 or csize*y <100):
    x, y ,csize =20, 20 ,20

temp = pgset.Init(csize,x,y)
bg,screen = temp[0],temp[1]

clock = pg.time.Clock()
root = True
ctemp = c.cell(x,y,k,initial_pos)
cell1,cellmode = ctemp[0],ctemp[1]
initial_pos = [0,0]
while(root):
    sub1 = True
    sub2 = True
    reset = False
    while sub1:
        clock.tick(30)
        cell2 = cell1
        for event in pg.event.get():
            if event.type == pg.QUIT:
                   sub1 = False
                   root = False
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                   sub1 = False
            elif event.type == pg.MOUSEBUTTONDOWN and (sub1 or root):
                cell2 = pgset.clicked(cell1,x,y,csize)
                btemp = pgset.button(x,y,root,cell1,sub1,sub2,1,reset,csize)
                root, sub1,sub2 = btemp[0],btemp[1],btemp[2]
        for i in range(x):
            for j in range(y):
                if (cell1[i][j]):
                    pg.draw.rect(bg, (0,0,255),[csize*i,csize*j, csize-1, csize-1], 0)
                else:
                    pg.draw.rect(bg, (255,255,255),[csize*i,csize*j, csize-1, csize-1], 0)
        cell1 = cell2
        screen.blit(bg, (0,0))
        pg.display.update()

    while sub2 and root:
        clock.tick(30)
        for event in pg.event.get():
            if event.type == pg.QUIT:
                   sub2 = False
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                   sub2 = False
            elif event.type == pg.MOUSEBUTTONDOWN:
                btemp = pgset.button(x,y,cell1,root,sub1,sub2,2,reset,csize)
                root, sub1,sub2,reset = btemp[0],btemp[1],btemp[2],btemp[3]

        cell2,cellmode ,bg = c.evolve(cell1,cellmode,bg,csize,x,y)
        cell1 = cell2
        screen.blit(bg, (0,0))
        pg.display.update()
    if reset:
        cell1 = c.cell(x,y,"0",[])[0]
    if root:
        sub1 ,sub2 = True, True
pg.quit()


from marshmallow import fields, Schema

from project.schemas.director import DirectorSchema
from project.schemas.genre import GenreSchema

class MovieSchema(Schema):
    id = fields.Int(required=True)
    title = fields.Str(required=True)
    description = fields.Str()
    trailer = fields.Str()
    year = fields.Int()
    rating = fields.Int()
    genre = fields.Nested(GenreSchema)
    director = fields.Nested(DirectorSchema)


from sys import argv
import glob
import time

from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelBinarizer
from torch import optim
from torch.autograd import Variable
import torch.nn as nn
import torch
import cv2
import numpy as np
import matplotlib.pyplot as plt

from fully_connected import FullyConnected

# -----------------------------------------------------------------------------
def arg_parse():
    if len(argv) == 2:
        _, training_data = argv
        return training_data, None
    elif len(argv) == 3:
        _, training_data, test_data = argv
        return training_data, test_data
    else:
        print("Invalid Argument(s).")
        print("USAGE: {0} <training-data> <test-data>".format(argv[0]))
        exit()

# -----------------------------------------------------------------------------
def get_img_names(root_dir):
    grass = glob.glob(root_dir + "/grass/*.JPEG")
    ocean = glob.glob(root_dir + "/ocean/*.JPEG")
    redcarpet = glob.glob(root_dir + "/redcarpet/*.JPEG")
    road = glob.glob(root_dir + "/road/*.JPEG")
    wheatfield = glob.glob(root_dir + "/wheatfield/*.JPEG")

    print("Grass:", len(grass), "images")
    print("Ocean:", len(ocean), "images")
    print("Red carpet:", len(redcarpet), "images")
    print("Road:", len(road), "images")
    print("Wheatfield:", len(wheatfield), "images")
    print()

    return grass, ocean, redcarpet, road, wheatfield

# -----------------------------------------------------------------------------
def preprocess(img_list, m=0, n=0):
    X = []
    y = []
    for img_name in img_list:
        img = cv2.imread(img_name, cv2.IMREAD_COLOR)

        # resize if applicable
        if m > 0 and n > 0:
            img = cv2.resize(img, (m, n))

        # flatten and add to the dataset
        img = np.ravel(img)
        X.append(img)

    return np.array(X), np.array(y)

# -----------------------------------------------------------------------------
def make_label_vectors(length):
    # build label vector
    grass = np.zeros(length)
    ocean = np.ones(length)
    redcarpet = 2 * np.ones(length)
    road = 3 * np.ones(length)
    wheatfield = 4 * np.ones(length)

    y = np.hstack((grass, ocean, redcarpet, road, wheatfield))

    # Binarize the labels
    # lb = LabelBinarizer()
    # y = lb.fit_transform(y)

    return y
# -----------------------------------------------------------------------------
def get_data(directory, m, n, split=False, scaler=None):
    img_names = get_img_names(directory)

    # read and preprocess all images
    start = time.time()
    X = []
    for j, img_set in enumerate(img_names):
        X_partial, y_partial = preprocess(img_set, m, n)
        X.append(X_partial)

    # format, shape, and scale
    X = np.array(X)
    X = X.reshape(X.shape[0] * X.shape[1], X.shape[2])

    if scaler == None:
        scaler = StandardScaler()
        X = scaler.fit_transform(X)
    else:
        X = scaler.transform(X)

    # build label vector
    y = make_label_vectors(len(img_names[0]))

    if split:
        X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size = 0.2, random_state = 0)

    duration = round(time.time()-start, 2)
    print(duration, "seconds to extract images and build label tensor")
    print("Total images:", X.shape[0])
    print("Flattened image size:", X.shape[1])

    if split:
        X_train = Variable(torch.tensor(X_train, dtype=torch.float))
        y_train = Variable(torch.tensor(y_train, dtype=torch.long))
        X_valid = Variable(torch.tensor(X_valid, dtype=torch.float))
        y_valid = Variable(torch.tensor(y_valid, dtype=torch.long))
        return X_train, y_train, X_valid, y_valid, scaler
    else:
        X = Variable(torch.tensor(X, dtype=torch.float))
        y = Variable(torch.tensor(y, dtype=torch.long))
        return X, y

# -----------------------------------------------------------------------------
def train(X_train, y_train, X_valid, y_valid, m, n):
    #  Set parameters to control the process
    num_epochs = 3
    batch_size = 16
    learning_rate=1e-4
    n_train = X_train.size()[0]
    n_batches = int(np.ceil(n_train / batch_size))
    log_interval = 1

    print("\nNumber of batches:", n_batches)

    model = FullyConnected(m,n)
    optimizer = optim.Adam(model.parameters(), lr=learning_rate)
    criterion = nn.CrossEntropyLoss()

    print("\n\nBegin Training...")
    start = time.time()

    for ep in range(num_epochs):
        #  Create a random permutation of the indices of the row vectors.
        indices = torch.randperm(n_train)

        #  Run through each mini-batch
        for b in range(n_batches):
            #  Use slicing (of the pytorch Variable) to extract the
            #  indices and then the data instances for the next mini-batch
            batch_indices = indices[b*batch_size:(b+1)*batch_size]
            batch_X = X_train[batch_indices]
            batch_Y = y_train[batch_indices]

            #  Run the network on each data instance in the minibatch
            #  and then compute the object function value
            y_pred = model(batch_X)
            loss = criterion(y_pred, batch_Y)

            #  Back-propagate the gradient through the network using the
            #  implicitly defined backward function, but zero out the
            #  gradient first.  The step is made here by the optimizer
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

        if ep % log_interval == 0:
            print("Epoch {}:\n  ".format(ep), end='')
            test(model, criterion, X_valid, y_valid)

    print(round(time.time()-start, 2), "seconds to train\n")
    return model, criterion

# -----------------------------------------------------------------------------
def test(model, criterion, X_test, y_test):
    # make predictions
    y_pred = model(X_test)

    # sum up batch loss and compute accuracy
    loss = criterion(y_pred, y_test)
    accuracy, correct, incorrect = success_rate(y_pred, y_test)

    print('Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(
            loss, correct, X_test.size()[0], accuracy * 100.0))

    return y_pred

# -----------------------------------------------------------------------------
def success_rate(pred_Y, Y):
    '''
    Calculate and return the success rate from the predicted output Y and the
    expected output.  There are several issues to deal with.  First, the pred_Y
    is non-binary, so the classification decision requires finding which column
    index in each row of the prediction has the maximum value.  This is achieved
    by using the torch.max() method, which returns both the maximum value and the
    index of the maximum value; we want the latter.  We do this along the column,
    which we indicate with the parameter 1.  Second, the once we have a 1-d vector
    giving the index of the maximum for each of the predicted and target, we just
    need to compare and count to get the number that are different.  We could do
    using the Variable objects themselve, but it is easier syntactically to do this
    using the .data Tensors for obscure PyTorch reasons.
    '''
    _,pred_Y_index = torch.max(pred_Y, -1)
    num_equal = torch.sum(pred_Y_index.data == Y.data).item()
    num_different = torch.sum(pred_Y_index.data != Y.data).item()
    rate = num_equal / float(num_equal + num_different)
    return rate, num_equal, num_different # rate.item()

# -----------------------------------------------------------------------------
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()
    plt.savefig("fc_confusion_matrix.png")

# =============================================================================
if __name__ == "__main__":
    training_data, test_data = arg_parse()
    names = ["grass", "ocean", "redcarpet", "road", "wheatfield"]

    # Desired image size
    m = 48
    n = 72

    print("\nGetting training data")
    X_train, y_train, X_valid, y_valid, scaler = get_data(training_data, m , n, split=True, scaler=None)

    model, criterion = train(X_train, y_train, X_valid, y_valid, m, n)

    if test_data:
        print("Getting test data")
        X_test, y_test = get_data(test_data, m, n, split=False, scaler=scaler)
        print("\nRunning through model")
        y_pred_one_hot = test(model, criterion, X_test, y_test)
        _, y_pred = torch.max(y_pred_one_hot, -1)
        np.save("fc_y_pred", y_pred)

        cm = confusion_matrix(y_test, y_pred.numpy())
        # print(cm)
        plot_confusion_matrix(cm, names)


from distutils.core import setup, Extension
MOD = 'Pythonbepi'
setup(
    name=MOD,
    ext_modules=[
        Extension(
            MOD,
            sources=['../mmg/mcxt.c',
                     '../mmg/aset.c',
                     '../znbase/znbase.c',
                     '../znbase/expr.c',
                     '../utils/elog.c',
                     '../utils/list.c',
                     '../utils/nodes.c',
                     '../utils/string.c',
                     '../utils/stringinfo.c',
                     '../utils/hashmap.c',
                     '../plsql/pl_comp.c',
                     '../plsql/pl_exec.c',
                     '../plsql/pl_handler.c',
                     '../plsql/pl_scanner.c',
                     '../plsql/pl_funcs.c',
                     './python_depi.c',
                     '../parser/pl_gram.tab.c',
                     '../parser/scan.c',
                     '../parser/kwlookup.c',
                     '../parser/scansup.c',
                     '../utils/decoding.c',
                     '../cson/cJSON.c',
                     './plpy_result.c',
                     './plpy_type.c'],
            # sources=['./python_depi.c', '../cson/cJSON.c'],
            extra_compile_args=['-Wall', '-g', '-O0', '-fPIC', '-export-dynamic'],
            include_dirs = ['../include']
        )
    ]
)


import numpy as np
import matplotlib.pyplot as plt
from statistics import mean
import xlsxwriter

mu1 = 0.8 #Mean parameter of the first Gaussian distribution
sigma1 = 0.4 #Standard deviation parameter of the first Gaussian distribution

mu2 = 0.7 # Mean parameter of the second Gaussian distribution
sigma2 = 0.6 #Standard deviation parameter of the second Gaussian distribution

def simulate_Data_LR_HR(mu1, sigma1, mu2, sigma2):

    Featurematrix = [];
    max_Featurematrix=[];
    AV_Featurematrix=[];

    c1 = int(input("Select the number of class 1 graphs: "))
    while not c1:
        c1 = int(input('Please give a number: '))
    while c1 < 5:
        c1 = int(input('Please choose a number > 4: '))

    c2 = int(input('Select the number of class 2 graphs: '))
    while not c2:
        c2 = int(input('Please give a number: '))
    while c2 < 5:
        c2 = int(input('Please choose a number > 4: '))

    m = int(input('Select the number of nodes (i.e. ROI\'s for brain graphs): '))
    while not m:
        m = int(input('Please give a number: '))
    while (m < 20) | (m%4 != 0):
        m = int(input('Please choose a number > 20 and a multiple of 4: '))

    N = c1 + c2
    datac1 = np.random.normal(mu1, sigma1, [c1, m, m]) # Normal random distribution
    datac2 = np.random.normal(mu2, sigma2, [c2, m, m]) # Normal random distribution
    data1 = np.concatenate((datac1, datac2), axis=0)

    # Creating a 1D vector from the entries of datac1 and datac2 vectors in order to draw a histogram graph.
    datac1_vector = datac1.flatten()
    datac2_vector = datac2.flatten()
    # Drawing samples from two different distributions to simulate both classes
    plt.hist(datac1_vector, bins = 115, edgecolor=(0, 1, 0, 1), fc=(0, 1, 0, 0.8))
    plt.hist(datac2_vector, bins = 115, edgecolor=(0, 0, 1, 0.4), fc=(0, 0, 1, 0.3))
    plt.show()

    V = np.zeros((int(m/4), 4, 4))
    AV = np.zeros((N, int(m/4), int(m/4)))
    maxi = np.zeros((N, int(m/4), int(m/4)))
    Featurematrix = np.zeros((0,m*m))
    z = np.zeros((1,1))

    for i in range(0,N):
        x = np.zeros((0,1))
        LR = np.zeros((int(m/4), 4, 4))
        data1[i][:][:] = np.squeeze(data1[i][:][:]) - np.diag(np.diag(np.squeeze(data1[i][:][:]))) #Eliminating self-symmetry
        data1[i][:][:] = np.true_divide((np.squeeze(data1[i][:][:]) + np.transpose(np.squeeze(data1[i][:][:]))),2) #Insure data symmetry
        t = np.triu(np.squeeze(data1[i,:,:]),1) #Upper triangular matrix constructed
        #t is vectorized:
        for ii in range(0,m):
            for jj in range(0,m):
                z[0,0] = t[jj,ii]
                x = np.append(x, z, axis=0)
        x1 = np.transpose(x) #transpose of x is x1
        Featurematrix = np.append(Featurematrix, x1, axis=0)

        jp=0
        jc=3
        r=-1
        H = np.zeros((int(m/4), int(m/4), 4, 4))
        while jp < m:
            r = r + 1
            for v in range(jp, jc+1, 4):
                ip = 0
                ic = 3
                o = 0
                while (ic < m):
                    mm = 0
                    for k in range(ip, ic+1):
                        n = 0
                        for l in range(jp, jc+1):
                            LR[o][mm][n] = np.squeeze(data1[i][k][l])
                            n = n+1
                        mm = mm+1
                    ip = ic+1
                    ic = ip+3
                    o = o+1
            for p in range(0, int(m/4)):
                for j in range(0, 4):
                    for s in range(0, 4):
                        H[r][p][j][s] = LR[p][j][s]
            jp = jc+1
            jc = jp+3

        for a1 in range(0, int(m/4)):

            for g in range(0, int(m/4)):
                for j in range(0, 4):
                    for s in range(0, 4):
                        V[g][j][s] = H[a1][g][j][s]

            for b1 in range(0,int(m/4)):
                q1 = np.squeeze(V[b1][:][:])
                maxi[i][b1][a1] = np.amax(np.amax(q1[:][:], axis=0), axis=0)
                AV[i][b1][a1] = np.mean(np.mean(q1, axis=0), axis = 0)

    def pooling_LR_data(max_av):
        t = np.triu(np.squeeze(max_av[i,:,:]),1) # Upper triangular part of matrix
        #vectorizing t (triangular matrix) into 1 column vector
        x = np.zeros((0,1))
        for ii in range(0,int(m/4)):
            for jj in range(0,int(m/4)):
                z[0,0] = t[jj,ii]
                x = np.append(x, z, axis=0)
        x = np.reshape(x, (1,len(x)))
        max_av_Featurematrix = np.zeros((0, len(t)*len(t)))
        max_av_Featurematrix = np.append(max_av_Featurematrix, x, axis=0)
        LR_data_x = max_av
        return max_av_Featurematrix, LR_data_x

    max_Featurematrix, LR_data_max_x = pooling_LR_data(maxi)
    LR_data_max_Featurematrix = Featurematrix
    LR_data_max_Labels = np.concatenate((np.ones((c1,1)),-1*np.ones((c2,1))), axis=0)

    AV_Featurematrix, LR_data_av_x = pooling_LR_data(AV)
    LR_average_Featurematrix = Featurematrix
    LR_data_av_Labels = np.concatenate((np.ones((c1,1)),-1*np.ones((c2,1))), axis=0)

    HR_data_Featurematrix = Featurematrix
    HR_data_x = data1
    HR_data_Labels = np.concatenate((np.ones((c1,1)),-1*np.ones((c2,1))), axis=0)

    return LR_data_max_Featurematrix, LR_data_max_x, LR_data_max_Labels, LR_average_Featurematrix, LR_data_av_x, LR_data_av_Labels, HR_data_Featurematrix, HR_data_x, HR_data_Labels, c1, c2


import numpy

inputs = [s.rsplit(maxsplit=3) for s in open("input.txt").read().splitlines()]

grid = numpy.zeros((1000,1000), dtype=int)
for i in inputs:
    n = [*map(int, i[1].split(','))]
    m = [*map(int, i[3].split(','))]
    if i[0] == "turn on":
        grid[n[0]:m[0]+1,n[1]:m[1]+1] = 1
    elif i[0] == "turn off":
        grid[n[0]:m[0]+1,n[1]:m[1]+1] = 0
    elif i[0] == "toggle":
        for x in range(n[0], m[0]+1):
            for y in range(n[1], m[1]+1):
                if grid[x,y] == 1:
                    grid[x,y] = 0
                elif grid[x,y] == 0:
                    grid[x,y] = 1
    else:
        raise StopIteration

print("part1:", grid.sum())

grid = numpy.zeros((1000,1000), dtype=int)
for i in inputs:
    n = [*map(int, i[1].split(','))]
    m = [*map(int, i[3].split(','))]
    if i[0] == "turn on":
        grid[n[0]:m[0]+1,n[1]:m[1]+1] += 1
    elif i[0] == "turn off":
        for x in range(n[0], m[0]+1):
            for y in range(n[1], m[1]+1):
                grid[x,y] = max(0, grid[x,y]-1)
    elif i[0] == "toggle":
        grid[n[0]:m[0]+1,n[1]:m[1]+1] += 2
    else:
        raise StopIteration

print("part2:", grid.sum())


#!/usr/bin/env python
from __future__ import print_function
import sys

def normalize(content):
    # Ignore newline differences (e.g. on Windows, std::endl is "\r\n") and any extra whitespace
    # at beginning/end of content
    return content.replace('\r\n', '\n').strip()

if __name__ == '__main__':
    assert len(sys.argv) == 4

    test_name = sys.argv[1]
    a_file_path = sys.argv[2]
    b_file_path = sys.argv[3]
    assert a_file_path != b_file_path

    with open(a_file_path, 'rb') as a:
        with open(b_file_path, 'rb') as b:
            a_content = normalize(a.read())
            b_content = normalize(b.read())
            if a_content == b_content:
                exit(0)
            import difflib
            diff = difflib.ndiff(a_content.splitlines(), b_content.splitlines(),
                                 charjunk=lambda c: False)
            diff = list(diff)

            if diff:
                print('Output headers of test %s differ:' % test_name, file=sys.stderr)
                for line in diff:
                    print(line, file=sys.stderr)
                exit(1)


"""Input: single 'món ăn'
   Output: the related 'mâm cơm'
   Method : search by keywords"""

import csv
from models.tokenization.dict_models import LongMatchingTokenizer

def sententce_process(string):
    lm_tokenizer = LongMatchingTokenizer()
    tokens = lm_tokenizer.tokenize(string)
    return  tokens
    # print(tokens)

def findMam(item):
    with open("C:/Users/HungDo/Documents/GitHub/News/Beautiful Soup/utils/items_demo.csv", 'r', encoding="utf8") as csvfile:
        reader = csv.DictReader(csvfile)

        result_arr = []
        for row in reader:
            recipes = row['recipes']
            if item.strip() in recipes:
                title = row['title']

                temp = [title, recipes]
                result_arr.append(temp)
                # print('Gợi ý:',title, ' với menu: ', recipes)
        # print(result_arr)
    return result_arr
    csvfile.close()

def main():
    sententce = 'học sinh chiên '
    result = findMam(sententce)

    splits = sententce_process(sententce.strip())
    print(splits)
    count = 0
    while result == [] and count < len(splits):
        new_sentence = splits[count].replace('_',' ')
        print(new_sentence)
        result = findMam(new_sentence)
        count+=1

    print(result)

main()


import json
import requests
#한국 투자 증권api를 사용하는데 필요한 보안 토큰을 발급하기 위한 코드 입니다#

def Auth(APP_KEY, APP_SECRET, URL_BASE):
    #rest api의 구성
    #권한 인증 등에 활용되는 header
    headers = {"content-type":"application/json"}
    #body는 POST 방식에 활용, GET방식 할 때 query string 사용
    body = {"grant_type":"client_credentials",
            "appkey":APP_KEY,
            "appsecret":APP_SECRET}
    #위치를 나타내는 path
    PATH = "oauth2/tokenP"

    URL = URL_BASE + '/' + PATH

    res = requests.post(URL, headers=headers, data=json.dumps(body))

    # POST 요청을 진행하면 보안인증키 얻어옴
    ACCESS_TOKEN = res.json()["access_token"]
    return ACCESS_TOKEN


import shutil
import subprocess
from argparse import ArgumentParser
from multiprocessing import Pool
from pathlib import Path

import numpy as np
from tqdm import tqdm

from src import DATA_PATHS as PATHS
from src.utils import io

def read_array(path):
    with open(path, "rb") as fid:
        width, height, channels = np.genfromtxt(fid, delimiter="&", max_rows=1, usecols=(0, 1, 2), dtype=int)
        fid.seek(0)
        num_delimiter = 0
        byte = fid.read(1)
        while True:
            if byte == b"&":
                num_delimiter += 1
                if num_delimiter >= 3:
                    break
            byte = fid.read(1)
        array = np.fromfile(fid, np.float32)
    array = array.reshape((width, height, channels), order="F")
    return np.transpose(array, (1, 0, 2)).squeeze().astype(np.float32)

def export_split(split, src, dst, overwrite=False):
    print(f'-> Exporting "{split}" split...')
    dst = dst/split
    io.mkdirs(dst)

    seqs = io.get_dirs(src/split)
    # fails = {}
    # for s in tqdm(seqs):
    #     try:
    #         export_seq((s, dst/s.stem, overwrite))
    #     except Exception as e:
    #         fails[s.stem] = e

    dsts = [dst/s.stem for s in seqs]
    ovs = [overwrite for _ in seqs]

    with Pool(8) as p:
        for _ in tqdm(p.imap_unordered(export_seq, zip(seqs, dsts, ovs)), total=len(seqs)): pass
    return {}

def export_seq(args):
    try:
        src, dst, overwrite = args
        depth_dir = dst/'depths'
        if not overwrite and depth_dir.is_dir():
            print(f'-> Skipping "{src.parent.stem}" sequence "{src.stem}"...')
            return

        print(f'-> Exporting "{src.parent.stem}" sequence "{src.stem}"...')

        shutil.rmtree(dst, ignore_errors=True)
        io.mkdirs(dst)

        db_path = dst/'database.db'
        img_dir = dst/'images'
        sparse_dir = dst/'sparse'
        refined_dir = dst/'refined'
        dense_dir = dst/'dense'
        io.mkdirs(img_dir, sparse_dir, refined_dir, dense_dir)

        [shutil.copy(f, img_dir) for f in io.get_files(src, key=lambda f: f.suffix == '.jpg')]

        subprocess.call([
            'colmap', 'feature_extractor',
            '--ImageReader.single_camera', '1',
            '--ImageReader.default_focal_length_factor', '0.85',
            '--SiftExtraction.peak_threshold', '0.02',
            '--database_path', db_path,
            '--image_path', img_dir,
        ])

        subprocess.call([
            'colmap', 'exhaustive_matcher',
            '--SiftMatching.max_error', '3',
            '--SiftMatching.min_inlier_ratio', '0.3',
            '--SiftMatching.min_num_inliers', '30',
            '--SiftMatching.guided_matching', '1',
            '--database_path', db_path,
        ])

        subprocess.call([
            'colmap', 'mapper',
            '--Mapper.tri_merge_max_reproj_error', '3',
            '--Mapper.ignore_watermarks', '1',
            '--Mapper.filter_max_reproj_error', '2',
            '--database_path', db_path,
            '--image_path', img_dir,
            '--output_path', sparse_dir,
        ])

        subprocess.call([
            'colmap', 'bundle_adjuster',
            '--input_path', sparse_dir/'0',
            '--output_path', refined_dir,
        ])

        subprocess.call([
            'colmap', 'image_undistorter',
            '--input_path', refined_dir,
            '--image_path', img_dir,
            '--output_path', dense_dir,
            '--output_type', 'COLMAP',
            '--max_image_size', '1600',
        ])

        subprocess.call([
            'colmap', 'patch_match_stereo',
            '--PatchMatchStereo.window_radius', '5',
            '--PatchMatchStereo.num_samples', '15',
            '--PatchMatchStereo.geom_consistency_regularizer', '1',
            '--PatchMatchStereo.geom_consistency_max_cost', '1.5',
            '--PatchMatchStereo.filter_min_ncc', '0.2',
            '--PatchMatchStereo.filter_min_num_consistent', '3',
            '--PatchMatchStereo.geom_consistency', 'true',
            '--workspace_path', dense_dir,
            '--workspace_format', 'COLMAP',
        ])

        files = io.get_files(dense_dir/'stereo'/'depth_maps', key=lambda f: 'geometric' in str(f))
        [np.save(src/f'{f.name.split(".")[0]}.npy', read_array(f)) for f in files]
        io.mkdirs(depth_dir)
    except:
        pass

def main(root):
    dst = root / 'colmap'
    io.mkdirs(dst)

    splits = ['test']
    fails = {}
    for s in tqdm(splits):
        fails[s] = export_split(s, root, dst, overwrite=False)

    print(fails)

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('root', type=Path, default=PATHS['mannequin'])
    args = parser.parse_args()

    main(args.src)


filename=input("File name: ")
try:
    infile = open(filename)
except:
    print("that file does not exist")
wordcount=0

linecount= len(infile.readlines())
infile.close()
charactercount=0
infile = open(filename)
data=infile.read()
infile.close()
words=data.split()
wordcount=len(words)
charactercount=len(data)
print(f'Characters: {charactercount}')
print(f'Words: {wordcount}')
print(f'Lines: {linecount}')


from collections import defaultdict

def reboot(p1):
    C = defaultdict(int)
    for line in open("22.txt"):
        line = line.strip().split(" ")
        ordr = 1 if line[0] == "on" else -1
        x, y, z = line[1].split(",")
        x1, x2 = map(int, x[2:].split(".."))
        y1, y2 = map(int, y[2:].split(".."))
        z1, z2 = map(int, z[2:].split(".."))
        if p1 and any([c not in range(-50, 51) for c in (x1, x2, y1, y2, z1, z2)]):
            continue
        # Try to find intersections between previous cuboids (_p) and the current one:
        for (x1_p, x2_p, y1_p, y2_p, z1_p, z2_p), ordr_p in C.copy().items():
            intr_x1 = max(x1_p, x1)
            intr_x2 = min(x2_p, x2)
            intr_y1 = max(y1_p, y1)
            intr_y2 = min(y2_p, y2)
            intr_z1 = max(z1_p, z1)
            intr_z2 = min(z2_p, z2)
            if (  # if there's an intersection between that previous cuboid and the current one
                intr_x1 < intr_x2 and intr_y1 < intr_y2 and intr_z1 < intr_z2
            ):
                # we 'cancel' its order
                C[(intr_x1, intr_x2, intr_y1, intr_y2, intr_z1, intr_z2)] -= ordr_p
        # if order is `on`, we turn on the current cuboid:
        C[(x1, x2, y1, y2, z1, z2)] += max(0, ordr)

    cnt = 0
    for (x1, x2, y1, y2, z1, z2), ordr in C.items():
        cnt += (x2 - x1 + 1) * (y2 - y1 + 1) * (z2 - z1 + 1) * ordr
    return cnt

print(f"P1: {reboot(p1=True)}")
print(f"P2: {reboot(p1=False)}")


#!/usr/bin/python3

import rclpy
from rclpy.node import Node
from sensor_msgs.msg import JointState
from trajectory_msgs.msg import JointTrajectory

class Generator(Node):
    def __init__(self):
        super().__init__('generator')
        # pub end_effector_state to kinematics_server
        self.publisher = self.create_publisher(JointState,'/ref',10)
        self.rate = 5.0 #Hz
        timer_period = 1/self.rate #second
        self.timer = self.create_timer(timer_period,self.timer_callback)
        self.ref_position = [1.0,2.0,3.0]  # initial reference position
        self.ref_velocity = [6.0,5.0,4.0]  # initial velocity position

        # sub initial, final via point, duration from scheduler
        self.subscribe = self.create_subscription(JointTrajectory,'/scheduler',self.sub_scheduler_callback,10)

    def sub_scheduler_callback(self,msg:JointTrajectory):
        self.get_logger().info('Publishing: "%s"' % msg.points)

    def timer_callback(self):
        # publish the reference position and velocity in taskspace
        msg = JointState()
        msg.name = ['joint_1', 'joint_2', 'joint_3']
        msg.position = self.ref_position
        msg.velocity = self.ref_velocity
        self.publisher.publish(msg)

def main(args=None):
    rclpy.init(args=args)
    generator = Generator()
    rclpy.spin(generator)
    generator.destroy_node()
    rclpy.shutdown()

if __name__=='__main__':
    main()


from statuses import CellStatus, TurnStatus, COMPUTER_CELL, PLAYER_CELL

def score(game, depth) -> int:
    if game.is_win(COMPUTER_CELL):
        return 10 - depth
    if game.is_win(PLAYER_CELL):
        return depth - 10
    return 0

conditions = dict()

def already_calculated(game) -> bool:
    return (str(game.board), game.current_turn) in conditions.keys()

def minimax_algorithm(game, depth=0, debug=False) -> int:
    if game.is_game_over():
        return score(game, depth)

    depth += 1
    final_score = None
    final_move = game.possible_moves()[0]

    for move in game.possible_moves():
        if debug:
            game.display_board()
            print(game.current_turn)
            print()

        current_turn = game.current_turn
        game.board[move[0]][move[1]] = PLAYER_CELL if game.current_turn == TurnStatus.PLAYER_TURN else COMPUTER_CELL
        game.current_turn = game.next_turn()

        key = (str(game.board), game.current_turn)
        if already_calculated(game):
            current_score = conditions[key]
        else:
            current_score = minimax_algorithm(game, depth, debug)
            conditions[key] = current_score

        if current_turn == TurnStatus.COMPUTER_TURN:
            if final_score is None or current_score > final_score:
                final_score = current_score
                final_move = move
        else:
            if final_score is None or current_score < final_score:
                final_score = current_score
                final_move = move

        if debug:
            game.display_board()
            print(final_score)
            print('-' * 20)

        game.board[move[0]][move[1]] = CellStatus.EMPTY_CELL
        game.current_turn = current_turn

    game.choice = final_move
    if debug:
        print("final move: ", game.choice, final_score)
    return final_score


class Node:
    def __init__(self, val=0, neighbors=None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []

class Solution:
    def cloneGraph(self, node: 'Node') -> 'Node':
        if not node:
            return node

        origToCopy = {}
        q = []

        q.append(node)

        while (q):
            cnt = len(q)
            for i in range(cnt):
                n = q.pop(0)

                if n not in origToCopy:
                    origToCopy[n] = Node(n.val)

                c = origToCopy[n]
                for neighbor in n.neighbors:
                    if neighbor in origToCopy:
                        c.neighbors.append(origToCopy[neighbor])
                        continue

                    q.append(neighbor)
                    neighborCopy = Node(neighbor.val)
                    origToCopy[neighbor] = neighborCopy
                    c.neighbors.append(neighborCopy)

        return origToCopy[node]


#-*- coding:utf-8 -*-
'''
Created on 2017年4月11日

@author: huangjiaxin
'''
import requests
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def getPage(url):
    response = requests.get(url)
    content = response.text
    return content
#     print content

def catchInformation(content):
    soup = BeautifulSoup(content, 'lxml')
    groupList = soup.find(name='div', attrs={'class':'group-list'})
    for group in groupList.find_all(name='div', attrs={'class':'result'}):
        groupName = str(group.h3.a.text)
        groupLink = str(group.h3.a['href'])
        if "广州" in groupName:
            with open('group-guangzhou.txt', 'a') as file:
                file.write(groupName + ',' + groupLink + '\n')

if __name__ == '__main__':
    for i in range(0, 701, 20):
        url = 'https://www.douban.com/group/explore?start=' + str(i) + '&tag=%E7%A7%9F%E6%88%BF'
        content = getPage(url)
        catchInformation(content)


__all__ = [
    "SlidingWindowSplitter",
    "CutoffSplitter",
    "SingleWindowSplitter",
    "temporal_train_test_split",
]
__author__ = ["Markus Löning"]

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

from sktime.utils.validation.forecasting import check_cutoffs
from sktime.utils.validation.forecasting import check_fh
from sktime.utils.validation.forecasting import check_step_length
from sktime.utils.validation.forecasting import check_time_index
from sktime.utils.validation.forecasting import check_window_length

DEFAULT_STEP_LENGTH = 1
DEFAULT_WINDOW_LENGTH = 10
DEFAULT_FH = 1

class BaseSplitter:
    """Base class for splitting time series during temporal cross-validation

    Parameters
    ----------
    window_length : int
        Length of rolling window
    fh : array-like  or int, optional, (default=None)
        Single step ahead or array of steps ahead to forecast.
    """

    def __init__(self, fh=DEFAULT_FH, window_length=DEFAULT_WINDOW_LENGTH):
        self.window_length = window_length
        self.fh = fh

    def split(self, y):
        """Split y into windows.

        Parameters
        ----------
        y : pd.Series or pd.Index
            Time series to split

        Yields
        ------
        training_window : np.array
            Training window indices
        test_window : np.array
            Test window indices
        """
        y = self._check_y(y)
        for training_window, test_window in self._split_windows(y):
            yield training_window[training_window >= 0], test_window[test_window >= 0]

    def _split_windows(self, y):
        """Internal split method"""
        raise NotImplementedError("abstract method")

    def get_n_splits(self, y=None):
        """Return the number of splits."""
        raise NotImplementedError("abstract method")

    def get_cutoffs(self, y=None):
        """Return the cutoff points in time at which y is split."""
        raise NotImplementedError("abstract method")

    def get_fh(self):
        """Return the forecasting horizon"""
        return check_fh(self.fh)

    @staticmethod
    def _check_y(y):
        # allow for pd.Series
        if isinstance(y, pd.Series):
            y = y.index
        return check_time_index(y)

    def _check_fh(self):
        return check_fh(self.fh, enforce_relative=True).to_numpy()

class CutoffSplitter(BaseSplitter):
    """Manual window splitter to split time series at given cutoff points.

    Parameters
    ----------
    cutoffs : np.array
        cutoff points, positive and integer-index like, usable with pandas
        .iloc[] indexing
    fh : int, list or np.array
    window_length : int
    """

    def __init__(self, cutoffs, fh=DEFAULT_FH, window_length=DEFAULT_WINDOW_LENGTH):
        self.cutoffs = cutoffs
        super(CutoffSplitter, self).__init__(fh, window_length)

    def _split_windows(self, y):
        # cutoffs
        cutoffs = check_cutoffs(self.cutoffs)
        if not np.max(cutoffs) < len(y):
            raise ValueError("`cutoffs` are out-of-bounds for given `y`.")

        fh = self._check_fh()

        if np.max(cutoffs) + np.max(fh) > len(y):
            raise ValueError("`fh` is out-of-bounds for given `cutoffs` and `y`.")
        window_length = check_window_length(self.window_length)

        for cutoff in cutoffs:
            training_window = np.arange(cutoff - window_length, cutoff) + 1
            test_window = cutoff + fh
            yield training_window, test_window

    def get_n_splits(self, y=None):
        """Return the number of splits"""
        return len(self.cutoffs)

    def get_cutoffs(self, y=None):
        """Return the cutoff points"""
        return check_cutoffs(self.cutoffs)

class BaseWindowSplitter(BaseSplitter):
    """Base class for window splits"""

    def __init__(self, fh=None, window_length=None):
        super(BaseWindowSplitter, self).__init__(fh=fh, window_length=window_length)

    def split_initial(self, y):
        raise NotImplementedError("abstract method")

    def _get_end(self, y):
        """Helper function to compute the end of the last window"""
        n_timepoints = len(y)
        fh = self._check_fh()
        window_length = check_window_length(self.window_length)

        # end point is end of last window
        is_in_sample = np.all(fh <= 0)
        if is_in_sample:
            end = n_timepoints + 1
        else:
            fh_max = fh[-1]
            end = n_timepoints - fh_max + 1  # non-inclusive end indexing

            # check if computed values are feasible with the provided index
            if window_length is not None:
                if window_length + fh_max > n_timepoints:
                    raise ValueError(
                        "The window length and forecasting horizon are "
                        "incompatible with the length of `y`"
                    )
        return end

class SlidingWindowSplitter(BaseWindowSplitter):
    """Sliding window splitter

    Parameters
    ----------
    fh : int, list or np.array
        Forecasting horizon
    window_length : int
    step_length : int
    initial_window : int
    start_with_window : bool, optional (default=True)
    """

    def __init__(
        self,
        fh=DEFAULT_FH,
        window_length=DEFAULT_WINDOW_LENGTH,
        step_length=DEFAULT_STEP_LENGTH,
        initial_window=None,
        start_with_window=False,
    ):

        self.step_length = step_length
        self.start_with_window = start_with_window
        self.initial_window = initial_window
        super(SlidingWindowSplitter, self).__init__(fh=fh, window_length=window_length)

    def _split_windows(self, y):
        step_length = check_step_length(self.step_length)
        window_length = check_window_length(self.window_length)
        fh = self._check_fh()

        end = self._get_end(y)
        start = self._get_start()
        for split_point in range(start, end, step_length):
            training_window = np.arange(split_point - window_length, split_point)
            test_window = split_point + fh - 1
            yield training_window, test_window

    def split_initial(self, y):
        """Split initial window

        This is useful during forecasting model selection where we want to
        fit the forecaster on some part of the
        data first before doing temporal cross-validation

        Parameters
        ----------
        y : pd.Series

        Returns
        -------
        intial_training_window : np.array
        initial_test_window : np.array
        """
        if self.initial_window is None:
            raise ValueError(
                "Please specify initial window, found: `initial_window`=None"
            )

        initial = check_window_length(self.initial_window)
        initial_training_window = np.arange(initial)
        initial_test_window = np.arange(initial, len(y))
        return initial_training_window, initial_test_window

    def get_n_splits(self, y=None):
        """Return number of splits

        Parameters
        ----------
        y : pd.Series or pd.Index, optional (default=None)

        Returns
        -------
        n_splits : int
        """
        if y is None:
            raise ValueError(
                f"{self.__class__.__name__} requires `y` to compute the "
                f"number of splits."
            )
        return len(self.get_cutoffs(y))

    def get_cutoffs(self, y=None):
        """Get the cutoff time points.

        Parameters
        ----------
        y : pd.Series or pd.Index, optional (default=None)

        Returns
        -------
        cutoffs : np.array
        """
        if y is None:
            raise ValueError(
                f"{self.__class__.__name__} requires `y` to compute the " f"cutoffs."
            )
        y = self._check_y(y)
        end = self._get_end(y)
        start = self._get_start()
        step_length = check_step_length(self.step_length)
        return np.arange(start, end, step_length) - 1

    def _get_start(self):
        window_length = check_window_length(self.window_length)
        if self.start_with_window:
            return window_length
        else:
            return 0

class SingleWindowSplitter(BaseWindowSplitter):
    """Single window splitter

    Split time series once into a training and test window.

    Parameters
    ----------
    fh : int, list or np.array
    window_length : int
    """

    def __init__(self, fh, window_length=None):
        super(SingleWindowSplitter, self).__init__(fh, window_length)

    def _split_windows(self, y):
        window_length = check_window_length(self.window_length)
        fh = self._check_fh()

        end = self._get_end(y) - 1
        start = 0 if window_length is None else end - window_length
        training_window = np.arange(start, end)
        test_window = end + fh - 1
        yield training_window, test_window

    def get_n_splits(self, y=None):
        """Return number of splits

        Parameters
        ----------
        y : pd.Series, optional (default=None)

        Returns
        -------
        n_splits : int
        """
        return 1

    def get_cutoffs(self, y=None):
        """Get the cutoff time points.

        Parameters
        ----------
        y : pd.Series or pd.Index, optional (default=None)

        Returns
        -------
        cutoffs : np.array
        """
        if y is None:
            raise ValueError(
                f"{self.__class__.__name__} requires `y` to compute the " f"cutoffs."
            )
        training_window, _ = next(self._split_windows(y))
        return training_window[-1:]  # array outpu

    def split_initial(self, y):
        """Split initial window

        This is useful during forecasting model selection where we want to
        fit the forecaster on some part of the
        data first before doing temporal cross-validation

        Parameters
        ----------
        y : pd.Series

        Returns
        -------
        intial_training_window : np.array
        initial_test_window : np.array
        """
        # the single window splitter simply returns the single split
        training_window, _ = next(self._split_windows(y))
        test_window = np.arange(training_window[-1] + 1, len(y))
        return training_window, test_window

def temporal_train_test_split(*arrays, test_size=None, train_size=None):
    """Split arrays or matrices into sequential train and test subsets
    Creates train/test splits over endogenous arrays an optional exogenous
    arrays. This is a wrapper of scikit-learn's ``train_test_split`` that
    does not shuffle.

    Parameters
    ----------
    *arrays : sequence of indexables with same length / shape[0]
        Allowed inputs are lists, numpy arrays, scipy-sparse
        matrices or pandas dataframes.
    test_size : float, int or None, optional (default=None)
        If float, should be between 0.0 and 1.0 and represent the proportion
        of the dataset to include in the test split. If int, represents the
        relative number of test samples. If None, the value is set to the
        complement of the train size. If ``train_size`` is also None, it will
        be set to 0.25.
    train_size : float, int, or None, (default=None)
        If float, should be between 0.0 and 1.0 and represent the
        proportion of the dataset to include in the train split. If
        int, represents the relative number of train samples. If None,
        the value is automatically set to the complement of the test size.

    Returns
    -------
    splitting : list, length=2 * len(arrays)
        List containing train-test split of inputs.

    References
    ----------
    ..[1]  adapted from https://github.com/alkaline-ml/pmdarima/
    """
    return train_test_split(
        *arrays,
        shuffle=False,
        stratify=None,
        test_size=test_size,
        train_size=train_size,
    )


import sys
import pygame

class Ship:
    """ A class to manage the player ship."""

    def __init__(self, ai_game):
        """Init the ship and set its starting position."""
        self.screen = ai_game.screen

        self.screen_rect = ai_game.screen.get_rect()

        # load the ship image and get its rect
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()

        # Start each new ship at the bottom center of the screen.
        self.rect.center = self.screen_rect.center

        # store a decimal value for the ships horizontal position
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)

        # Movements flag
        self.moving_right = False
        self.moving_left = False
        self.moving_top = False
        self.moving_bottom = False

    def update(self):
        """Update the ship's position based on the movement flag."""
        # Update the ship's x value not the rect value.
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.x += 1.5
        if self.moving_left and self.rect.left > 0:
            self.x -= 1.5
        if self.moving_top and self.rect.top > self.screen_rect.top:
            self.y -= 1.5
        if self.moving_bottom and self.rect.bottom < self.screen_rect.bottom:
            self.y += 1.5

        # update rect object from self.x and self.y
        self.rect.x = self.x
        self.rect.y = self.y

    def blitme(self):
        """Draw the ship att its current location."""
        self.screen.blit(self.image, self.rect)

class Rocket:

    def __init__(self):
        """Initialize the game, and create game resources."""
        # (1)
        pygame.init()

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.screen_width = 1000
        self.screen_height = 800
        self.bg_color = (230, 230, 230)
        pygame.display.set_caption("Rocket")

        self.ship = Ship(self)

    def run_game(self):
        while True:
            # Watch the keyboard and mouse events.
            # (4)
            self._check_events()
            self.ship.update()
            self._update_screen()

    def _check_events(self):
        """Respond to key presses and mouse events."""
        for event in pygame.event.get():
            # (5)
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

    def _check_keydown_events(self, event):
        """Respond to keypresses."""
        if event.key == pygame.K_RIGHT:
            # move the ship to the right
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            # move the ship to the left
            self.ship.moving_left = True
        elif event.key == pygame.K_UP:
            self.ship.moving_top = True
        elif event.key == pygame.K_DOWN:
            self.ship.moving_bottom = True
        elif event.key == pygame.K_q:
            sys.exit()

    def _check_keyup_events(self, event):
        """respond to key releases"""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            # stopping move the ship to the left
            self.ship.moving_left = False
        elif event.key == pygame.K_UP:
            self.ship.moving_top = False
        elif event.key == pygame.K_DOWN:
            self.ship.moving_bottom = False

    def _update_screen(self):
        """Update images on te screen, and flip to the new screen."""
        # Redraw the screen during each pass through the loop.
        self.screen.fill(self.bg_color)
        self.ship.blitme()

        # Make the most recently drawn screen visible.
        pygame.display.flip()

if __name__ == '__main__':
    # make a game instance and run the game.
    ai = Rocket()
    ai.run_game()


#=================================================================================================
# RECIPE DICTIONARY
recipeDictionary = {}
# ex. dictionary input
# { name : [ description, {itemName: itemAmount, itemName: itemAmount, ...  } ] }
# the keys in the recipe dictionary will be the name with a value list
# the list value would have the following:
# 0 index : description
# 1 index : another dictionary of ingredients , this dictionary would have:
## ingredient name as the key and ingredient amount as value (ex. {itemName: itemAmount})

#########################
# add something that will read a file to populate the recipeDictionary

# RECIPE BOOK FUNCTIONS
def addRecipe():
    global recipeDictionary
    # Ask user for recipe name

    # Ask user for recipe description

    # Ask user for number of ingredients (this is to know how many time we should ask the user for ingredients)

    # This wil be used to hold the ingredients inputted by the user that does not exist
    nonexistentIngredients = []
    # Loop equal to the number of ingredients
    # inside the loop ask user for each ingredient name and ingredient amount
    # Check each ingredient name per iteration if it is in supplyDictionary, if not add to nonexistendIngredients

    # Loop through the nonexistentIngredients list and call addRecordSupply for each element

    # Update the file of the recipeDictionary
    ...

def deleteRecipe():
    global recipeDictionary
    # Show all Recipe in the dictionary
    # One way to do this is to loop through the dictionary and show all the names

    # Ask user input for recipe name to delete

    # Check first if it exists
    # If it does , then delete it and show a message indicating success
    # update the file for the recipe dictionary

    # if it does not then just print something to indicate failure
    ...

def deleteAllRecipe():
    # OPTIONAL : Ask user for Y input if they really want to delete all recipe
    # if Y then just loop through each keys in the dictionary and delete them all

    # if anything other than Y then just print something to indicate invalid input
    ...

def viewRecipe():
    # Loop through all keys of the recipe dictionary and print them all

    # Ask user for input of recipe name

    # check if recipe name is in dictionary
    # if it is print it
    # if not print something to indicate invalid input
    ...

def executeRecipe():
    # Show all recipe names

    # Ask user for input of recipe name to execute

    #check if recipe name is in the dictionary
    # if it is show all ingredient name with their corresponding amount
    # show options: [1] Done [2] cancel
    # if Done
    # check if an each ingredient has sufficient amount in the supply dictionary
    # if not print something for error and exit function
    # if sufficient, reduce ingredient amount in supply dictionary with proper amount
    # if Cancel
    # just print something for cancel and exit the function

    ...
#=================================================================================================

#=================================================================================================
#supply dictionary
supplyDictionary = {}
# ex. dictionary input
# supplyDictionary = {name : [stock , price] }

# lagay ng magbabasa from file ng mga dictionary input

# SUPPLY RECORD FUNCTIONS
# functions will be the same as above , if natapos na yun pareho lang mga next
# just follow the parameters in the pdf file, but same logic as previous functions
def addRecordSupply():
    global supplyDictionary
    ...

def deleteRecordSupply():
    global supplyDictionary
    ...

def deleteAllRecordSupply():
    global supplyDictionary
    ...

def viewRecordSupply():
    global supplyDictionary
    ...

#=================================================================================================
# dictionary
supplierDictionary = {}
# ex. dictionary input
# supplierDictionary = {name : contact}

# SUPPLIER RECORDS FUNCTIONS
def addSupplierRecord():
    ...

def deleteSupplierRecord():
    ...

def deleteAllSupplierRecord():
    ...

def viewSupplierRecord():
    ...

#=================================================================================================
# MAIN

def main():
    while True:
        # Just edit this if you want design
        print("=============WELCOME===============\n")
        print("Select Something to Edit")
        print("[1] Recipe Book")
        print("[2] Supply Records")
        print("[3] Supplier Records")
        print("[0] EXIT")
        print("===================================\n")
        choice = int(input("Enter Choice: "))
        if choice == 0:
            break
        elif choice == 1:
            print("===================================")
            print("Select Something to do")
            print("[1] Add Recipe")
            print("[2] Delete Recipe ")
            print("[3] Delete All Recipes")
            print("[4] View Recipe")
            print("[5] Execute Recipe")
            print("[0] EXIT")
            print("===================================")
            choice = int(input("Enter Choice: "))
            if choice == 0:
                break
            elif choice == 1:
                addRecipe()
            elif choice == 2:
                deleteRecipe()
            elif choice == 3:
                deleteAllRecipe()
            elif choice == 4:
                viewRecipe()
            elif choice == 5:
                executeRecipe()
            else:
                print("Invalid Input")
        elif choice == 2:
            print("===================================")
            print("Select Something to do")
            print("[1] Add Record ")
            print("[2] Delete Record ")
            print("[3] Delete All Records ")
            print("[4] View Record ")
            print("[0] EXIT")
            print("===================================")
            choice = int(input("Enter Choice: "))
            if choice == 0:
                break
            elif choice == 1:
                addRecordSupply
            elif choice == 2:
                deleteRecordSupply
            elif choice == 3:
                deleteAllRecordSupply
            elif choice == 4:
                viewRecordSupply
            else:
                print("Invalid Input")
        elif choice == 3:
            print("===================================")
            print("Select Something to do")
            print("[1] Add Record ")
            print("[2] Delete Record ")
            print("[3] Delete All Records ")
            print("[4] View Record ")
            print("[0] EXIT")
            print("===================================")
            choice = int(input("Enter Choice: "))
            if choice == 0:
                break
            elif choice == 1:
                addSupplierRecord
            elif choice == 2:
                deleteSupplierRecord
            elif choice == 3:
                deleteAllSupplierRecord
            elif choice == 4:
                viewSupplierRecord
            else:
                print("Invalid Input")
        else:
            print("Invalid Input")

main()


from flask import render_template, flash, redirect, url_for, request
from app import app
from flask_wtf import FlaskForm
from wtforms import SelectField, SubmitField
from wtforms.validators import DataRequired
import auxFunctions as aux

SQL_PATH = app.root_path + "/sql"
MONTH_YEAR_DROPDOWN = aux.getSqlStatementFromFile(SQL_PATH, "12.1 Display State Volume by Category.sql")
STATE_VOLUME_REPORT = aux.getSqlStatementFromFile(SQL_PATH, "12.2 Display State Volume by Category.sql")
STORE_DETAIL_REPORT = aux.getSqlStatementFromFile(SQL_PATH, "12.3 Display State Volume by Category.sql")

@app.route('/state_volume/', defaults={'state': '', 'category': '', 'units': '', 'monthYear': ''}, methods=['GET', 'POST'])
@app.route('/state_volume/<state>/<category>/<units>/<monthYear>/', methods=['GET', 'POST'])
def state_volume(state, category, units, monthYear):
	ret = aux.get_table_rl(MONTH_YEAR_DROPDOWN)
	if not ret[0]:
		flash(ret[1])
		return render_template('state_volume.html', title='Store Revenue', monthsYears='')
	monthsYears = ret[1]
	ddlMonthsYears = [(m_y, m_y) for (m_y,) in monthsYears]
	stateVolumeForm = StateVolumeForm()
	stateVolumeForm.monthYearDDL.choices = ddlMonthsYears

	# monthYearDropDownTable = list(aux.get_table2(MONTH_YEAR_DROPDOWN))
	# monthYearDropDownResult = list(monthYearDropDownTable)

	if request.method == 'POST':
		# the Generate button was clicked

		# app.logger.warning('[APP_LOG] Selected Month Year:  %s', request.form.get("selected_month_year"))
		# param = request.form.get("selected_month_year")
		# param = param.split("-")

		monthYear = stateVolumeForm.monthYearDDL.data
		monthYearList = monthYear.split('-')
		month = monthYearList[0]
		year = monthYearList[1]
		parameterList = [month, year, month, year]
		ret = aux.get_table_rl(STATE_VOLUME_REPORT, parameterList)
		if not ret[0]:
			flash(ret[1])
			return render_template('state_volume.html', title='State Volume', state_volume='')
		stateVolReport = ret[1]
		return render_template('state_volume.html',
								title='State Volume Drill',
								form=stateVolumeForm,
								state_vol=stateVolReport,
								monthYear=monthYear)

		# stateVolReport = aux.get_table4(STATE_VOLUME_REPORT, param)
		# stateVolReport = tuple(zip(stateVolReport.Category, stateVolReport.State, stateVolReport.Units))
		# # converting into a tuple of tuples so jinja2 can iterate in the template
		#
		# return render_template('state_vol_drill.html',
		# 					   title='State Volume Drill',
		# 					   form=stateVolumeForm,
		# 					   state_vol=stateVolReport,
		# 					   month_years=monthYear)

	else:
		# either this is the initial display of the page, or we are drilling
		if state == '':
			# this is the initial display of the page
			return render_template('state_volume.html', title='State Volume', form=stateVolumeForm)
		else:
			# we are drilling
			table = aux.get_table1_5(STORE_DETAIL_REPORT, state)
			return render_template('state_volume.html', title='State Volume', form=stateVolumeForm,
									table=table, state=state, category=category, units=units, monthYear=monthYear)

# @app.route('/store_details')
# def store_details():
# 	stateName = request.args['state']
# 	categoryName = request.args['category']
# 	units = request.args['units']
# 	table = aux.get_table1_5(STORE_DETAIL_REPORT, stateName)
# 	return render_template('store_details.html', title='Store Details', table=table, category=categoryName,
# 						   state = stateName, units=units)
#
#
# @app.route('/delete_me_store_revenue2', methods=['GET', 'POST'])
# def store_revenue2():
# 	stateSQLResult = aux.get_df(SELECT_MANAGERS_SQL)
# 	state_sql = '''SELECT DISTINCT state FROM City ORDER BY state;'''
# 	states = list(get_table2(state_sql))
#
# 	if request.method =='POST':
# 		param = request.form.get("selected_state")
# 		stores = get_table2(SQL_STORE_REVENUE,param)
# 		# todo make code use submit bootstrap styling, like manager/
# 		return render_template('store_revenue.html', title='Store Revenue', states=states, stores=stores, state_nam=param)
#
# 	return render_template('store_revenue.html', title='Store Revenue', states=states)

class StateVolumeForm(FlaskForm):
    monthYearDDL = SelectField('<br>Select month-year from which to list highest volume stores in each category:')
    generate = SubmitField('Generate')


# isPhoneAndEmail.py - Finds all the phone numbers and the emails on the clipboard.

import pyperclip, re

# Mathces nummber in formats +91-0000000000 and 0000000000

phoneRegex = re.compile(r'([+91]-)?(\d{10})')

emailRegex = re.compile(r'''(
    [a-zA-Z0-9._%+-]+      # username
    @                      # @ symbol
    [a-zA-Z0-9.-]+         # domain name
    (\.[a-zA-Z]{2,4})      # dot-something
    )''', re.VERBOSE)

text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
       phoneNum = '+91-'+(groups[1])
       matches.append(phoneNum)
for groups in emailRegex.findall(text):
       matches.append(groups[0])

if len(matches) > 0:
    pyperclip.copy('\n'.join(matches))
    print('Copied to clipboard:')
    print('\n'.join(matches))
else:
    print('No phone numbers or email addresses found.')


import os
import argparse
import Tkinter as tk
import tkFileDialog

from tools_TkTooltip import ToolTip

# Argument groups to not show in the window
_OPTION_HIDE_ARGUMENT_GROUPS = ('CLI-only arguments','CLI arguments')

# Empty argument values
_OPTION_EMPTY_VALUES = ('',None,'None')

# Metavar values to trigger file browser
_OPTION_FILE_METAVARS = ('FILE',)

# Metavar values to trigger directory browser
_OPTION_DIR_METAVARS = ('DIR',)

class OptionsWindow(tk.Frame):
	def __init__(self, master, options):
		self.master = master
		self.master.title('Set Options')
		self.master.resizable(width=False, height=False)

		self.master.protocol('WM_DELETE_WINDOW', self.saveWindow)
		self.master.bind("<Return>", self.saveWindow)

		self.options = options
		self.option_keys = options.keys()

		tk.Frame.__init__(self,master)
		self.pack(expand=True,fill='both',padx=6,pady=6)
		self.pack_propagate(True)

		self.createWidgets()
		self.returncode = 0

	def saveWindow(self, evt=None):
		for i,k in enumerate(self.options):

			if self.options[k]['group'] in _OPTION_HIDE_ARGUMENT_GROUPS:
				break

			try:
				self.options[k]['value'] = self.optionValues[i].get()
			except ValueError:
				self.options[k]['value'] = None

			if self.options[k]['value'] in _OPTION_EMPTY_VALUES:
				self.options[k]['value'] == None

		self.returncode = 0
		self.close()

	def close(self):
		self.master.destroy()

	def cancel(self):
		self.returncode = 1
		self.close()

	def updateFileButton(self, evt):
		for i,b in enumerate(self.optionEntries):
			if b == evt.widget:
				break
		tmp = tkFileDialog.askopenfilename(parent=self.master,title=self.options[self.option_keys[i]]['dest'])
		self.optionValues[i].set(tmp)
		self.optionEntries[i].config(text=os.path.basename(tmp))

	def updateDirButton(self, evt):
		for i,b in enumerate(self.optionEntries):
			if b == evt.widget:
				break
		tmp = tkFileDialog.askdirectory(parent=self.master,title=self.options[self.option_keys[i]]['help'])
		self.optionValues[i].set(tmp)
		self.optionEntries[i].config(text=os.path.basename(os.path.normpath(tmp)))

	def createWidgets(self):
		self.container = tk.Frame(self)
		self.container.grid(padx=6,pady=6)

		self.optionGroups	= {}
		self.optionLabels	= []
		self.optionToolTips	= []
		self.optionValues	= []
		self.optionEntries	= []

		self.optionGroups[''] = tk.Frame(self.container,border=0)
		self.optionGroups[''].grid(column=0,row=0,columnspan=2,sticky=tk.W)

		# create option groups beforehand
		for k,option in self.options.iteritems():
			if option['group'] in _OPTION_HIDE_ARGUMENT_GROUPS:
				break

			if option['group'] == 'optional arguments':
				option['group'] = ''
			if option['group'] not in self.optionGroups:
				self.optionGroups[option['group']] = tk.LabelFrame(self.optionGroups[''],text=option['group'])

		rowcounter = 0
		for k,option in self.options.iteritems():
			if option['group'] in _OPTION_HIDE_ARGUMENT_GROUPS:
				break
			if option['value'] in _OPTION_EMPTY_VALUES:
				option['value'] = option['default']
			if str(option['value']) == 'None':
				option['value'] = ''

			container = self.optionGroups[option['group']]
			if len(container.winfo_children()) == 0: # group hasn't been placed in window yet
				container.grid(column=0,row=rowcounter,columnspan=2,sticky=tk.W+tk.E)
				rowcounter+=1

			# what do we show for the entry label?
			if option['metavar'] in _OPTION_FILE_METAVARS:
				text = option['dest'][0].upper()+option['dest'][1:]+" file:"
			elif option['metavar'] in _OPTION_DIR_METAVARS:
				text = option['dest'][0].upper()+option['dest'][1:]+" folder:"
			elif option['metavar'] == None:
				text = option['dest'][0].upper()+option['dest'][1:]
			else:
				text = option['metavar']

			self.optionLabels.append( tk.Label(container,text=text) )
			self.optionLabels[-1].grid(column=0,row=rowcounter,sticky=tk.W)
			self.optionToolTips.append( ToolTip(self.optionLabels[-1],follow_mouse=0,text=option['help']) )

			# file input are handled a bit differently
			if option['metavar'] in _OPTION_FILE_METAVARS: #file
				rowcounter+=1
				self.optionValues.append( tk.StringVar() )
				self.optionValues[-1].set( option['value'] )
				self.optionEntries.append( tk.Button(container,text=os.path.basename(str(option['value'])),justify=tk.LEFT) )
				self.optionEntries[-1].bind('<ButtonRelease-1>',self.updateFileButton)
				self.optionEntries[-1].grid(column=0,columnspan=2,row=rowcounter,sticky=tk.W+tk.E)
				rowcounter+=1
				continue

			elif option['metavar'] in _OPTION_DIR_METAVARS: #directory
				rowcounter+=1
				self.optionValues.append( tk.StringVar() )
				self.optionValues[-1].set( option['value'] )
				self.optionEntries.append( tk.Button(container,text=os.path.basename(os.path.normpath(str(option['value']))),justify=tk.LEFT) )
				self.optionEntries[-1].bind('<ButtonRelease-1>',self.updateDirButton)
				self.optionEntries[-1].grid(column=0,columnspan=2,row=rowcounter,sticky=tk.W+tk.E)
				rowcounter+=1
				continue

			elif(option['choices'] != None): #multiple choice
				self.optionValues.append( tk.StringVar() )
				self.optionEntries.append( tk.OptionMenu(container,self.optionValues[-1],*option['choices']) )
				self.optionEntries[-1].config(width=12)
				if option['value'] not in option['choices']:
					option['value'] = option['default']
			elif(option['nargs'] == 0): #boolean
				self.optionValues.append( tk.IntVar() )
				self.optionEntries.append( tk.Checkbutton(container,variable=self.optionValues[-1]) )
			elif(option['type'] == type(0)): #int
				self.optionValues.append( tk.IntVar() )
				self.optionEntries.append( tk.Entry(container,textvariable=self.optionValues[-1],width=4) )
			elif(option['type'] == type(0.0)): #float
				self.optionValues.append( tk.DoubleVar() )
				self.optionEntries.append( tk.Entry(container,textvariable=self.optionValues[-1],width=8) )
			else: #string
				self.optionValues.append( tk.StringVar() )
				self.optionEntries.append( tk.Entry(container,textvariable=self.optionValues[-1],width=12) )

			self.optionValues[-1].set( option['value'] )
			self.optionEntries[-1].grid(column=1,row=rowcounter,sticky=tk.W)
			rowcounter+=1

		self.cancelButton = tk.Button(self.container,text='Cancel',command=self.cancel)
		self.cancelButton.grid(column=0,row=rowcounter,sticky=tk.E,pady=(8,0))
		self.saveButton = tk.Button(self.container,text='Apply',command=self.saveWindow,width=8,default=tk.ACTIVE)
		self.saveButton.grid(column=1,row=rowcounter,sticky=tk.W,pady=(8,0))


import json

print ("\n\tSistema CLI para agregar una guerra a la base de dato de regcoc \n")
json_dict = {}
json_dict["total_estrellas"] = int(input("Total de estrellas:"))
json_dict["estrellas_ganadas"] = int(input("Estrellas ganadas:"))
json_dict["total_destruccion_porcentaje"] = float(input ("Porcentaje de destruccion total:"))
json_dict["isLiga"] = bool(input("Es liga de guerra de clanes (Y/ ):"))
total_jugadores = int(input("Total de jugadores:"))
json_dict["jugadores"]=[]
json_dict["ganada"] =  bool(input("Se gano (Y/ ):"))
for i in range(total_jugadores):
    nombre = input("Nombre del jugador "+str(i+1)+":")
    ataques=[]
    if(not json_dict["isLiga"] ) :
        estrellas =int(input("Estrellas 1 del jugador "+str(i+1)+":"))
        porcentaje = float(input("Porcentaje 1 del jugador "+str(i+1)+":"))
        ataques.append({"estrellas":estrellas,"porcentaje":porcentaje})
        estrellas= int(input("Estrellas 2 del jugador "+str(i+1)+":"))
        porcentaje= float(input("Porcentaje 2 del jugador "+str(i+1)+":"))
        ataques.append({"estrellas":estrellas,"porcentaje":porcentaje})
    else:
        estrellas = int(input("Estrellas del jugador "+str(i+1)+":"))
        porcentaje = float(input("Porcentaje del jugador "+str(i+1)+":"))
        ataques.append({"estrellas":estrellas,"porcentaje":porcentaje})
    json_dict["jugadores"].append({
            "nombre":nombre,
            "ataques":ataques
    })
with open("resultado.json", "w") as outfile:
    json.dump(json_dict, outfile)
print("Resultado escrito en resulatdo.json")