"""
url = http://www.xyfcj.com/html/jplp/index.html
city : 新余
CO_INDEX : 55
小区数量：
对应关系：
    小区与楼栋：co_id
    楼栋与房屋：bu_id
"""

import requests
from backup.comm_info import Comm, Building, House
from backup.get_page_num import AllListUrl
import re

url = 'http://www.xyfcj.com/html/jplp/index.html'
co_index = '55'
city = '新余'

count = 0

class Xinyu(object):
    def __init__(self):
        self.headers = {
            'User-Agent':
                'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119Safari/537.36',
        }

    def start_crawler(self):
        b = AllListUrl(first_page_url=url,
                       request_method='get',
                       analyzer_type='regex',
                       encode='utf-8',
                       page_count_rule='共(.*?)页',
                       headers=self.headers
                       )
        page = b.get_page_count()
        for i in range(1, int(page) + 1):
            if i is 1:
                all_page_url = 'http://www.xyfcj.com/html/jplp/index.html'
            else:
                all_page_url = 'http://www.xyfcj.com/html/jplp/index_' + str(i) + '.html'
            response = requests.get(all_page_url, headers=self.headers)
            html = response.text
            comm_url_list = re.findall('<a style="COLOR: #000000" target="_blank" href="(.*?)"', html, re.S | re.M)
            self.get_comm_info(comm_url_list)

    def get_comm_info(self, comm_url_list):
        for i in comm_url_list:
            try:
                response = requests.get(i, headers=self.headers)
                html = response.text
                comm = Comm(co_index)
                comm.co_name = re.findall('PROJECT_XMMC">(.*?)<', html, re.S | re.M)[0]
                comm.co_develops = re.findall('PROJECT_KFQY_NAME">(.*?)<', html, re.S | re.M)[0]
                comm.co_address = re.findall('PROJECT_XMDZ">(.*?)<', html, re.S | re.M)[0]
                comm.area = re.findall('PROJECT_SZQY">(.*?)<', html, re.S | re.M)[0]
                comm.co_volumetric = re.findall('PROJECT_RJL">(.*?)<', html, re.S | re.M)[0]
                comm.co_build_size = re.findall('PROJECT_GHZJZMJ">(.*?)<', html, re.S | re.M)[0]
                comm.co_pre_sale = re.findall('YSXKZH">(.*?)<', html, re.S | re.M)[0]
                comm.co_id = re.findall('PROJECT_XMBH">(.*?)<', html, re.S | re.M)[0]
                comm.insert_db()
                global count
                count += 1
                print(count)
                bu_info = re.search('id="buildInfo".*?value="(.*?)"', html, re.S | re.M).group(1)
                self.get_build_info(bu_info, comm.co_id, i)
            except Exception as e:
                print('小区错误,co_index={},url={}'.format(co_index, i), e)

    def get_build_info(self, bu_info, co_id, build_url):
        build_list = bu_info.split(';;')
        for i in build_list:
            try:
                build = Building(co_index)
                bu_code_list = i.split(',,')
                build.bu_num = bu_code_list[1]
                build.bu_id = bu_code_list[0]
                build.co_id = co_id
                build.insert_db()
                self.get_house_info(build.bu_id, co_id)
            except Exception as e:
                print('楼栋错误,co_index={},url={}'.format(co_index, build_url), e)

    def get_house_info(self, bu_id, co_id):
        house_url = "http://www.xyfdc.gov.cn/wsba/Common/Agents/ExeFunCommon.aspx"
        payload = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n<param funname=\"SouthDigital.Wsba.CBuildTableEx.GetBuildHTMLEx\">\r\n<item>" + \
                  bu_id + "</item>\r\n<item>1</item>\r\n<item>1</item>\r\n<item>80</item>\r\n<item>840</item>\r\n<item>g_oBuildTable</item>\r\n<item> 1=1</item>\r\n<item>1</item>\r\n<item>false</item>\r\n</param>\r\n"
        headers = {
            'Content-Type': "text/xml",
        }
        response = requests.request("POST", house_url, data=payload, headers=headers)
        html = response.text
        house_info_list = re.findall("onclick=.g_oBuildTable.clickRoom.*? title='(.*?)'", html, re.S | re.M)
        for i in house_info_list:
            try:
                house = House(co_index)
                house.ho_name = re.search('房号：(.*?)单元：', i, re.S | re.M).group(1)
                house.ho_build_size = re.search('总面积：(.*?)平方米', i, re.S | re.M).group(1)
                house.ho_type = re.search('用途：(.*?)户型', i, re.S | re.M).group(1)
                house.ho_room_type = re.search('户型：(.*?)状态', i, re.S | re.M).group(1)
                house.info = i
                house.bu_id = bu_id
                house.co_id = co_id
                house.insert_db()
            except Exception as e:
                print('房号错误，co_index={},url={},data={}'.format(co_index, house_url, payload), e)


import datetime
import sys

answer_format = '%m/%d'
link_format = '%b_%d'
link = 'https://en.wikipedia.org/wiki/{}'

while True:
    lst = []
    num_links = input("How many links do we want or 'QUIT' for quitting: ")
    if num_links.upper() == 'QUIT':
        break
    try:
        if int(num_links)!= int:
            pass
    except ValueError:
        continue
    while len(lst) < int(num_links):
        try:
            answer = input('Please enter a date (MM/DD)')
            date = datetime.datetime.strptime(answer, answer_format)
            output = link.format(date.strftime(link_format))
            lst.append(output)

        except ValueError:
            print('That is not a input. Try again.')
    print(lst)


# -*- coding:gb18030 -*-
from django.shortcuts import render

from notifications.models import Notification
from workdocuments.models import Document
from messagebook.models import Message,MessageForm

def homepage(request):
	notifications=Notification.objects.all().order_by('-pub_date')[:10]
	documents=Document.objects.filter(filetype='indep').order_by('-pub_date')[:10]
	messages=Message.objects.all().order_by('-pub_date')
	for message in messages:
		if message.reply_to:
			message.reply_to=Message.objects.get(id=message.reply_to_id)
	return render(request,'mainpage/index.html',{
		'notifications':notifications,
		'documents':documents,
		'messages':messages,
		'form':MessageForm(),
		})


nomes = ['Guilherme', 'Gabi', 'Gabriel']

# Laço For
# Para cada nome, dentro de nomes me mostra o nome
# Nome pode ser qualquer coisa, ele é um item
for nome in nomes:
    print(nome)

# Função RANGE() cria uma lista de numeros
# Tambem podemos determinar intervalos como por exemplo
# Range(5,10), vai contar do 5 ao 10
# Podemos usar o Passo tambem
# Range(0,100,2), vai contar de 0 a 100 com passo 2 (mostra os numeros pares)
lista_de_numeros = range(5)

for numero in lista_de_numeros:
    print(numero)

# Usando o Range no For
# 0,1,2,3
for item in range(3):
    print(nomes[item])

# Usando o Len para retornar o tamanho da lista
for i in range(len(nomes)):
    print(nomes[i])
    nomes.append('Adicionado')
    print(nomes)

# Contador
for cont in range(100):
    print(cont)

# Pegando letras de strings (Tambem são coleções)
palavra = 'Guilherme'
for letra in palavra:
    print(letra)

# Laço WHILE (enquanto)
i = 0
while i < 10:
    print('i ainda é menor que 10: ', i)
    i = i + 1

print('Acabou o While, o i é igual a:', i)

# Podemos usar and e or no while para ele retornar verdadeiro
# Podemos usar o +=

i = i + 1
# Ambos são iguais
i += 1

lista_frutas = ['Maçã', 'Pera', 'Uva', 'Abacaxi', 'Goiaba']

count = 0

# Se não existisse a Função Len
for fruta in lista_frutas:
    count += 1

print(count)
print(len(lista_frutas))

# Usando o BREAK
numero = 0
while True:
    print(numero)
    if numero == 20:
        break
    numero += 1

print('Saiu do While')


code = input("请输入您的身份证编号：")
name = input("请输入您的姓名：")
gender = input("请输入您的性别：")
age = input("请输入您的年龄：")
herght = input("请输入您的身高：")
live = input("请输入您的居住地址：")

info = '''
++++++++++个人信息++++++++++
身份证编号：%s，
姓名：     %s，
性别：     %s，
年龄：     %s，
身高：     %s，
居住地址：  %s
+++++++++++++++++++++++++++
'''
print(info % (code,name,gender,age,herght,live))


#!/usr/bin/env python3

import base64
import getpass
import os
import pprint
import sys
import time
from typing import Dict, List

import eblocbroker.Contract as Contract
import libs.eudat as eudat
import libs.gdrive as gdrive
import libs.git as git
import libs.ipfs as ipfs
import libs.slurm as slurm

from broker.config import QuietExit, env, logging, setup_logger
from broker.imports import connect
from broker.lib import (
    calculate_folder_size,
    eblocbroker_function_call,
    is_dir,
    remove_files,
    run,
    run_stdout_to_file,
    state_code,
    subprocess_call,
)
from broker.utils import (
    WHERE,
    StorageID,
    _colorize_traceback,
    byte_to_mb,
    bytes32_to_ipfs,
    eth_address_to_md5,
    is_dir_empty,
    log,
    mkdir,
    read_file,
    read_json,
    remove_empty_files_and_folders,
    silent_remove,
)

eBlocBroker, w3 = connect()
Ebb = Contract.eblocbroker

class Common:
    """Prevents "Class" has no attribute "method" mypy warnings."""

    def __init__(self) -> None:
        self.results_folder_prev = ""
        self.patch_file = ""
        self.requester_gpg_fingerprint = ""
        self.patch_upload_name = ""
        self.results_folder = ""
        self.data_transfer_out = 0.0

class IpfsGPG(Common):
    def initialize(self):
        pass

    def upload(self, *_) -> bool:
        """Upload files right after all the patchings are completed."""
        try:
            ipfs.gpg_encrypt(self.requester_gpg_fingerprint, self.patch_file)
        except:
            silent_remove(self.patch_file)
            sys.exit(1)
        return True

class Ipfs(Common):
    def initialize(self):
        pass

    def upload(self, *_) -> bool:
        """Upload files after all patchings are completed."""
        return True

class Eudat(Common):
    def __init__(self) -> None:
        self.encoded_share_tokens = {}  # type: Dict[str, str]

    def initialize(self):
        try:
            eudat.login(env.OC_USER, f"{env.LOG_PATH}/.eudat_provider.txt", env.OC_CLIENT)
        except:
            pass

        try:
            self.get_shared_tokens()
        except:
            sys.exit(1)

    def upload(self, source_code_hash, *_) -> bool:
        try:
            uploaded_file_size = eudat.get_size(f_name=f"{source_code_hash}/{self.patch_upload_name}")
            size_in_bytes = calculate_folder_size(self.patch_file, _type="bytes")
            if uploaded_file_size == float(size_in_bytes):
                log(f"==> {self.patch_file} is already uploaded")
                return True
        except Exception:  # First time uploading
            pass

        _data_transfer_out = calculate_folder_size(self.patch_file)
        logging.info(f"[{source_code_hash}]'s data_transfer_out => {_data_transfer_out} MB")
        self.data_transfer_out += _data_transfer_out
        success = eudat.upload_results(
            self.encoded_share_tokens[source_code_hash],
            self.patch_upload_name,
            self.patch_folder,
            5,
        )
        return success

class Gdrive(Common):
    def initialize(self):
        pass

    def upload(self, key, is_job_key) -> bool:
        try:
            if not is_job_key:
                success, meta_data = gdrive.get_data_key_ids(self.results_folder_prev)
                if not success:
                    return False

                try:
                    key = meta_data[key]
                except:
                    logging.error(f"[{WHERE(1)}] E: {key} does not have a match in meta_data.json")
                    return False

            cmd = [env.GDRIVE, "info", "--bytes", key, "-c", env.GDRIVE_METADATA]
            gdrive_info = subprocess_call(cmd, 5)
        except:
            logging.error(f"[{WHERE(1)}] E: {key} does not have a match. meta_data={meta_data}")
            return False

        mime_type = gdrive.get_file_info(gdrive_info, "Mime")
        logging.info(f"mime_type={mime_type}")
        self.data_transfer_out += calculate_folder_size(self.patch_file)
        logging.info(f"data_transfer_out={self.data_transfer_out} MB => rounded={int(self.data_transfer_out)} MB")
        if "folder" in mime_type:
            cmd = [env.GDRIVE, "upload", "--parent", key, self.patch_file, "-c", env.GDRIVE_METADATA]
        elif "gzip" in mime_type or "/zip" in mime_type:
            cmd = [env.GDRIVE, "update", key, self.patch_file, "-c", env.GDRIVE_METADATA]
        else:
            logging.error("E: Files could not be uploaded")
            return False

        try:
            logging.info(subprocess_call(cmd, 5))
        except:
            logging.error(f"[{WHERE(1)}] E: gdrive could not upload the file")
            return False

        return True

