# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3393)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /home/stephan/.virtualenvs/drf_amsterdam/lib/python3.7/site-packages/tests/models.py
"""Test models."""
from django.contrib.gis.db import models

class WeatherStation(models.Model):
    number = models.IntegerField(unique=True)
    centroid = models.PointField(name='centroid', srid=4326)
    centroid_rd = models.PointField(name='centroid_rd', srid=28992)

    def __str__(self):
        return 'DISPLAY FIELD CONTENT'

class TemperatureRecord(models.Model):

    class Meta:
        unique_together = ('station', 'date')

    station = models.ForeignKey(WeatherStation, on_delete=(models.CASCADE))
    date = models.DateField()
    temperature = models.DecimalField(decimal_places=3, max_digits=6)


import httplib2
import oauth2client
import os

from apiclient import discovery
from datetime import datetime, timedelta
from oauth2client import client, tools

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-<app_short_name>.json
SCOPES = {'all': 'https://www.googleapis.com/auth/calendar',
          'readonly': 'https://www.googleapis.com/auth/calendar.readonly'}
SOCCER_DIR = os.path.join(os.path.expanduser('/Users/sutedja'), 'play', 'soccer')
CLIENT_SECRET_FILE = os.path.join(SOCCER_DIR, 'client_secret.json')

def get_scope(scope_level):
    return SCOPES.get(scope_level, SCOPES['readonly'])

def get_credentials(application_name_tup, scope_level, client_secret_file=None):
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    full_name, short_name = application_name_tup
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'calendar-{}.json'.format(short_name))

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        scope = get_scope(scope_level)
        client_secret_file = client_secret_file or CLIENT_SECRET_FILE
        flow = client.flow_from_clientsecrets(client_secret_file, scope)
        flow.user_agent = full_name
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def get_calendar_service(application_name_tup, scope_level, client_secret_file=None):
    """
    Creates a Google Calendar API service object.
    """
    credentials = get_credentials(application_name_tup, scope_level, client_secret_file=client_secret_file)
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)
    return service

def list_calendars(service):
    clist = service.calendarList().list(pageToken=None).execute()
    return [(c['summary'], c['id']) for c in clist['items']]

def create_event(service, calendar_id, event):
    """
    https://developers.google.com/google-apps/calendar/create-events
    """
    create = service.events().insert(calendarId=calendar_id, body=event).execute()
    return create

def get_event(service, calendar_id, event_id):
    event_id = event_id.replace('@google.com', '')
    return service.events().get(calendarId=calendar_id, eventId=event_id).execute()

def delete_event(service, calendar_id, event_id, logger=None):
    event_id = event_id.replace('@google.com', '')
    if logger:
        to_delete = get_event(service, calendar_id, event_id)
        logger.info("Deleting {}".format(to_delete['summary']))
    return service.events().delete(calendarId=calendar_id, eventId=event_id).execute()

