"""
ZeroMQ connection.
"""
from collections import deque, namedtuple

from zmq import constants, error
from zmq import Socket

from zope.interface import implements

from twisted.internet import reactor
from twisted.internet.interfaces import IFileDescriptor, IReadDescriptor
from twisted.python import log

from zmq import zmq_version_info
ZMQ3 = zmq_version_info()[0] >= 3

class ZmqEndpointType(object):
    """
    Endpoint could be "bound" or "connected".
    """
    bind = "bind"
    connect = "connect"

ZmqEndpoint = namedtuple('ZmqEndpoint', ['type', 'address'])

class ZmqConnection(object):
    """
    Connection through ZeroMQ, wraps up ZeroMQ socket.

    @cvar socketType: socket type, from ZeroMQ
    @cvar allowLoopbackMulticast: is loopback multicast allowed?
    @type allowLoopbackMulticast: C{boolean}
    @cvar multicastRate: maximum allowed multicast rate, kbps
    @type multicastRate: C{int}
    @cvar highWaterMark: hard limit on the maximum number of outstanding
        messages 0MQ shall queue in memory for any single peer
    @type highWaterMark: C{int}

    @ivar factory: ZeroMQ Twisted factory reference
    @type factory: L{ZmqFactory}
    @ivar socket: ZeroMQ Socket
    @type socket: L{Socket}
    @ivar endpoints: ZeroMQ addresses for connect/bind
    @type endpoints: C{list} of L{ZmqEndpoint}
    @ivar fd: file descriptor of zmq mailbox
    @type fd: C{int}
    @ivar queue: output message queue
    @type queue: C{deque}
    """
    implements(IReadDescriptor, IFileDescriptor)

    socketType = None
    allowLoopbackMulticast = False
    multicastRate = 100
    highWaterMark = 0

    # Only supported by zeromq3 and pyzmq>=2.2.0.1
    tcpKeepalive = 0
    tcpKeepaliveCount = 0
    tcpKeepaliveIdle = 0
    tcpKeepaliveInterval = 0

    def __init__(self, factory, endpoint=None, identity=None):
        """
        Constructor.

        One endpoint is passed to the constructor, more could be added
        via call to C{addEndpoints}.

        @param factory: ZeroMQ Twisted factory
        @type factory: L{ZmqFactory}
        @param endpoint: ZeroMQ address for connect/bind
        @type endpoint: C{list} of L{ZmqEndpoint}
        @param identity: socket identity (ZeroMQ)
        @type identity: C{str}
        """
        self.factory = factory
        self.endpoints = []
        self.identity = identity
        self.socket = Socket(factory.context, self.socketType)
        self.queue = deque()
        self.recv_parts = []
        self.read_scheduled = None

        self.fd = self.socket_get(constants.FD)
        self.socket_set(constants.LINGER, factory.lingerPeriod)

        if not ZMQ3:
            self.socket_set(
                constants.MCAST_LOOP, int(self.allowLoopbackMulticast))

        self.socket_set(constants.RATE, self.multicastRate)

        if not ZMQ3:
            self.socket_set(constants.HWM, self.highWaterMark)
        else:
            self.socket_set(constants.SNDHWM, self.highWaterMark)
            self.socket_set(constants.RCVHWM, self.highWaterMark)

        if ZMQ3 and self.tcpKeepalive:
            self.socket_set(
                constants.TCP_KEEPALIVE, self.tcpKeepalive)
            self.socket_set(
                constants.TCP_KEEPALIVE_CNT, self.tcpKeepaliveCount)
            self.socket_set(
                constants.TCP_KEEPALIVE_IDLE, self.tcpKeepaliveIdle)
            self.socket_set(
                constants.TCP_KEEPALIVE_INTVL, self.tcpKeepaliveInterval)

        if self.identity is not None:
            self.socket_set(constants.IDENTITY, self.identity)

        if endpoint:
            self.addEndpoints([endpoint])

        self.factory.connections.add(self)

        self.factory.reactor.addReader(self)
        self.doRead()

    def addEndpoints(self, endpoints):
        """
        Add more connection endpoints. Connection may have
        many endpoints, mixing protocols and types.

        @param endpoints: list of endpoints to add
        @type endpoints: C{list}
        """
        self.endpoints.extend(endpoints)
        self._connectOrBind(endpoints)

    def shutdown(self):
        """
        Shutdown connection and socket.
        """
        self.factory.reactor.removeReader(self)

        self.factory.connections.discard(self)

        self.socket.close()
        self.socket = None

        self.factory = None

        if self.read_scheduled is not None:
            self.read_scheduled.cancel()
            self.read_scheduled = None

    def __repr__(self):
        return "%s(%r, %r)" % (
            self.__class__.__name__, self.factory, self.endpoints)

    def fileno(self):
        """
        Part of L{IFileDescriptor}.

        @return: The platform-specified representation of a file descriptor
                 number.
        """
        return self.fd

    def connectionLost(self, reason):
        """
        Called when the connection was lost.

        Part of L{IFileDescriptor}.

        This is called when the connection on a selectable object has been
        lost.  It will be called whether the connection was closed explicitly,
        an exception occurred in an event handler, or the other end of the
        connection closed it first.

        @param reason: A failure instance indicating the reason why the
                       connection was lost.  L{error.ConnectionLost} and
                       L{error.ConnectionDone} are of special note, but the
                       failure may be of other classes as well.
        """
        if self.factory:
            self.factory.reactor.removeReader(self)

    def _readMultipart(self):
        """
        Read multipart in non-blocking manner, returns with ready message
        or raising exception (in case of no more messages available).
        """
        while True:
            self.recv_parts.append(self.socket.recv(constants.NOBLOCK))
            if not self.socket_get(constants.RCVMORE):
                result, self.recv_parts = self.recv_parts, []

                return result

    def doRead(self):
        """
        Some data is available for reading on your descriptor.

        ZeroMQ is signalling that we should process some events,
        we're starting to to receive incoming messages.

        Part of L{IReadDescriptor}.
        """
        if self.read_scheduled is not None:
            if not self.read_scheduled.called:
                self.read_scheduled.cancel()
            self.read_scheduled = None

        while True:
            if self.factory is None:  # disconnected
                return

            events = self.socket_get(constants.EVENTS)

            if (events & constants.POLLIN) != constants.POLLIN:
                return

            try:
                message = self._readMultipart()
            except error.ZMQError as e:
                if e.errno == constants.EAGAIN:
                    continue

                raise e

            log.callWithLogger(self, self.messageReceived, message)

    def logPrefix(self):
        """
        Part of L{ILoggingContext}.

        @return: Prefix used during log formatting to indicate context.
        @rtype: C{str}
        """
        return 'ZMQ'

    def send(self, message):
        """
        Send message via ZeroMQ.

        Sending is performed directly to ZeroMQ without queueing. If HWM is
        reached on ZeroMQ side, sending operation is aborted with exception
        from ZeroMQ (EAGAIN).

        @param message: message data
        @type message: message could be either list of parts or single
            part (str)
        """
        if not hasattr(message, '__iter__'):
            self.socket.send(message, constants.NOBLOCK)
        else:
            for m in message[:-1]:
                self.socket.send(m, constants.NOBLOCK | constants.SNDMORE)
            self.socket.send(message[-1], constants.NOBLOCK)

        if self.read_scheduled is None:
            self.read_scheduled = reactor.callLater(0, self.doRead)

    def messageReceived(self, message):
        """
        Called on incoming message from ZeroMQ.

        @param message: message data
        """
        raise NotImplementedError(self)

    def _connectOrBind(self, endpoints):
        """
        Connect and/or bind socket to endpoints.
        """
        for endpoint in endpoints:
            if endpoint.type == ZmqEndpointType.connect:
                self.socket.connect(endpoint.address)
            elif endpoint.type == ZmqEndpointType.bind:
                self.socket.bind(endpoint.address)
            else:
                assert False, "Unknown endpoint type %r" % endpoint

    # Compatibility shims
    def socket_get(self, constant):
        return self.socket.get(constant)

    def socket_set(self, constant, value):
        return self.socket.set(constant, value)


from enum import Enum
import can

class Pid(Enum):
    def __get__(self, instance, owner):
        return self.value

    SEND_OBD = 0x7DF
    RECEIVE_OBD = 0x7E8
    """PIDS"""
    RPM = 0x0C
    SPEED = 0x0D

class Can_ids(Enum):
    def __get__(self, instance, owner):
        return self.value

    WINDOWS = 0x0FA
    PDC = 0x24a

class MessageBuilder():
    canbus = None

    def __init__(self, canbus: can.Bus):
        self.canbus = canbus

    def control_windows(self, front, up):
        msg = None
        if front:
            if up:
                msg = can.Message(arbitration_id=Can_ids.WINDOWS,
                                  data=[193, 0x0, 0xff],
                                  is_extended_id=False)
            else:
                msg = can.Message(arbitration_id=Can_ids.WINDOWS,
                                  data=[hex(195), 0x0, 0xff],
                                  is_extended_id=False)
        else:
            if up:
                msg = can.Message(arbitration_id=Can_ids.WINDOWS,
                                  data=[hex(193), 0x0, 0xff],
                                  is_extended_id=False)
            else:
                msg = can.Message(arbitration_id=Can_ids.WINDOWS,
                                  data=[hex(195), 0x0, 0xff],
                                  is_extended_id=False)
        self.canbus.send(msg)


import gdal
import csv
from osgeo import ogr, osr
import numpy as np

def reproject(x, y):
    source = osr.SpatialReference()
    source.ImportFromEPSG(28992)
    target = osr.SpatialReference()
    target.ImportFromEPSG(4326)
    text = "POINT({0} {1})".format(x, y)
    point = ogr.CreateGeometryFromWkt(text)
    transform = osr.CoordinateTransformation(source, target)
    point.Transform(transform)
    return [point.GetX(), point.GetY()]

def extractSingleData(tif, x, y, numband):
    geotransform = tif.GetGeoTransform()
    originX = geotransform[0]
    originY = geotransform[3]
    pixel_width = geotransform[1]
    pixel_height = geotransform[5]

    xoffset = int(np.divide(x - originX, pixel_width))
    yoffset = int(np.divide(y - originY, pixel_height))

    band = tif.GetRasterBand(numband)
    data = band.ReadAsArray(xoffset, yoffset, 1, 1)

    if data == None:
        return -99
    else:
        return data[0][0]

################
# Main program #
################

path_raster = r"D:/UTwente/IGM_PhD_Materials/data/geo/raster/Beleving_Reclass_RD_New.tif"
path_points = r"D:/UTwente/IGM_PhD_Materials/data/geo/vector/1km_clipped/1km_clipped_centroids_text.csv"
path_out = r"D:/PycharmProjects/IGM_PhD_Materials/data/P04/out/features/country_features/Centroids_NR_BL.csv"

tif = gdal.Open(path_raster)

with open(path_points, "r", newline="") as r:
    with open(path_out, "w", newline="") as w:
        reader = csv.reader(r, delimiter=";")
        writer = csv.writer(w, delimiter=";")
        next(reader)
        i = 0
        for row in reader:
            rowid = int(row[2])
            latitude = float(row[1])
            longitude = float(row[0])
            value = extractSingleData(tif, longitude, latitude, 1)
            writer.writerow([i, value])
            i += 1


#######################################################
# A Launcher to run NNScore in parallel               #
#                                                     #
# Please edit the variable names according to the     #
#  requirements.                                      #
#######################################################

import glob
import re
import os
import sys

script_name = 'NNScore2.01_binana.py'
vina_executable = '/opt/autodock_vina_1_1_2_linux_x86/bin/vina'
ligands = sorted(glob.glob("/home/mhassan/proteins2.0/**/*_ligand.pdbqt", recursive=True))
receptors = sorted(glob.glob("/home/mhassan/proteins2.0/**/*_protein.pdbqt", recursive=True))
process_count = 100