class ENDCODE(IpfsGPG, Ipfs, Eudat, Gdrive):
    def __init__(self, **kwargs) -> None:
        args = " ".join(["{!r}".format(v) for k, v in kwargs.items()])
        self.job_key = kwargs.pop("job_key")
        self.index = kwargs.pop("index")
        self.received_block_number = kwargs.pop("received_block_number")
        self.folder_name = kwargs.pop("folder_name")
        self.slurm_job_id = kwargs.pop("slurm_job_id")
        self.share_tokens = {}  # type: Dict[str, str]
        self.data_transfer_in = 0
        self.data_transfer_out = 0.0
        self.elapsed_time = 0
        self.source_code_hashes_to_process: List[str] = []
        self.source_code_hashes: List[str] = []
        self.result_ipfs_hash = ""
        self.requester_gpg_fingerprint = ""
        self.end_time_stamp = ""
        self.modified_date = None
        self.encoded_share_tokens = {}  # type: Dict[str, str]

        # [https://stackoverflow.com/a/4453495/2402577, https://stackoverflow.com/a/5971326/2402577]
        # my_env = os.environ.copy();
        # my_env["IPFS_PATH"] = HOME + "/.ipfs"
        # print(my_env)
        os.environ["IPFS_PATH"] = f"{env.HOME}/.ipfs"
        logging = setup_logger(f"{env.LOG_PATH}/end_code_output/{self.job_key}_{self.index}.log")
        # logging.info(f"==> Entered into {self.__class__.__name__} case.") # delete
        # logging.info(f"START: {datetime.datetime.now()}") # delete
        self.job_id = 0  # TODO: should be mapped slurm_job_id
        log(f"{env.EBLOCPATH}/broker/end_code.py {args}", color="blue")
        log(f"slurm_job_id={self.slurm_job_id}")
        if self.job_key == self.index:
            logging.error("E: Given key and index are same")
            sys.exit(1)

        try:
            self.job_info = eblocbroker_function_call(
                lambda: Ebb.get_job_info(
                    env.PROVIDER_ID,
                    self.job_key,
                    self.index,
                    self.job_id,
                    self.received_block_number,
                ),
                10,
            )
            self.cloud_storage_ids = self.job_info["cloudStorageID"]
            requester_id = self.job_info["job_owner"]
            requester_id_address = eth_address_to_md5(requester_id)
            self.requester_info = Ebb.get_requester_info(requester_id)
        except:
            sys.exit(1)

        self.results_folder_prev = f"{env.PROGRAM_PATH}/{requester_id_address}/{self.job_key}_{self.index}"
        self.results_folder = f"{self.results_folder_prev}/JOB_TO_RUN"
        if not is_dir(self.results_folder) and not is_dir(self.results_folder_prev):
            sys.exit(1)

        self.results_data_link = f"{self.results_folder_prev}/data_link"
        self.results_data_folder = f"{self.results_folder_prev}/data"
        self.private_dir = f"{env.PROGRAM_PATH}/{requester_id_address}/cache"
        self.patch_folder = f"{self.results_folder_prev}/patch"
        self.patch_folder_ipfs = f"{self.results_folder_prev}/patch_ipfs"

        mkdir(self.patch_folder)
        mkdir(self.patch_folder_ipfs)

        remove_empty_files_and_folders(self.results_folder)
        log(f"whoami: {getpass.getuser()} - {os.getegid()}")
        log(f"home: {env.HOME}")
        log(f"pwd: {os.getcwd()}")
        log(f"results_folder: {self.results_folder}")
        log(f"job_key: {self.job_key}")
        log(f"index: {self.index}")
        log(f"cloud_storage_ids: {self.cloud_storage_ids}")
        log(f"folder_name: {self.folder_name}")
        log(f"provider_id: {env.PROVIDER_ID}")
        log(f"requester_id_address: {requester_id_address}")
        log(f"received: {self.job_info['received']}")

    def get_shared_tokens(self):
        try:
            share_ids = read_json(f"{self.private_dir}/{self.job_key}_shareID.json")
        except:
            pass

        for source_code_hash in self.source_code_hashes_to_process:
            try:
                share_token = share_ids[source_code_hash]["share_token"]
                self.share_tokens[source_code_hash] = share_token
                self.encoded_share_tokens[source_code_hash] = base64.b64encode(
                    (f"{share_token}:").encode("utf-8")
                ).decode("utf-8")
            except KeyError:
                try:
                    share_token = Ebb.mongo_broker.find_key(Ebb.mongo_broker.mc["eBlocBroker"]["shareID"], self.job_key)
                    self.share_tokens[source_code_hash] = share_token
                    self.encoded_share_tokens[source_code_hash] = base64.b64encode(
                        (f"{share_token}:").encode("utf-8")
                    ).decode("utf-8")
                except:
                    logging.error(f"E: share_id cannot detected from key: {self.job_key}")
                    raise

        for key in share_ids:
            value = share_ids[key]
            encoded_value = self.encoded_share_tokens[key]
            logging.info("shared_tokens: ({}) => ({}) encoded:({})".format(key, value["share_token"], encoded_value))

    def get_cloud_storage_class(self, _id):
        """Returns cloud storage used for the id of the data."""
        if self.cloud_storage_ids[_id] == StorageID.IPFS:
            return Ipfs
        if self.cloud_storage_ids[_id] == StorageID.IPFS_GPG:
            return IpfsGPG
        if self.cloud_storage_ids[_id] == StorageID.EUDAT:
            return Eudat
        if self.cloud_storage_ids[_id] == StorageID.GDRIVE:
            return Gdrive
        return None

    def set_source_code_hashes_to_process(self):
        for idx, source_code_hash in enumerate(self.source_code_hashes):
            if self.cloud_storage_ids[idx] in [StorageID.IPFS, StorageID.IPFS_GPG]:
                ipfs_hash = bytes32_to_ipfs(source_code_hash)
                self.source_code_hashes_to_process.append(ipfs_hash)
            else:
                self.source_code_hashes_to_process.append(w3.toText(source_code_hash))

    def ipfs_add_folder(self, folder_path):
        try:
            self.result_ipfs_hash = ipfs.add(folder_path)
            logging.info(f"result_ipfs_hash={self.result_ipfs_hash}")
            ipfs.pin(self.result_ipfs_hash)
            data_transfer_out = ipfs.get_cumulative_size(self.result_ipfs_hash)
        except:
            _colorize_traceback()
            raise

        data_transfer_out = byte_to_mb(data_transfer_out)
        self.data_transfer_out += data_transfer_out

    def process_payment_tx(self):
        try:
            tx_hash = eblocbroker_function_call(
                lambda: Ebb.process_payment(
                    self.job_key,
                    self.index,
                    self.job_id,
                    self.elapsed_time,
                    self.result_ipfs_hash,
                    self.cloud_storage_ids,
                    self.end_time_stamp,
                    self.data_transfer_in,
                    self.data_transfer_out,
                    self.job_info["core"],
                    self.job_info["run_time"],
                ),
                10,
            )
            logging.info(f"tx_hash={tx_hash}")
        except:
            _colorize_traceback()
            sys.exit(1)

        with open(f"{env.LOG_PATH}/transactions/{env.PROVIDER_ID}.txt", "a") as f:
            f.write(f"processPayment {self.job_key} {self.index} {tx_hash}")

    def clean_before_upload(self):
        remove_files(f"{self.results_folder}/.node-xmlhttprequest*")

    def remove_source_code(self):
        """Client's initial downloaded files are removed."""
        timestamp_file = f"{self.results_folder_prev}/timestamp.txt"
        try:
            cmd = ["find", self.results_folder, "-type", "f", "!", "-newer", timestamp_file]
            files_to_remove = run(cmd)
        except:
            sys.exit()

        if not files_to_remove or files_to_remove:
            logging.info(f"Files to be removed: \n{files_to_remove}\n")

        run(["find", self.results_folder, "-type", "f", "!", "-newer", timestamp_file, "-delete"])

    def git_diff_patch_and_upload(self, source, name, storage_class, is_job_key):
        if is_job_key:
            log(f"==> patch_base={self.patch_folder}")
            log(f"==> Patch for the source code {name}")
        else:
            log(f"==> Patch for the data file {name}")

        try:
            if storage_class is Ipfs or storage_class is IpfsGPG:
                target_path = self.patch_folder_ipfs
            else:
                target_path = self.patch_folder

            self.patch_upload_name, self.patch_file, is_file_empty = git.diff_patch(
                source, name, self.index, target_path
            )
            if not is_file_empty:
                if not storage_class.upload(self, name, is_job_key):
                    raise
        except Exception as e:
            raise Exception("E: Problem on git_diff_patch_and_upload()") from e

    def upload_driver(self):
        self.clean_before_upload()
        try:
            storage_class = self.get_cloud_storage_class(0)
            self.git_diff_patch_and_upload(self.results_folder, self.job_key, storage_class, is_job_key=True)
        except Exception as e:
            raise Exception("E: Problem on git_diff_patch_and_upload()") from e

        for idx, name in enumerate(self.source_code_hashes_to_process[1:], 1):
            # starting from 1st index for data files
            source = f"{self.results_data_folder}/{name}"
            storage_class = self.get_cloud_storage_class(idx)
            try:
                self.git_diff_patch_and_upload(source, name, storage_class, is_job_key=False)
            except Exception as e:
                raise Exception("E: Problem on git_diff_patch_and_upload()") from e

        if not is_dir_empty(self.patch_folder_ipfs):
            # it will upload files after all the patchings are completed
            # in case any file is created via ipfs
            self.ipfs_add_folder(self.patch_folder_ipfs)

    def sacct_result(self):
        # CPUTime = NCPUS * Elapsed
        #
        # To get stats about real CPU usage you need to look at SystemCPU and
        # UserCPU, but the docs warns that it only measure CPU time for the
        # parent process and not for child processes.
        slurm_log_output_file = f"{self.results_folder}/slurm_job_info.out"
        cmd = ["sacct", "-X", "--job", self.slurm_job_id, "--format"]
        cmd.append("JobID,jobname,User,Account,Group,Cluster,AllocCPUS,REQMEM,TotalCPU,Elapsed")
        run_stdout_to_file(cmd, slurm_log_output_file)
        with open(slurm_log_output_file, "a") as myfile:
            myfile.write("\n\n")

        cmd.pop()
        cmd.append("NNodes,NTasks,ncpus,CPUTime,State,ExitCode,End,CPUTime,MaxRSS")
        run_stdout_to_file(cmd, slurm_log_output_file, mode="a")
        with open(slurm_log_output_file, "a") as myfile:
            myfile.write("\n")

    def run(self):
        try:
            data = read_json(f"{self.results_folder_prev}/data_transfer_in.json")
            self.data_transfer_in = data["data_transfer_in"]
            log(f"==> data_transfer_in={self.data_transfer_in} MB -> rounded={int(self.data_transfer_in)} MB")
        except:
            logging.error("E: data_transfer_in.json does not exist")

        try:
            self.modified_date = read_file(f"{self.results_folder_prev}/modified_date.txt")
            log(f"==> modified_date={self.modified_date}")
        except:
            log("==> E: modified_date.txt file could not be read")

        self.requester_gpg_fingerprint = self.requester_info["gpg_fingerprint"]
        log("job_owner's info", color="green")
        log("================", color="green")
        log("{0: <17}".format("email:") + self.requester_info["email"], color="green")
        log("{0: <17}".format("gpg_fingerprint:") + self.requester_gpg_fingerprint, color="green")
        log("{0: <17}".format("ipfs_id:") + self.requester_info["ipfs_id"], color="green")
        log("{0: <17}".format("f_id:") + self.requester_info["f_id"], color="green")

        if self.job_info["stateCode"] == str(state_code["COMPLETED"]):
            log("==> Job is already completed and its money is received")
            raise QuietExit

        run_time = self.job_info["run_time"]
        log(f"==> requested_run_time={run_time[self.job_id]} minutes")
        is_print = True
        for attempt in range(10):
            if self.job_info["stateCode"] == state_code["RUNNING"]:
                # it will come here eventually, when setJob() is deployed
                log("==> Job has been started")
                break  # wait until does values updated on the blockchain

            if self.job_info["stateCode"] == state_code["COMPLETED"]:
                # detects an error on the slurm side
                log("==> Job is already completed job and its money is received")
                raise QuietExit

            try:
                self.job_info = eblocbroker_function_call(
                    lambda: Ebb.get_job_info(
                        env.PROVIDER_ID, self.job_key, self.index, self.job_id, self.received_block_number, is_print
                    ),
                    10,
                )
                is_print = False
            except:
                sys.exit(1)

            log(f"==> start_code tx of the job is not obtained yet. Waiting for {attempt * 15} seconds to pass")
            # short sleep here so this loop is not keeping CPU busy due to
            # setJobSuccess may deploy late
            time.sleep(15)
        else:  # failed all the attempts, abort
            sys.exit(1)

        try:
            self.job_info = eblocbroker_function_call(
                lambda: Ebb.get_job_source_code_hashes(
                    self.job_info,
                    env.PROVIDER_ID,
                    self.job_key,
                    self.index,
                    self.job_id,
                    self.received_block_number,
                ),
                10,
            )
        except:
            sys.exit(1)

        self.source_code_hashes = self.job_info["source_code_hash"]
        self.set_source_code_hashes_to_process()
        self.sacct_result()

        self.end_time_stamp = slurm.get_job_end_time(self.slurm_job_id)
        self.elapsed_time = slurm.get_elapsed_time(self.slurm_job_id)
        if self.elapsed_time > int(run_time[self.job_id]):
            self.elapsed_time = run_time[self.job_id]

        logging.info(f"finalized_elapsed_time={self.elapsed_time}")
        _job_info = pprint.pformat(self.job_info)
        log(f"## job_info:\n{_job_info}", color="green")
        try:
            self.get_cloud_storage_class(0).initialize(self)
            self.upload_driver()
        except:
            _colorize_traceback()
            sys.exit(1)

        data_transfer_sum = self.data_transfer_in + self.data_transfer_out
        log(f"data_transfer_in={self.data_transfer_in} MB => rounded={int(self.data_transfer_in)} MB")
        log(f"data_transfer_out={self.data_transfer_out} MB => rounded={int(self.data_transfer_out)} MB")
        log(f"data_transfer_sum={data_transfer_sum} MB => rounded={int(data_transfer_sum)} MB")
        self.process_payment_tx()
        log("SUCCESS")
        # TODO: garbage collector, removed downloaded code from local since it is not needed anymore