def get_past_events_id_list(service, calendar_id, time_max=None):
    if not time_max:
        time_max = (datetime.utcnow() - timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%SZ')
    past_events = service.events().list(calendarId=calendar_id, timeMax=time_max).execute()['items']
    return [x['iCalUID'] for x in past_events]

def get_future_events(service, calendar_id, time_min=None):
    if not time_min:
        time_min = (datetime.utcnow() - timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%SZ')
    past_events = service.events().list(calendarId=calendar_id, timeMin=time_min).execute()['items']
    return past_events

def delete_all_events(service, calendar_id):
    all_events = service.events().list(calendarId=calendar_id).execute()['items']
    event_id_list = [x['iCalUID'] for x in all_events]
    for event_id in event_id_list:
        event_id = event_id.replace('@google.com', '')
        service.events().delete(calendarId=calendar_id, eventId=event_id).execute()


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

__all__ = ['Planet']

class Planet():
    """
    The class called Planet is initialised with constants appropriate
    for the given target planet, including the atmospheric density profile
    and other constants.
    """

    def __init__(self, atmos_func='exponential', atmos_filename=None,
                 Cd=1., Ch=0.1, Q=1e7, Cl=1e-3, alpha=0.3, Rp=6371e3,
                 g=9.81, H=8000., rho0=1.2, fragmentation=True, num_scheme='RK', ensemble=False):
        """
        Set up the initial parameters and constants for the target planet

        Parameters
        ----------

        atmos_func : string, optional
            Function which computes atmospheric density, rho, at altitude, z.
            Default is the exponential function ``rho = rho0 exp(-z/H)``.
            Options are ``exponential``, ``tabular``, ``constant`` and ``mars``

        atmos_filename : string, optional
            If ``atmos_func`` = ``'tabular'``, then set the filename of the table
            to be read in here.

        Cd : float, optional
            The drag coefficient

        Ch : float, optional
            The heat transfer coefficient

        Q : float, optional
            The heat of ablation (J/kg)

        Cl : float, optional
            Lift coefficient

        alpha : float, optional
            Dispersion coefficient

        Rp : float, optional
            Planet radius (m)

        rho0 : float, optional
            Air density at zero altitude (kg/m^3)

        g : float, optional
            Surface gravity (m/s^2)

        H : float, optional
            Atmospheric scale height (m)

        Returns
        -------
        None
        """
        # Input constants
        self.Cd = Cd
        self.Ch = Ch
        self.Q = Q
        self.Cl = Cl
        self.alpha = alpha
        self.Rp = Rp
        self.g = g
        self.H = H
        self.rho0 = rho0

        if atmos_func == 'exponential':
            self.rhoa = lambda x: rho0 * np.exp(-x/self.H)
        elif atmos_func == 'tabular':
            #BASE_PATH = os.path.dirname(os.path.dirname(__file__))
            #atmos_filename = os.sep.join((BASE_PATH,'/data/AltitudeDensityTable.csv'))
            table = pd.read_csv(atmos_filename, header=None, delim_whitespace=True, skiprows=6)
            #'Altitude':table.iloc[:,0],'Density':iloc[:,1],'Scale_Height':iloc[:,2]
            self.rhoa = lambda x: table.iloc[int(x/10),1]*np.exp((table.iloc[int(x/10),0]-x)/table.iloc[int(x/10),2])

        elif atmos_func == 'mars':
            self.rhoa = lambda x: 0.699*np.exp(-0.00009*x)/(0.1921*((249.7-0.00222*x)*(x>=7000)+(242.1-0.000998*x)*(x<7000)))
        elif atmos_func == 'constant':
            self.rhoa = lambda x: rho0
        else:
            raise NotImplementedError

    def impact(self, radius, velocity, density, strength, angle,
               init_altitude=100e3, dt=0.05, radians=False,
               fragmentation=True, num_scheme='RK', ensemble=False):
        """
        Solve the system of differential equations for a given impact event.
        Also calculates the kinetic energy lost per unit altitude and
        analyses the result to determine the outcome of the impact.

        Parameters
        ----------

        radius : float
            The radius of the asteroid in meters

        velocity : float
            The entery speed of the asteroid in meters/second

        density : float
            The density of the asteroid in kg/m^3

        strength : float
            The strength of the asteroid (i.e., the ram pressure above which
            fragmentation and spreading occurs) in N/m^2 (Pa)

        angle : float
            The initial trajectory angle of the asteroid to the horizontal
            By default, input is in degrees. If 'radians' is set to True, the
            input should be in radians

        init_altitude : float, optional
            Initial altitude in m

        dt : float, optional
            The output timestep, in s

        radians : logical, optional
            Whether angles should be given in degrees or radians. Default=False
            Angles returned in the DataFrame will have the same units as the
            input

        Returns
        -------

        Result : DataFrame
            A pandas DataFrame containing the solution to the system.
            Includes the following columns:
            ``velocity``, ``mass``, ``angle``, ``altitude``,
            ``distance``, ``radius``, ``time``, ``dedz``

        outcome : Dict
            dictionary with details of airburst and/or cratering event.
            For an airburst, this will contain the following keys:
            ``burst_peak_dedz``, ``burst_altitude``, ``burst_total_ke_lost``.

            For a cratering event, this will contain the following keys:
            ``impact_time``, ``impact_mass``, ``impact_speed``.

            All events should also contain an entry with the key ``outcome``,
            which should contain one of the following strings:
            ``Airburst``, ``Cratering`` or ``Airburst and cratering``
        """

        result = self.solve_atmospheric_entry(radius, velocity, density, strength, angle,
        init_altitude, dt, radians, fragmentation, num_scheme, ensemble)
        result = self.calculate_energy(result)
        outcome = self.analyse_outcome(result)

        return result, outcome

    def solve_atmospheric_entry(
            self, radius, velocity, density, strength, angle,
            init_altitude=100e3, dt=0.05, radians=False,
            fragmentation=True, num_scheme='RK', ensemble=False):
        """
        Solve the system of differential equations for a given impact scenario

        Parameters
        ----------

        radius : float
            The radius of the asteroid in meters

        velocity : float
            The entery speed of the asteroid in meters/second

        density : float
            The density of the asteroid in kg/m^3

        strength : float
            The strength of the asteroid (i.e., the ram pressure above which
            fragmentation and spreading occurs) in N/m^2 (Pa)

        angle : float
            The initial trajectory angle of the asteroid to the horizontal
            By default, input is in degrees. If 'radians' is set to True, the
            input should be in radians

        init_altitude : float, optional
            Initial altitude in m

        dt : float, optional
            The output timestep, in s

        radians : logical, optional
            Whether angles should be given in degrees or radians. Default=False
            Angles returned in the DataFrame will have the same units as the
            input

        Returns
        -------
        Result : DataFrame
            A pandas DataFrame containing the solution to the system.
            Includes the following columns:
            ``velocity``, ``mass``, ``angle``, ``altitude``,
            ``distance``, ``radius``, ``time``
        """
        num_scheme_dict = {
            'EE': self.explicit_euler,
            'IE': self.implicit_euler,
            'MIE': self.midpoint_implicit_euler,
            'RK': self.runge_kutta
            }
        if ensemble is True:
            num_scheme = 'EE'
        if radians is False: # converts degrees to radians
            angle = angle * (np.pi)/180

        T = 12000 # max duration of simulation in seconds
        T_arr = [] # list to store the all timesteps
        t = 0 # inital time assumed to be zero
        T_arr.append(0) # storing first time

        mass = density * 4/3 * radius**3 * np.pi # defining the mass of astroid assuming a sphere shape
        init_distance = 0 # intial distance assumed to be zero
        y = np.array([velocity, mass, angle, init_altitude, init_distance, radius]) # defining initial condition array

        Y = [] # empty list to store solution array for every timestep
        Y.append(y) # store initial condition
        while t <= T: # initiate timeloop

            if strength <= (self.rhoa(y[3]) * y[0]**2) and fragmentation is True:
                fragmented = True # define status of fragmentation
            else:
                fragmented = False

            y_next = num_scheme_dict[num_scheme](y, self.f, dt, fragmented, density) # compute values for next timestep

            if ensemble is True and y[2] > (89 * np.pi/180): # for purpose of ensemble: break after airburst
                break

            if y_next[1] <= 0 or y_next[3] <= 0: # stop simulation if mass or altitude become zero
                break

            t += dt
            T_arr.append(t) # store new timestep

            Y.append(y_next) #store caomputed values
            y = y_next

        Y = np.array(Y)

        if radians is False:
            Y[:, 2] = np.round_(list(map(lambda x: x * 180/np.pi, Y[:, 2])), decimals=10)

        return pd.DataFrame({'velocity': Y[:, 0], # return all the stored values in pd.DataFrame
                             'mass': Y[:, 1],
                             'angle': Y[:, 2],
                             'altitude': Y[:, 3],
                             'distance': Y[:, 4],
                             'radius': Y[:, 5],
                             'time': T_arr})#, index=range(1))

    def calculate_energy(self, result):
        """
        Function to calculate the kinetic energy lost per unit altitude in
        kilotons TNT per km, for a given solution.

        Parameters
        ----------

        result : DataFrame
            A pandas DataFrame with columns for the velocity, mass, angle,
            altitude, horizontal distance and radius as a function of time

        Returns
        -------

        Result : DataFrame
            Returns the DataFrame with additional column ``dedz`` which is the
            kinetic energy lost per unit altitude
        """
        dedz_vec = np.zeros(len(result)) # create array to store dedz results
        velocity = np.array(result.velocity)
        mass = np.array(result.mass)
        altitude = np.array(result.altitude)

        # get dedz as released energy per altitude
        ke = ((1/2 * mass[1:] * velocity[1:]**2) - (1/2 * mass[:-1] * velocity[:-1]**2)) / 4.184e12
        alt = (altitude[1:] - altitude[:-1]) / 1e3 # get kinetic energy and altitude differnces between timesteps
        dedz_vec[1:] = ke / alt # devide energy over altitude, note the first entry stays zero
        i = np.where(dedz_vec < 0) # turn all negative value to zero
        dedz_vec[i] = 0
        '''
        dedz = np.zeros(len(result)) # create array to store dedz results
        for i in range(1,len(result)): # loop through all rows of result
            energy = ((1/2 * result.mass[i] * result.velocity[i]**2) - (1/2 *result.mass[i-1] * result.velocity[i-1]**2))/4.184e12
            alt = (result.altitude[i] - result.altitude[i-1])/1e3
            dedz[i] = energy / alt
            if dedz[i] < 0:
                dedz[i] = 0'''
        #print('Vectorisation of calculate_energy(): ', np.allclose(dedz, dedz_vec))

        result.insert(len(result.columns), 'dedz', dedz_vec) # add dedz to DataFrame 'result'

        return result

    def analyse_outcome(self, result):
        """
        Inspect a prefound solution to calculate the impact and airburst stats

        Parameters
        ----------

        result : DataFrame
            pandas DataFrame with velocity, mass, angle, altitude, horizontal
            distance, radius and dedz as a function of time

        Returns
        -------

        outcome : Dict
            dictionary with details of airburst and/or cratering event.
            For an airburst, this will contain the following keys:
            ``burst_peak_dedz``, ``burst_altitude``, ``burst_total_ke_lost``.

            For a cratering event, this will contain the following keys:
            ``impact_time``, ``impact_mass``, ``impact_speed``.

            All events should also contain an entry with the key ``outcome``,
            which should contain one of the following strings:
            ``Airburst``, ``Cratering`` or ``Airburst and cratering``
        """
        outcome = {} # set empty dictionary
        event = 0 # set classifying index to zero

        index_max = result.dedz.idxmax() # determine index at which airburst happens
        if result.altitude[index_max] > 0: # check for Airburst
            burst_peak_dedz = result.dedz[index_max] # released energy at airbusrt
            burst_altitude = result.altitude[index_max] # altitude of airburst
            burst_total_ke_lost = (1/2 * ((result.mass[0] * result.velocity[0]**2) - (result.mass[index_max] * result.velocity[index_max]**2))) / 4.184e12
            # above is: total released energy
            # add the above three parameters to dictionary below
            outcome['burst_peak_dedz'] = burst_peak_dedz
            outcome['burst_altitude'] = burst_altitude
            outcome['burst_total_ke_lost'] = burst_total_ke_lost

            event += 1 # increase classifying index to by one

        if result.altitude[index_max] <= 5000: # check for Cratering with mass being zero when simulation is finished
            impact_time = result.time.iloc[-1] # difference in seconds between entering atmosphere and impact
            impact_mass = result.mass.iloc[-1] #
            impact_speed = result.velocity.iloc[-1]

            outcome['impact_time'] = impact_time
            outcome['impact_mass'] = impact_mass
            outcome['impact_speed'] = impact_speed

            event += 2 # increase classifying index to by two

        if event == 1:
            outcome['outcome'] = 'Airburst'
        elif event == 2:
            outcome['outcome'] = 'Cratering'
        elif event == 3:
            outcome['outcome'] = 'Airburst and cratering'
        else:
            raise ValueError
        return outcome

    def f(self, y, fragmented, density):
        '''
        0: velocity
        1: mass
        2: angle
        3: altitude
        4: distance
        5: radius
        '''
        f = np.zeros_like(y)
        f[0] = - (self.Cd * self.rhoa(y[3]) * y[0]**2 * np.pi * y[5]**2) / (2 * y[1]) + (self.g * np.sin(y[2]))
        f[1] = - (self.Ch * self.rhoa(y[3]) * np.pi * y[5]**2 * y[0]**3) / (2 * self.Q)
        f[2] = (self.g * np.cos(y[2])) / y[0]  - (self.Cl * self.rhoa(y[3]) * np.pi * y[5]**2 * y[0]) / (2 * y[1]) - (y[0] * np.cos(y[2])) / (self.Rp + y[3])
        f[3] = - y[0] * np.sin(y[2])
        f[4] = (y[0] * np.cos(y[2])) / (1 + y[3] / self.Rp)
        if fragmented == True:
            f[5] = np.sqrt(7/2 * self.alpha * self.rhoa(y[3]) / density) * y[0]
        else:
            f[5] = 0
        return f

    def explicit_euler(self, y, f, dt, fragmented, density):
        y1 = y + f(y, fragmented, density) * dt
        return y1

    def implicit_euler(self, y, f, dt, fragmented, density):
        y_dummy = y + f(y, fragmented, density) * dt
        y = y + f(y_dummy, fragmented, density) * dt
        return y

    def midpoint_implicit_euler(self, y, f, dt, fragmented, density):
        y_dummy = y + f(y, fragmented, density) * dt
        y = y + (f(y, fragmented, density) + f(y_dummy, fragmented, density)) * 0.5 * dt
        return y

    def runge_kutta(self, y, f, dt, fragmented, density):
        k1 = f(y, fragmented, density) * dt
        k2 = f(y+k1/2, fragmented, density) * dt
        k3 = f(y+k2/2, fragmented, density) * dt
        k4 = f(y+k3, fragmented, density) * dt

        y = y + (k1 + 2 * (k2 + k3) + k4) / 6
        return y

    def plot_results(self, result):
        fig = plt.figure(figsize=(12, 8))
        fig.tight_layout()
        ax1 = plt.subplot(321)
        ax2 = plt.subplot(322)
        ax3 = plt.subplot(323)
        ax4 = plt.subplot(324)
        ax5 = plt.subplot(325)
        ax6 = plt.subplot(326)

        ax1.scatter(result.altitude, result.time, marker='.', color='r')
        #ax1.set_xlabel('altitude [m]')
        ax1.set_ylabel('time [s]')
        ax1.grid()

        ax2.scatter(result.altitude, result.velocity, marker='.', color='r')
        #ax2.set_xlabel('altitude [m]')
        ax2.set_ylabel('velocity [m/s]')
        ax2.grid()

        ax3.scatter(result.altitude, result.dedz, marker='.', color='r')
        #ax3.set_xlabel('altitude [m]')
        ax3.set_ylabel('dedz [kT-TNT/km]')
        ax3.grid()

        ax4.scatter(result.altitude, result.mass, marker='.', color='r')
        #ax4.set_xlabel('altitude [m]')
        ax4.set_ylabel('mass [kg]')
        ax4.grid()

        ax5.scatter(result.altitude, result.radius, marker='.', color='r')
        ax5.set_xlabel('altitude [m]')
        ax5.set_ylabel('radius [m]')
        ax5.grid()

        ax6.scatter(result.altitude, result.angle, marker='.', color='r')
        ax6.set_xlabel('altitude [m]')
        ax6.set_ylabel('angle [°]')
        ax6.grid()

        plt.show()


#encoding:utf-8
import datetime

from django.utils import simplejson
from django.db.models import Q

from dajaxice.decorators import dajaxice_register
from dajaxice.utils import deserialize_form
from dajax.core import Dajax

from Programas.models import TipoSeguro, SubTipoSeguro, Programa, Cobertura, CoberturaPrograma, AreaInfluenciaPrograma
from ConexosAgropecuarios.models import AreaInfluencia, Municipio, Persona
from Programas.forms import ProgramaForm
from ConexosAgropecuarios.models import ContratoFondo,Moneda
from Cotizador.models import Cotizador

@dajaxice_register
def cargar_Combo_TipoSeguro(request): # Método que busca los tipos de seguro y los carga en el combo IdTipoSeguro.
    dajax = Dajax()
    tiposSeguros = TipoSeguro.objects.using('catalogos').all()

    out = []
    out.append("<option value='#'>%s</option>" % "---------")
    for tipo in tiposSeguros:
        out.append("<option value='" + str(tipo.IdTipoSeguro) + "'>%s</option>" % tipo.DescripcionTipoSeguro)

    dajax.assign('#IdTipoSeguro', 'innerHTML', ''.join(out))

    return dajax.json()

@dajaxice_register
def cargar_Combo_SubTipoSeguro(request, idTipoSeguro): # Método que busca los sub tipos de seguro pasandole el id del tipo de seguro
    dajax = Dajax()
    subTipoSeguros = SubTipoSeguro.objects.using('catalogos').filter(TipoSeguro_id = idTipoSeguro)

    out = []
    for subTipo in subTipoSeguros:
        out.append("<option value='" + str(subTipo.IdSubTipoSeguro) + "'>%s</option>" % subTipo.DescripcionSubTipoSeguro)

    dajax.assign('#IdSubTipoSeguro', 'innerHTML', ''.join(out))

    return dajax.json()

@dajaxice_register
def cargar_Combo_Coberturas(request, idTipoSeguro): # Método que busca las coberturas ligadas al id tipo seguro.
    dajax = Dajax()
    try:
        coberturasTipoSeguro = Cobertura.objects.using('catalogos').filter(TipoSeguro_id = idTipoSeguro)
        datos = list()

        for cobertura in coberturasTipoSeguro:
            datos.append({'IdCobertura':cobertura.IdCobertura, 'Descripcion':cobertura.Descripcion})

    except:
        return dajax.json()

    return simplejson.dumps({'coberturas':datos})

@dajaxice_register
def guardar_programas(request, formulario, coberturas, folio, areaInfluencia):# Método que recibe el formulario de programas obtenido de programa.html y lo deserializa para obtener la información de sus controles y lo valida con ProgramaForm, si la información es valida guarda los datos y limpia los controles del formulario mediante una función de js.
    dajax = Dajax()

    formulario_deserializado = deserialize_form(formulario)

    datos = {'IdTipoSeguro':formulario_deserializado.get('IdTipoSeguro'), 'IdSubTipoSeguro':formulario_deserializado.get('IdSubTipoSeguro'),
             'IdTipoMoneda':formulario_deserializado.get('IdTipoMoneda'), 'Ejercicio':formulario_deserializado.get('Ejercicio'),
             'Observaciones':formulario_deserializado.get('Observaciones'), 'PersonaHabilitador': formulario_deserializado.get('varIdHabilitador')}
    formulario = ProgramaForm(datos)

    if formulario.is_valid():

        if formulario_deserializado.get('varIdPrograma') == '':

            fechaPrograma = datetime.datetime.now()

            programaAGuardar = Programa(IdTipoSeguro = formulario_deserializado.get('IdTipoSeguro'), IdSubTipoSeguro = formulario_deserializado.get('IdSubTipoSeguro'),
                                      IdTipoMoneda = formulario_deserializado.get('IdTipoMoneda'), Ejercicio = formulario_deserializado.get('Ejercicio'),
                                      FechaPrograma = fechaPrograma, Observaciones = formulario_deserializado.get('Observaciones').upper(),
                                      IdContratoFondo = formulario_deserializado.get('IdContratoFondo'), Utilizado = 0, PersonaHabilitador_id = formulario_deserializado.get('varIdHabilitador'))
            programaAGuardar.save()

            folioAGuardar = folio.upper() + str(programaAGuardar.IdPrograma)

            Programa.objects.filter(IdPrograma = programaAGuardar.IdPrograma).update(FolioPrograma = folioAGuardar)

            for cobertura in coberturas:
                guardarCoberturas(cobertura, programaAGuardar.IdPrograma)

            for area in areaInfluencia:
                guardarAreaInfluencia(area, programaAGuardar.IdPrograma)

            dajax.add_data(folioAGuardar, 'mensajePrograma')

        else:
            actualizar_programa(formulario_deserializado, coberturas, areaInfluencia)
            dajax.script('manejadorMensajes(2);')

    else:
        dajax.alert('El formulario es invalido')

    return dajax.json()

def guardarCoberturas(cobertura, idPrograma): # Método que permite guardar las coberturas en la base de datos pasando el id del programa para enlazar.
    dajax = Dajax()

    cuberturaAGuardar = CoberturaPrograma(Programa_id = idPrograma, IdCobertura = cobertura)
    cuberturaAGuardar.save()

    return dajax.json()

def guardarAreaInfluencia(area, idPrograma): # Método que permite guardar el área de influencia de un programa.
    dajax = Dajax()

    areaInfluenciaAGuardar = AreaInfluenciaPrograma(Programa_id = idPrograma, IdAreaInfluencia = area)
    areaInfluenciaAGuardar.save()

    return dajax.json()

def actualizar_coberturas(coberturas, idPrograma): # Método que permite actualizar las coberturas en la base de datos.
    dajax = Dajax()

    coberturasGuardadas = CoberturaPrograma.objects.filter(Programa_id = idPrograma)

    encontradoAElimiar = 1
    for coberturaAEliminar in coberturasGuardadas:
        for coberturaABuscar in coberturas:
            if coberturaABuscar == coberturaAEliminar.IdCobertura:
                encontradoAElimiar = 0
                break
        if encontradoAElimiar == 1:
            eliminar_cobertura(coberturaAEliminar.IdCoberturaPrograma)

    coberturaAGuardar = 1
    for cobertura in coberturas:
        for coberturaEncontrada in coberturasGuardadas:
            if coberturaEncontrada.IdCobertura == cobertura:
                coberturaAGuardar = 0
                break

        if coberturaAGuardar == 1:
            guardarCoberturas(cobertura, idPrograma)

    return dajax.json()

def actualizar_area_influencia_programa(areaInfluencia, idPrograma): # Método que permite actualizar las coberturas en la base de datos.
    dajax = Dajax()

    areaInfluenciaGuardadas = AreaInfluenciaPrograma.objects.filter(Programa_id = idPrograma)

    encontradoAElimiar = 1
    for areaProgramaAEliminar in areaInfluenciaGuardadas:
        for area in areaInfluencia:
            if area == areaProgramaAEliminar.IdAreaInfluencia:
                encontradoAElimiar = 0
                break
        if encontradoAElimiar == 1:
            eliminar_area_influencia_programa(areaProgramaAEliminar.IdAreaInfluenciaPrograma)

    coberturaAGuardar = 1
    for area in areaInfluencia:
        for areaProgramaGuardada in areaInfluenciaGuardadas:
            if areaProgramaGuardada.IdAreaInfluencia == area:
                coberturaAGuardar = 0
                break
        if coberturaAGuardar == 1:
            guardarAreaInfluencia(area, idPrograma)

    return dajax.json()

@dajaxice_register
def eliminar_area_influencia_programa(idAreaInfluenciaPrograma): #Método que recibe el id cobertura programa para eliminarlo de la base de datos.
    dajax = Dajax()
    AreaInfluenciaPrograma.objects.filter(IdAreaInfluenciaPrograma = idAreaInfluenciaPrograma).delete()

    return dajax.json()

@dajaxice_register
def eliminar_cobertura(idCoberturaPrograma): #Método que recibe el id cobertura programa para eliminarlo de la base de datos.
    dajax = Dajax()
    CoberturaPrograma.objects.filter(IdCoberturaPrograma = idCoberturaPrograma).delete()

    return dajax.json()

def actualizar_programa(formularioPrograma, coberturas, areaInfluencia): # Método que permite actualizar los datos del programa.
    dajax = Dajax()

    Programa.objects.filter(IdPrograma = formularioPrograma.get('varIdPrograma')).update(
                            IdTipoSeguro = formularioPrograma.get('IdTipoSeguro'), IdSubTipoSeguro = formularioPrograma.get('IdSubTipoSeguro'),
                            Ejercicio = str(formularioPrograma.get('Ejercicio')), IdTipoMoneda = formularioPrograma.get('IdTipoMoneda'),
                            Observaciones = formularioPrograma.get('Observaciones').upper(), IdContratoFondo = formularioPrograma.get('IdContratoFondo'),
                            PersonaHabilitador = formularioPrograma.get('varIdHabilitador'))

    actualizar_coberturas(coberturas, formularioPrograma.get('varIdPrograma'))
    actualizar_area_influencia_programa(areaInfluencia, formularioPrograma.get('varIdPrograma'))

    return dajax.json()

@dajaxice_register
def obtener_programas(req): # Función que busca todos los programas ingresados a la base de datos para mostrarlos en el listado de programas.
    dajax = Dajax()
    try:
        datos = list()
        listaProgramas = Programa.objects.all().order_by("-IdPrograma")
        tieneCotizador = 0

        for programa in listaProgramas:
            tipoSeguro = TipoSeguro.objects.using('catalogos').filter(IdTipoSeguro = programa.IdTipoSeguro)[0]
            subTipoSeguro = SubTipoSeguro.objects.using('catalogos').filter(IdSubTipoSeguro = programa.IdSubTipoSeguro)[0]
            contrato = ContratoFondo.objects.filter(IdContratoFondo = programa.IdContratoFondo)[0]
            cotizadores = Cotizador.objects.filter(Programa_id = programa.IdPrograma)

            if cotizadores:
                tieneCotizador = 1

            datos.append({'IdPrograma':programa.IdPrograma,'TipoSeguro':tipoSeguro.DescripcionTipoSeguro,'SubTipoSeguro':subTipoSeguro.DescripcionSubTipoSeguro,
            'Ejercicio':programa.Ejercicio,'IdTipoSeguro':programa.IdTipoSeguro,'IdSubTipoSeguro':programa.IdSubTipoSeguro,
            'IdTipoMoneda':programa.IdTipoMoneda,'Observaciones':programa.Observaciones,'NumeroContrato':contrato.NumeroContrato,'FolioPrograma':programa.FolioPrograma,
            'Utilizado':programa.Utilizado, 'TieneCotizador':int(tieneCotizador)})

    except:
        return dajax.json()

    return simplejson.dumps({'programas':datos})

@dajaxice_register
def obtener_areas_infuencia_fondo(req): # Función que busca todos los programas ingresados a la base de datos para mostrarlos en el listado de programas.
    dajax = Dajax()
    try:
        datos = list()
        listaAreaInfluencia = AreaInfluencia.objects.all()

        for areaInfluencia in listaAreaInfluencia:
            municipio = Municipio.objects.using('catalogos').filter(IdMunicipio = areaInfluencia.Municipio_id)[0]

            datos.append({'IdAreaInfluencia':areaInfluencia.IdAreaInfluencia,'Descripcion':municipio.Descripcion})

    except:
        return dajax.json()

    return simplejson.dumps({'areasInfluencia':datos})

@dajaxice_register
def buscar_programas_ejercicio_actual(req, buscarPrograma, tipoSolicitud): # Función que busca todos los programas con cotizador ingresados a la base de datos para mostrarlos en el listado de programas.
    dajax = Dajax()
    try:
        datos = list()
        year = datetime.datetime.now().year

        programasFiltrados = TipoSeguro.objects.using('catalogos').filter(Q(DescripcionTipoSeguro__contains = buscarPrograma))
        listaProgramas = Programa.objects.filter(Ejercicio = year, Utilizado=1)

        for programaFiltrado in programasFiltrados:
            for programa in listaProgramas:
                # tipoSolicitud = 1 ANUAL, tipoSolicitud = 2 A DECLARACION
                # ANUAL solo muestra los programas PATRIMONIAL y MAQUINARIA
                # A DECLARACION muestra programas PATRIMONIAL (BODEGAS, SILOS Y CONTENIDOS), TRANSPORTE Y RIESGOS ALGODONEROS
                if programaFiltrado.IdTipoSeguro == int(programa.IdTipoSeguro) and (((programaFiltrado.IdTipoSeguro == 1 or programaFiltrado.IdTipoSeguro == 3) and tipoSolicitud==1) or ((programaFiltrado.IdTipoSeguro == 1 or programaFiltrado.IdTipoSeguro == 2 or programaFiltrado.IdTipoSeguro == 4) and tipoSolicitud==2)):
                    tipoSeguro = TipoSeguro.objects.using('catalogos').filter(IdTipoSeguro = programa.IdTipoSeguro)[0]
                    subTipoSeguro = SubTipoSeguro.objects.using('catalogos').filter(IdSubTipoSeguro = programa.IdSubTipoSeguro)[0]
                    contrato = ContratoFondo.objects.filter(IdContratoFondo = programa.IdContratoFondo)[0]
                    descripcionMoneda = Moneda.objects.using('catalogos').filter(IdMoneda = programa.IdTipoMoneda)[0]

                    datos.append({'IdPrograma':programa.IdPrograma,'TipoSeguro':tipoSeguro.DescripcionTipoSeguro,'SubTipoSeguro':subTipoSeguro.DescripcionSubTipoSeguro,
                    'Ejercicio':programa.Ejercicio,'IdTipoSeguro':programa.IdTipoSeguro,'IdSubTipoSeguro':programa.IdSubTipoSeguro, 'DescripcionMoneda':descripcionMoneda.Nombre,
                    'IdTipoMoneda':programa.IdTipoMoneda,'Observaciones':programa.Observaciones, 'NumeroContrato':contrato.NumeroContrato,'FolioPrograma':programa.FolioPrograma})

    except:
        return dajax.json()

    return simplejson.dumps({'programas':datos})

@dajaxice_register
def obtener_programas_ejercicio_actual(req): # Método ue busca todos los programas del ciclo actual pasandole el año.
    dajax = Dajax()

    try:
        datos = list()
        year = datetime.datetime.now().year
        programasEjercicioActual = Programa.objects.filter(Ejercicio = year, Utilizado = 0)

        for programa in programasEjercicioActual:
            tipoSeguro = TipoSeguro.objects.using('catalogos').filter(IdTipoSeguro = programa.IdTipoSeguro)[0]
            subTipoSeguro = SubTipoSeguro.objects.using('catalogos').filter(IdSubTipoSeguro = programa.IdSubTipoSeguro)[0]
            descripcionMoneda = Moneda.objects.using('catalogos').filter(IdMoneda = programa.IdTipoMoneda)[0]

            datos.append({'IdPrograma':programa.IdPrograma,'TipoSeguro':tipoSeguro.DescripcionTipoSeguro,'SubTipoSeguro':subTipoSeguro.DescripcionSubTipoSeguro,
            'Ejercicio':programa.Ejercicio,'IdTipoMoneda':programa.IdTipoMoneda,'FolioPrograma':programa.FolioPrograma,'DescripcionMoneda':descripcionMoneda.Descripcion})

    except:
        return dajax.json()

    return simplejson.dumps({'programasActuales':datos})

@dajaxice_register
def buscar_programa(request, idPrograma): # Método que busca la información del programa pasandole el id del programa a buscar.
    dajax = Dajax()

    try:
        programasEncontrados = Programa.objects.filter(IdPrograma = idPrograma)
        datos = list()
        for programa in programasEncontrados:
            persona = Persona.objects.filter(IdPersona = programa.PersonaHabilitador_id)[0]
            contrato = ContratoFondo.objects.filter(IdContratoFondo = programa.IdContratoFondo)[0]
            tipoSeguro = TipoSeguro.objects.using('catalogos').filter(IdTipoSeguro = programa.IdTipoSeguro)[0]
            subTipoSeguro = SubTipoSeguro.objects.using('catalogos').filter(IdSubTipoSeguro = programa.IdSubTipoSeguro)[0]
            datos.append({'IdPrograma':programa.IdPrograma, 'IdTipoSeguro': programa.IdTipoSeguro,'IdSubSeguro':programa.IdSubTipoSeguro,
                          'IdTipoMoneda':programa.IdTipoMoneda, 'Ejercicio':programa.Ejercicio, 'Observaciones':programa.Observaciones,
                          'IdContratoFondo':programa.IdContratoFondo, 'Utilizado':programa.Utilizado, 'RazonSocial':persona.RazonSocial,
                          'IdPersona':persona.IdPersona, 'NumeroContrato':contrato.NumeroContrato,'TipoSeguro':tipoSeguro.DescripcionTipoSeguro,
                          'SubTipoSeguro':subTipoSeguro.DescripcionSubTipoSeguro, 'FolioPrograma':programa.FolioPrograma})

    except:
        return dajax.json()

    return simplejson.dumps({'programaEncontrado':datos})

@dajaxice_register
def buscar_cobertura_programa(request, idPrograma): # Método que busca la información del programa pasandole el id del programa a buscar.
    dajax = Dajax()

    try:
        coberturasPrograma = CoberturaPrograma.objects.filter(Programa_id = idPrograma)
        datos = list()
        for cobertura in coberturasPrograma:
            datos.append({'IdCobertura':cobertura.IdCobertura})

    except:
        return dajax.json()

    return simplejson.dumps({'coberturasprograma':datos})

@dajaxice_register
def buscar_cobertura_programa_descripcion(request, idPrograma): # Método que busca la información de las coberturas pasandole el id del programa a buscar.
    dajax = Dajax()

    try:
        coberturasPrograma = CoberturaPrograma.objects.filter(Programa_id = idPrograma)
        datos = list()
        for cobertura in coberturasPrograma:
            coberturaCatalogos = Cobertura.objects.using('catalogos').filter(IdCobertura = cobertura.IdCobertura)[0]
            datos.append({'Descripcion':coberturaCatalogos.Descripcion})

    except:
        return dajax.json()

    return simplejson.dumps({'coberturasprograma':datos})

@dajaxice_register
def buscar_area_influencia_descripcion(request, idPrograma): # Método que busca la información de las areas de influencia pasandole el id del programa a buscar.
    dajax = Dajax()

    try:
        areaInfluenciaPrograma = AreaInfluenciaPrograma.objects.filter(Programa_id = idPrograma)
        datos = list()
        for areaInfluencia in areaInfluenciaPrograma:
            areaCatalogo = AreaInfluencia.objects.filter(IdAreaInfluencia = areaInfluencia.IdAreaInfluencia)[0]
            municipio = Municipio.objects.using('catalogos').filter(IdMunicipio = areaCatalogo.Municipio_id)[0]
            datos.append({'Descripcion':municipio.Descripcion})

    except:
        return dajax.json()

    return simplejson.dumps({'areasInfluenciaDescripcion':datos})

@dajaxice_register
def obtener_cobertura_con_idprograma(req, idPrograma): # Método que obtiene de la base de datos las coberturas pasandole el id de programa y buscando la descripcion en los catalogos.
    dajax = Dajax()

    try:
        coberturasProgramas = CoberturaPrograma.objects.filter(Programa_id = idPrograma)
        datos = list()

        for coberturaPrograma in coberturasProgramas:
            coberturaCatalogo = Cobertura.objects.using('catalogos').filter(IdCobertura = coberturaPrograma.IdCobertura)[0]

            remocion = 0
            if coberturaPrograma.IdCobertura == 3:
                remocion = 1

            datos.append({'IdCoberturaPrograma':coberturaPrograma.IdCoberturaPrograma,'Descripcion':coberturaCatalogo.Descripcion, 'Remocion':remocion})

    except:
        return dajax.json()

    return simplejson.dumps({'coberturasPorPrograma':datos})

@dajaxice_register
def obtener_area_influencia_con_idprograma(req, idPrograma): # Método que obtiene de la base de datos el área de influencia del programa pasando el id del mismo.
    dajax = Dajax()

    try:
        areaInfluenciaPrograma = AreaInfluenciaPrograma.objects.filter(Programa_id = idPrograma)
        datos = list()

        for area in areaInfluenciaPrograma:
            datos.append({'IdAreaInfluenciaPrograma':area.IdAreaInfluenciaPrograma,'IdAreaInfluencia':area.IdAreaInfluencia})

    except:
        return dajax.json()

    return simplejson.dumps({'areaInfluenciaPrograma':datos})

@dajaxice_register
def eliminar_programa(request, idPrograma): #Función que permite eliminar el programa seleccionado de la base de datos.
    dajax = Dajax()
    Programa.objects.filter(IdPrograma = idPrograma).delete()

    return dajax.json()

@dajaxice_register
def programaUtilizado(request, idPrograma): #Función que permite verificar si un programa se encuentra con cotizador, la función devuelve un 0 si no esta utilizado y un 1 si esta utilizado.

    tieneCotizador = 0

    cotizadores = Cotizador.objects.filter(Programa_id = idPrograma)

    if cotizadores:
        tieneCotizador = 1

    return simplejson.dumps({'tieneCotizador':tieneCotizador})


"""Implementation of Vanilla GAN, Wasserstein GAN, and Improved
Wasserstein GAN (denoted GAN, WGAN, and IWGAN, respectively).

Which model is added to the graph is based on args.model ('gan',
'wgan', or 'iwgan'), along with the other associated arguments
(e.g. args.optimizer, args.latent_size, etc.)

Supports multi-GPU training.

Sources:
-------
- `Generative Adversarial Networks`
https://arxiv.org/abs/1406.2661

- `Wasserstein GAN`
https://arxiv.org/abs/1701.07875

- `Improved Training of Wasserstein GANs`
https://arxiv.org/abs/1704.00028
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf
from tensorflow.contrib.layers import batch_norm
from tensorflow.contrib.framework.python.ops.arg_scope import arg_scope

from util import * #tower_scope_range, average_gradients, init_optimizer, default_to_cpu, merge_all_summaries
from ops.layers import dense, conv2d, deconv2d, flatten
from ops.activations import lrelu
from ops.summaries import montage_summary, summarize_gradients, summarize_activations, summarize_losses, summarize_weights_biases

@default_to_cpu
def gan(x, args):
    """Initialize model.

    Args:
    x: Tensor, the real images.
    args: Argparse structure.
    """
    g_opt, d_opt = init_optimizer(args), init_optimizer(args)
    g_tower_grads, d_tower_grads = [], []

    x = flatten(x)
    x = 2 * (x - 0.5)
    # rescale [0,1] to [-1,1] depending on model
    # if args.model in ['wgan', 'iwgan']:
    # x = 2 * (x - 0.5)

    for x, scope, gpu_id in tower_scope_range(x, args.n_gpus, args.batch_size):
        # model
        with tf.variable_scope('generator'):
            g = generator(args.batch_size, args.latent_size, args, reuse=(gpu_id>0))
        with tf.variable_scope('discriminator'):
            d_real = discriminator(x, args, reuse=(gpu_id>0))
            d_fake = discriminator(g, args, reuse=True)
        # losses
        g_loss, d_loss = losses(x, g, d_fake, d_real, args)
        # compute gradients
        g_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'generator')
        d_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'discriminator')
        g_tower_grads.append(g_opt.compute_gradients(g_loss, var_list=g_params))
        d_tower_grads.append(d_opt.compute_gradients(d_loss, var_list=d_params))
        # only need one batchnorm update (ends up being updates for last tower)
        batchnorm_updates = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope)

    # summaries
    summaries(g, x, args)

    # average and apply gradients
    g_grads = average_gradients(g_tower_grads)
    d_grads = average_gradients(d_tower_grads)
    summarize_gradients(g_grads + d_grads)
    global_step = tf.train.get_global_step()
    g_apply_grads = g_opt.apply_gradients(g_grads, global_step=global_step)
    d_apply_grads = d_opt.apply_gradients(d_grads, global_step=global_step)

    # training
    if args.model == 'gan':
        train_func = _train_gan(g_apply_grads, d_apply_grads, batchnorm_updates)
    elif args.model == 'wgan':
        train_func = _train_wgan(g_apply_grads, g_params, d_apply_grads, d_params, batchnorm_updates)
    elif args.model == 'iwgan':
        train_func = _train_iwgan(g_apply_grads, d_apply_grads, batchnorm_updates)

    return train_func

def summaries(g, x, args):
    """Adds histogram and montage summaries for real and fake examples."""
    with tf.variable_scope('examples'):
        tf.summary.histogram('fakes', g)
        tf.summary.histogram('real', x)
        with tf.variable_scope('rescale'):
            # need to rescale images from [-1,1] to [0,1]
            real_examples = (x[0:args.examples] + 1.0) / 2
            fake_examples = (g[0:args.examples] + 1.0) / 2
        montage_summary(tf.reshape(real_examples, [-1, 64, 64, 3]), 8, 8, 'inputs')
        montage_summary(tf.reshape(fake_examples, [-1, 64, 64, 3]), 8, 8, 'fake')
    summarize_activations()
    summarize_losses()
    summarize_weights_biases()

def _train_gan(g_apply_grads, d_apply_grads, batchnorm_updates):
    """Generates helper to train a GAN.

    Original GAN implementation. Batchnorm is applied to both
    discriminator and generator. We alternate training of discriminator
    and generator equally.

    Args:
      g_apply_grads: Operation, to apply gradient updates to generator.
      d_apply_grads: Operation, to apply gradient updates to discriminator.

    Returns:
      Helper function to be used by train.py
    """
    with tf.control_dependencies(batchnorm_updates):
        g_train_op = g_apply_grads
        d_train_op = d_apply_grads
    losses = collection_to_dict(tf.get_collection('losses'))
    def helper(sess, args):
        _, _, l = sess.run([d_train_op, g_train_op, losses])
        return l
    return helper

def _train_wgan(g_apply_grads, g_params, d_apply_grads, d_params, batchnorm_updates):
    """Generates helper to train a WGAN.

    This training method uses weight clipping and trains the
    discriminator to convergence before training the generator.
    Batchnorm updates are applied to both discriminator and generator.
    """
    # add weight clipping method
    clip_D = [p.assign(tf.clip_by_value(p, -0.01, 0.01)) for p in d_params]
    clip_G = [p.assign(tf.clip_by_value(p, -0.01, 0.01)) for p in g_params]
    with tf.control_dependencies(batchnorm_updates):
        with tf.control_dependencies(clip_D):
            d_train_op = d_apply_grads
        with tf.control_dependencies(clip_G):
            g_train_op = g_apply_grads
    losses = collection_to_dict(tf.get_collection('losses'))
    def helper(sess, args):
        for i in range(args.n_disc_train):
            sess.run(d_train_op)
        _, l = sess.run([g_train_op, losses])
        return l
    return helper

def _train_iwgan(g_apply_grads, d_apply_grads, batchnorm_updates):
    """Generates helper to train a IWGAN.

    Batchnorm updates are applies only to discriminator, since generator
    doesn't use batchnorm. Discriminator is trained to convergence
    before training the generator.
    """
    g_train_op = g_apply_grads
    with tf.control_dependencies(batchnorm_updates):
        d_train_op = d_apply_grads
    losses = collection_to_dict(tf.get_collection('losses'))
    def helper(sess, args):
        for i in range(args.n_disc_train):
            sess.run(d_train_op)
        _, l = sess.run([g_train_op, losses])
        return l

    return helper

def losses(x, g, d_fake, d_real, args):
    """Add loss nodes to the graph depending on the model type.

    Args:
      x: Tensor, real images.
      g: Tensor, the generator.
      d_fake: Tensor, the fake discriminator.
      d_real: Tensor, the real discriminator.
      args: Argparse structure.

    Returns:
      g_loss: Tensor, the generator's loss function.
      d_loss: Tensor, the discriminator's loss function.
    """
    if args.model == 'gan':
        g_loss = tf.reduce_mean(-tf.log(d_fake + 1e-8), name='g_loss')
        d_loss = tf.identity(tf.reduce_mean(-tf.log(d_real + 1e-8) - tf.log(1 - d_fake + 1e-8)), name='d_loss')
    elif args.model == 'wgan':
        g_loss = tf.identity(-tf.reduce_mean(d_fake), name='g_loss')
        d_loss = tf.identity(tf.reduce_mean(d_fake) - tf.reduce_mean(d_real), name='d_loss')
    elif args.model == 'iwgan':
        l_term = 10.0

        g_loss = tf.identity(-tf.reduce_mean(d_fake), name='g_loss')
        with tf.variable_scope('discriminator'):
            gp = gradient_penalty(x, g, args)
        d_loss = tf.reduce_mean(d_fake) - tf.reduce_mean(d_real) + l_term * gp
        d_loss = tf.identity(d_loss, name='d_loss')

    tf.add_to_collection('losses', g_loss)
    tf.add_to_collection('losses', d_loss)
    # tf.summary.scalar('g_loss', g_loss)
    # tf.summary.scalar('d_loss', d_loss)
    return g_loss, d_loss

def gradient_penalty(x, g, args):
    """Calculate gradient penalty for discriminator.

    This requires creating a separate discriminator path.

    Args:
    x: Tensor, the real images.
    g: Tensor, the fake images.
    args: Argparse structure.
    """
    alpha = tf.random_uniform(shape=[args.batch_size, 1], minval=0.0, maxval=1.0)
    differences = g - x
    interpolates = x + (alpha * differences)
    d_interpolates = discriminator(interpolates, args, reuse=True)
    gradients = tf.gradients(d_interpolates, [interpolates])[0]
    slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients)))
    penalty = tf.reduce_mean((slopes-1.0)**2)
    return penalty

def generator(batch_size, latent_size, args, reuse=False):
    """Adds generator nodes to the graph.

    From noise, applies deconv2d until image is scaled up to match
    the dataset.
    """
    # final_activation = tf.tanh if args.model in ['wgan', 'iwgan'] else tf.nn.sigmoid
    output_dim = 64*64*3
    with arg_scope([dense, deconv2d],
                       reuse = reuse,
                       use_batch_norm = True,
                       activation = tf.nn.relu):
        z = tf.random_normal([batch_size, latent_size])
        y = dense(z, latent_size, 4*4*4*latent_size, name='fc1')
        y = tf.reshape(y, [-1, 4, 4, 4*latent_size])
        y = deconv2d(y, 4*latent_size, 2*latent_size, 5, 2, name='dc1')
        y = deconv2d(y, 2*latent_size, latent_size, 5, 2, name='dc2')
        y = deconv2d(y, latent_size, int(latent_size/2), 5, 2, name='dc3')
        y = deconv2d(y, int(latent_size/2), 3, 5, 2, name='dc4', activation=tf.tanh, use_batch_norm=False)
        y = tf.reshape(y, [-1, output_dim])
    return y

def discriminator(x, args, reuse=False):
    """Adds discriminator nodes to the graph.

    From the input image, successively applies convolutions with
    striding to scale down layer sizes until we get to a single
    output value, representing the discriminator's estimate of fake
    vs real. The single final output acts similar to a sigmoid
    activation function.

    Args:
    x: Tensor, input.
    args: Argparse structure.
    reuse: Boolean, whether to reuse variables.

    Returns:
    Final output of discriminator pipeline.
    """
    use_bn = False if args.model == 'iwgan' else True
    final_activation = None if args.model in ['wgan', 'iwgan'] else tf.nn.sigmoid
    with arg_scope([conv2d],
                       use_batch_norm = use_bn,
                       activation = lrelu,
                       reuse = reuse):
        x = tf.reshape(x, [-1, 64, 64, 3])
        x = conv2d(x, 3, args.latent_size, 5, 2, name='c1', use_batch_norm=False)
        x = conv2d(x, args.latent_size, args.latent_size*2, 5, 2, name='c2')
        x = conv2d(x, args.latent_size*2, args.latent_size*4, 5, 2, name='c3')
        x = tf.reshape(x, [-1, 4*4*4*args.latent_size])
        x = dense(x, 4*4*4*args.latent_size, 1, use_batch_norm=False, activation=final_activation, name='fc2', reuse=reuse)
        x = tf.reshape(x, [-1])
    return x


from flask import Flask, render_template, redirect
from flask_pymongo import pymongo
import scrape_mars

# Create instance of Flask app
app = Flask(__name__)

# Flask_pymongo to set up mongo connection
mongo = PyMongo(app, uri="mongodb://localhost:27017/mars_app")

# Create route that renders index.html template
@app.route("/")
def index():
    # Find one record of data from the mongo mars database
    mars_data = mongo.db.mars_data.find_one()

    # Return template and data
    return render_template("index.html, mars_data=mars_data")

# Create route that triggers the scrape function
@app.route("/scrape")
def scrape():

    # Run the scrape function
    mars_data = mongo.db.mars_data
    mars_data_scrape = scrape_mars.scrape()

    # Update mongo database using update and upsert=True
    mars_data.update({}, mars_data_scrape, upsert=True)

    # Redirect back to home page
    return redirect("/", code=302)

if __name__ == "__main__":
    app.run(debug = True)


# decisiontrees.py
# Import the relevant modules from graphviz. Digraph means a graph with directions.
from graphviz import Digraph

# Create a type called Node. A class is a complex object with associated attributes and functions.
class Node(object):
    ''' An object corresponding to an individual node in a decision tree.
    There are three types of nodes: event, decision, or outcome (or value) nodes.

        The attributes are:
            - name: a user specified string that denotes the Node.
            - type: a string that specifies the type of the node. Outcome nodes are denoted using the name "value."
            - children: list of the immediate nodes that descend from this node. Empty if is an outcome/value node.
            - probabilities: (exists for event nodes only) a list of the corresponding probabilities for the children.
            - value: (exists for outcome nodes only) the value of the node.

        The functions are:
            evaluate(): Return the value of the node using backward induction.
            graph(showValues): Return a graphviz object that corresponds to the decision tree.
                Use showValues=True to see the values after solving by backward induction.
                Use showValues=False to see the structure of the tree without solving.

    '''
    def __init__(self,name,children=[],probabilities=[],value=0):
        ''' To create a node, use the following syntax:
            x=Node(name,children,probabilities) (For event nodes)
            x=Node(name,children) (For decision nodes)
            x=Node(name,value=value) (For outcome nodes)
        '''
        self.name=name
        # Decide what type of node it is based on existence of function inputs.
        if probabilities:
            self.type='event'
            self.children=children
            self.probabilities=probabilities
            assert len(probabilities)==len(children), 'The length of the lists "children" and "probabilities" must equal!'
        elif children:
            self.type='decision'
            self.children=children
        else:
            self.type='value'
            self.children=[]
            self.value=value

    def evaluate(self):
        ''' Function that evaluates the current node by backward induction '''
        if self.type=='value':
            # For outcome nodes, return value
            return self.value
        elif self.type=='event':
            # For event nodes, return expected value
            return sum([self.probabilities[i]*self.children[i].evaluate() for i in range(len(self.children))])
        else:
            # For decision nodes, return the value of the best decision
            return max([self.children[i].evaluate() for i in range(len(self.children))])

    def _drawNodes(self,graph,showValues=True):
        ''' Function to draw all nodes that are descendent of the current node.'''
        if self.type=='value':
            graph.attr('node',shape='plaintext')
        elif self.type=='event':
            graph.attr('node',shape='oval')
        else:
            graph.attr('node',shape='square')
        if showValues:
            myLabel='{:.0f}'.format(self.evaluate())
        else:
            myLabel=self.type
        graph.node(str(self),myLabel)
        for child in self.children:
            child._drawNodes(graph,showValues)

    def _drawEdges(self,graph):
        ''' Function to draw all edges that are descendent of the current node.'''
        for i,child in enumerate(self.children):
            if self.type=='decision':
                myLabel=child.name
            else:
                myLabel='{0} ({1:.0%})'.format(child.name,self.probabilities[i])
            graph.edge(str(self),str(child),label=myLabel)
        for child in self.children:
            child._drawEdges(graph)

    def graph(self,showValues=True,treeName='decision tree'):
        ''' Function to return a graphviz object that graphically represent the decision tree from this node
        Inputs:
            - showValues: True if draw the values; False if draw the shape only.
            - treeName: a name for the decision tree that is used by the underlying graphviz package.
        '''
        graph=Digraph(treeName)
        self._drawNodes(graph,showValues)
        self._drawEdges(graph)
        return graph


# uncompyle6 version 3.6.7
# Python bytecode 2.4 (62061)
# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: build/bdist.macosx-10.3-i386/egg/collective/allowsearch/adapters.py
# Compiled at: 2008-03-13 07:09:46
__author__ = 'Stefan Eletzhofer <stefan.eletzhofer@inquant.de>'
__docformat__ = 'plaintext'
__revision__ = '$Revision: 60620 $'
__version__ = '$Revision: 60620 $'[11:-2]
from zope import component
from zope import interface
from collective.allowsearch.interfaces import IAllowedRolesAndUsers
from collective.allowsearch.interfaces import IAllowAnonymousSearchMarker

class AllowAnonSearch(object):
    """ adapter to which checks for an interface on its context
        to determine if 'Anonymous' users are to view catalog
        brains for the given object. """
    __module__ = __name__
    interface.implements(IAllowedRolesAndUsers)
    ROLE = 'Anonymous'

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

    def __call__(self, obj, portal, **kw):
        allowed = component.getUtility(IAllowedRolesAndUsers, 'collective.allowsearch.default')(obj, portal, **kw)
        if IAllowAnonymousSearchMarker.providedBy(obj):
            if self.ROLE not in allowed:
                allowed.append(self.ROLE)
        return allowed


# -*- coding: utf-8 -*-
from openerp import http
import openerp.http as htp
import json
from openerp import http
from openerp.http import request
import jinja2
import os

path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'views'))
loader = jinja2.FileSystemLoader(path)
env = jinja2.Environment(loader=loader, autoescape=True)

ACCESS_TOKEN = r'osdf8sncd5'
class project_json_data_get(http.Controller):
    @http.route('/project_json_data_get', auth='public', website=True)
    def project_json_data_get(self, **kw):
        access_token = kw.get('access_token')
        if access_token == ACCESS_TOKEN:
            #set db cr uid
            #htp.request.db = #
            #htp.request.uid =
            project_obj = htp.request.env['project.project']
            project = project_obj.search([])
            res= {'name': project[0].name}
            return json.dumps(res)

        else:
            return 'Error access token'

    @http.route('/seaerp/<path:page>', auth='none', website=True)
    def app_page(self,  page, **post):
        '''mobile app api'''
        return env.get_template(page).render()


"""
Spells
------

Spells is a database of pathfinder spells available as either a command line
application or as a web-based application.
"""
from setuptools import setup
from setuptools.command.install import install
from load_database import load_data

class install_spell_data(install):
    def run(self):
        install.run(self)
        load_data("spell_full.csv")

setup(
    name='spells',
    version='0.1-dev',
    url='http://github.com/greylurk/spells/',
    license='BSD',
    author='Adam Ness',
    author_email='adam.ness@gmail.com',
    description='Look up Pathfinder spells',
    long_description=__doc__,
    cmdclass={ "install": install_spell_data },
    include_package_data=True,
    zip_safe=False,
    packages=[
        'spells',
        'spells.views'
    ],
    platforms='any',
    install_requires=[
        'Flask>=0.10.1',
        'SQLAlchemy>=0.8.2'
    ],
    classifiers=[
        'Development status :: 4 - Beta',
    ],
)


import re
from datetime import date,time
today = date.today().day
today_time = time.time().hour
print(today_time)
def chi2engTime(s):
    nowdate = str(today.year)+str(today.month)+str(today.day)+str(toda.year)+str(today.year)+str(today.year)
    dat = ['大前天','前天','昨天','今天','明天','后天','大后天']
    day_time = {'早上','中午','下午','晚上','凌晨'}
    chi_time = {'一':1,'二':2,'两':2,'三':3,'四':4,'五':5,'六':6,'七':7,'八':8,'九':9,'十':10,'十一':11,'十二':12,'十三':13,'十四':14,'十五':15,'十六':16,'十七':17,'十八':18,'十九':19,'二十':20,'二十一':21,'二十二':22,'二十三':23,'二十四':24}
    pat_dat = re.compile('.{1,2}天')
    pat_day = re.compile('.{1,2}天')
    pat_time = re.compile('.{1}点')

    if re.search(pat,s).group()[0] in chi_time:
        print(True)

#chi2engTime('今天明天下午两点')


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('article', '0003_comment_commentid'),
    ]

    operations = [
        migrations.CreateModel(
            name='LikeByUser',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('userLike', models.IntegerField(default=0)),
                ('articleId', models.ForeignKey(to='article.Article')),
                ('userId', models.ForeignKey(to='article.User_1')),
            ],
        ),
    ]