# Get the pdb ids that have both ligand and protein files available.
lig_files = {}
rec_files = {}
for lig in ligands:
    f = re.findall('\w\w\w\w/', lig)
    pdb_id = f[len(f)-1].strip('/')
    lig_files[pdb_id] = lig

for rec in receptors:
    f = re.findall('\w\w\w\w/', rec)
    pdb_id = f[len(f)-1].strip('/')
    rec_files[pdb_id] = rec

pdb_ids = [k for k in lig_files if k in rec_files]
#print('Total pdb ids: ', len(pdb_ids))

# Comment the following line to execute NNScore for all the files
#pdb_ids = pdb_ids[:10]

result_count = 0
run_count = 0
counter = 0

commands = []

for id in pdb_ids:
    commands.append('python -W ignore ' + script_name + ' -receptor ' + rec_files[id] + ' -ligand ' + lig_files[id] + ' -vina_executable ' + vina_executable + ' & \n')
    counter = counter + 1
    if counter%process_count == 0:
        commands.append('wait\n')
f = open('batch_run.sh', 'w')

for com in commands:
    f.write(com)
#print('python launcher.py > batch_run.sh')
f.close()
os.system('bash batch_run.sh')

# for id in pdb_ids:
    # if not os.path.isfile('output/' + id + '_predicted_values.csv'):
        # commands.append('python -W ignore ' + script_name + ' -receptor ' + rec_files[id] + ' -ligand ' + lig_files[id] + ' -vina_executable ' + vina_executable + ' & \n')
        # counter = counter + 1
        # if counter%16 == 0:
            # commands.append('wait\n')
    # else:
        # result_count = result_count + 1

# if result_count < len(pdb_ids):
    # f = open('batch_run.sh', 'w')
    # for com in commands:
        # f.write(com)
    # #print('python launcher.py > batch_run.sh')
    # f.close()
    # os.system('bash batch_run.sh')
    # run_count = run_count + 1
    # if run_count > 3: # Total number of session
        # sys.exit()


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

__author__ = 'bwz'

from scrapy.spiders import CrawlSpider
from scrapy.http import Request
from scrapy.selector import Selector
from crawdbmz.items import DoubanMeizi

class Douban(CrawlSpider):
    name = 'douban'
    redis_key = 'douban:start_urls'
    start_urls = ['http://www.dbmeinv.com',]

    url = "http://www.dbmeinv.com/"

    def parse(self, response):

        items = []
        selector = Selector(response)
        Meizies = selector.xpath('//li[@class="span3"]')

        for meizi in Meizies:
            item = DoubanMeizi()
            src = meizi.css('img::attr(src)').extract()[0]
            name = meizi.css('img::attr(alt)').extract()[0]
            item['name'] = name
            item['src'] = src
            items.append(item)
            yield item
        nextlink = selector.xpath('//li[@class="next next_page"]').css('a::attr(href)').extract()

        if nextlink:
            next_url = str(nextlink[0]).replace('/','')
            print ('next:'+self.url+next_url)
            yield  Request(self.url+next_url,callback=self.parse)


from app.models.customer import Customer
import unittest
import os

from serve import run
from app.controllers.customer_controller import CustomerController
from app.models.customer import Customer

class TestServe(unittest.TestCase):

      def setUp(self):
            self.input_path = "./input_files/"
            self.output_path = "./output_files/output.txt"
            self.distance = '100.'
            self.office_latitude = '53.339428'
            self.office_longitude = '-6.257664'

            self.sample_data = {
                  "latitude": "52.833502",
                  "user_id": 25,
                  "name": "David Behan",
                  "longitude": "-8.522366"
            }

      def test_customer_controller(self):

            obj = CustomerController(self.input_path)

            # Test total input customers
            self.assertEqual(len(obj.data), 32)

            # Test input has all the keys from the input
            self.assertEqual(list(obj.data[0].keys()), [
                  'latitude',
                  'user_id',
                  'name',
                  'longitude',
                  ]
            )

            # Test First Customer user id
            self.assertEqual(obj.data[0]['user_id'], 12)

            # Test if Controller creates same number of Cutomer Objects
            # after calling create() method
            obj.create()
            self.assertEqual(len(obj.customers), 32)

            # Test the type of Customer objects also the the directory structure
            print(type(obj.customers[0]))
            self.assertEqual(str(type(obj.customers[0])), "<class 'app.models.customer.Customer'>")

            # Test fetch_customer_by_distance() method
            obj.fetch_customer_by_distance(
                  float(self.office_latitude),
                  float(self.office_longitude),
                  float(self.distance)
            )
            self.assertEqual(len(obj.filtered_data), 16)

            # Test if the filtered data is in ascending order w.r.t user_id
            user_ids = [i['user_id'] for i in obj.filtered_data]
            self.assertEqual(user_ids, sorted(user_ids))

            # Test output_customer() method
            obj.output_customer(self.output_path)
            self.assertEqual(os.path.exists(self.output_path), True)

      def test_model(self):

            # Test create object
            customer = Customer(
                  float(self.sample_data['latitude']),
                  float(self.sample_data['longitude']),
                  self.sample_data['user_id'],
                  self.sample_data['name']
            )
            self.assertEqual(customer.name, self.sample_data['name'])

            # Test Check for radians
            from math import sin, cos, radians
            self.assertEqual(customer.lat_radians, radians(customer.latitude))
            self.assertEqual(customer.lon_radians, radians(customer.longitude))

            # Test filter_by_distance() method
            obj = CustomerController(self.input_path)
            obj.create()
            filtered_customers = customer.filter_by_distance(
                  float(self.office_latitude),
                  float(self.office_longitude),
                  obj.customers,
                  float(self.distance)
            )
            self.assertEqual(len(filtered_customers), 16)

            # Test filter_by_distance() within 10KM distance
            filtered_customers = customer.filter_by_distance(
                  float(self.office_latitude),
                  float(self.office_longitude),
                  obj.customers,
                  10.
            )
            self.assertEqual(len(filtered_customers), 0)

            # Test filter_by_distance() with distance in negative value
            filtered_customers = customer.filter_by_distance(
                  self.office_latitude,
                  self.office_longitude,
                  obj.customers,
                  -10.
            )
            self.assertEqual(len(filtered_customers), 0)

            # Test to_json() method
            self.assertDictEqual(customer.to_json(), {
                  "user_id": self.sample_data['user_id'],
                  "name": self.sample_data['name']
            })

      def test_final(self):
            run()
            self.assertEqual(os.path.exists(self.output_path), True)


import sys
from PyQt5.QtWidgets import QWidget, QLabel,QPushButton,QGridLayout,QListWidget
from PyQt5.QtGui import QPixmap,QFont,QImage
from PyQt5.QtCore import QRect,Qt
from urllib import request
from app.gui.components import GuiComponent
from app.models.Movie import Movie

class MovieFrame(QWidget, GuiComponent):
    def __init__(self,parent=None, gui=None):
        super().__init__(parent)
        self.gui = gui
        self.gui.register_listener(self)
        self.initFrame()

    def initFrame(self):
        self.createWidgets()
        self.updateWidgets(Movie.get(7))
        self.show()

    def createWidgets(self):
        grid = QGridLayout()
        fontTitle = QFont('Arial',20)
        fontInfo = QFont('Arial',8)
        imgPix = QPixmap('noPoster.jpg')

        self.lblImg = QLabel(self)
        self.lblImg.setFixedSize(300, 465)
        self.lblImg.setScaledContents(True)

        self.lblTitle = QLabel("*No Title*",self)
        self.lblImg.setPixmap(imgPix)
        self.lblScenarist = QLabel("Writer : -", self)
        self.lblDirector = QLabel("Director: -", self)
        self.lblActors = QLabel("Actor(s): -",self)
        self.lblRuntime = QLabel("Runtime: -",self)
        self.lblRate = QLabel("IMDb Rate: -",self)
        self.lblAwards = QLabel("Awards : -",self)
        self.lblCountry = QLabel("Country : -",self)
        self.lblRelease = QLabel("Release date : -",self)
        self.lblPlot = QLabel("Plot: -",self)
        self.lstFile = QListWidget(self)

        #Set font to labels
        self.lblTitle.setFont(fontTitle)
        self.lblScenarist.setFont(fontInfo)
        self.lblDirector.setFont(fontInfo)
        self.lblActors.setFont(fontInfo)
        self.lblRuntime.setFont(fontInfo)
        self.lblRate.setFont(fontInfo)
        self.lblAwards.setFont(fontInfo)
        self.lblCountry.setFont(fontInfo)
        self.lblRelease.setFont(fontInfo)
        self.lblPlot.setFont(fontInfo)

        self.lblTitle.setWordWrap(True)
        self.lblScenarist.setWordWrap(True)
        self.lblDirector.setWordWrap(True)
        self.lblActors.setWordWrap(True)
        self.lblRuntime.setWordWrap(True)
        self.lblRate.setWordWrap(True)
        self.lblAwards.setWordWrap(True)
        self.lblCountry.setWordWrap(True)
        self.lblRelease.setWordWrap(True)
        self.lblPlot.setWordWrap(True)
        btnLauchnFilm = QPushButton("Launch Film",self)

        grid.addWidget(self.lblImg, 1, 0, 8, 0)

        grid.addWidget(self.lblTitle,0, 0, 1, 2)
        grid.addWidget(self.lblScenarist,1,1)
        grid.addWidget(self.lblDirector,2,1)
        grid.addWidget(self.lblActors,3,1)
        grid.addWidget(self.lblRuntime,4,1)
        grid.addWidget(self.lblRate,5,1)
        grid.addWidget(self.lblAwards,6,1)
        grid.addWidget(self.lblCountry,7,1)
        grid.addWidget(self.lblRelease,8,1)
        grid.addWidget(self.lblPlot,9,0,1,2)
        grid.addWidget(self.lstFile,10,0,1,2)
        grid.addWidget(btnLauchnFilm,11,0,2,2)
        self.setLayout(grid)
    def updateWidgets(self,film):
        if film.poster is not None:
            poster = self.importPosterFilm(film.poster)
        else :
            poster = self.importPosterFilm()
        self.lblImg.setPixmap(poster)
        if film.name is not None:
            self.lblTitle.setText(film.name)
        else:
            self.lblTitle.setText("*no title*")
        if film.writer is not None:
            self.lblScenarist.setText("Scenarist: "+film.writer)
        else:
            self.lblScenarist.setText("Scenarist: -")
        if film.directors is not None:
            self.lblDirector.setText("Directors: "+film.directors)
        else:
            self.lblDirector.setText("Directors: -")
        if film.actors is not None:
            self.lblActors.setText("Actors :"+film.actors)
        else:
            self.lblActors.setText("Actors : -")
        if film.runtime is not None :
            self.lblRuntime.setText("Runtime: " + film.runtime)
        else:
            self.lblRuntime.setText("Runtime: -")
        if film.rate is not None:
            self.lblRate.setText("Rate IMDb: "+ film.rate)
        else:
            self.lblRate.setText("Rate IMDb: -")
        # if film.awards is not None:
        #     self.lblAwards.setText("Awards: "+film.awards)
        # else:
        #     self.lblAwards.setText("Awards: -")
        # if film.Country is not None:
        #     self.lblCountry.setText("Country: "+film.Country)
        # else:
        #     self.lblCountry.setText("Country: -")
        if film.release is not None:
            self.lblRelease.setText("Release: "+str(film.release))
        else:
            self.lblRelease.setText("Release: -")
        if film.desc is not None:
            self.lblPlot.setText("Plot: "+film.desc)
        else:
            self.lblPlot.setText("Plot: -")

        if len(film.files) == 1:
            self.lstFile.hide()
        else:
            for file in film.files:
                self.lstFile.addItem("test")
            self.lstFile.show()

    def seeBtnClicked(self):
        pass
    def importPosterFilm(self, path=''):
        image = QImage()
        pixMap = QPixmap("noPoster.jpg")
        if path is '':
            return pixMap
        try:
            html = request.urlopen(path)
            data = html.read()
            flag = False
            image.loadFromData(data)
            pixMap = QPixmap(image)
        except request.URLError:  # in case there isn't the internet or the url gives 404 error or bad url
            print("a problem with the connection or the url has occurred")
        return pixMap

    def handleAction(self, name, data):
        pass

    def requestAction(self, name):
        pass