if __name__ == "__main__":
    kwargs = {
        "job_key": sys.argv[1],
        "index": sys.argv[2],
        "received_block_number": sys.argv[3],
        "folder_name": sys.argv[4],
        "slurm_job_id": sys.argv[5],
    }
    cloud_storage = ENDCODE(**kwargs)
    try:
        cloud_storage.run()
    except Exception as e:
        if type(e).__name__ != "QuietExit":
            _colorize_traceback()
        sys.exit(1)

# cmd = ["tar", "-N", self.modified_date, "-jcvf", self.output_file_name] + glob.glob("*")
# success, output = run(cmd)
# self.output_file_name = f"result-{PROVIDER_ID}-{self.job_key}-{self.index}.tar.gz"
"""Approach to upload as .tar.gz. Currently not used.
                remove_source_code()
                with open(f"{results_folder_prev}/modified_date.txt') as content_file:
                date = content_file.read().strip()
                cmd = ['tar', '-N', date, '-jcvf', self.output_file_name] + glob.glob("*")
                log.write(run(cmd))
                cmd = ['ipfs', 'add', results_folder + '/result.tar.gz']
                self.result_ipfs_hash = run(cmd)
                self.result_ipfs_hash = self.result_ipfs_hash.split(' ')[1]
                silent_remove(results_folder + '/result.tar.gz')
# ---------------
# cmd = ["tar", "-N", self.modified_date, "-jcvf", patch_file] + glob.glob("*")
# success, output = run(cmd)
# logging.info(output)

# self.remove_source_code()
# cmd: tar -jcvf result-$providerID-$index.tar.gz *
# cmd = ['tar', '-jcvf', self.output_file_name] + glob.glob("*")
# cmd = ["tar", "-N", self.modified_date, "-czfj", self.output_file_name] + glob.glob("*")
# success, output = run(cmd)
# logging.info(f"Files to be archived using tar: \n {output}")
"""


import sys

dry_run = True
if dry_run:
    file = open('res/input.txt')
    sys.stdin = file

global var
for t in range(int(input())):
    n = int(input())
    arr = [int(i) for i in input().split()]
    preset = set()
    posset = set()
    np = False
    for i in arr:
        if i in posset:
            np = True
            break
        if i in preset:
            posset.add(i)
        else:
            preset.add(i)
    if np or (len(posset) != 0 and max(preset) == max(posset)):
        print("NO")
    else:
        poslist = list(posset)
        print("YES")
        for i in preset:
            print(i, end=' ')
        for i in reversed(poslist):
            print(i, end=' ')
        print()


# -*- coding: utf-8 -*-
# @Author  : qiaohezhe
# @github : https://github.com/fengduqianhe
# @Date    :  2020/1/20 12:59
# version： Python 3.7.8
# @File : mlp.py
# @Software: PyCharm

import numpy as np
import matplotlib.pyplot as plt

def show():
    all_x = X[:,2]
    all_y = X[:,3]
if __name__== "__main__":
    n = 0
    lr = 0.10
    X = np.array([[1, 1, 2, 3], [1, 1, 4, 5], [1, 1, 1, 1], [1, 1, 5, 3], [1, 1, 0, 1]])
    Y = np.array([1, 1, -1, 1, -1])
    W = (np.random.random(X.shape[1]) - 0.5) * 2
    for iter in range(100):
        new_output = np.sign(np.matmul(X, W.T))
        if (new_output == Y).all():
            break
        new_W = W + lr * np.matmul((Y - new_output.T), X)/int(X.shape[0])
        W = new_W
        print("第%s次迭代权重为%s" % (iter, W))

    # X = np.array([[1, 1, 2, 3, 1], [1, 1, 4, 5, 1], [-1, -1, -1, -1, -1], [1, 1, 5, 3, 1], [-1, -1, 0, -1, -1]])
    # W = np.array([0, 0, 0, 0, 0])
    # n = 0
    # while 1:
    #     flag = 0
    #     for x in X:
    #         if np.matmul(x, W.T) <= 0:
    #             W = W + x
    #             flag = 1
    #         n += 1
    #         print("第%s次迭代权重为%s" % (n, W))
    #     if flag == 0:
    #         break

# print(new_output)


    # -*- coding: utf-8 -*-

"""
.. module:: write_cv.py.py
   :license: GPL/CeCIL
   :platform: Unix, Windows
   :synopsis: Maps raw EUSTACE-TEAM EUSTACE vocab files to normalized pyessv format.

.. moduleauthor:: Mark Conway-Greenslade <momipsl@ipsl.jussieu.fr>

"""
import argparse
import json
import os

import arrow

import pyessv

# Define command line options.
_ARGS = argparse.ArgumentParser("Maps raw EUSTACE-TEAM EUSTACE vocab files to normalized pyessv CV format.")
_ARGS.add_argument(
    "--source",
    help="Path from which raw EUSTACE-TEAM EUSTACE vocab files will be read.",
    dest="source",
    type=str
    )

# Ensure we use fixed creation date.
_CREATE_DATE = arrow.get("2017-05-31 00:00:00.000000+0000").datetime

# CV authority = EUSTACE-TEAM.
_AUTHORITY = pyessv.create_authority(
    name="EUSTACE-TEAM",
    description="EUSTACE TEAM",
    url="https://www.eustaceproject.eu",
    create_date=_CREATE_DATE
    )

# CV scope = EUSTACE.
_SCOPE_EUSTACE = pyessv.create_scope(
    authority=_AUTHORITY,
    name="EUSTACE",
    description="Controlled Vocabularies (CVs) for use in EUSTACE",
    url="https://github.com/eustace-test/EUSTACE_CVs",
    create_date=_CREATE_DATE
    )

# CV scope = GLOBAL.
_SCOPE_GLOBAL = pyessv.create_scope(
    authority=_AUTHORITY,
    name="GLOBAL",
    description="Global controlled Vocabularies (CVs)",
    url="https://github.com/eustace-test/EUSTACE_CVs",
    create_date=_CREATE_DATE
    )

# Map of EUSTACE collections to data factories.
_COLLECTIONS_EUSTACE = {
    'frequency': {},
    'institution_id': lambda obj, name: {'postal_address': obj[name]},
    'realm': None,
    'required_global_attributes': None
}

# Map of global collections to data factories.
_COLLECTIONS_GLOBAL = {
}

def _main(args):
    """Main entry point.

    """
    if not os.path.isdir(args.source):
        raise ValueError("EUSTACE-TEAM vocab directory does not exist")

    # Create EUSTACE collections.
    for typeof, data_factory in _COLLECTIONS_EUSTACE.items():
        _create_collection_eustace(args.source, typeof, data_factory)

    # Create GLOBAL collections.
    for typeof, data_factory in _COLLECTIONS_GLOBAL.items():
        _create_collection_global(args.source, typeof, data_factory)

    # Add to the archive.
    pyessv.add(_AUTHORITY)

    # Save (to file system).
    pyessv.save()

def _create_collection_eustace(source, collection_type, data_factory):
    """Creates eustace collection from a EUSTACE-TEAM JSON files.

    """
    # Load EUSTACE-TEAM json data.
    eustace_team_cv_data = _get_eustace_team_cv(source, collection_type, "EUSTACE_")

    # Create collection.
    collection_name = collection_type.replace("_", "-")
    collection = pyessv.create_collection(
        scope=_SCOPE_EUSTACE,
        name=collection_name,
        description="EUSTACE-TEAM EUSTACE CV collection: ".format(collection_name),
        create_date=_CREATE_DATE
        )

    # Create terms.
    for name in eustace_team_cv_data:
        pyessv.create_term(
            collection=collection,
            name=name,
            description=name,
            create_date=_CREATE_DATE,
            data=data_factory(eustace_team_cv_data, name) if data_factory else None
            )

def _create_collection_global(source, collection_type, data_factory):
    """Creates global collection from a EUSTACE-TEAM JSON files.

    """
    # Load EUSTACE-TEAM json data.
    eustace_team_cv_data = _get_eustace_team_cv(source, collection_type)

    # Create collection.
    collection_name = collection_type.replace("_", "-")
    collection = pyessv.create_collection(
        scope=_SCOPE_GLOBAL,
        name=collection_name,
        description="EUSTACE-TEAM GLOBAL CV collection: ".format(collection_name),
        create_date=_CREATE_DATE
        )

    # Create terms.
    for name in eustace_team_cv_data:
        pyessv.create_term(
            collection=collection,
            name=name,
            description=name,
            create_date=_CREATE_DATE,
            data=data_factory(eustace_team_cv_data, name) if data_factory else None
            )

def _get_eustace_team_cv(source, collection_type, prefix=""):
    """Returns raw EUSTACE-TEAM CV data.

    """
    fname = "{}{}.json".format(prefix, collection_type)
    fpath = os.path.join(source, fname)
    with open(fpath, 'r') as fstream:
        return json.loads(fstream.read())[collection_type]

# Entry point.
if __name__ == '__main__':
    _main(_ARGS.parse_args())


"""
Caculator
=====

Provides
  1. Base class defining basis process of calculating transient stability of power flow with wind machine

Design pattern
  1. Strategy pattern: define process of calculating TS, with different strategy in each step

"""
import time

import numpy as np

from series_generator import Monte_Carlo
import runTSAT as rt