import datetime
import pytest

from django.utils.timezone import make_naive
from django.core.management import (
    call_command,
    find_commands,
    load_command_class,
)
from django.test import TestCase
import django_peeringdb.models
from django_peeringdb import settings

# set this to 0 to fetch all objects during sync test (takes forever)
# setting this to anything > 0 will trigger missing object validation errors
# causing the test to also test the fallback solution for that scenario
FETCH_LIMIT = 3

def sync_test(f):
    """
    check for sync settings, configure
    return decorator for all tests that sync
    """
    sync = pytest.config.getoption("--sync")

    # check explicitly for False, none means default (which is prod)
    if sync == False:
        return pytest.mark.skip(reason="need --sync option to run sync tests")(f)

    f.sync_args = dict(
        debug=pytest.config.getoption('--sync-debug'),
        )

    sync_only = pytest.config.getoption("--sync-only")
    if sync_only:
        f.sync_args['only'] = sync_only

    sync_id = pytest.config.getoption("--sync-id")
    if sync_id:
        f.sync_args['id'] = sync_id

    if not sync or sync == 'prod':
        pass

    elif sync == 'beta':
        settings.SYNC_URL = 'https://beta.peeringdb.com/api'

    else:
        settings.SYNC_URL = sync

    return f

@sync_test
class SyncTests(TestCase):
    """ test sync command """

    def setUp(self):
        self.cmd = load_command_class('django_peeringdb', 'pdb_sync')

    def test_get_since_empty(self):
        for cls in self.cmd.get_class_list():
            if cls.handleref.tag == "poc":
                continue
            assert 0 == self.cmd.get_since(cls)

    def test_sync_all(self):
        kwargs = getattr(self, 'sync_args', {})
        if "limit" not in kwargs:
            kwargs["limit"] = FETCH_LIMIT
        print("syncing kwargs {}".format(kwargs))
        self.cmd.handle(**kwargs)
#        self.cmd.sync(self.cmd.get_class_list())

#        for cls in self.cmd.get_class_list():
#            data = self.cmd.get_objs(cls)
#            for row in data:
#                for field in cls._meta.get_fields():
#                    value = cls._meta.get_field(field.name)
#                    if isinstance(value, datetime.datetime):
#                        #cls._meta.get_field(field.name).make_naive()
#                        setattr(cls, field.name, make_naive(value))
#
#            self.cmd.update_db(cls, data)
#
#            self.update_db(cls, self.get_objs(cls))

        for cls in self.cmd.get_class_list():
            if cls.handleref.tag == "poc":
                continue
            assert 0 != self.cmd.get_since(cls)
            assert 0 != cls.objects.all().count()
            print(cls.objects.all().count())

    def test_sync_call_command(self):
        call_command('pdb_sync', limit=FETCH_LIMIT)


from account import Account
from time import sleep
from graphics import GraphWin, Circle, Point, Line, Rectangle, Text, Entry

# Storing accounts locally since we're not using a database
my_accounts = [
    {'first_name': 'Zubair', 'last_name': 'Aziz',
        'PIN': 1234, 'balance': 1000.00},
    {'first_name': 'Chase', 'last_name': 'Lindemann',
        'PIN': 1234, 'balance': 1234.00},
    {'first_name': 'Sam', 'last_name': 'Schacht',
        'PIN': 1234, 'balance': 812.00},
    {'first_name': 'Ian', 'last_name': 'Lawson',
        'PIN': 1234, 'balance': 885.00},
    {'first_name': 'Ashley', 'last_name': 'Lin',
        'PIN': 1234, 'balance': 811.00},
]

# Graphics Objects
screen = Rectangle(Point(100, 100), Point(700, 750))
screen.setFill('cyan')
heading = Text(Point(400, 50), "ATM")
heading.setSize(30)
# Hint
hintText = Text(Point(400, 700),
                "Try logging in with the userID `zaziz` and PIN `1234`\
                    \nother accounts inlude `alin`, `sschacht`, `ilawson`, `clindemann`\
                    \nPIN is `1234` for all accounts")
# Messages
errorMessage = Text(Point(400, 215), "Error")
errorMessage.setSize(18)
errorMessage.setTextColor('red')
message = Text(Point(400, 150), "Welcome to PyBank")
message.setSize(20)
message2 = Text(Point(400, 325), "Login")
message2.setSize(20)
message3 = Text(Point(400, 325), "What would you like to do?")
# User ID
uidText = Text(Point(400, 375), "User ID")
uidInput = Entry(Point(400, 400), 10)
# PIN
pinText = Text(Point(400, 425), "PIN")
pinInput = Entry(Point(400, 450), 4)
# Login
loginBtn = Rectangle(Point(375, 475), Point(425, 505))
loginBtn.setFill("green")
loginBtnText = Text(Point(400, 490), "Login")
# Deposit
depositBtn = Rectangle(Point(250, 375), Point(350, 405))
depositBtn.setFill("blue")
depositBtnText = Text(Point(300, 390), "Deposit")
# Withdraw
withdrawBtn = Rectangle(Point(450, 375), Point(550, 405))
withdrawBtn.setFill("blue")
withdrawBtnText = Text(Point(500, 390), "Withdraw")
# Balance
balanceBtn = Rectangle(Point(250, 575), Point(350, 605))
balanceBtn.setFill("blue")
balanceBtnText = Text(Point(300, 595), "Balance")
# Logout
logoutBtn = Rectangle(Point(450, 575), Point(550, 605))
logoutBtn.setFill("red")
logoutBtnText = Text(Point(500, 595), "Log Out")
# Amount
amountText = Text(Point(400, 375), "Amount")
amountInput = Entry(Point(400, 400), 10)
# Accept
acceptBtn = Rectangle(Point(375, 475), Point(425, 505))
acceptBtn.setFill("blue")
acceptBtnText = Text(Point(400, 490), "Accept")
# Back
backBtn = Rectangle(Point(375, 680), Point(425, 710))
backBtn.setFill("red")
backBtnText = Text(Point(400, 700), "Back")
# Back
quitBtn = Rectangle(Point(682, 102), Point(698, 118))
quitBtn.setFill("red")
quitBtnText = Text(Point(690, 110), "X")
quitBtnText.setTextColor("white")

def click(point, rectangle):
    ll = rectangle.getP1()  # assume p1 is ll (lower left)
    ur = rectangle.getP2()  # assume p2 is ur (upper right)
    return ll.getX() < point.getX() < ur.getX() and ll.getY()\
        < point.getY() < ur.getY()

def undrawAll():
    # Undraws all components on the screen
    message.undraw()
    message2.undraw()
    uidText.undraw()
    uidInput.undraw()
    pinText.undraw()
    pinInput.undraw()
    loginBtn.undraw()
    loginBtnText.undraw()
    depositBtn.undraw()
    withdrawBtn.undraw()
    balanceBtn.undraw()
    logoutBtn.undraw()
    depositBtnText.undraw()
    withdrawBtnText.undraw()
    balanceBtnText.undraw()
    logoutBtnText.undraw()
    backBtn.undraw()
    backBtnText.undraw()
    acceptBtn.undraw()
    acceptBtnText.undraw()
    amountText.undraw()
    amountInput.undraw()
    hintText.undraw()

def drawLoginScreen(target):
    # Draws screen components for login screen
    undrawAll()
    message.setText("Welcome to PyBank")
    message.draw(target)
    message2.setText('Login')
    message2.draw(target)
    uidText.draw(target)
    uidInput.draw(target)
    pinText.draw(target)
    pinInput.draw(target)
    loginBtn.draw(target)
    loginBtnText.draw(target)
    hintText.draw(target)

def drawMainMenu(target, displayName):
    # Draws screen components for main menu
    undrawAll()
    message.setText("Welcome to PyBank, {0}".format(displayName))
    message.setSize(30)
    message.draw(target)
    message2.setText("What would you like to do?")
    message2.draw(target)
    depositBtn.draw(target)
    withdrawBtn.draw(target)
    balanceBtn.draw(target)
    logoutBtn.draw(target)
    depositBtnText.draw(target)
    withdrawBtnText.draw(target)
    balanceBtnText.draw(target)
    logoutBtnText.draw(target)

def drawBalanceScreen(target, amount):
    # Draws screen components for balance screen
    undrawAll()
    message2.setText('Account Balance: ${0:.2f}'.format(amount))
    message2.draw(target)
    backBtn.draw(target)
    backBtnText.draw(target)

def drawDepositScreen(target):
    # Draws screen components for deposit screen
    undrawAll()
    message2.setText('Deposit')
    message2.draw(target)
    amountText.draw(target)
    amountInput.draw(target)
    acceptBtn.draw(target)
    acceptBtnText.draw(target)
    backBtn.draw(target)
    backBtnText.draw(target)

def drawWithdrawScreen(target):
    # Draws screen components for withdraw screen
    undrawAll()
    message2.setText('Withdraw')
    message2.draw(target)
    amountText.draw(target)
    amountInput.draw(target)
    acceptBtn.draw(target)
    acceptBtnText.draw(target)
    backBtn.draw(target)
    backBtnText.draw(target)

def showError(target, message, color='red'):
    # Shows errors and alerts
    errorMessage.setText(message)
    errorMessage.setTextColor(color)
    errorMessage.draw(target)
    sleep(1.5)
    errorMessage.undraw()

def quit(target, items):
    # Exit with `X` button
    for item in items[:]:
        item.undraw()
    exit()

class ATM:

    def __init__(self):
        # Initialize atm
        self.accounts = self.setAccounts(my_accounts)
        self.authenticated = False
        self.currentUser = None
        self.win = GraphWin('Python ATM', 800, 800)
        self.win.setBackground('gray')
        # Graphics Headings
        heading.draw(self.win)
        screen.draw(self.win)
        hintText.draw(self.win)
        quitBtn.draw(self.win)
        quitBtnText.draw(self.win)

    def setAccounts(self, account_list):
        accounts = []
        for i in range(len(account_list)):
            accounts.append(Account(account_list[i]['first_name'],
                                    account_list[i]['last_name'],
                                    account_list[i]['PIN'],
                                    account_list[i]['balance']))
        return accounts

    def setCurrentUser(self, userID):
        for user in self.accounts:
            if (user.userID == userID):
                self.currentUser = user

    def setAuthenticated(self, PIN):
        self.authenticated = self.currentUser.confirmPIN(PIN)

    def doLogin(self):
        # Draw login GUI
        drawLoginScreen(self.win)
        while (self.authenticated is False):
            clickPoint = self.win.getMouse()
            if clickPoint is None:
                pass
            elif click(clickPoint, loginBtn):
                try:
                    userID = uidInput.getText()
                    PIN = int(pinInput.getText())
                    self.setCurrentUser(userID)
                    if (self.currentUser is not None):
                        self.setAuthenticated(PIN)
                        if (not self.authenticated):
                            showError(self.win, "Error: Incorrect PIN")
                            self.currentUser = None
                    else:
                        showError(self.win, "Error: User not found")
                except ValueError as error:
                    showError(self.win, "Value Error: see console for details")
                    print(error)
            elif click(clickPoint, quitBtn):
                quit(self.win, self.win.items)
            else:
                pass

    def doDeposit(self):
        drawDepositScreen(self.win)
        showError(self.win, 'Balance: ${0:.2f}'.format(
            self.currentUser.balance), 'green')
        while (self.authenticated):
            clickPoint = self.win.getMouse()
            if clickPoint is None:
                pass
            elif click(clickPoint, acceptBtn):
                try:
                    amount = float(amountInput.getText())
                    self.currentUser.deposit(amount)
                    if (amount <= 0):
                        showError(
                            self.win, 'Amount cannot be less than or equal to 0')
                    else:
                        showError(self.win, 'New Balance: ${0:.2f}'.format(
                            self.currentUser.balance), 'green')
                except ValueError as error:
                    showError(self.win, "Value Error: see console for details")
                    print(error)
            elif click(clickPoint, backBtn):
                self.menu()
            elif click(clickPoint, quitBtn):
                quit(self.win, self.win.items)
            else:
                pass

    def doWithdraw(self):
        drawWithdrawScreen(self.win,)
        showError(self.win, 'Balance: ${0:.2f}'.format(
            self.currentUser.balance), 'green')
        while (self.authenticated):
            clickPoint = self.win.getMouse()
            if clickPoint is None:
                pass
            elif click(clickPoint, acceptBtn):
                try:
                    amount = float(amountInput.getText())
                    self.currentUser.withdraw(amount)
                    if (amount >= self.currentUser.balance):
                        showError(
                            self.win, 'Cannot withdraw more than your balance')
                    else:
                        showError(self.win, 'New Balance: ${0:.2f}'.format(
                            self.currentUser.balance), 'green')
                except ValueError as error:
                    showError(self.win, "Value Error: see console for details")
                    print(error)
            elif click(clickPoint, backBtn):
                self.menu()
            elif click(clickPoint, quitBtn):
                quit(self.win, self.win.items)
            else:
                pass

    def logout(self):
        self.authenticated = False
        self.currentUser = None
        self.menu()

    def __repr__(self):
        for account in self.accounts:
            print(account)
        return ""

    def menu(self):
        if (not self.authenticated):
            self.doLogin()
            self.menu()
        else:
            drawMainMenu(self.win, self.currentUser.first_name)
            while(self.authenticated):
                clickPoint = self.win.getMouse()
                if clickPoint is None:
                    pass
                elif click(clickPoint, balanceBtn):
                    drawBalanceScreen(self.win, self.currentUser.balance)
                    while(self.authenticated):
                        clickPoint = self.win.getMouse()
                        if clickPoint is None:
                            pass
                        elif click(clickPoint, backBtn):
                            self.menu()
                        elif click(clickPoint, quitBtn):
                            quit(self.win, self.win.items)
                        else:
                            pass
                elif click(clickPoint, depositBtn):
                    self.doDeposit()
                elif click(clickPoint, withdrawBtn):
                    self.doWithdraw()
                elif click(clickPoint, logoutBtn):
                    undrawAll()
                    showError(self.win, 'Thank you for using PyBank', 'blue')
                    self.logout()
                elif click(clickPoint, quitBtn):
                    quit(self.win, self.win.items)
                else:
                    pass


from RPG.game_classes.items.base_object import BaseObject

class BaseWeapon(BaseObject):
    def __init__(self, name, damage, loaded_ammo, max_ammo, price):
        self.max_ammo = max_ammo
        self.loaded_ammo = loaded_ammo
        self.info = f'🔫*{name}* \n' \
                    f'_🗡Daño_: {damage} \n' \
                    f'_🔋Tienda_: {self.loaded_ammo}/{self.max_ammo}\n'
        super().__init__(name, self.info, price)
        self.damage = damage

    def reload(self, player):
        if player.laser_ammo > 0:
            if self.loaded_ammo + player.laser_ammo >= self.max_ammo:
                player.laser_ammo -= (self.max_ammo - self.loaded_ammo)
                self.loaded_ammo = self.max_ammo
            else:
                self.loaded_ammo += player.laser_ammo
                player.laser_ammo = 0
            self.info = f'🔫*{self.name}* \n' \
                        f'_🗡Daño_: {self.damage} \n' \
                        f'_🔋Tienda_: {self.loaded_ammo}/{self.max_ammo}\n'
            return f'{self.name} ¡recargado con éxito!'
        else:
            return f'No se pudo recargar {self.name}: ¡no hay munición!'

    def use(self, player):
        if player.weapon is None:
            player.weapon = self
            player.inventory[player.inventory.index(self)] = None
            player.sort_inventory()
        else:
            player.inventory[player.inventory.index(self)] = player.weapon
            player.weapon = self

    def __str__(self):
        return f'🔫{self.name} 🗡{self.damage}'


# Copyright (c) 2014, Adaptiv Design
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:

# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.

# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.

# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from django.http import Http404

from sellmo.core import chaining
from sellmo.core.exceptions import ViewNotImplemented

from .models import Category

@chaining.define(provides=['category'])
def category(request, full_slug, **kwargs):

    # Find category
    parents = None
    categories = Category.objects.all()
    for slug in full_slug.split('/'):
        categories = Category.objects.filter(slug=slug)
        if parents is None:
            categories = categories.filter(parent__isnull=True)
        else:
            categories = categories.filter(parent__in=parents)

        # Get parent id's
        parents = categories.values_list('id', flat=True)
        if not parents:
            break

    count = categories.count()
    if count == 0:
        raise Http404("Category '{0}' not found.".format(full_slug))
    elif count > 1:
        raise Http404(
            "Category '{0}' could not be resolved.".format(full_slug)
        )

    category = categories[0]

    yield chaining.update(category=category)

    result = (yield chaining.forward).result
    if result is None:
        raise ViewNotImplemented


import os
from datetime import datetime

month = datetime.strptime(str(datetime.today().month), "%m").strftime("%B")

contest = month + "_" + input("Enter contest name: ")
os.system("mkdir " + contest)

problems = int(input("Enter the number of problems: "))
for problem in range(problems):
    print(" [Log] Creating file " + chr(ord('a') + problem) + ".cpp  and  " + chr(ord('a') + problem) + ".in ... ")
    os.system("cp template.cpp " + contest + "/" + chr(ord('a') + problem) + ".cpp")
    os.system("touch " + contest + "/" + chr(ord('a') + problem) + ".in")

print("Created " + str(problems*2) + " files!")


"""
remarkable.

Usage:
  remarkable [options] remark <path-to-markdown-file> [<title>]
  remarkable [options] reveal <path-to-markdown-file> <title>

  remarkable -h | --help

Options:
  --debug               Debug.

  -h --help             Show this screen.
"""
import logging
import os
import shutil
import sys

from docopt import docopt
from jinja2 import Environment, PackageLoader
from snide import Deck

import remarkable

log = logging.getLogger(__name__)

def render_template(template_name, context):
    return Environment(
        loader=PackageLoader('remarkable')
    ).get_template(template_name).render(context)

def ask(question):
    '''Display a Y/n question prompt, and return a boolean'''
    while True:
        print
        input_ = raw_input('%s [Y/n] ' % question)
        input_ = input_.strip().lower()
        if input_ in ('y', 'yes', ''):
            return True
        if input_ in ('n', 'no'):
            return False
        print('Invalid selection')

def render_template_directory(deck):
    output_directory = deck.title

    if os.path.exists(output_directory):
        if sys.stdout.isatty():
            if ask('%s already exists, shall I delete it?'):
                shutil.rmtree(output_directory)
        else:
            shutil.rmtree(output_directory)

    # copy support files to output directory
    template_directory_path = (
        '%s/templates/%s' %
        (remarkable.__path__[0], deck.presentation_type)
    )
    shutil.copytree(
        template_directory_path,
        output_directory,
    )

    # write index to output directory
    write_file(
        '%s/index.html' % output_directory,

        render_template(
            '%s/index.html' % deck.presentation_type,
            dict(slides=deck.slides),
        ),
    )

    return output_directory

def read_file(file_name):
    return open(file_name).read().decode('utf-8')

def write_file(file_name, content):
    with open(file_name, 'w') as html_file:
        html_file.write(content.encode('utf-8'))
    log.info('Created %s' % file_name)

def remark(arguments):
    html = render_template(
        'remark/index.html',
        dict(markdown=read_file(arguments['<path-to-markdown-file>'])),
    )

    title = arguments.get('<title>', 'Remark Presentation')
    write_file(
        '%s.html' % (title if title else 'remark'),
        html,
    )

def reveal(arguments):
    render_template_directory(Deck(
        arguments.get('<title>', 'Reveal Presentation'),
        read_file(arguments['<path-to-markdown-file>']),
        'reveal'
    ))

def main():
    arguments = docopt(__doc__, version=remarkable.__version__)

    logging.basicConfig(
        level=logging.DEBUG if arguments['--debug'] else logging.INFO
    )
    log.debug('arguments: %s', arguments)

    commands = ['remark', 'reveal']
    for command in commands:
        if arguments[command]:
            globals()[command](arguments)


from __future__ import print_function
import sys
import os
import keras
from tensorflow.python.platform import gfile
import numpy as np
import tensorflow as tf
from tensorflow.python.layers.core import Dense
from utils.data_manager import load_data
from utils.vocab import load_vocab_all
from utils.bleu import moses_multi_bleu
from collections import defaultdict
from argparse import ArgumentParser
import utils.vocab as vocab
import sys
reload(sys)
sys.setdefaultencoding('utf8')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

_PAD = vocab._PAD
_GO = vocab._GO
_END = vocab._END

def train(sess, env, X_data, y_data, epochs=10, load=False, shuffle=True, batch_size=128,
          name='model', base=0, model2load=''):
    """
    Train TF model by env.train_op
    """
    if load:
        print('\nLoading saved model')
        env.saver.restore(sess, model2load )

    print('\nTrain model')
    n_sample = X_data.shape[0]
    n_batch = int((n_sample+batch_size-1) / batch_size)
    for epoch in range(epochs):
        print('\nEpoch {0}/{1}'.format(epoch+1, epochs))
        sys.stdout.flush()
        if shuffle:
            print('\nShuffling data')
            ind = np.arange(n_sample)
            np.random.shuffle(ind)
            X_data = X_data[ind]
            y_data = y_data[ind]

        for batch in range(n_batch):
            print(' batch {0}/{1}'.format(batch+1, n_batch),end='\r')
            start = batch * batch_size
            end = min(n_sample, start+batch_size)
            sess.run(env.train_op, feed_dict={env.x: X_data[start:end],
                                              env.y: y_data[start:end],
                                              env.training: True})

        evaluate(sess, env, X_data, y_data, batch_size=batch_size)

        if (epoch+1) == epochs:
            print('\n Saving model')
            env.saver.save(sess, 'model/{0}-{1}'.format(name, base))
    return 'model/{0}-{1}'.format(name, base)

def evaluate(sess, env, X_data, y_data, batch_size=128):
    """
    Evaluate TF model by running env.loss and env.acc.
    """
    print('\nEvaluating')

    n_sample = X_data.shape[0]
    n_batch = int((n_sample+batch_size-1) / batch_size)
    loss, acc = 0, 0

    for batch in range(n_batch):
        print(' batch {0}/{1}'.format(batch+1, n_batch),end='\r')
        sys.stdout.flush()
        start = batch * batch_size
        end = min(n_sample, start+batch_size)
        cnt = end - start
        batch_loss, batch_acc = sess.run(
            [env.loss,env.acc],
            feed_dict={env.x: X_data[start:end],
                       env.y: y_data[start:end]})
        loss += batch_loss * cnt
        acc += batch_acc * cnt
    loss /= n_sample
    acc /= n_sample

    print(' loss: {0:.4f} acc: {1:.4f}'.format(loss, acc))
    return acc