class Caculator:
    def __init__(self, series_generator, distribution_solver, wind_turbine_and_farm):
        self.series_generator = series_generator
        self.distribution_solver = distribution_solver
        self.wind_turbine_and_farm = wind_turbine_and_farm

    def sample_test(self, length, bus_number=8, output_log=None, disp=False, sav=False):
        """
        Main process. It calls its strategy methods and calculates transient stability
        :param length: length of wind speed series, also decides running time of program
        :param bus_number: bus number where wind machine integrate
        :return:
        """
        t1 = time.clock()
        random_variables = self.series_generator.generate(length)
        wind_speed = self.distribution_solver.solve(random_variables)
        wind_power = self.wind_turbine_and_farm.power_out(wind_speed)
        result = rt.run_and_analyze(wind_power, bus_number)

        if not output_log:
            output_log = "output_{}MC.log".format("" if type(self.series_generator) == Monte_Carlo else "Q")
        with open(output_log, "w") as output:
            output.writelines("***********************************************************************\n")
            output.writelines("{0:>12}{1:>12}{2:>12}\n".format("风速(m/s)", "风机功率(MW)", "是否稳定"))
            for i in range(len(wind_power)):
                output.writelines("{0:>14.2f}{1:>16.2f}{2:>15}\n".format(
                    wind_speed[i], wind_power[i], "是" if result[0][i] else "否"))
            output.writelines("系统的暂态稳定概率为%.4f\n" % (result[0].count(True)/length))
            output.writelines("风速在{0:.3f}m/s~{1:.3f}m/s之间系统暂态稳定\n".format(
                min(wind_speed[np.array(result[0])]), max(wind_speed[np.array(result[0])])))
            output.writelines("***********************************************************************\n")

        t2 = time.clock()
        t = t2-t1

        if disp:
            for line in open(output_log):
                print(line, end="")

        if sav:
            with open("abstract_{}MC.txt".format("" if type(self.series_generator) == Monte_Carlo else "Q"), "a") as file:
                file.writelines("\n=================={}蒙特卡罗法=======================\n".format(
                    "" if type(self.series_generator) == Monte_Carlo else "拟"))
                file.writelines(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())))
                file.writelines("\n")
                file.writelines("样本数：{}\n".format(str(length)))
                file.writelines("总共花费时间：{}秒\n".format(str(t)))
                file.writelines("平均每点时间：{}秒\n".format(str(t/length)))
                file.writelines("系统暂态稳定概率为：{}\n".format(str(result[0].count(True)/length)))
                file.writelines("====================================================\n")

        return result[0].count(True), wind_speed[np.array(result[0])], t

    def calculate_ami(self, wind_speed, bus_number=8):
        wind_power = self.wind_turbine_and_farm.power_out(wind_speed)
        result, security_index = rt.run_and_analyze(wind_power, bus_number)
        return security_index

    def calculate_cct(self, wind_speed, bus_number=8):
        wind_power = self.wind_turbine_and_farm.power_out(wind_speed)
        result, security_index = rt.run_and_analyze(wind_power, bus_number, index="cct")
        return security_index


# coding:utf-8
"""
Created at 2018.06.21
for log output
@author : Administrator
"""
import logging,time,os
from logging.handlers import RotatingFileHandler

class Logger(object):
    """
    output log
    """
    def __init__(self, title_name):
        title = "logger for safeEmail Project"
        day = time.strftime("%Y%m%d%H", time.localtime(time.time()))
        filepath = os.path.dirname(__file__)
        files = os.path.join(filepath, day+'.log')
        self.formater = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.logger = logging.Logger(title_name)  # title
        # 不限制文件保存
        self.logfile = logging.FileHandler(files)
        self.logfile.setLevel(logging.DEBUG)        # set log level
        self.logfile.setFormatter(self.formater)
        self.logger.addHandler(self.logfile)
        # control输出到屏幕
        # self.control = logging.StreamHandler()
        # self.control.setLevel(logging.INFO)
        # self.control.setFormatter(self.formater)
        # self.logger.addHandler(self.control)
        # 定义一个RotatingFileHandler，最多备份3个日志文件，每个日志文件最大1K
        # self.rHandler = RotatingFileHandler(file,maxBytes = 512*1024,backupCount = 3)
        # self.rHandler.setLevel(logging.INFO)
        # self.rHandler.setFormatter(self.formater)
        # self.logger.addHandler(self.rHandler)

    def debug_log(self, msg):
        self.logger.debug(msg)

    def info_log(self, msg):
        self.logger.info(msg)

    def warn_log(self, msg):
        self.logger.warning(msg)

    def error_log(self, msg):
        self.logger.error(msg)
if __name__ == "__main__":
    day = time.strftime("%Y%m%d%H", time.localtime(time.time()))
    filepath = os.getcwd()
    file = os.path.join(filepath, day + '.log')
    print(file)


import numpy as np
import time
from PyQt5.QtGui import *
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.path import Path
import matplotlib.patches as patches
from PyQt5.QtWidgets import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from midi_extended.UtilityBox import *

from midi_extended.UtilityBox import *

class SegmentCanvas(FigureCanvas):

    def __init__(self, width=4, height=7,  dpi=100):
        fig = Figure(figsize = (width, height), dpi=dpi, facecolor='#FFFAF0')
        FigureCanvas.__init__(self, fig)
        self.axes = fig.add_subplot(111)
        self.axes.set_xlim(0, 8)
        self.axes.set_xticks(np.arange(0, 8, 1))
        self.axes.set_ylim(60, 84)
        self.axes.set_yticks(np.arange(60, 84, 12))

    def plot(self, msgs):
        try:
            final_time = msgs[-1][2] + msgs[-1][1]
            min_note = min([min([msg[0] for msg in msgs]) - 6, 60])
            max_note = max([max([msg[0] for msg in msgs]) + 6, 72])
        except:
            final_time = 0.5
            min_note = 60
            max_note = 72
        note_texts = [get_note_name_by_midi_value(note) for note in range(min_note, max_note+1)]
        self.axes.set_xlim(0, final_time)
        self.axes.set_xticks(np.arange(0, final_time, 0.5))
        self.axes.set_ylim(min_note, max_note)
        self.axes.set_yticks(np.arange(min_note, max_note, 1))
        self.axes.tick_params(axis='both', which='minor', labelsize=10)
        # print(note_texts)
        self.axes.set_yticklabels(note_texts)
        bar_width = 0.5
        for msg in msgs:
            note = msg[0]
            length = msg[1]
            time = msg[2]
            verts = [
                (time, note - bar_width/2),
                (time, note + bar_width/2),
                (time + length, note + bar_width/2),
                (time + length, note - bar_width/2),
                (time, note - bar_width/2)
            ]
            codes = [
                Path.MOVETO,
                Path.LINETO,
                Path.LINETO,
                Path.LINETO,
                Path.CLOSEPOLY,
            ]
            path = Path(verts, codes)
            patch = patches.PathPatch(path, facecolor='#CD853F', lw=1)
            self.axes.add_patch(patch)
        # self.axes.plot(times, notes)

class SegmentWindow(QMainWindow):
    def __init__(self, music_segment):
        super().__init__()
        self.music_segment = music_segment
        self.initUI()

    def initUI(self):
        self.graphic_view = QGraphicsView()
        self.graphic_view.setObjectName('graphic_view')

        self.segment_canvas = SegmentCanvas()
        self.segment_canvas.plot(self.music_segment.msgs)
        graphic_scene = QGraphicsScene()
        graphic_scene.addWidget(self.segment_canvas)
        self.graphic_view.setScene(graphic_scene)
        self.graphic_view.show()
        self.setCentralWidget(self.graphic_view)
        self.graphic_view.setFixedSize(400, 700)

        self.setWindowIcon(QIcon('./icon/gramophone.png'))
        self.setWindowTitle('MusicCritique Notes Display')
        self.move(1505, 125)
        self.show()

    def closeEvent(self, e):
        self.music_segment.window_on = False


from itertools import product
from functools import partial
import pickle
import pathlib
import pandas as pd

from utility.AllNothingFrankWolf import AllNothingFrankWolfModel

df_demand = pd.read_excel('data.xlsx', sheet_name='demand')

list_centroid = [1] + list(df_demand.index[df_demand[1] != 0])

def cal_money_cost(x, t_a0, c_a, ex):
    return 2 * t_a0 * (1 + 0.15 * (x / c_a) **4) + ex

net_info_dir_path = pathlib.Path('net_info')
result_dir_path = pathlib.Path('scheme2')

result_dir_path.mkdir(exist_ok=True)

with open('net_info/net_info_000000.bin','rb') as readfile:
    net_info = pickle.load(readfile)

df_path = pd.read_csv('scheme1/result_00000000.csv')

for i in product(range(10), repeat=3):
    result_file_path = result_dir_path / ('result_' + ''.join([*map(str, i)]) + '.csv')
    if result_file_path.exists():
        continue

    df_path_copy = df_path.copy()
    df_path_copy['ex'] = 0
    df_path_copy.loc[df_path['v/c'] > 1.1 ,'ex'] = i[0]
    df_path_copy.loc[df_path['v/c'].between(1,1.1),'ex'] = i[1]
    df_path_copy.loc[df_path['v/c'].between(0.9,1),'ex'] = i[2]

    ex_list = df_path_copy.ex

    cost_func_list = [partial(cal_money_cost, t_a0=row['t0'], c_a=row['ca'], ex=row['ex']) for _, row in df_path_copy.iterrows()]

    model = AllNothingFrankWolfModel(net_info, list_centroid, df_demand, cost_func_list)
    model.init()
    model.update()
    convergence_count = 0
    while not model.convergence_test():
        model.update()
        convergence_count += 1
        if convergence_count >= 20:
            break

    print('{0} complete after {1} epoch'.format(''.join([*map(str, i)]), convergence_count))
    df_path_copy['volumn'] = model.x
    df_path_copy['v/c'] = model.vc_ratio(df_path_copy.ca.values)
    df_path_copy.to_csv(str(result_file_path), index=False, encoding='utf8')


#!/usr/bin/env python

import sys
import rospy
import time

from boogaloo.msg import JointCommand, PoseCommand, RobotState, MassChange

curr_state = RobotState()

def robot_state_callback(data):
    global curr_state
    curr_state = data

def pub_and_wait(pub, msg):
    global curr_state

    pub.publish(msg)

    rospy.sleep(rospy.Duration(0.5))

    while curr_state.is_at_target == False and not rospy.is_shutdown():
        rospy.sleep(rospy.Duration(0.1))

if __name__ == '__main__':
    rospy.init_node('scripted_runner')

    rospy.Subscriber("/robot_state", RobotState, robot_state_callback)
    joint_pub = rospy.Publisher('/joint_goal', JointCommand, queue_size=10)
    tip_pub = rospy.Publisher('/tip_goal', PoseCommand, queue_size=10)
    mass_pub = rospy.Publisher('/mass_updates', MassChange, queue_size=10)

    rospy.sleep(rospy.Duration(2))

    while curr_state.is_at_target == False and not rospy.is_shutdown():
        rospy.sleep(rospy.Duration(0.1))

    mass = MassChange()
    mass.mass_status = MassChange.EMPTY
    mass_pub.publish(mass)

    cmd = JointCommand()

    pub_and_wait(joint_pub, cmd)

    cmd = PoseCommand()
    cmd.pos.x = 0.63
    cmd.pos.y = 0.20
    cmd.pos.z = 0.2
    cmd.wrist_angle = 0
    cmd.wrist_roll = -2.4
    cmd.gripper = 0
    cmd.pose_follow = True

    pub_and_wait(tip_pub, cmd)

    cmd.pos.z = -0.02
    pub_and_wait(tip_pub, cmd)

    cmd.gripper = 1

    pub_and_wait(tip_pub, cmd)

    mass.mass_status = MassChange.BOTTLE_SIDE
    mass_pub.publish(mass)

    cmd.pos.z = 0.2

    pub_and_wait(tip_pub, cmd)

    cmd.wrist_roll = 0
    cmd.wrist_angle = 1.57

    pub_and_wait(tip_pub, cmd)

    cmd.pos.z = 0.05
    pub_and_wait(tip_pub, cmd)

    mass.mass_status = MassChange.EMPTY
    mass_pub.publish(mass)

    cmd.gripper = 0
    pub_and_wait(tip_pub, cmd)

    cmd.pos.x = 0.55
    cmd.pos.z = 0.20
    cmd.wrist_angle = 0
    pub_and_wait(tip_pub, cmd)

    cmd.pos.z = 0.17
    cmd.pos.x = 0.65
    cmd.pos.y = 0.22
    pub_and_wait(tip_pub, cmd)

    cmd.gripper = 1
    pub_and_wait(tip_pub, cmd)

    mass.mass_status = MassChange.BOTTLE_TOP
    mass_pub.publish(mass)

    cmd = JointCommand()
    cmd.gripper = 1
    cmd.pose_follow = True

    pub_and_wait(joint_pub, cmd)

    print('yay!')