def _decode_data(sess, env, X_data, batch_size, reverse_vocab_dict):
    print('\nDecoding')
    logics_all = []
    n_sample = X_data.shape[0]
    n_batch = int((n_sample+batch_size-1) / batch_size)
    for batch in range(n_batch):
        print(' batch {0}/{1}'.format(batch+1, n_batch),end='\r')
        sys.stdout.flush()
        start = batch * batch_size
        end = min(n_sample, start+batch_size)
        cnt = end - start
        ybar = sess.run(env.pred_ids,
                        feed_dict={env.x: X_data[start:end]})
        ybar = np.asarray(ybar)
        ybar = np.squeeze(ybar[:,0,:])  # pick top prediction
        for seq in ybar:
            seq = np.append(seq, _END)
            seq = seq[:list(seq).index(_END)]
            logic = " ".join([reverse_vocab_dict[idx] for idx in seq])
            logics_all.append(logic)
    return logics_all

def decode_data_recover(sess, env, args, X_data, y_data, s, batch_size=128):
    """
    Inference and calculate EM acc based on recovered SQL
    """
    annotation_path = args.annotation_path
    i, acc = 0, 0
    _, reverse_vocab_dict, _, _ = load_vocab_all(args)
    inf_logics = _decode_data(sess, env, X_data, batch_size, reverse_vocab_dict)
    xtru, ytru = X_data, y_data
    with gfile.GFile(annotation_path+'%s_infer.txt'%s, mode='w') as output, gfile.GFile(annotation_path+'%s_ground_truth.txt'%s, mode='r') as S_ori_file, \
        gfile.GFile(annotation_path+'%s_sym_pairs.txt'%s, mode='r') as sym_pair_file:

        sym_pairs = sym_pair_file.readlines()  # annotation pairs from question & table files
        S_oris = S_ori_file.readlines()  # SQL files before annotation
        for true_seq, logic, x, sym_pair, S_ori in zip(ytru, inf_logics, xtru, sym_pairs, S_oris):
            sym_pair = sym_pair.replace('<>\n','')
            S_ori = S_ori.replace('\n','')
            Qpairs = []
            for pair in sym_pair.split('<>'):
                Qpairs.append(pair.split('=>'))

            true_seq = true_seq[1:]    #delete <bos>
            x = x[1:]   #delete <bos>

            true_seq = true_seq[:list(true_seq).index(_END)]
            x = np.append(x, _END)
            x = x[:list(x).index(_END)]

            xseq = " ".join([reverse_vocab_dict[idx] for idx in x])
            true_logic = " ".join([reverse_vocab_dict[idx] for idx in true_seq])

            logic = logic.replace(' (','').replace(' )','')
            true_logic = true_logic.replace(' (','').replace(' )','')

            logic = _switch_cond(logic, true_logic)

            recover_S = logic
            for sym, word in Qpairs:
                recover_S = recover_S.replace(sym, word)

            acc += (recover_S==S_ori)
            output.write(recover_S + '\n')
            i += 1

    print('EM: %.4f'%(acc*1./len(y_data)))
    print('number of correct ones:%d'%acc)

    return acc*1./len(y_data)

def decode_data(sess, env, args, X_data, y_data, batch_size=128, filename='output.txt'):
    """
    Inference w/o recover annotation symbols
    """
    i, acc = 0, 0
    _, reverse_vocab_dict, _, _ = load_vocab_all(args)
    logics_all = _decode_data(sess, env, X_data, batch_size, reverse_vocab_dict)
    xtru, ytru = X_data, y_data

    for true_seq, logic, x in zip(ytru, logics_all, xtru):
        true_seq = true_seq[1:]
        x = x[1:]
        true_seq = np.append(true_seq, _END)
        x = np.append(x, _END)

        true_seq=true_seq[:list(true_seq).index(_END)]
        x=x[:list(x).index(_END)]

        xseq = " ".join([reverse_vocab_dict[idx] for idx in x ])
        true_logic = " ".join([reverse_vocab_dict[idx] for idx in true_seq ])

        logic = logic.replace(' (','').replace(' )','')
        true_logic = true_logic.replace(' (','').replace(' )','')
        logic = _switch_cond(logic, true_logic)

        acc += (logic==true_logic)
        i += 1
    print('EM: %.4f'%(acc*1./len(y_data)))
    print('number of correct ones:%d'%acc)

    return acc*1./len(y_data)

def _switch_cond(logic, true_logic):
    logic_tokens = logic.split()
    if len(logic_tokens) > 8 and logic_tokens[5] == 'and':
        newlogic = [x for x in logic_tokens]
        newlogic[2], newlogic[6], newlogic[4], newlogic[8] = logic_tokens[6], logic_tokens[2], logic_tokens[8], logic_tokens[4]
        newline = ' '.join(newlogic)
        if newline == true_logic:
            logic = newline
    elif len(logic_tokens) > 9 and logic_tokens[6] == 'and':
        newlogic = [x for x in logic_tokens]
        newlogic[3], newlogic[7], newlogic[5], newlogic[9] = logic_tokens[7], logic_tokens[3], logic_tokens[9], logic_tokens[5]
        newline = ' '.join(newlogic)
        if newline == true_logic:
            logic = newline
    return logic


#coding=utf-8
import configparser

class ConfigTools:

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

    def get_err(self):
        print(self.filepath)

    # # 获取配置文件中的元素
    # def get_config(self,data):
    #
    #
    #     self.inifile.read(self.filepath, 'UTF-8')
    #
    #     # print(self.inifile.get(data[0], data[1]))
    #
    #
    #     return self.inifile.get(data[0], data[1])
    #
    # # 修改或添加配置文件中的应用
    # def update_config(self,data):
    #     # 添加新的配置文件,或修改配置
    #     self.inifile['web']['pwd'] = '198.333.444'
    #
    #     with open(self.filepath, 'w') as config:
    #         self.inifile.write(config)
    #     return 'updata success'

aa = '.\config.ini'
tt=ConfigTools(aa)

# tt.get_config(['db','ip'])
tt.get_err()

print('aa')


from django.contrib.auth.models import Permission

def test_anonymous_users_denied(client):
    response = client.get("/dashboard/?sql=select+1")
    assert response.status_code == 302
    assert response.url == "/accounts/login/?next=/dashboard/%3Fsql%3Dselect%2B1"

def test_superusers_allowed(admin_client, dashboard_db):
    response = admin_client.get("/dashboard/")
    assert response.status_code == 200
    assert b"<title>Django SQL Dashboard</title>" in response.content

def test_must_have_execute_sql_permission(client, django_user_model, dashboard_db):
    execute_sql = Permission.objects.get(
        content_type__app_label="django_sql_dashboard",
        content_type__model="dashboard",
        codename="execute_sql",
    )
    not_staff = django_user_model.objects.create(username="not_staff")
    staff_no_permisssion = django_user_model.objects.create(
        username="staff_no_permission", is_staff=True
    )
    staff_with_permission = django_user_model.objects.create(
        username="staff_with_permission", is_staff=True
    )
    staff_with_permission.user_permissions.add(execute_sql)
    assert staff_with_permission.has_perm("django_sql_dashboard.execute_sql")
    client.force_login(not_staff)
    assert client.get("/dashboard/").status_code == 302
    client.force_login(staff_no_permisssion)
    assert client.get("/dashboard/").status_code == 302
    client.force_login(staff_with_permission)
    assert client.get("/dashboard/").status_code == 200


# Import base test
from TestRunBaseTest import TestRunBaseTest
from datetime import datetime

class PySysTest(TestRunBaseTest):

	def execute(self):

		test_id = 'Test 1'
		ret = self.deleteTestRun(test_id)
		self.log.info(ret)

		ret = self.createTestRun(test_id)
		self.log.info(ret)

		for i in range(7):
			measurement = { 'timestamp' : datetime.now(), 'value' : i * 10 }
			if i % 2 == 0:
				ret = self.addMeasurementToTestRun(test_id, 'total_documents', measurement)
			else:
				ret = self.addMeasurementToTestRun(test_id, 'cpu', measurement)
			self.log.info(ret)

		ret = self.getTestRun(test_id)
		self.log.info(ret)

	def validate(self):
		self.assertGrep('run.log', expr="'_id': 'Test 1'")


from django.db import models
from django.utils import timezone