# -*- coding:utf-8 -*-

# @version: 1.0
# @author: liujia

import time
from tencent_acg_news import tencentAcgNews
import acgnews.redis.redisutils as redisutils

def run():
    start_number=1
    page_count=2
    tencent_downloader=tencentAcgNews()
    tencentAcgNews.extractor(tencent_downloader,start_number,page_count)

if __name__ == "__main__":
    while(True):
        run()
        redisutils.mysql_news_to_redis(100)
        time.sleep(3600)


#-------------------------------------------------------------------------------
# Name:        sleuth
# Purpose:
#
# Author:      r.dean
#
# Created:     09/08/2012
# Copyright:   (c) r.dean 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
from itertools import cycle
from random import shuffle

from Player import Player
from GameBoard import GameBoard

weaponCards = [("Lead Pipe", "w"), ("Candlestick", "w"), ("Revolver", "w"), ("Rope" , "w"), ("Knife", "w"), ("Wrench", "w")]
roomCards = [("Conservatory", "r"), ("Kitchen", "r"), ("Billards Room", "r"), ("Ballroom","r"), ("Hall","r"), ("Dining Room","r"), ("Study","r"), ("Lounge", "r"), ("Library", "r")]
suspectCards = [("Mrs. White", "s"), ("Mr. Green", "s"), ("Miss Scarlet","s"), ("Professor Plum","s"), ("Colonel Mustard","s"), ("Ms. Peacock","s")]
suspects = ["Mr. Green", "Professor Plum", "Miss Scarlet"]  # DEBUG

class Sleuth(object):
    _board = GameBoard()

    def __init__(self, suspects):
        self.player_count = len(suspects)
        self.players = [Player(s) for s in suspects]
        deck = Deck()
        self.solution = deck.solution
        deck.deal(self.players)

    @classmethod
    def board(cls):
        return cls._board

class Room(object):
    def __init__(self, neighbors, room_name):
        self.name = room_name

class Card (object):
    def __init__(self, name, catagory):
        self.name = name
        self.catagory = catagory

    def __str__(self):
        return self.name

class Deck(object):
    def __init__(self):
        self.weaponCards = [Card(arg1, arg2) for arg1, arg2 in weaponCards]
        self.roomCards = [Card(arg1, arg2) for arg1, arg2 in roomCards]
        self.suspectCards = [Card(arg1, arg2) for arg1, arg2 in suspectCards]
        shuffle(self.weaponCards)
        shuffle(self.suspectCards)
        shuffle(self.roomCards)
        self.solution = self.solution()
        self.deck = self.buildDeck()

    def buildDeck(self):
        return (self.weaponCards + self.suspectCards + self.roomCards)

    def solution(self):
        return {self.weaponCards.pop(),
                self.roomCards.pop(),
                self.suspectCards.pop()}

    def deal(self, players):
        for player, card in zip(cycle(players), self.deck):
            player.addCard(card)


"""
romnum_parser.py:
Contains romnum_parser, which turns roman numerals into numeric values.
"""

NUMBER_MAP = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}

def romnum_parser(input_string):
    """
    romnum_parser():
    Accepts string and transforms characters into ints representing values.
    Iterates over number_map to force accumulation of two-character expressions
    before one-character options are considered.
    """

    running_total = 0
    last_value = None
    for character in input_string:
        if last_value is None:
            running_total += NUMBER_MAP[character]
        elif last_value < NUMBER_MAP[character]:
            running_total += NUMBER_MAP[character] - (2 * last_value)
        else:
            running_total += NUMBER_MAP[character]
        last_value = NUMBER_MAP[character]
    return running_total


from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('predict', views.predict, name="predict"),
    path('predicted', views.predicted, name="predicted"),
    path('restapi/', views.restapi, name='restapi'),

]

#  http://127.0.0.1:8000/restapi/?value1=1&value2=1&value3=1&value4=1&value5=1&value6=1&value7=1&value8=1


''' Wallpaper Downloader '''

''' Download wallpapers from wallpaper gallery sites '''

''' Allow designation of set amount of wallpapers, or pages, or all?'''

import requests, bs4, os

os.chdir('../../Desktop')
wallpaperFolder = os.makedirs('Wallpapers', exist_ok=True)

pageCount = 1
GalleryUrl = 'https://wall.alphacoders.com/search.php?search=Game+Of+Thrones&page=%s' % (pageCount)

linkList = []
# skip if not enough likes on image?
while not GalleryUrl.endswith('page=3'):
    # Download the page
    GalleryUrl = 'https://wall.alphacoders.com/search.php?search=Game+Of+Thrones&page=%s' % (pageCount)
    print('Opening gallary... %s' % (GalleryUrl))
    res = requests.get(GalleryUrl)
    res.raise_for_status()
    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    # find urls to image page
    section = soup.find_all('div', attrs={'class': 'boxgrid'})

    for images in section:
        imageLink = images.find_all('a')
        for a in imageLink:
            imageUrl = a.get('href')
            linkList.append(imageUrl)
            print('Image found at... ' + imageUrl)
    linkCount = 0
# Follow links and download images on page.
    while linkCount <= len(linkList):
        print('Downloading image at... %s' % (str(linkList[linkCount])))
        imagePageUrl = ('https://wall.alphacoders.com/' + str(linkList[linkCount]))
        res = requests.get(imagePageUrl)

        wallpaperSoup = bs4.BeautifulSoup(res.text, 'html.parser')

        link = wallpaperSoup.find(id='main_wallpaper')
        imageSrc = link['src']

        # Save image to folder

        res = requests.get(imageSrc)
        imageFile = open(os.path.join(os.getcwd(), 'Wallpapers', os.path.basename(imageSrc)), 'wb')
        for chunk in res.iter_content(12000):
            imageFile.write(chunk)
        imageFile.close()
        linkCount += 1

    # Move to next page and empty link list
    pageCount += 1
    del linkList[:]

print('Done')


from pytube import YouTube

url = "https://www.youtube.com/watch?v=EpsQx8JDIvI"
video = YouTube(url)
resol = "1080p"
file_type = "mp4"
path = 'e:/mov'

Streams = video.streams
vid = Streams.filter(progressive=True)
vid = Streams.filter(res=resol, file_extension=file_type).first()

vid.download(path)


# Filemanager

import json
import math
import datetime
from pprint import pprint

a = []

with open('ubexport.json') as data_file:
    data = json.load(data_file)

def addNameToArray (name):
    if name in a:
        return a.index(name)
    else:
        a.append(name)
        print (name , " is: " , a.index(name))
        return a.index(name)

for i in data:
	outS = ""
	d = data[i].get('date')
	addrStr = addNameToArray( data[i].get('pathname') )
	outS = str(addrStr) + "," + str(data[i].get('usesMobile')) + "," + d + ""
	#print outS


# coding: utf-8
from __future__ import unicode_literals
from functools import partial
import os
from click.testing import CliRunner
import pw, pw.cli
import xerox

DIRNAME = os.path.dirname(os.path.abspath(__file__))

def invoke_cli(*args, **kwargs):
  # determine db path
  assert not kwargs.keys() or list(kwargs.keys()) == ['db_path']
  db_path = kwargs.get('db_path', 'db.yaml')
  db_path = os.path.join(DIRNAME, db_path)

  # run CLI
  runner = CliRunner()
  os.environ['PW_GPG_HOMEDIR'] = os.path.join(DIRNAME, 'keys')
  return runner.invoke(pw.cli.pw, ['--database-path', db_path] + list(args))

def test_basic():
  expected = u"""
goggles: alice@gogglemail.com | *** PASSWORD COPIED TO CLIPBOARD *** | https://mail.goggles.com/
goggles: bob+spam@gogglemail.com
laptop: alice | default user
laptop: bob
phones.myphone
phones.samson
router: ädmin
"""
  result = invoke_cli()
  assert not result.exception and result.exit_code == 0
  assert result.output.strip() == expected.strip()

def test_version():
  result = invoke_cli('--version')
  assert not result.exception and result.exit_code == 0
  assert pw.__version__ in result.output.strip()

def test_missing():
  result = invoke_cli(db_path='MISSING')
  assert isinstance(result.exception, SystemExit) and result.exit_code != 0
  assert "not found" in result.output

def test_search():
  # search for key
  expected = """
goggles: alice@gogglemail.com | https://mail.goggles.com/
goggles: bob+spam@gogglemail.com
"""
  result = invoke_cli('--no-copy', '--no-echo', 'goggle')
  assert not result.exception and result.exit_code == 0
  assert result.output.strip() == expected.strip()

  # search for user
  expected = """
goggles: bob+spam@gogglemail.com
laptop: bob
"""
  result = invoke_cli('--no-copy', '--no-echo', 'bob@')
  assert not result.exception and result.exit_code == 0
  assert result.output.strip() == expected.strip()

  # search for both user and key
  expected = "goggles: bob+spam@gogglemail.com"
  result = invoke_cli('--no-copy', '--no-echo', 'bob@goggle')
  assert not result.exception and result.exit_code == 0
  assert result.output.strip() == expected.strip()

def test_echo_vs_copy():
  # no copy nor echo
  expected = "phones.myphone"
  xerox.copy('')
  result = invoke_cli('--no-copy', '--no-echo', 'myphone')
  assert not result.exception and result.exit_code == 0
  assert result.output.strip() == expected.strip()
  assert xerox.paste() == ''

  # only echo
  expected = "phones.myphone | 0000"
  xerox.copy('')
  result = invoke_cli('--no-copy', '--echo', 'myphone')
  assert not result.exception and result.exit_code == 0
  assert result.output.strip() == expected.strip()
  assert xerox.paste() == ''

  # only echo
  expected = "phones.myphone | *** PASSWORD COPIED TO CLIPBOARD ***"
  xerox.copy('')
  result = invoke_cli('--copy', '--no-echo', 'myphone')
  assert not result.exception and result.exit_code == 0
  assert result.output.strip() == expected.strip()
  assert xerox.paste() == '0000'

  # both copy and echo
  expected = "phones.myphone | 0000 | *** PASSWORD COPIED TO CLIPBOARD ***"
  xerox.copy('')
  result = invoke_cli('--copy', '--echo', 'myphone')
  assert not result.exception and result.exit_code == 0
  assert result.output.strip() == expected.strip()
  assert xerox.paste() == '0000'

def test_strict():
  # single result
  expected = "phones.myphone"
  result = invoke_cli('--no-copy', '--no-echo', '--strict', 'myphone')
  assert not result.exception and result.exit_code == 0
  assert result.output.strip() == expected.strip()

  # multiple results (expect failure)
  result = invoke_cli('--no-copy', '--no-echo', '--strict', 'phones')
  assert isinstance(result.exception, SystemExit) and result.exit_code != 0

def test_gpg():
  expected = "pin | *** PASSWORD COPIED TO CLIPBOARD ***"

  # ASCII armor
  result = invoke_cli(db_path='db.yaml.asc')
  assert not result.exception and result.exit_code == 0
  assert result.output.strip() == expected.strip()

  # binary
  result = invoke_cli(db_path='db.yaml.gpg')
  assert not result.exception and result.exit_code == 0
  assert result.output.strip() == expected.strip()


from abc import ABCMeta, abstractmethod
import sys
import os
import socket

class UDPClient(metaclass=ABCMeta):

	def __init__(self, UDP_IP, UDP_PORT):
		self.UDP_PORT = UDP_PORT
		self.UDP_IP = UDP_IP
		self.BUFFER_SIZE = 4096

		try:
			self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.s.settimeout(5)
		except socket.error as msg:
			print('Something went wrong in the process of socket creation')
			sys.exit(1)

	# return the reply from the server
	def sendMessage(self, message):
		message = str.encode(message)
		message += b'\n'
		print('Sent to', (self.UDP_IP, self.UDP_PORT), "is", message)
		self.s.sendto(message, (self.UDP_IP, self.UDP_PORT))

		receivedMessage = b""
		while True:
			# receive (part of) message from the socket
			i = 0
			while i < 3:
				try:
					data, addr = self.s.recvfrom(self.BUFFER_SIZE)
					i = 4
				except socket.timeout:
					i += 1
				except Exception:
					print("Cannot receive the answer")
					os._exit(1)
			if i == 3:
				print("Cannot receive the answer")

			receivedMessage += data

			# if data has \n, it means that is necessary interpret the message
			if b'\n' in data:
				print('From', addr, 'is', receivedMessage)

				print(b"received: " + receivedMessage)
				receivedMessage = receivedMessage.decode('UTF-8')
				# to verify if data received ends with \n
				dataArray = receivedMessage.split("\n")
				if len(dataArray) != 2 or dataArray[1] != '':
					self.s.sendto(b'ERR', (self.UDP_IP, self.UDP_PORT))
					return "ERR"

				# to verify if data has more than one space between words
				if "" in receivedMessage.split(" "):
					self.s.sendto(b'ERR', (self.UDP_IP, self.UDP_PORT))
					return "ERR"

				return receivedMessage


##
#  Class project 1
#
from flask import Flask, render_template
from bokeh.embed import components
from bokeh.plotting import figure
from bokeh.resources import INLINE
from bokeh.util.string import encode_utf8
import datetime
import sqlite3
from db import GREENHOUSE_DB

#  App config.
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'

@app.route("/")
def hello():
   return 'Hello'

##
#  Draw a chart using a single dataset
#
@app.route("/chart")
def chart():
   # create a chart
   plot = figure( plot_width=400, plot_height=400, x_axis_type='datetime' )
   # add a line renderer
   ## plot.line( [1,2,4,6,7,9], [2,7,4,9,7,3], line_width=2 )
   ## plot.line( [7,5,4,6,7,9], [3,7,4,8,7,8], line_width=4 )
   ## plot.line( [2,5,4,6,7,9], [3,7,4,6,7,8], line_width=4 )
   x = []
   y = []
   try:
      rows = get_data()
   except:
      return 'Unable to open db. Run db_create.sh to create it and try again.'
   ## print( 'Calling see_data 2' )
   ## see_data( rows )
   for row in rows:
      if row[1] != 0.0:
         date = datetime.datetime.fromtimestamp( row[0] )
         x.append( date )
         y.append( row[1] )
   plot.line( x,y )
   js_resources = INLINE.render_js()
   css_resources = INLINE.render_css()
   script, div = components( plot )
   return render_template(
      'chart.html',
      plot_script=script,
      plot_div=div,
      js_resources=js_resources,
      css_resources=css_resources
   )

##
#  Draw a chart using two datasets
#
@app.route("/twolines")
def twolines():
   # create a chart
   plot = figure( plot_width=1000, plot_height=700, x_axis_type='datetime' )
   unix_time_1 = []
   temperature_1 = []
   unix_time_3 = []
   temperature_3 = []
   try:
      rows = get_data()
   except:
      return 'Unable to open db. Run db_create.sh to create it and try again.'
   for row in rows:
      date = datetime.datetime.fromtimestamp( row[0] )
      if row[1] != 0.0:
         unix_time_1.append( date )
         temperature_1.append( row[1] )
      elif row[2] != 0.0:
         unix_time_3.append( date )
         temperature_3.append( row[2] )
   plot.multi_line( [unix_time_1,unix_time_3], [temperature_1,temperature_3],
        color=["firebrick", "navy"], alpha=[0.8, 0.3], line_width=1 )
   js_resources = INLINE.render_js()
   css_resources = INLINE.render_css()
   script, div = components( plot )
   return render_template(
      'chart.html',
      plot_script=script,
      plot_div=div,
      js_resources=js_resources,
      css_resources=css_resources
   )

##
#  Draw a chart using all of the datasets
#
@app.route("/all")
def all():
   # create a chart
   plot = figure( plot_width=1000, plot_height=700, x_axis_type='datetime' )
   unix_time_1 = []
   temperature_1 = []
   unix_time_3 = []
   temperature_3 = []
   unix_time_4 = []
   temperature_4 = []
   unix_time_5 = []
   temperature_5 = []
   unix_time_6 = []
   temperature_6 = []
   unix_time_7 = []
   temperature_7 = []
   unix_time_8 = []
   temperature_8 = []
   unix_time_9 = []
   temperature_9 = []
   unix_time_10 = []
   temperature_10 = []
   unix_time_11 = []
   temperature_11 = []
   unix_time_12 = []
   temperature_12 = []
   unix_time_13 = []
   temperature_13 = []
   try:
      rows = get_data()
   except:
      return 'Unable to open db. Run db_create.sh to create it and try again.'
   for row in rows:
      date = datetime.datetime.fromtimestamp( row[0] )
      if row[1] != 0.0:
         unix_time_1.append( date )
         temperature_1.append( row[1] )
      elif row[2] != 0.0:
         unix_time_3.append( date )
         temperature_3.append( row[2] )
      elif row[3] != 0.0:
         unix_time_4.append( date )
         temperature_4.append( row[2] )
      elif row[4] != 0.0:
         unix_time_5.append( date )
         temperature_5.append( row[2] )
      elif row[5] != 0.0:
         unix_time_6.append( date )
         temperature_6.append( row[2] )
      elif row[6] != 0.0:
         unix_time_7.append( date )
         temperature_7.append( row[2] )
      elif row[7] != 0.0:
         unix_time_8.append( date )
         temperature_8.append( row[2] )
      elif row[8] != 0.0:
         unix_time_9.append( date )
         temperature_9.append( row[2] )
      elif row[9] != 0.0:
         unix_time_10.append( date )
         temperature_10.append( row[2] )
      elif row[10] != 0.0:
         unix_time_11.append( date )
         temperature_11.append( row[2] )
      elif row[11] != 0.0:
         unix_time_12.append( date )
         temperature_12.append( row[2] )
      elif row[12] != 0.0:
         unix_time_13.append( date )
         temperature_13.append( row[2] )
   ## plot.multi_line( [unix_time_1,unix_time_3], [temperature_1,temperature_3],
   ##     color=["firebrick", "navy"], alpha=[0.8, 0.3], line_width=1 )
   plot.multi_line(
      [unix_time_1,unix_time_3,unix_time_4,unix_time_5,unix_time_6,unix_time_7,unix_time_8,unix_time_9,unix_time_10,unix_time_11,unix_time_12,unix_time_13],
      [temperature_1,temperature_3,temperature_4,temperature_5,temperature_6,temperature_7,temperature_8,temperature_9,temperature_10,temperature_11,temperature_12,temperature_13],
      color=[ "firebrick", "red", "yellow", "orange", "brown", "magenta", "green", "cyan", "lightskyblue", "blue", "navy", "purple"],
      alpha=[0.1, 0.2, 0.3, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.8, 0.9], line_width=1 )
   js_resources = INLINE.render_js()
   css_resources = INLINE.render_css()
   script, div = components( plot )
   return render_template(
      'chart.html',
      plot_script=script,
      plot_div=div,
      js_resources=js_resources,
      css_resources=css_resources
   )

##
#  Draw a separate chart using each of the datasets
#  First we will try it by brute force.
#  If and when that works, maybe we will get fancy
#
@app.route("/each")
def each():
   # create 12 charts
   plot1 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   plot3 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   plot4 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   plot5 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   plot6 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   plot7 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   plot8 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   plot9 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   plot10 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   plot11 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   plot12 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   plot13 = figure( plot_width=200, plot_height=150, x_axis_type='datetime' )
   unix_time_1 = []
   temperature_1 = []
   unix_time_3 = []
   temperature_3 = []
   unix_time_4 = []
   temperature_4 = []
   unix_time_5 = []
   temperature_5 = []
   unix_time_6 = []
   temperature_6 = []
   unix_time_7 = []
   temperature_7 = []
   unix_time_8 = []
   temperature_8 = []
   unix_time_9 = []
   temperature_9 = []
   unix_time_10 = []
   temperature_10 = []
   unix_time_11 = []
   temperature_11 = []
   unix_time_12 = []
   temperature_12 = []
   unix_time_13 = []
   temperature_13 = []
   try:
      rows = get_data()
   except:
      return 'Unable to open db. Run db_create.sh to create it and try again.'
   for row in rows:
      date = datetime.datetime.fromtimestamp( row[0] )
      if row[1] != 0.0:
         unix_time_1.append( date )
         temperature_1.append( row[1] )
      if row[2] != 0.0:
         unix_time_3.append( date )
         temperature_3.append( row[2] )
      if row[3] != 0.0:
         unix_time_4.append( date )
         temperature_4.append( row[2] )
      if row[4] != 0.0:
         unix_time_5.append( date )
         temperature_5.append( row[2] )
      if row[5] != 0.0:
         unix_time_6.append( date )
         temperature_6.append( row[2] )
      if row[6] != 0.0:
         unix_time_7.append( date )
         temperature_7.append( row[2] )
      if row[7] != 0.0:
         unix_time_8.append( date )
         temperature_8.append( row[2] )
      if row[8] != 0.0:
         unix_time_9.append( date )
         temperature_9.append( row[2] )
      if row[9] != 0.0:
         unix_time_10.append( date )
         temperature_10.append( row[2] )
      if row[10] != 0.0:
         unix_time_11.append( date )
         temperature_11.append( row[2] )
      if row[11] != 0.0:
         unix_time_12.append( date )
         temperature_12.append( row[2] )
      if row[12] != 0.0:
         unix_time_13.append( date )
         temperature_13.append( row[2] )
   plot1.line( unix_time_1, temperature_1 )
   plot3.line( unix_time_3, temperature_3 )
   plot4.line( unix_time_4, temperature_4 )
   plot5.line( unix_time_5, temperature_5 )
   plot6.line( unix_time_6, temperature_6 )
   plot7.line( unix_time_7, temperature_7 )
   plot8.line( unix_time_8, temperature_8 )
   plot9.line( unix_time_9, temperature_9 )
   plot10.line( unix_time_10, temperature_10 )
   plot11.line( unix_time_11, temperature_11 )
   plot12.line( unix_time_12, temperature_12 )
   plot13.line( unix_time_13, temperature_13 )
   js_resources = INLINE.render_js()
   css_resources = INLINE.render_css()
   plot_1_script, plot_1_div = components( plot1 )
   plot_3_script, plot_3_div = components( plot3 )
   plot_4_script, plot_4_div = components( plot4 )
   plot_5_script, plot_5_div = components( plot5 )
   plot_6_script, plot_6_div = components( plot6 )
   plot_7_script, plot_7_div = components( plot7 )
   plot_8_script, plot_8_div = components( plot8 )
   plot_9_script, plot_9_div = components( plot9 )
   plot_10_script, plot_10_div = components( plot10 )
   plot_11_script, plot_11_div = components( plot11 )
   plot_12_script, plot_12_div = components( plot12 )
   plot_13_script, plot_13_div = components( plot13 )
   return render_template(
      'each.html',
      plot_1_script=plot_1_script,
      plot_3_script=plot_3_script,
      plot_4_script=plot_4_script,
      plot_5_script=plot_5_script,
      plot_6_script=plot_6_script,
      plot_7_script=plot_7_script,
      plot_8_script=plot_8_script,
      plot_9_script=plot_9_script,
      plot_10_script=plot_10_script,
      plot_11_script=plot_11_script,
      plot_12_script=plot_12_script,
      plot_13_script=plot_13_script,
      plot_1_div=plot_1_div,
      plot_3_div=plot_3_div,
      plot_4_div=plot_4_div,
      plot_5_div=plot_5_div,
      plot_6_div=plot_6_div,
      plot_7_div=plot_7_div,
      plot_8_div=plot_8_div,
      plot_9_div=plot_9_div,
      plot_10_div=plot_10_div,
      plot_11_div=plot_11_div,
      plot_12_div=plot_12_div,
      plot_13_div=plot_13_div,
      js_resources=js_resources,
      css_resources=css_resources
   )

##
#  Get all the data
#
def get_data():
   rows = []
   with sqlite3.connect( GREENHOUSE_DB ) as connection:
      curs = connection.cursor()
      curs.execute( 'SELECT * from greenhouse')
      rows = curs.fetchall()
      ## print( 'Calling see_data 1' )
      ## see_data( rows )
   return rows

##
#  Print out the rows retrieved
#
def see_data( rows ):
   for row in rows:
      print( "row:", row )

##
#  Run the app!
#
if __name__ == "__main__":
    app.run()


#!/usr/bin/env python

from __future__ import print_function

import sys, os, re
import argparse
import tempfile
import time
import shlex
import subprocess as sp