class Posts(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    description = models.TextField(default='')
    photo = models.ImageField(upload_to="uploaded_files",default='',blank=True,null=True)
    slug = models.SlugField(max_length=200,unique=True)
    publish = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def post_photo(self):
        return """""" % ((self.photo.name, self.photo.name))
    post_photo.allow_tags = True

    def __str__(self):
        return self.title

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    class Meta:
        verbose_name = "Posts"
        verbose_name_plural = "Posts Entry"
        ordering = ["created"]


"""
Helpers to track the evolution of a node through transformations,
notably source code location.

Consider:

    with About(original_node, 'my-transform'):
        return f(original_node)

Any node (as defined in myia.stx.nodes) created while the ``with``
block is active, in this case during the execution of ``f``, will have
its ``about`` field set to the ``About`` instance. This will mark it
as being "about" ``original_node``, with the tag ``my-transform``. The
``about`` field can thus form a chain going all the way back to the
original node made during parsing.

All code transforms should use ``with About(...)`` in their implementation
in order to preserve this chain, with as fine a granularity as possible.
"""

from typing import Any
import threading
import textwrap

class MyiaSyntaxError(Exception):
    """
    Class for syntax errors in Myia. This exception type should be
    raised for any feature that is not supported.

    Attributes:
        message: A precise assessment of the problem.
        location: The error's location in the original source. If not
            provided, it will be extracted from the node we are currently
            About.
    """
    def __init__(self, message: str, location: 'Location' = None) -> None:
        self.location = location or current_location()
        self.message = message
        super().__init__(self.message, self.location)

# We use per-thread storage for the about stack.
_about = threading.local()
_about.stack = [None]

def top():
    """
    Return the currently active ``About`` instance.
    """
    return _about.stack[-1]

def current_location():
    """
    Follow the about chain of the node we are currently about in order
    to find where in the source code it ultimately came from.
    """
    abt = top()
    while abt:
        node = abt.node
        if getattr(node, 'about', None):
            abt = node.about
        else:
            abt = None
    if isinstance(node, Location):
        return node
    return None

class About:
    """
    Any code executed during the ``About`` context manager is understood
    to be "about" the node given in the constructor. It is up to
    compliant object constructors to consult what node they are about and
    to store that information. This is done by ``MyiaASTNode`` instances.

    ``About`` instances are pushed on a per-thread stack, therefore
    ``with`` calls to ``About`` can be nested.
    """
    def __init__(self, node, transform):
        self.node = node
        self.transform = transform

    def __enter__(self):
        _about.stack.append(self)

    def __exit__(self, etype, evalue, etraceback):
        _about.stack.pop()

class AboutPrinter:
    """
    Through its ``__hrepr__`` representation, an AboutPrinter can be
    printed out to Buche and will display a chain of about nodes that
    can be navigated, along with stack traces for the creation of each
    node when they are available.
    """
    def __init__(self, node):
        self.node = node

    def node_hrepr(self, node, H, hrepr):
        if hasattr(node, 'trace'):
            views = H.tabbedView()
            views = views(H.view(H.tab('node'), H.pane(hrepr(node))))
            views = views(H.view(H.tab('trace'), H.pane(hrepr(node.trace))))
            return views
        else:
            return hrepr(node)

    def __hrepr__(self, H, hrepr):
        views = H.tabbedView()
        node = self.node

        nodes = [self.node_hrepr(node, H, hrepr)]
        transforms = []

        while node and getattr(node, 'about', None):
            about = node.about
            node = about.node
            nodes.append(self.node_hrepr(node, H, hrepr))
            transforms.append(about.transform)
        transforms.append('orig')

        for transform, node in reversed(list(zip(transforms, nodes))):
            tab = H.tab(transform)
            pane = H.pane(node)
            views = views(H.view(tab, pane))

        return views

class Location:
    """
    Represents a source code location for an AST node.

    Attributes:
        url (str): The path of the code file.
        line (int): The line number in that file.
        column (int): The column number in that file.
    """

    def __init__(self,
                 url: str,
                 line: int,
                 column: int,
                 node: Any = None) -> None:
        self.url = url
        self.line = line
        self.column = column
        self.node = node

    def traceback(self) -> str:
        """
        Print out a "traceback" that corresponds to this location,
        with the line printed out and a caret at the right column.
        Basically:

        >>> loc.traceback()
          File {url}, line {line}, column {column}
            x = f(y)
                ^

        This is mostly meant for printing out ``MyiaSyntaxError``s.
        """
        try:
            with open(self.url) as file:
                raw_code = file.readlines()[self.line - 1].rstrip("\n")
                raw_caret = ' ' * self.column + '^'
                code, caret = textwrap.dedent(
                    raw_code + '\n' + raw_caret
                ).split("\n")
            return '  File "{}", line {}, column {}\n    {}\n    {}'.format(
                self.url, self.line, self.column, code, caret)
        except FileNotFoundError:
            return '  File "{}", line {}, column {}'.format(
                self.url, self.line, self.column)

    def __str__(self) -> str:
        return '{}@{}:{}'.format(self.url, self.line, self.column)

    def __hrepr__(self, H, hrepr):
        return H.codeSnippet(
            src = self.url,
            language = "python",
            line = self.line,
            column = self.column + 1,
            context = 4
        )


from db.run_sql import run_sql
from models.player import Player
from models.team import Team

# add new team to database
def save(team):
    sql = "INSERT INTO teams (team_name, location, stadium_name, stadium_capacity, fixtures_played, fixtures_won, fixtures_drawn, fixtures_lost, points, score) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id"
    values = [team.team_name, team.location, team.stadium_name, team.stadium_capacity, team.fixtures_played, team.fixtures_won, team.fixtures_drawn, team.fixtures_lost, team.points, team.score]
    results = run_sql(sql, values)
    id = results[0]['id']
    team.id = id

# get all teams from database
def select_all():
    teams = []
    sql = "SELECT * FROM teams"
    results = run_sql(sql)
    for result in results:
        team = Team(result["team_name"], result["location"], result["stadium_name"], result["stadium_capacity"], result["fixtures_played"], result["fixtures_won"], result["fixtures_drawn"], result["fixtures_lost"], result["points"], result["score"], result["id"])
        teams.append(team)
    return teams

# get specific team from database
def select(id):
    sql = "SELECT * FROM teams WHERE id = %s"
    values = [id]
    result = run_sql(sql, values)[0]
    team = Team(result["team_name"], result["location"], result["stadium_name"], result["stadium_capacity"], result["fixtures_played"], result["fixtures_won"], result["fixtures_drawn"], result["fixtures_lost"], result["points"], result["score"], result["id"])
    return team

# update specific fixture in database
def update(team):
    sql = "UPDATE teams SET (team_name, location, stadium_name, stadium_capacity, fixtures_played, fixtures_won, fixtures_drawn, fixtures_lost, points, score) = (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) WHERE id = %s"
    values = [team.team_name, team.location, team.stadium_name, team.stadium_capacity, team.fixtures_played, team.fixtures_won, team.fixtures_drawn, team.fixtures_lost, team.points, team.score, team.id]
    run_sql(sql, values)

# delete all
def delete_all():
    sql = "DELETE FROM teams"
    run_sql(sql)

#delete specific entry
def delete(id):
    sql = "DELETE FROM teams WHERE id = %s"
    values = [id]
    run_sql(sql, values)


import os
from config import Config
import numpy as np
from bert_model import BertModel
import tensorflow as tf

def train():
    """
    train the model on toy task:
        learn to count,sum up input, and distinct whether the total value of input is below or greater than a threshold.
    usage:
        use train() to train the model, and it will save checkpoint to file system;
        use predict() to make a prediction based on the trained model.
    """
    # 1.init config and model
    config = Config()
    threshold = (config.sequence_length / 2) + 1  # 有何用？
    model = BertModel(config)
    gpu_config = tf.ConfigProto()
    gpu_config.gpu_options.allow_growth = True
    saver = tf.train.Saver()
    # save_path = config.ckpt_dir + "model.ckpt"
    save_path = os.path.join(config.ckpt_dir, 'model.ckpt')
    # batch_size = 8
    if not os.path.exists(config.ckpt_dir):
        os.makedirs(config.ckpt_dir)
    with tf.Session(config=gpu_config) as sess:
        sess.run(tf.global_variables_initializer())
        if os.path.exists(config.ckpt_dir):  #
            saver.restore(sess, tf.train.latest_checkpoint(save_path))
        for i in range(10000):
            # 2.feed data
            input_x = np.random.randn(config.batch_size, config.sequence_length)  # [None, self.sequence_length]
            input_x[input_x >= 0] = 1
            input_x[input_x < 0] = 0
            input_y = generate_label(input_x, threshold)
            # p_mask_lm = [i for i in range(batch_size)]
            # 3.run session to train the model, print some logs.
            loss, _ = sess.run([model.loss_val, model.train_op],
                               feed_dict={model.input_x: input_x,
                                          model.input_y: input_y,
                                          # model.p_mask_lm: p_mask_lm,
                                          model.dropout_keep_prob: config.dropout_keep_prob})
            print(i, "loss:", loss, "-------------------------------------------------------")
            if i == 300:
                print("label[0]:", input_y[0])
                print("input_x:", input_x)
            if i % 500 == 0:
                saver.save(sess, save_path, global_step=i)

def predict():
    """
    use saved checkpoint from model to make prediction, and print it,
    to see whether it is able to do toy task successfully.
    :return:
    """
    config = Config()
    threshold = (config.sequence_length / 2) + 1
    config.batch_size = 1
    model = BertModel(config)
    gpu_config = tf.ConfigProto()
    gpu_config.gpu_options.allow_growth = True
    saver = tf.train.Saver()
    ckpt_dir = config.ckpt_dir
    print("ckpt_dir:", ckpt_dir)
    with tf.Session(config=gpu_config) as sess:
        sess.run(tf.global_variables_initializer())
        saver.restore(sess, tf.train.latest_checkpoint(ckpt_dir))
        for i in range(100):
            # 2.feed data
            input_x = np.random.randn(config.batch_size, config.sequence_length)  # [None, self.sequence_length]
            input_x[input_x >= 0] = 1
            input_x[input_x < 0] = 0
            target_label = generate_label(input_x, threshold)
            input_sum = np.sum(input_x)
            # 3.run session to train the model, print some logs.
            logit, prediction = sess.run([model.logits, model.predictions],
                                         feed_dict={model.input_x: input_x,
                                                    model.dropout_keep_prob: config.dropout_keep_prob})
            print("target_label:", target_label, ";input_sum:", input_sum, "threshold:", threshold,
                  ";prediction:", prediction)
            print("input_x:", input_x, ";logit:", logit)

def generate_label(input_x, threshold):
    """
    generate label with input
    :param input_x: shape of [batch_size, sequence_length]
    :param threshold:
    :return: y:[batch_size]
    """
    batch_size, sequence_length = input_x.shape
    y = np.zeros((batch_size, 2))
    for i in range(batch_size):
        input_single = input_x[i]
        _sum = np.sum(input_single)
        if i == 0: print("sum:", _sum, ";threshold:", threshold)
        y_single = 1 if _sum > threshold else 0
        y[i] = [0, 1] if y_single == 1 else [1, 0]
    return y


n = int(input())
if n > 0:
    a = list(map(int, input().split()))

sum = 0

if not a:
    print(0)
sum  = max([min(i + 1, c) for i, c in enumerate(sorted(a, reverse=True))])

print(sum)


# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

import os

from spack.package import *

class Esmf(MakefilePackage):
    """The Earth System Modeling Framework (ESMF) is high-performance, flexible
    software infrastructure for building and coupling weather, climate, and
    related Earth science applications. The ESMF defines an architecture for
    composing complex, coupled modeling systems and includes data structures
    and utilities for developing individual models."""

    homepage = "https://www.earthsystemcog.org/projects/esmf/"
    url = "https://github.com/esmf-org/esmf/archive/ESMF_8_0_1.tar.gz"
    git = "https://github.com/esmf-org/esmf.git"

    maintainers = ["climbfuji", "jedwards4b"]

    # Develop is a special name for spack and is always considered the newest version
    version("develop", branch="develop")
    version(
        "8.3.0",
        sha256="0ff43ede83d1ac6beabd3d5e2a646f7574174b28a48d1b9f2c318a054ba268fd",
    )
    version("8.3.0b09", commit="5b7e546c4b")
    version(
        "8.2.0",
        sha256="3693987aba2c8ae8af67a0e222bea4099a48afe09b8d3d334106f9d7fc311485",
    )
    version(
        "8.1.1",
        sha256="58c2e739356f21a1b32673aa17a713d3c4af9d45d572f4ba9168c357d586dc75",
    )
    version(
        "8.0.1",
        sha256="9172fb73f3fe95c8188d889ee72fdadb4f978b1d969e1d8e401e8d106def1d84",
    )
    version(
        "8.0.0",
        sha256="051dca45f9803d7e415c0ea146df15ce487fb55f0fce18ca61d96d4dba0c8774",
    )
    version(
        "7.1.0r",
        sha256="ae9a5edb8d40ae97a35cbd4bd00b77061f995c77c43d36334dbb95c18b00a889",
    )

    variant("mpi", default=True, description="Build with MPI support")
    variant(
        "external-lapack",
        default=False,
        description="Build with external LAPACK support",
    )
    variant("netcdf", default=True, description="Build with NetCDF support")
    variant("pnetcdf", default=True, description="Build with pNetCDF support")
    variant("xerces", default=True, description="Build with Xerces support")
    variant(
        "parallelio",
        default=True,
        description="Build with external parallelio library",
        when="@8.3:",
    )
    variant(
        "parallelio",
        default=False,
        description="Build with external parallelio library",
        when="@8.3.b09",
    )
    variant(
        "pio",
        default=True,
        description="Enable Internal ParallelIO support",
        when="@:8.2.99",
    )
    variant(
        "pio",
        default=True,
        description="Enable Internal ParallelIO support",
        when="@8.3.0b09",
    )
    variant("debug", default=False, description="Make a debuggable version of the library")

    # Required dependencies
    depends_on("zlib")
    depends_on("libxml2")

    # Optional dependencies
    depends_on("mpi", when="+mpi")
    depends_on("lapack@3:", when="+external-lapack")
    depends_on("netcdf-c@3.6:", when="+netcdf")
    depends_on("netcdf-fortran@3.6:", when="+netcdf")
    depends_on("parallel-netcdf@1.2.0:", when="+pnetcdf")
    depends_on("xerces-c@3.1.0:", when="+xerces")
    depends_on("parallelio@2.5.8:", when="+parallelio")

    # Testing dependencies
    depends_on("perl", type="test")

    # Make esmf build with newer intel versions
    patch("intel.patch", when="@:7.0 %intel@17:")
    # Make esmf build with newer gcc versions
    # https://sourceforge.net/p/esmf/esmf/ci/3706bf758012daebadef83d6575c477aeff9c89b/
    patch("gcc.patch", when="@:7.0 %gcc@6:")

    # Fix undefined reference errors with mvapich2
    # https://sourceforge.net/p/esmf/esmf/ci/34de0ccf556ba75d35c9687dae5d9f666a1b2a18/
    patch("mvapich2.patch", when="@:7.0")

    # explicit type cast of variables from long to int
    patch("cce.patch", when="@:8.4.0 %cce@13.99:")

    # Allow different directories for creation and
    # installation of dynamic libraries on OSX:
    patch("darwin_dylib_install_name.patch", when="platform=darwin @:7.0")

    # Missing include file for newer gcc compilers
    # https://trac.macports.org/ticket/57493
    patch("cstddef.patch", when="@7.1.0r %gcc@8:")

    # Make script from mvapich2.patch executable
    @when("@:7.0")
    @run_before("build")
    def chmod_scripts(self):
        chmod = which("chmod")
        chmod("+x", "scripts/libs.mvapich2f90")

    def url_for_version(self, version):
        if version < Version("8.0.0"):
            return "http://www.earthsystemmodeling.org/esmf_releases/public/ESMF_{0}/esmf_{0}_src.tar.gz".format(
                version.underscored
            )
        elif version < Version("8.2.1"):
            return "https://github.com/esmf-org/esmf/archive/ESMF_{0}.tar.gz".format(
                version.underscored
            )
        else:
            # Starting with ESMF 8.2.1 releases are now in the form vx.y.z
            return "https://github.com/esmf-org/esmf/archive/refs/tags/v{0}.tar.gz".format(
                version.dotted
            )

    def edit(self, spec, prefix):
        # Installation instructions can be found at:
        # http://www.earthsystemmodeling.org/esmf_releases/last_built/ESMF_usrdoc/node9.html

        # Unset any environment variables that may influence the installation.
        for var in os.environ:
            if var.startswith("ESMF_"):
                os.environ.pop(var)

        ######################################
        # Build and Installation Directories #
        ######################################

        # The environment variable ESMF_DIR must be set to the full pathname
        # of the top level ESMF directory before building the framework.
        os.environ["ESMF_DIR"] = os.getcwd()

        # This variable specifies the prefix of the installation path used
        # with the install target.
        os.environ["ESMF_INSTALL_PREFIX"] = prefix

        # Installation subdirectories default to:
        # bin/binO/Linux.gfortran.64.default.default
        os.environ["ESMF_INSTALL_BINDIR"] = "bin"
        os.environ["ESMF_INSTALL_LIBDIR"] = "lib"
        os.environ["ESMF_INSTALL_MODDIR"] = "include"

        # Allow compiler flags to carry through from compiler spec
        os.environ["ESMF_CXXCOMPILEOPTS"] = " ".join(spec.compiler_flags["cxxflags"])
        os.environ["ESMF_F90COMPILEOPTS"] = " ".join(spec.compiler_flags["fflags"])
        # ESMF will simply not build with Intel using backing GCC 8, in that
        # case you need to point to something older, below is commented but is
        # an example
        # os.environ["ESMF_CXXCOMPILEOPTS"] = \
        #     "-O2 -std=c++11 -gcc-name=/usr/bin/gcc"
        # os.environ["ESMF_F90COMPILEOPTS"] = \
        #     "-O2 -gcc-name=/usr/bin/gcc"

        ############
        # Compiler #
        ############

        # ESMF_COMPILER must be set to select which Fortran and
        # C++ compilers are being used to build the ESMF library.
        if self.compiler.name == "gcc":
            os.environ["ESMF_COMPILER"] = "gfortran"
            gfortran_major_version = int(
                spack.compiler.get_compiler_version_output(self.compiler.fc, "-dumpversion").split(
                    "."
                )[0]
            )
        elif self.compiler.name == "intel":
            os.environ["ESMF_COMPILER"] = "intel"
        elif self.compiler.name in ["clang", "apple-clang"]:
            os.environ["ESMF_COMPILER"] = "gfortranclang"
            gfortran_major_version = int(
                spack.compiler.get_compiler_version_output(self.compiler.fc, "-dumpversion").split(
                    "."
                )[0]
            )
        elif self.compiler.name == "nag":
            os.environ["ESMF_COMPILER"] = "nag"
        elif self.compiler.name == "pgi":
            os.environ["ESMF_COMPILER"] = "pgi"
        elif self.compiler.name == "cce":
            os.environ["ESMF_COMPILER"] = "cce"
        else:
            msg = "The compiler you are building with, "
            msg += '"{0}", is not supported by ESMF.'
            raise InstallError(msg.format(self.compiler.name))

        if "+mpi" in spec:
            os.environ["ESMF_CXX"] = spec["mpi"].mpicxx
            os.environ["ESMF_F90"] = spec["mpi"].mpifc
        else:
            os.environ["ESMF_CXX"] = os.environ["CXX"]
            os.environ["ESMF_F90"] = os.environ["FC"]

        # This environment variable controls the build option.
        if "+debug" in spec:
            # Build a debuggable version of the library.
            os.environ["ESMF_BOPT"] = "g"
        else:
            # Build an optimized version of the library.
            os.environ["ESMF_BOPT"] = "O"

        if self.compiler.name in ["gcc", "clang", "apple-clang"] and gfortran_major_version >= 10:
            os.environ["ESMF_F90COMPILEOPTS"] = "-fallow-argument-mismatch"

        #######
        # OS  #
        #######

        # ESMF_OS must be set for Cray systems
        if "platform=cray" in self.spec:
            os.environ["ESMF_OS"] = "Unicos"

        #######
        # MPI #
        #######

        # ESMF_COMM must be set to indicate which MPI implementation
        # is used to build the ESMF library.
        if "+mpi" in spec:
            if "platform=cray" in self.spec:
                os.environ["ESMF_COMM"] = "mpi"
            elif "^mvapich2" in spec:
                os.environ["ESMF_COMM"] = "mvapich2"
            elif "^mpich" in spec:
                # esmf@7.0.1 does not include configs for mpich3,
                # so we start with the configs for mpich2:
                os.environ["ESMF_COMM"] = "mpich2"
                # The mpich 3 series split apart the Fortran and C bindings,
                # so we link the Fortran libraries when building C programs:
                os.environ["ESMF_CXXLINKLIBS"] = "-lmpifort"
            elif "^openmpi" in spec or "^hpcx-mpi" in spec:
                os.environ["ESMF_COMM"] = "openmpi"
            elif (
                "^intel-parallel-studio+mpi" in spec
                or "^intel-mpi" in spec
                or "^intel-oneapi-mpi" in spec
            ):
                os.environ["ESMF_COMM"] = "intelmpi"
            elif "^mpt" in spec:
                # MPT is the HPE (SGI) variant of mpich
                os.environ["ESMF_COMM"] = "mpt"
        else:
            # Force use of the single-processor MPI-bypass library.
            os.environ["ESMF_COMM"] = "mpiuni"

        ##########
        # LAPACK #
        ##########

        if "+external-lapack" in spec:
            # A system-dependent external LAPACK/BLAS installation is used
            # to satisfy the external dependencies of the LAPACK-dependent
            # ESMF code.
            os.environ["ESMF_LAPACK"] = "system"

            # FIXME: determine whether or not we need to set this
            # Specifies the path where the LAPACK library is located.
            # os.environ["ESMF_LAPACK_LIBPATH"] = spec["lapack"].prefix.lib

            # Specifies the linker directive needed to link the LAPACK library
            # to the application.
            os.environ["ESMF_LAPACK_LIBS"] = spec["lapack"].libs.link_flags  # noqa
        else:
            os.environ["ESMF_LAPACK"] = "internal"

        ##########
        # NetCDF #
        ##########

        if "+netcdf" in spec:
            # ESMF provides the ability to read Grid and Mesh data in
            # NetCDF format.
            os.environ["ESMF_NETCDF"] = "nc-config"
            os.environ["ESMF_NFCONFIG"] = "nf-config"

        ###################
        # Parallel-NetCDF #
        ###################

        if "+pnetcdf" in spec:
            # ESMF provides the ability to write Mesh weights
            # using Parallel-NetCDF.

            # When defined, enables the use of Parallel-NetCDF.
            # ESMF_PNETCDF_LIBS will be set to "-lpnetcdf".
            os.environ["ESMF_PNETCDF"] = "pnetcdf-config"

        ##############
        # ParallelIO #
        ##############
        if "+parallelio" in spec and "+mpi" in spec:
            os.environ["ESMF_PIO"] = "external"
            os.environ["ESMF_PIO_LIBPATH"] = spec["parallelio"].prefix.lib
            os.environ["ESMF_PIO_INCLUDE"] = spec["parallelio"].prefix.include
        elif "+pio" in spec and "+mpi" in spec:
            # ESMF provides the ability to read and write data in both binary
            # and NetCDF formats through ParallelIO (PIO), a third-party IO
            # software library that is integrated in the ESMF library.
            # PIO-dependent features will be enabled and will use the
            # PIO library that is included and built with ESMF.
            os.environ["ESMF_PIO"] = "internal"
        else:
            # Disables PIO-dependent code.
            os.environ["ESMF_PIO"] = "OFF"

        ##########
        # XERCES #
        ##########

        if "+xerces" in spec:
            # ESMF provides the ability to read Attribute data in
            # XML file format via the XERCES C++ library.

            # ESMF_XERCES_LIBS will be set to "-lxerces-c".
            os.environ["ESMF_XERCES"] = "standard"

            # FIXME: determine if the following are needed
            # ESMF_XERCES_INCLUDE
            # ESMF_XERCES_LIBPATH

    @run_after("install")
    def install_findesmf(self):
        install_tree("cmake", self.prefix.cmake)

    def check(self):
        make("check", parallel=False)

    def setup_dependent_build_environment(self, env, dependent_spec):
        env.set("ESMFMKFILE", os.path.join(self.prefix.lib, "esmf.mk"))

    def setup_run_environment(self, env):
        env.set("ESMFMKFILE", os.path.join(self.prefix.lib, "esmf.mk"))


import os
from glob import glob
import re
import sys
from TTS.tts.utils.generic_utils import split_dataset

def load_meta_data(datasets):
	meta_data_train_all = []
	meta_data_eval_all = []
	for dataset in datasets:
		name = dataset['name']
		root_path = dataset['path']
		meta_file_train = dataset['meta_file_train']
		meta_file_val = dataset['meta_file_val']
		preprocessor = get_preprocessor_by_name(name)

		meta_data_train = preprocessor(root_path, meta_file_train)
		if meta_file_val is None:
			meta_data_eval, meta_data_train = split_dataset(meta_data_train)
		else:
			meta_data_eval = preprocessor(root_path, meta_file_val)
		meta_data_train_all += meta_data_train
		meta_data_eval_all += meta_data_eval
	return meta_data_train_all, meta_data_eval_all

def get_preprocessor_by_name(name):
	"""Returns the respective preprocessing function."""
	thismodule = sys.modules[__name__]
	return getattr(thismodule, name.lower())

def tweb(root_path, meta_file):
	"""Normalize TWEB dataset.
	https://www.kaggle.com/bryanpark/the-world-english-bible-speech-dataset
	"""
	txt_file = os.path.join(root_path, meta_file)
	items = []
	speaker_name = "tweb"
	with open(txt_file, 'r') as ttf:
		for line in ttf:
			cols = line.split('\t')
			wav_file = os.path.join(root_path, cols[0] + '.wav')
			text = cols[1]
			items.append([text, wav_file, speaker_name])
	return items

# def kusal(root_path, meta_file):
#     txt_file = os.path.join(root_path, meta_file)
#     texts = []
#     wavs = []
#     with open(txt_file, "r", encoding="utf8") as f:
#         frames = [
#             line.split('\t') for line in f
#             if line.split('\t')[0] in self.wav_files_dict.keys()
#         ]
#     # TODO: code the rest
#     return  {'text': texts, 'wavs': wavs}

def mozilla(root_path, meta_file):
	"""Normalizes Mozilla meta data files to TTS format"""
	txt_file = os.path.join(root_path, meta_file)
	items = []
	speaker_name = "mozilla"
	with open(txt_file, 'r') as ttf:
		for line in ttf:
			cols = line.split('|')
			wav_file = cols[1].strip()
			text = cols[0].strip()
			wav_file = os.path.join(root_path, "wavs", wav_file)
			items.append([text, wav_file, speaker_name])
	return items

def mozilla_de(root_path, meta_file):
	"""Normalizes Mozilla meta data files to TTS format"""
	txt_file = os.path.join(root_path, meta_file)
	items = []
	speaker_name = "mozilla"
	with open(txt_file, 'r', encoding="ISO 8859-1") as ttf:
		for line in ttf:
			cols = line.strip().split('|')
			wav_file = cols[0].strip()
			text = cols[1].strip()
			folder_name = f"BATCH_{wav_file.split('_')[0]}_FINAL"
			wav_file = os.path.join(root_path, folder_name, wav_file)
			items.append([text, wav_file, speaker_name])
	return items

def mailabs(root_path, meta_files=None):
	"""Normalizes M-AI-Labs meta data files to TTS format"""
	speaker_regex = re.compile("by_book/(male|female)/(?P<speaker_name>[^/]+)/")
	if meta_files is None:
		csv_files = glob(root_path + "/**/metadata.csv", recursive=True)
	else:
		csv_files = meta_files
	# meta_files = [f.strip() for f in meta_files.split(",")]
	items = []
	for csv_file in csv_files:
		txt_file = os.path.join(root_path, csv_file)
		folder = os.path.dirname(txt_file)
		# determine speaker based on folder structure...
		speaker_name_match = speaker_regex.search(txt_file)
		if speaker_name_match is None:
			continue
		speaker_name = speaker_name_match.group("speaker_name")
		print(" | > {}".format(csv_file))
		with open(txt_file, 'r') as ttf:
			for line in ttf:
				cols = line.split('|')
				if meta_files is None:
					wav_file = os.path.join(folder, 'wavs', cols[0] + '.wav')
				else:
					wav_file = os.path.join(root_path, folder.replace("metadata.csv", ""), 'wavs', cols[0] + '.wav')
				if os.path.isfile(wav_file):
					text = cols[1].strip()
					items.append([text, wav_file, speaker_name])
				else:
					raise RuntimeError("> File %s does not exist!" % (wav_file))
	return items

def ljspeech(root_path, meta_file):
	"""Normalizes the Nancy meta data file to TTS format"""
	txt_file = os.path.join(root_path, meta_file)
	items = []
	speaker_name = "ljspeech"
	with open(txt_file, 'r') as ttf:
		for line in ttf:
			cols = line.split('|')
			wav_file = os.path.join(root_path, 'wavs', cols[0] + '.wav')
			text = cols[1]
			items.append([text, wav_file, speaker_name])
	return items

def nancy(root_path, meta_file):
	"""Normalizes the Nancy meta data file to TTS format"""
	txt_file = os.path.join(root_path, meta_file)
	items = []
	speaker_name = "nancy"
	with open(txt_file, 'r') as ttf:
		for line in ttf:
			utt_id = line.split()[1]
			text = line[line.find('"') + 1:line.rfind('"') - 1]
			wav_file = os.path.join(root_path, "wavn", utt_id + ".wav")
			items.append([text, wav_file, speaker_name])
	return items

def common_voice(root_path, meta_file):
	"""Normalize the common voice meta data file to TTS format."""
	txt_file = os.path.join(root_path, meta_file)
	items = []
	with open(txt_file, 'r') as ttf:
		for line in ttf:
			if line.startswith("client_id"):
				continue
			cols = line.split("\t")
			text = cols[2]
			speaker_name = cols[0]
			wav_file = os.path.join(root_path, "clips", cols[1] + ".wav")
			items.append([text, wav_file, speaker_name])
	return items

def libri_tts(root_path, meta_files=None):
	"""https://ai.google/tools/datasets/libri-tts/"""
	items = []
	if meta_files is None:
		meta_files = glob(f"{root_path}/**/*trans.tsv", recursive=True)
	for meta_file in meta_files:
		_meta_file = os.path.basename(meta_file).split('.')[0]
		speaker_name = _meta_file.split('_')[0]
		chapter_id = _meta_file.split('_')[1]
		_root_path = os.path.join(root_path, f"{speaker_name}/{chapter_id}")
		with open(meta_file, 'r') as ttf:
			for line in ttf:
				cols = line.split('\t')
				wav_file = os.path.join(_root_path, cols[0] + '.wav')
				text = cols[1]
				items.append([text, wav_file, speaker_name])
	for item in items:
		assert os.path.exists(item[1]), f" [!] wav files don't exist - {item[1]}"
	return items

def aishell_3(root_path, meta_file):
	items = []
	with open(os.path.join(root_path, meta_file), "r", encoding="utf-8") as f:
		while 1:
			line = f.readline()
			if not line:
				break
			filename, text = line.split("|")
			speaker_name = filename[:7]
			wav_file = os.path.join(root_path, meta_file.split("/")[0], "wav", speaker_name, filename + ".wav")
			items.append([text, wav_file, 'AISHELL_' + speaker_name])
	return items

def private_data(root_path, meta_file):
	items = []
	with open(os.path.join(root_path, meta_file), "r", encoding="utf-8") as f:
		while 1:
			line = f.readline()
			if not line:
				break
			filename, text = line.split("|")
			speaker_name = filename.split("_")[0]
			wav_file = os.path.join(root_path, "wavs", speaker_name, filename + ".wav")
			items.append([text, wav_file, 'private_' + speaker_name])
	return items

def m2voc(root_path, meta_file):
	items = []
	speakers = os.listdir(root_path)
	for speaker in speakers:
		with open(os.path.join(root_path, speaker, meta_file), "r", encoding="utf-8") as f:
			while 1:
				line = f.readline()
				if not line:
					break
				filename, text = line.split("|")
				speaker_name, _ = filename.split("_")
				assert speaker == speaker_name
				wav_file = os.path.join(root_path, speaker, "wavs", filename + ".wav")
				items.append([text, wav_file, 'm2voc_' + speaker_name])
	return items

def jiang(root_path, meta_file):
	items = []
	with open(os.path.join(root_path, meta_file), "r", encoding="utf-8") as f:
		while 1:
			line = f.readline()
			if not line:
				break
			filename, text = line.split("|")
			speaker_name = "jiang"
			wav_file = os.path.join(root_path, "wav", speaker_name, filename + ".wav")
			items.append([text, wav_file, speaker_name])
	return items

def baker(root_path, meta_file):
	txt_file = os.path.join(root_path, meta_file)
	items = []
	speaker_name = "baker"
	with open(txt_file, 'r') as ttf:
		for line in ttf:
			cols = line.split('|')
			wav_file = os.path.join(root_path, 'wavs', cols[0] + '.wav')
			text = cols[1]
			items.append([text, wav_file, speaker_name])
	return items

def niuman(root_path, meta_file):
	txt_file = os.path.join(root_path, meta_file)
	items = []
	speaker_name = "niuman"
	with open(txt_file, 'r') as ttf:
		for line in ttf:
			cols = line.split('|')
			wav_file = os.path.join(root_path, 'wavs', cols[0] + '.wav')
			text = cols[1]
			items.append([text, wav_file, speaker_name])
	return items

def haitian(root_path, meta_file):
	txt_file = os.path.join(root_path, meta_file)
	items = []
	speaker_name = "haitian031"
	with open(txt_file, 'r') as ttf:
		for line in ttf:
			cols = line.split('|')
			wav_file = os.path.join(root_path, 'wavs_multi', cols[0] + '.wav')
			text = cols[1]
			items.append([text, wav_file, speaker_name])
	return items

def custom_turkish(root_path, meta_file):
	txt_file = os.path.join(root_path, meta_file)
	items = []
	speaker_name = "turkish-female"
	skipped_files = []
	with open(txt_file, 'r', encoding='utf-8') as ttf:
		for line in ttf:
			cols = line.split('|')
			wav_file = os.path.join(root_path, 'wavs', cols[0].strip() + '.wav')
			if not os.path.exists(wav_file):
				skipped_files.append(wav_file)
				continue
			text = cols[1].strip()
			items.append([text, wav_file, speaker_name])
	print(f" [!] {len(skipped_files)} files skipped. They don't exist...")
	return items

# ToDo: add the dataset link when the dataset is released publicly
def brspeech(root_path, meta_file):
	'''BRSpeech 3.0 beta'''
	txt_file = os.path.join(root_path, meta_file)
	items = []
	with open(txt_file, 'r') as ttf:
		for line in ttf:
			if line.startswith("wav_filename"):
				continue
			cols = line.split('|')
			# print(cols)
			wav_file = os.path.join(root_path, cols[0])
			text = cols[2]
			speaker_name = cols[3]
			items.append([text, wav_file, speaker_name])
	return items

def vctk(root_path, meta_files=None, wavs_path='wav48'):
	"""homepages.inf.ed.ac.uk/jyamagis/release/VCTK-Corpus.tar.gz"""
	test_speakers = meta_files
	items = []
	meta_files = glob(f"{os.path.join(root_path, 'txt')}/**/*.txt", recursive=True)
	for meta_file in meta_files:
		_, speaker_id, txt_file = os.path.relpath(meta_file, root_path).split(os.sep)
		file_id = txt_file.split('.')[0]
		if isinstance(test_speakers, list):  # if is list ignore this speakers ids
			if speaker_id in test_speakers:
				continue
		with open(meta_file) as file_text:
			text = file_text.readlines()[0]
		wav_file = os.path.join(root_path, wavs_path, speaker_id, file_id + '.wav')
		items.append([text, wav_file, speaker_id])

	return items


import matplotlib.pyplot as plt
import math

def analitica(A,B,t):
    k = 1
    m = 1
    a = -(math.sqrt(k/m))

    return A * math.cos(a*t) + B * math.sin(a*t)

def euler():
    aproxER = []
    real = []

    t = 0
    atualV = 0
    atualX = 1
    k = m = 1
    a = -(k/m)
    dt = 0.1
    res = 0.1

    for i in range(0,100):
        proxV = atualV + a*atualX*dt - res*atualX
        proxX = atualX + atualV*dt
        ana = analitica(1,1,dt*i)
        real.append(ana)
        aproxER.append(proxX)
        atualV = proxV
        atualX = proxX

    return aproxER

def main():
    aproxE = []
    real = []

    t = 0
    atualV = 0
    atualX = 1
    k = m = 1
    a = -(k/m)
    dt = 0.1
    res = 0.1

    for i in range(0,100):
        print(atualX)
        proxV = atualV + a*atualX*dt - res*atualX
        proxX = atualX + atualV*dt
        ana = analitica(1,1,dt*i)
        real.append(ana)
        print(proxX)
        aproxE.append(proxX)
        atualV = proxV
        atualX = proxX

    plt.plot(real, color = 'red', label = 'Analitica')
    plt.plot(aproxE, color = 'blue', label = 'Método de Euler')
    plt.grid(True)
    plt.xlabel('x = Tempo (s)')
    plt.ylabel('y = Posição (m)')
    plt.legend(loc = 'upper left')
    plt.show()

main()