"""
Wrapper to call the ancil_top program with certain options and environment
variables. Some explanation here:

https://trac.nci.org.au/trac/access/wiki/LandMask

Used to regenerate some UM ancils based on a new land mask.
"""

class AncilTop:

    def __init__(self, output, mask):
        self.output = output
        self.mask = mask

        ancil_top = self.temp_check_ancil_top()
        self.ancil_top_cmd = '{} -model n96 -mask {} -queue express -time 10800 -memory 16 -search 200 -search_row 20 -search_col 20'.format(ancil_top, mask)

    def temp_check_ancil_top(self):
        """
        Use a local copy of ancil_top for now.
        """

        # Call this to check that the module is loaded.
        ancil_top = self.check_ancil_top()

        my_path = os.path.dirname(os.path.realpath(__file__))

        return os.path.join(my_path, 'contrib', 'ancil_top')

    def check_ancil_top(self):
        """
        Find the path to the ancil_top.
        """

        path = None
        try:
            path = sp.check_output(['which', 'ancil_top'])
            path = path.strip()
        except sp.CalledProcessError:
            print('Error: ancil_top not found, try: module load cap',
                  file=sys.stderr)
            raise

        return path

    def wait(self, run_ids):
        """
        Wait for some qsub id's to complete.
        """

        while True:
            time.sleep(10)
            print('.', end='')
            sys.stdout.flush()

            for id in run_ids:
                qsub_out = ''
                try:
                    qsub_out = sp.check_output(['qstat', id],
                                               stderr=sp.STDOUT)
                except sp.CalledProcessError as err:
                    qsub_out = err.output

                if 'Job has finished' in qsub_out:
                    run_ids.remove(id)
                    break

            if run_ids == []:
                break

    def find_qsub_id(self, str):

        m = re.search(r'^\d{7}\.r-man2$', str, re.MULTILINE)
        assert(m is not None)

        return m.group()

    def make_orog(self):
        """
        Make orogrophy files.
        """

        # Set up output directory.
        output_dir = tempfile.mkdtemp(dir=self.output)
        cmd = '{} -output {}'.format(self.ancil_top_cmd, output_dir)
        print('Executing {}'.format(cmd))

        os.environ['WORKDIR'] = output_dir
        os.environ['DATASETS'] = 'orog'
        out = sp.check_output(shlex.split(cmd))
        qsub_id = self.find_qsub_id(out)

        output_files = []
        artifacts = ['qrparm.veg.frac', 'qrparm.veg.func', 'qrparm.veg.dist',
                     'qrparm.soil.dust', 'qrparm.soil']
        for f in artifacts:
            output_files.append(os.path.join(output_dir, f))

        return qsub_id, output_dir, output_files

    def make_vegfrac(self):

        output_dir = tempfile.mkdtemp(dir=self.output)
        cmd = '{} -output {}'.format(self.ancil_top_cmd, output_dir)
        print('Executing {}'.format(cmd))

        os.environ['WORKDIR'] = output_dir
        os.environ['DATASETS'] = 'vegfrac'
        os.environ['VEGFOPTS'] = '-g4 -s -t0.4 -h -rdefault -qmodis -3 -x -A1 -B1 -CIGBP -DCH'
        out = sp.check_output(shlex.split(cmd))
        qsub_id = self.find_qsub_id(out)

        output_files = []
        for f in ['qrparm.orog']:
            output_files.append(os.path.join(output_dir, f))

        return qsub_id, output_dir, output_files

    def make_ancils(self, debug=False):

        orog_run_id, orog_output_dir, orog_output_files = self.make_orog()
        veg_run_id, veg_output_dir, veg_output_files = self.make_vegfrac()

        self.wait([orog_run_id, veg_run_id])

        # Copy output files input place and delete run directories
        for f in orog_output_files + veg_output_files:
            assert(os.path.exists(f))
            shutil.copy(f, self.output)

        if not debug:
            os.rmtree(orog_output_dir)
            os.rmtree(veg_output_dir)

        return 0

def main():

    parser = argparse.ArgumentParser()

    parser.add_argument("--output",
                        help="The output directory.")
    parser.add_argument("--mask",
                        help="The land fraction file in UM format.")
    parser.add_argument("--debug", default=False, action='store_true',
                        help="Leave temporary files lying around for debugging.")

    args = parser.parse_args()

    # Set up some more complex defaults.
    if args.output is None:
        my_path = os.path.dirname(os.path.realpath(__file__))
        args.output = os.path.join(my_path, 'outputs')

    if args.mask is None:
        args.mask = os.path.join(args.output, 'qrparm.mask')

    ancil = AncilTop(args.output, args.mask)
    ret = ancil.make_ancils(args.debug)

    # Check that expected files exist.

    return ret

if __name__ == "__main__":
    sys.exit(main())


from setuptools import setup, find_packages, Extension

setup(name='bbo_benchmarks',
      version='1.0',
      description='Black-Box Optimization Benchmarks',
      author='Computational Intelligence Laboratory, Peking University',
      author_email='liyfieng0039@gmail.com',
      license='Apache 2.0',
      packages=['bbo_benchmarks', 'bbo_benchmarks/cec2013', 'bbo_benchmarks/cec2017'],
      #packages=find_packages(),
      ext_modules = [Extension('_cec13',
                               sources=['bbo_benchmarks/cec2013/cec13.i', 'bbo_benchmarks/cec2013/cec13.c'],
                               swig_opts=['-modern', '-I../include']),
                     Extension('_cec17',
                                sources=['bbo_benchmarks/cec2017/cec17.i', 'bbo_benchmarks/cec2017/cec17.c'],
                                swig_opts=['-modern', '-I../include'])],
     )

import zipfile, os

input_data_13_dir = 'bbo_benchmarks/cec2013/input_data.zip'
input_data_17_dir = 'bbo_benchmarks/cec2017/input_data.zip'

data_dir = os.path.expanduser('~/.bbo_benchmark')
if not os.path.exists(data_dir):
    print('creating dir ~/.bbo_benchmark')
    os.makedirs(data_dir)
else:
    print('~/.bbo_benchmark already exists')

if not os.path.exists(os.path.join(data_dir, 'cec2013')):
    print('extracting cec2013 input data')
    with zipfile.ZipFile(input_data_13_dir) as zf:
        os.makedirs('cec2013')
        zf.extractall(os.path.join(data_dir, 'cec2013'))

if not os.path.exists(os.path.join(data_dir, 'cec2017')):
    print('extracting cec2013 input data')
    with zipfile.ZipFile(input_data_17_dir) as zf:
        os.makedirs('cec2017')
        zf.extractall(os.path.join(data_dir, 'cec2017'))


def swap(a,b, arr):
    #arr[a], arr[b] = arr[b],arr[a]
    if a!=b:
        temp = arr[a]
        arr[a] = arr[b]
        arr[b] = temp

def partition(elements, start, end):
    pivot_index = start
    pivot = elements[pivot_index]

    while start < end:
        while start < len(elements) and elements[start] <= pivot:
            start += 1

        while elements[end] > pivot:
            end -= 1

        #swap them
        if start < end:
            swap(start, end, elements)

    swap(pivot_index, end, elements)

    return end

def quick_sort(elements, start, end):
    if start < end:
        partition_index = partition(elements, start, end)
        quick_sort(elements, start, partition_index-1) #left partition
        quick_sort(elements, partition_index+1, end) #right partition

if __name__ == '__main__':
    elements = [11, 9, 29, 7 , 2, 15, 28]
    quick_sort(elements, 0, len(elements)-1)
    print(elements)


#coding=utf-8
import cv2
import numpy as np
import  os

'''
for each vedio in vedios
    分解视频成图像
'''

def mkdir(path):
    folder = os.path.exists(path)
    if not folder:                   #判断是否存在文件夹如果不存在则创建为文件夹
        os.makedirs(path)

SourceImgPath = "/data/qg_data/video/data1-data2-clipped"  # 视频读取路径
vedionamelist = os.listdir(SourceImgPath)  # 获得所有视频名字列表

ImgWritePath = "/data/qg_data/host_img"  # 图像保存路径
img_end = ".jpg"
img_start = 0

mkdir(ImgWritePath)
print(vedionamelist)

print("From: \n {} \n to: \n {}".format(SourceImgPath,ImgWritePath))

for vedio_path in vedionamelist:
    VedioPath = os.path.join(SourceImgPath, vedio_path) # 获得文件夹下所有文件的路径   读取路径和保存路径
    cap = cv2.VideoCapture(VedioPath)
    while cap.read():
        # get a frame
        ret, frame = cap.read()
        if ret == False:
            print("{} is finished!".format(vedio_path))
            break #读到文件末尾

        # 显示第几帧
        frames_num = cap.get(cv2.CAP_PROP_POS_FRAMES)
        # 显示实时帧数
        FPS = cap.get(cv2.CAP_PROP_FPS)
        # 总帧数
        total_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)
        # show information of frame
        # cv2.putText(frame, "FPS:"+str(FPS), (17, 13), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255))
        # cv2.putText(frame, "NUM OF FRAME:"+str(frames_num), (222, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255))
        # cv2.putText(frame, "TOTAL FRAME:" + str(total_frame), (504, 17), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255))
        # show a frame
        #cv2.imshow("capture", frame)
        # img name
        img_name = str(img_start) + img_end
        img_start = img_start + 1
        # 存储
        if frames_num % 24 == 0:
            cv2.imwrite(os.path.join(ImgWritePath,img_name), frame)
            print("writing {}'s frame {} to {}".format(vedio_path,frames_num,img_name))

        # if cv2.waitKey(1) & 0xFF == ord('q'):
        #     break

    cap.release()
    cv2.destroyAllWindows()


from functools import reduce

def main():
    # 切り捨て
    # 4 // 3
    # 切り上げ
    #-(-4 // 3)

    # 初期値用:十分大きい数(100億)
    # 1e10

    # 初期値用:十分小さい数(-100億)
    # -1e10

    # 1文字のみを読み込み
    # 入力:2
    # a = input().rstrip()
    # 変数:a='2'

    # スペース区切りで標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a, b, c, d = (int(_) for _ in input().split())
    # 変数:a=2 b=4 c=5 d =7

    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a = list(int(_) for _ in input().split())
    # 変数:a = [2, 4, 5, 7]

    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2457
    # a = list(int(_) for _ in input())
    # 変数:a = [2, 4, 5, 7]
    T = [
        ['d','r','e','a','m'],
        ['d','r','e','a','m','e','r'],
        ['e','r','a','s','e'],
        ['e','r','a','s','e','r']
    ]
    # S = list(_ for _ in input())
    S = input()
    S = S[::-1]
    # S.reverse()
    # S.sort(reversed=True)

    for i in range(4):
        T[i].reverse()
    while len(S)>0:
        if(''.join(S[0:len(T[0])]) == ''.join(T[0])):
            S = S[len(T[0]):]
            # for i in range(len(T[0])):
            #     S.pop(0)
        elif(''.join(S[0:len(T[1])]) == ''.join(T[1])):
            S = S[len(T[1]):]
            # for i in range(len(T[1])):
            #     S.pop(0)
        elif(''.join(S[0:len(T[2])]) == ''.join(T[2])):
            S = S[len(T[2]):]
            # for i in range(len(T[2])):
            #     S.pop(0)
        elif(''.join(S[0:len(T[3])]) == ''.join(T[3])):
            S = S[len(T[3]):]
            # for i in range(len(T[3])):
            #     S.pop(0)
        else:
            print('NO')
            break

    if(len(S) ==0):
        print('YES')

if __name__ == '__main__':
    main()


# coding=utf-8
from math import *

# def dist(start, end, status):
#     """
#     计算机器人到规划路径之间的距离
#     :param start: 路径起始点坐标[x,y]
#     :param end: 路径终点坐标[x,y]
#     :param status: 机器人目前的状态[x,y,ori,vt,vn]
#     :return:
#     """
#     [x1, x2, y1, y2] = [start[0], end[0], start[1], end[1]]
#     if start[1] - end[1] == 0:  # 两点连线水平
#         d = status[0] - start[0]
#         return d
#     else:
#         # 将直线写作ax+by+c=0的形式
#         a = 1
#         b = (x2 - x1) / (y1 - y2)
#         c = (x1 * y2 - x2 * y1) / (y1 - y2)
#         d = abs(a * status[0] + b * status[1] + c) / sqrt(a ** 2 + b ** 2)
#         return d

# def rotate(end, status):
#     """
#     将机器人转动到期望方向
#     :param end: 终点坐标[x,y]
#     :param status: 机器人目前的状态[x,y,ori,vt,w]
#     :return: 机器人的速度[v,w]
#     """
#     w = pi / 3  # 机器人的转动速度
#     angle = atan2(end[1] - status[1], end[0] - status[0])  # 起点位置到终点位置的全局夹角[-pi,pi]
#     robot_angle = status[2]
#     angle_thres = 5 * pi / 180  # 5度作为阈值
#     if abs(robot_angle - angle) > angle_thres:
#     return [0, w]
#     else:
#         return [0, 0]

# def control(start, end, status, end_thres):
#     w = pi / 6  # 机器人的转动速度
#     u = 1  # 机器人的直行速度
#     angle = atan2(end[1] - status[1], end[0] - status[0])  # 机器人位置到终点位置的全局夹角[-pi,pi]
#     robot_angle = status[2]
#     angle_thres = 5 * pi / 180  # 5度作为阈值
#     d_thres = 0.1  # 0.2作为偏离直线的阈值
#     angle_delta = angle - robot_angle
#     print(angle_delta * 180 / pi)
#     if sqrt((start[0] - status[0]) ** 2 + (start[1] - status[1]) ** 2) < end_thres and abs(
#             angle_delta) > angle_thres:  # 在初始节点的位置，需要先调节方向
#         if angle_delta > 0:
#             v = [u, w]
#         else:
#             v = [u, -w]
#         return v
#     d = dist(start, end, status)
#     if d > d_thres and abs(angle_delta) > angle_thres:  # 当偏离规划直线较远时
#         if angle_delta > 0:
#             v = [u, w]
#         else:
#             v = [u, -w]
#         return v
#     else:
#         v = [u, 0]
#         return v

def control(end, status):
    if end[2] == 2:
        u = 1  # 机器人钝角减速
    if end[2] == 1:
        u = 2  # 机器人锐角减速
    else:
        u = 2.3  # 机器人直行全速
    angle = atan2(end[1] - status[1], end[0] - status[0])  # 机器人位置到终点位置的全局夹角[-pi,pi]
    robot_angle = status[2]
    angle_delta = angle - robot_angle
    print(angle_delta * 180 / pi)
    vt = u * cos(angle_delta)
    vn = u * sin(angle_delta)
    v = [vt, vn]
    return v


import socket

s = socket.socket()

# Hostname is a label assigned to a device connected to a network
host = socket.gethostname()

# Port identifies a specific process
port = 12345
s.bind((host, port))

s.listen(5)
while True:
    c, addr = s.accept()
    print('Got connection from', addr)
    c.send('Thank you fro connecting'.encode())
    c.close()


def conv2d(input, num_filters, name=None, filter_size=[1, 1], act=None, groups=None, stride=[1, 1], padding=None, bias_attr=None, param_attr=None, main_program=None, startup_program=None):
    '\n    This function creates the op for a 2-dimensional Convolution.\n    This is performed using the parameters of filters(size, dimensionality etc)\n    , stride and other configurations for a Convolution operation.\n    This funciton can also append an activation on top of the\n    conv-2d output, if mentioned in the input parameters.\n    '
    helper = LayerHelper('conv2d', **locals())
    dtype = helper.input_dtype()
    num_channels = input.shape[1]
    if (groups is None):
        num_filter_channels = num_channels
    else:
        if ((num_channels % groups) is not 0):
            raise ValueError('num_channels must be divisible by groups.')
        num_filter_channels = (num_channels / groups)
    if isinstance(filter_size, int):
        filter_size = [filter_size, filter_size]
    if isinstance(stride, int):
        stride = [stride, stride]
    if isinstance(padding, int):
        padding = [padding, padding]
    input_shape = input.shape
    filter_shape = ([num_filters, num_filter_channels] + filter_size)
    std = ((2.0 / ((filter_size[0] ** 2) * num_channels)) ** 0.5)
    filter = helper.create_parameter(attr=helper.param_attr, shape=filter_shape, dtype=dtype, initializer=NormalInitializer(0.0, std, 0))
    pre_bias = helper.create_tmp_variable(dtype)
    helper.append_op(type='conv2d', inputs={
        'Input': input,
        'Filter': filter,
    }, outputs={
        'Output': pre_bias,
    }, attrs={
        'strides': stride,
        'paddings': padding,
        'groups': groups,
    })
    pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2)
    return helper.append_activation(pre_act)


import lyricsgenius
import pymysql;
import pandas as pd;
import DbFunctions as db
import matplotlib.pyplot as plt

def getProfaneWords():
    stopwordsFile = "C:\\Users\\cressm\\Desktop\\TCSS 554\\profanity.txt"
    stopwords = []
    with open(stopwordsFile, "r") as f:
       for line in f:
         stopwords.extend(line.split())
    return stopwords

connection = db.GetCloudConnection()
repIndex = db.GetRepIndexGroupedByYearToken(connection)

metric = []
profaneWords = getProfaneWords()
for index, row in repIndex.iterrows():
    #if index < 1000:
        for word in profaneWords:
            if row[1] == word:
                metric.append([row[0],row[2]])
    #else:
    #    break

metric2 = []
yearTotals = repIndex.groupby('Year').agg({'Count': ['sum']}).reset_index()
metricDf = pd.DataFrame(data=metric, columns=['Year','Count'])
for index, row in metricDf.iterrows():
    total = yearTotals[yearTotals['Year'] == row['Year']]
    total = total['Count'].to_numpy().ravel()
    metric2.append([row[0], row[1]/total[0]])

metricDf = pd.DataFrame(data=metric2, columns=['Year','Count'])
gr = metricDf.groupby('Year').agg({'Count': ['mean']}).reset_index()

x = gr[['Year']].to_numpy().ravel()
y = gr[['Count']].to_numpy().ravel()

colors = (0,0,0)
plt.plot(x, y)
plt.title('Scatter plot pythonspot.com')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('foo2.png')
plt.show()
y = 0


from django.urls import path
from projectapp import views
from .views import Register

urlpatterns = [
    # path('index/',views.home, name='index'),
    path('',views.home, name='home'),
    path('index/',views.index),
    path('login/',views.login,name='login'),
    path('register/',Register.as_view(), name='register'),
    path('logout/',views.logout,name='logout'),
    path('account-verify/<slug:token>',views.account_verify, name='account-verify'),
    path('shopdetail',views.shop,name='shopdetail'),
    path('location',views.location,name='location'),
    path('cart',views.cart,name='cart'),

]


import csv

def write_to_file(filename, data):
    with open(filename, "w") as f:
        for text in data:
            f.write("%s\n" % text)

def write_to_csv(filename, data, authors, works):
    with open(filename, 'a') as f:
        csv_writer = csv.writer(f, delimiter='\t')
        for text, author, work in zip(data, authors, works):
            csv_writer.writerow([text, author, work])

def write_spurious_to_csv(filename, data, works):
    with open(filename, 'a') as f:
        csv_writer = csv.writer(f, delimiter='\t')
        for text, work in zip(data, works):
            csv_writer.writerow([text, work])


class Ticket:
    def __init__(self, source, destination):
        self.source = source
        self.destination = destination

def reconstruct_trip(tickets, length):
    """
    YOUR CODE HERE
    """
    # Setup
    route = [None] * length
    cache = {}

    # For all of the tickets we have...
    for ticket in tickets:
        # Set the ticket source in our cache to be our destination
        cache[ticket.source] = ticket.destination

    # Because our final destination must be "NONE"
    next = cache['NONE']

    # Iterate through, adding stop.
    for current in range(length):
        route[current] = next
        next = cache[next]
    return route  # Return our route


"""
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

OJ's undirected graph serialization:
Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:

       1
      / \
     /   \
    0 --- 2
         / \
         \_/
"""

# Definition for an undirected graph node
class UndirectedGraphNode:
    def __init__(self, x):
        self.label = x
        self.neighbors = []

class Solution1:
    def cloneGraph(self, node):
        """
        :param node: an undirected graph node
        :return: an undirected graph node
        """
        def cloneGraph(node, dic):
            if node.label in dic: return dic[node.label]

            cloned = UndirectedGraphNode(node.label)
            dic[node.label] = cloned
            for neighbor in node.neighbors:
                cloned.neighbors.append(cloneGraph(neighbor, dic))
            return cloned

        if not node: return None
        return cloneGraph(node, {})

class Solution2:
    def cloneGraph(self, node):
        """
        :param node: an undirected graph node
        :return: an undirected graph node
        """
        if not node: return None

        stack = [node]
        first = UndirectedGraphNode(node.label)
        dic = {node.label: first}
        while stack:
            curr = stack.pop()
            cloned = dic[curr.label]
            for neighbor in curr.neighbors:
                if neighbor.label not in dic:
                    dic[neighbor.label] = UndirectedGraphNode(neighbor.label)
                    stack.append(neighbor)
                cloned.neighbors.append(dic[neighbor.label])
        return first

import collections

class Solution3:
    def cloneGraph(self, node):
        """
        :param node: an undirected graph node
        :return: an undirected graph node
        """
        if not node: return None

        q = collections.deque([node])
        first = UndirectedGraphNode(node.label)
        dic = {node.label: first}
        while q:
            curr = q.popleft()
            cloned = dic[curr.label]
            for neighbor in curr.neighbors:
                if neighbor.label not in dic:
                    dic[neighbor.label] = UndirectedGraphNode(neighbor.label)
                    q.append(neighbor)
                cloned.neighbors.append(dic[neighbor.label])
        return first


from __future__ import print_function
from flask import Flask, abort, render_template
from flask import url_for, redirect, request, make_response, session, send_from_directory
import os
import functions
dBase32 = '0123456789ABCDEFGHJKLMNPRSTUVWXY'

app = Flask(__name__, static_url_path='/static')

app.secret_key = "not a secret key"

@app.route('/')
def index():
    return render_template('index.html', name = "index")

@app.route('/submit', methods = ['POST'])
def submit_offer():
    #functions.insertOrUpdate(location, price, 1, time)
    phone_num = request.form.get('telNo')
    dining_hall = request.form.get('location')
    time_slot = request.form.get('time_slot')
    price = request.form.get('price')
    print (dining_hall)
    print(price)
    print(time_slot)
    functions.insertOrUpdate(dining_hall, price, 1, time_slot, time_slot)
    return redirect(url_for('index'))
@app.route('/search', methods = ['GET', 'POST'])
def find_offers():
    return render_template('search.html', name = "search")

@app.route('/get_offers', methods = ['GET', 'POST'])
def get_offers():
    dining_hall = request.form.get('requested_location')
    time_slot = request.form.get('requested_time_slot')
    price = request.form.get('requested_price')
    print(dining_hall)
    print(price)
    print(time_slot)
    match = functions.queryByAttributes(dining_hall, price, time_slot, 1)
    info = ""
    print (match)
    if(match):
        for i in match:
            info+=(i+'\n')
    else:
        print("There is no matching database")
        info = "No Matching Database Entry"""
    filtered_info = ""
    for i in range(len(info)):
        if not info[i].isdigit():
            filtered_info += info[i]
    return redirect(url_for('search', info = info))

@app.route('/select_offer', methods = ['GET', 'POST'])
def select_offers():
    selection = request.form.get('selection')
    return redirect(url_for('search', selection = selection))

if __name__ == '__main__':
    app.run()


import matplotlib.pyplot as plt

f = open("../data/electric/energyVaryingTimeStep.txt")
lines = f.readlines()
lines = list(filter(lambda x: x.strip() != '', lines))

dts = []
times = []
energies = []

for i in range(int(len(lines)/2)):
    dt = float(lines[2*i].strip())
    dts.append(dt)
    e = list(map(float,lines[2*i + 1].strip().split(" ")))
    energies.append(e)
    aux_times = []
    for i in range(len(e)):
        aux_times.append(i * dt)
    times.append(aux_times)
    plt.plot(aux_times,e,label=dt)

ax = plt.gca()
ax.figure.set_size_inches(16,12)
ax.set_yscale('log')
ax.set_xlabel("Tiempo (s)",fontsize=15)
ax.set_ylabel("Variación de energía mecánica (J)",fontsize=15)
ax.legend(fontsize=12)

plt.show()
f.close()