import math as m
import numpy as np
import matplotlib.pyplot as plt
import json

with open("./NEAT_RUN_STATS/silverstone-base-run-1.json", 'r') as f:
    baseline_run1 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-base-run-2.json", 'r') as f:
    baseline_run2 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-base-run-3.json", 'r') as f:
    baseline_run3 = json.load(f)

generations = baseline_run1['generations'][:20]
baseline_run1_popmax = np.array(baseline_run1['best_fitness'][:20])
baseline_run2_popmax = np.array(baseline_run2['best_fitness'][:20])
baseline_run3_popmax = np.array(baseline_run3['best_fitness'][:20])
baseline_runs_popmaxes = np.vstack((baseline_run1_popmax, baseline_run2_popmax, baseline_run3_popmax))
baseline_means = baseline_runs_popmaxes.mean(axis=0)
baseline_stds = baseline_runs_popmaxes.std(axis=0, ddof=1)

with open("./NEAT_RUN_STATS/silverstone-4species-run-1.json", 'r') as f:
    species4_run1 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-4species-run-2.json", 'r') as f:
    species4_run2 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-4species-run-3.json", 'r') as f:
    species4_run3 = json.load(f)

# generations = baseline_run1['generations']
species4_run1_popmax = np.array(species4_run1['best_fitness'])
species4_run2_popmax = np.array(species4_run2['best_fitness'])
species4_run3_popmax = np.array(species4_run3['best_fitness'])
species4_runs_popmaxes = np.vstack((species4_run1_popmax, species4_run2_popmax, species4_run3_popmax))
species4_means = species4_runs_popmaxes.mean(axis=0)
species4_stds = species4_runs_popmaxes.std(axis=0, ddof=1)

with open("./NEAT_RUN_STATS/silverstone-8species-run-1.json", 'r') as f:
    species8_run1 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-8species-run-2.json", 'r') as f:
    species8_run2 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-8species-run-3.json", 'r') as f:
    species8_run3 = json.load(f)

# generations = baseline_run1['generations']
species8_run1_popmax = np.array(species8_run1['best_fitness'])
species8_run2_popmax = np.array(species8_run2['best_fitness'])
species8_run3_popmax = np.array(species8_run3['best_fitness'])
species8_runs_popmaxes = np.vstack((species8_run1_popmax, species8_run2_popmax, species8_run3_popmax))
species8_means = species8_runs_popmaxes.mean(axis=0)
species8_stds = species8_runs_popmaxes.std(axis=0, ddof=1)

with open("./NEAT_RUN_STATS/silverstone-30pop-run-1.json", 'r') as f:
    pop30_run1 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-30pop-run-2.json", 'r') as f:
    pop30_run2 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-30pop-run-3.json", 'r') as f:
    pop30_run3 = json.load(f)

# generations = baseline_run1['generations']
pop30_run1_popmax = np.array(pop30_run1['best_fitness'])
pop30_run2_popmax = np.array(pop30_run2['best_fitness'])
pop30_run3_popmax = np.array(pop30_run3['best_fitness'])
pop30_runs_popmaxes = np.vstack((pop30_run1_popmax, pop30_run2_popmax, pop30_run3_popmax))
pop30_means = pop30_runs_popmaxes.mean(axis=0)
pop30_stds = pop30_runs_popmaxes.std(axis=0, ddof=1)

with open("./NEAT_RUN_STATS/silverstone-50pop-run-1.json", 'r') as f:
    pop50_run1 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-50pop-run-2.json", 'r') as f:
    pop50_run2 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-50pop-run-3.json", 'r') as f:
    pop50_run3 = json.load(f)

# generations = baseline_run1['generations']
pop50_run1_popmax = np.array(pop50_run1['best_fitness'])
pop50_run2_popmax = np.array(pop50_run2['best_fitness'])
pop50_run3_popmax = np.array(pop50_run3['best_fitness'])
pop50_runs_popmaxes = np.vstack((pop50_run1_popmax, pop50_run2_popmax, pop50_run3_popmax))
pop50_means = pop50_runs_popmaxes.mean(axis=0)
pop50_stds = pop50_runs_popmaxes.std(axis=0, ddof=1)

with open("./NEAT_RUN_STATS/silverstone-ts5-run-1.json", 'r') as f:
    ts5_run1 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-ts5-run-2.json", 'r') as f:
    ts5_run2 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-ts5-run-3.json", 'r') as f:
    ts5_run3 = json.load(f)

# generations = baseline_run1['generations']
ts5_run1_popmax = np.array(ts5_run1['best_fitness'])
ts5_run2_popmax = np.array(ts5_run2['best_fitness'])
ts5_run3_popmax = np.array(ts5_run3['best_fitness'])
ts5_runs_popmaxes = np.vstack((ts5_run1_popmax, ts5_run2_popmax, ts5_run3_popmax))
ts5_means = ts5_runs_popmaxes.mean(axis=0)
ts5_stds = ts5_runs_popmaxes.std(axis=0, ddof=1)

with open("./NEAT_RUN_STATS/silverstone-ts7-run-1.json", 'r') as f:
    ts7_run1 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-ts7-run-2.json", 'r') as f:
    ts7_run2 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-ts7-run-3.json", 'r') as f:
    ts7_run3 = json.load(f)

# generations = baseline_run1['generations']
ts7_run1_popmax = np.array(ts7_run1['best_fitness'])
ts7_run2_popmax = np.array(ts7_run2['best_fitness'])
ts7_run3_popmax = np.array(ts7_run3['best_fitness'])
ts7_runs_popmaxes = np.vstack((ts7_run1_popmax, ts7_run2_popmax, ts7_run3_popmax))
ts7_means = ts7_runs_popmaxes.mean(axis=0)
ts7_stds = ts7_runs_popmaxes.std(axis=0, ddof=1)

with open("./NEAT_RUN_STATS/silverstone-addnode6-run-1.json", 'r') as f:
    addnode6_run1 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-addnode6-run-2.json", 'r') as f:
    addnode6_run2 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-addnode6-run-3.json", 'r') as f:
    addnode6_run3 = json.load(f)

# generations = baseline_run1['generations']
addnode6_run1_popmax = np.array(addnode6_run1['best_fitness'])
addnode6_run2_popmax = np.array(addnode6_run2['best_fitness'])
addnode6_run3_popmax = np.array(addnode6_run3['best_fitness'])
addnode6_runs_popmaxes = np.vstack((addnode6_run1_popmax, addnode6_run2_popmax, addnode6_run3_popmax))
addnode6_means = addnode6_runs_popmaxes.mean(axis=0)
addnode6_stds = addnode6_runs_popmaxes.std(axis=0, ddof=1)

with open("./NEAT_RUN_STATS/silverstone-addnode9-run-1.json", 'r') as f:
    addnode9_run1 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-addnode9-run-2.json", 'r') as f:
    addnode9_run2 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-addnode9-run-3.json", 'r') as f:
    addnode9_run3 = json.load(f)

# generations = baseline_run1['generations']
addnode9_run1_popmax = np.array(addnode9_run1['best_fitness'])
addnode9_run2_popmax = np.array(addnode9_run2['best_fitness'])
addnode9_run3_popmax = np.array(addnode9_run3['best_fitness'])
addnode9_runs_popmaxes = np.vstack((addnode9_run1_popmax, addnode9_run2_popmax, addnode9_run3_popmax))
addnode9_means = addnode9_runs_popmaxes.mean(axis=0)
addnode9_stds = addnode9_runs_popmaxes.std(axis=0, ddof=1)

with open("./NEAT_RUN_STATS/silverstone-wm40-run-1.json", 'r') as f:
    wm40_run1 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-wm40-run-2.json", 'r') as f:
    wm40_run2 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-wm40-run-3.json", 'r') as f:
    wm40_run3 = json.load(f)

# generations = baseline_run1['generations']
wm40_run1_popmax = np.array(wm40_run1['best_fitness'])
wm40_run2_popmax = np.array(wm40_run2['best_fitness'])
wm40_run3_popmax = np.array(wm40_run3['best_fitness'])
wm40_runs_popmaxes = np.vstack((wm40_run1_popmax, wm40_run2_popmax, wm40_run3_popmax))
wm40_means = wm40_runs_popmaxes.mean(axis=0)
wm40_stds = wm40_runs_popmaxes.std(axis=0, ddof=1)

with open("./NEAT_RUN_STATS/silverstone-wm60-run-1.json", 'r') as f:
    wm60_run1 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-wm60-run-2.json", 'r') as f:
    wm60_run2 = json.load(f)

with open("./NEAT_RUN_STATS/silverstone-wm60-run-3.json", 'r') as f:
    wm60_run3 = json.load(f)

# generations = baseline_run1['generations']
wm60_run1_popmax = np.array(wm60_run1['best_fitness'])
wm60_run2_popmax = np.array(wm60_run2['best_fitness'])
wm60_run3_popmax = np.array(wm60_run3['best_fitness'])
wm60_runs_popmaxes = np.vstack((wm60_run1_popmax, wm60_run2_popmax, wm60_run3_popmax))
wm60_means = wm60_runs_popmaxes.mean(axis=0)
wm60_stds = wm60_runs_popmaxes.std(axis=0, ddof=1)

fig, (ax, ax2, ax3, ax4, ax5) = plt.subplots(5, 1, sharex=True, sharey=True)

# print(baseline_means)
fig.set_size_inches(8, 10.4)

first_hatch = ""
second_hatch = ""
third_hatch = ""
first_color = "black"
second_color = "darkblue"
third_color = "darkred"
first_alpha = 0.5
second_alpha = 0.2
third_alpha = 0.2

baseline_errorbar_1 = ax.errorbar(generations, baseline_means, baseline_stds, linestyle="none", marker='o', color=first_color, elinewidth=1, capsize=1, markersize=2)
species4_errorbar = ax.errorbar(generations, species4_means, species4_stds, linestyle="none", marker='o', color=second_color, elinewidth=1, capsize=1, markersize=2)
species8_errorbar = ax.errorbar(generations, species8_means, species8_stds, linestyle="none", marker='o', color=third_color, elinewidth=1, capsize=1, markersize=2)
species4_errorbar[-1][0].set_linestyle('--')
species8_errorbar[-1][0].set_linestyle('--')
ax.fill_between(generations, baseline_means + baseline_stds, baseline_means - baseline_stds, color=first_color, alpha=first_alpha, hatch=first_hatch, label="species target 6 (BL)")
ax.fill_between(generations, species4_means + species4_stds, species4_means - species4_stds, color=second_color, alpha=second_alpha, hatch=second_hatch, label="Species target 4")
ax.fill_between(generations, species8_means + species8_stds, species8_means - species8_stds, color=third_color, alpha=third_alpha, hatch=third_hatch, label="Species target 8")
ax.set_xlabel("Generation")
ax.set_ylabel("Pop. Best Fitness")
ax.legend()

baseline_errorbar_2 = ax2.errorbar(generations, baseline_means, baseline_stds, linestyle="none", marker='o', color=first_color, elinewidth=1, capsize=1, markersize=2)
pop30_errorbar = ax2.errorbar(generations, pop30_means, pop30_stds, linestyle="none", marker='o', color=second_color, elinewidth=1, capsize=1, markersize=2)
pop50_errorbar = ax2.errorbar(generations, pop50_means, pop50_stds, linestyle="none", marker='o', color=third_color, elinewidth=1, capsize=1, markersize=2)
pop30_errorbar[-1][0].set_linestyle('--')
pop50_errorbar[-1][0].set_linestyle('--')
ax2.fill_between(generations, baseline_means + baseline_stds, baseline_means - baseline_stds, color=first_color, hatch=first_hatch, alpha=first_alpha, label="Population size 40 (BL)")
ax2.fill_between(generations, pop30_means + pop30_stds, pop30_means - pop30_stds, color=second_color, alpha=second_alpha, hatch=second_hatch, label="Population size 30")
ax2.fill_between(generations, pop50_means + pop50_stds, pop50_means - pop50_stds, color=third_color, alpha=third_alpha, hatch=third_hatch, label="Population size 50")
ax2.set_xlabel("Generation")
ax2.set_ylabel("Pop. Best Fitness")
ax2.legend()

baseline_errorbar_3 = ax3.errorbar(generations, baseline_means, baseline_stds, linestyle="none", marker='o', color=first_color, elinewidth=1, capsize=1, markersize=2)
ts5_errorbar = ax3.errorbar(generations, ts5_means, ts5_stds, linestyle="none", marker='o', color=second_color, elinewidth=1, capsize=1, markersize=2)
ts7_errorbar = ax3.errorbar(generations, ts7_means, ts7_stds, linestyle="none", marker='o', color=third_color, elinewidth=1, capsize=1, markersize=2)
ts5_errorbar[-1][0].set_linestyle('--')
ts7_errorbar[-1][0].set_linestyle('--')
ax3.fill_between(generations, baseline_means + baseline_stds, baseline_means - baseline_stds, color=first_color, hatch=first_hatch, alpha=first_alpha, label="Tournament size 3 (BL)")
ax3.fill_between(generations, ts5_means + ts5_stds, ts5_means - ts5_stds, color=second_color, alpha=second_alpha, hatch=second_hatch, label="Tournament size 5")
ax3.fill_between(generations, ts7_means + ts7_stds, ts7_means - ts7_stds, color=third_color, alpha=third_alpha, hatch=third_hatch, label="Tournament size 7")
ax3.set_xlabel("Generation")
ax3.set_ylabel("Pop. Best Fitness")
ax3.legend()

baseline_errorbar_4 = ax4.errorbar(generations, baseline_means, baseline_stds, linestyle="none", marker='o', color=first_color, elinewidth=1, capsize=1, markersize=2)
addnode6_errorbar = ax4.errorbar(generations, addnode6_means, addnode6_stds, linestyle="none", marker='o', color=second_color, elinewidth=1, capsize=1, markersize=2)
addnode9_errorbar = ax4.errorbar(generations, addnode9_means, addnode9_stds, linestyle="none", marker='o', color=third_color, elinewidth=1, capsize=1, markersize=2)
addnode6_errorbar[-1][0].set_linestyle('--')
addnode9_errorbar[-1][0].set_linestyle('--')
ax4.fill_between(generations, baseline_means + baseline_stds, baseline_means - baseline_stds, color=first_color, hatch=first_hatch, alpha=first_alpha, label="Node addition 3% (BL)")
ax4.fill_between(generations, addnode6_means + addnode6_stds, addnode6_means - addnode6_stds, color=second_color, alpha=second_alpha, hatch=second_hatch, label="Node addition 6%")
ax4.fill_between(generations, addnode9_means + addnode9_stds, addnode9_means - addnode9_stds, color=third_color, alpha=third_alpha, hatch=third_hatch, label="Node addition 9%")
ax4.set_xlabel("Generation")
ax4.set_ylabel("Pop. Best Fitness")
ax4.legend()

baseline_errorbar_5 = ax5.errorbar(generations, baseline_means, baseline_stds, linestyle="none", marker='o', color=first_color, elinewidth=1, capsize=1, markersize=2)
wm40_errorbar = ax5.errorbar(generations, wm40_means, wm40_stds, linestyle="none", marker='o', color=second_color, elinewidth=1, capsize=1, markersize=2)
wm60_errorbar = ax5.errorbar(generations, wm60_means, wm60_stds, linestyle="none", marker='o', color=third_color, elinewidth=1, capsize=1, markersize=2)
wm40_errorbar[-1][0].set_linestyle('--')
wm60_errorbar[-1][0].set_linestyle('--')
ax5.fill_between(generations, baseline_means + baseline_stds, baseline_means - baseline_stds, color=first_color, hatch=first_hatch, alpha=first_alpha, label="Weight mutation 80% (BL)")
ax5.fill_between(generations, wm40_means + wm40_stds, wm40_means - wm40_stds, color=second_color, alpha=second_alpha, hatch=second_hatch, label="Weight mutation 40%")
ax5.fill_between(generations, wm60_means + wm60_stds, wm60_means - wm60_stds, color=third_color, alpha=third_alpha, hatch=third_hatch, label="Weight mutation 60%")
ax5.set_xlabel("Generation")
ax5.set_ylabel("Pop. Best Fitness")
ax5.legend()

# fig.text(0.04, 0.5, 'common Y', va='center', rotation='vertical')
# plt.ylabel("Population Best Fitness")

fig.tight_layout()
plt.subplots_adjust(wspace=0)
plt.subplots_adjust(hspace=.0)
fig.savefig("stacked_sensitivity_plots.png")
plt.show()


from OpenGL.GL import*
from OpenGL.GLU import*
from OpenGL.GLUT import*
import sys
from math import*

def rasiocanvas():
    glClearColor(0.0,0.8,0.9,1.0)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluOrtho2D(-4,12,-4,12)
    glMatrixMode (GL_MODELVIEW)
    glLoadIdentity()

def Circle_polygon(x_pos, y_pos, radius, sides):
    glBegin(GL_POLYGON)
    for i in range(100):
        cosine= radius * cos(i*2*pi/sides) + x_pos
        sine  = radius * sin(i*2*pi/sides) + y_pos
        glVertex2f(cosine,sine)

def lingkaran_c(x,y):
    glColor3ub(255, 102, 227)
    Circle_polygon(x,y,50.00,100.00)
    glEnd()

def lingkaran_d(x,y):
    glColor3f(0,0,0)
    Circle_polygon(x -18.00,y+ 4.00,10.00,100.00)
    glEnd()

def lingkaran_f(x,y):
    glColor3f(0,0,0)
    Circle_polygon(x+ 18.00,y+ 4.00,10.00,100.00)
    glEnd()

def lingkaran_g(x,y):
    glColor3f(0,0,0)
    Circle_polygon(x -8.00,y+ -15.00,10.00,100.00)
    glEnd()

def lingkaran_h(x,y):
    glColor3f(0,0,0)
    Circle_polygon(x+ 8.00,y+ -15.00,10.00,100.00)
    glEnd()

def gabung(x,y):
    lingkaran_c(x,y)
    lingkaran_d(x,y)
    lingkaran_f(x,y)
    lingkaran_g(x,y)
    lingkaran_h(x,y)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 27 11:29:05 2023

@author: aswinpaul
"""

import numpy as np
from scipy.stats import dirichlet

# %%

class z_learning_agent():
    def __init__(self, numS, numA):
        self.c = 5
        self.eta = 1
        self.epsilon = 0.1

        self.numS = numS
        self.numA = numA

        self.z = np.ones(numS)
        self.p_counts = np.ones((numS, numS))
        self.p = np.zeros((numS, numS))

        for i in range(numS):
            self.p[:,i] = dirichlet.mean(self.p_counts[:,i])

        self.model_counts = np.ones((numS, numA, numS))
        self.model = np.zeros((numS, numA, numS))
        #self.normalise_model()

    def decision_making(self, observation, cond=False):

        self.policy = np.matmul(np.reshape(self.p[:,observation],(self.numS,1)),
                                np.reshape(self.z, (1,self.numS)))
        normaliser = np.sum(self.policy)
        if(normaliser != 0):
            self.policy = self.policy/normaliser

        desired_next_state = np.argmax(self.policy[:,observation])
        self.q_a = self.model_counts[observation,:,desired_next_state]

        #Exploration-rate for e-greedy
        exploration_rate = np.random.uniform(0, 1)

        #Greedy-action
        if(exploration_rate > self.epsilon):
            action = np.argmax(self.q_a)
        #Random-action
        else:
            action = np.random.randint(0,self.numA)
        return(action)

    def update_z(self, prev_obs, reward, observation, tau, terminal=False):
        self.eta = 0.8 #self.c / (self.c + tau)
        term1 = (1 - self.eta)*self.z[prev_obs]
        exp_reward = np.clip(np.exp(reward), None, 1e+5)

        if(terminal):
            term2 = exp_reward
        else:
            term2 = self.eta * exp_reward * self.z[observation]
        self.z[prev_obs] =  term1 + term2

    def update_model(self, prev_obs, action, observation):
        self.model_counts[prev_obs, action, observation] += 1

    def normalise_model_and_p(self):
        for i in range(self.numS):
            for j in range(self.numA):
                self.model[i, j, :] = dirichlet.mean(self.model_counts[i, j, :])

        self.p = np.zeros((self.numS, self.numS))
        for i in range(self.numS):
            self.p[:,i] = dirichlet.mean(self.p_counts[:,i])

        for i in range(self.numS):
            for j in range(self.numS):
                if(self.model_counts[i,:,j].max() < 2):
                    self.p[j,i] = 0
                else:
                    self.p[j,i] = 1

all trial and error/MiniGrid_Empty_small/agent_zlearning.py


import discord, random
from discord.ext import commands

PHONE_ID = "150009549196099584"
KMAC_ID = "206283655159480320"
BOOWER_ID = "152526530239660034"
NIGHTS_ID = "153153882355138560"
ASDF_ID = "134781032086896641"
big_think_limit = 3
big_springu_limit = 3

class General:

  thinking_lines = []
  springu_lines = []

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

  @commands.command(hidden=True)
  async def bigbrains(self, ctx):
    '''
    the brain chamber
    '''

    await ctx.send("BIG BRAINS ONLY <@{0}> <@{1}> <@{2}> <@{3}>".format(KMAC_ID, BOOWER_ID, ASDF_ID, PHONE_ID))

  @commands.command()
  async def emo(self, ctx):
    '''
    im dead inside
    '''

    await ctx.send("I'm so baaadddd <@{0}> :sob:".format(ASDF_ID))

  @commands.command()
  async def jjonak(self, ctx):
    '''
    Is there anyone who can stop this man
    '''

    await ctx.send("LITERAL WALKING BRAIN <@{0}>".format(KMAC_ID));

  @commands.command()
  async def hello(self, ctx):
    '''
    Say hello!
    '''

    msg = 'Hello {0.author.mention}!'.format(ctx.message)
    await ctx.send(msg)

  @commands.command(aliases=["regard"])
  async def thank(self, ctx, *, name:str = None):
    '''
    Thank the bot for its unpayed work
    '''

    msg = ":ok_hand: {0.mention}"

    if name == None:
      msg=msg.format(ctx.message.author)
    else:
      users = ctx.bot.get_all_members()
      match = None

      for user in users:
        if user.name.lower() == name.lower():
          match = user
          break
        elif not user.nick == None:
          if user.nick.lower() == name.lower():
            match = user
            break

      if match == None:
        msg = f"Couldn't thank \"{name}\" because I couldn't find them :sob:"
      else:
        msg=msg.format(match)

    await ctx.send(msg)

  @commands.command()
  async def look(self, ctx):
    '''
    Give them the looker
    '''

    await ctx.send(":eyes:")

  @commands.command()
  async def ping(self, ctx):
    '''
    Ping pong!
    '''

    await ctx.send("Pong! {0}".format(ctx.message.author.mention))

  @commands.command()
  async def daddy(self, ctx):
    '''
    DADDY NO
    '''

    await ctx.send("<@{0}> DADDY NO".format(PHONE_ID))

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


import zope.interface

from repoze.who.interfaces import IChallengeDecider
from repoze.who.plugins.friendlyform import FriendlyFormPlugin as BasePlugin

def challenge_decider(environ, status, headers):
    return status.startswith('403') or status.startswith('401')
zope.interface.directlyProvides(challenge_decider, IChallengeDecider)

class FriendlyFormPlugin(BasePlugin):
    def _get_full_path(self, path, environ):
        """
        Return the full path to ``path`` by prepending the SCRIPT_NAME.
        If ``path`` is a URL, do nothing.
        BBB: If ``path`` start with double /, do nothing
        """
        if path.startswith('//'):
            path = path[1:]
        elif path.startswith('/'):
            path = environ.get('SCRIPT_NAME', '') + path
        return path

def make_plugin(login_form_url, login_handler_path, logout_handler_path,
                rememberer_name, post_login_url=None, post_logout_url=None,
                login_counter_name=None):

    if login_form_url is None:
        raise ValueError(
            'must include login_form_url in configuration')
    if login_handler_path is None:
        raise ValueError(
            'login_handler_path must not be None')
    if logout_handler_path is None:
        raise ValueError(
            'logout_handler_path must not be None')
    if rememberer_name is None:
        raise ValueError(
            'must include rememberer key (name of another IIdentifier plugin)')

    plugin = FriendlyFormPlugin(login_form_url,
                                login_handler_path,
                                post_login_url,
                                logout_handler_path,
                                post_logout_url,
                                rememberer_name,
                                login_counter_name,
                                charset=None)
    return plugin

def rolefinder(identity, request):
    roles = set()
    user = request.authenticated_user or identity.get('user')
    if user and user.active:
        context = request.challenge_item or request.model_instance
        roles = set(['role:%s' % a for a in user.roles_in_context(context)])
    return roles


# from keras_implementation import generator
# from keras_implementation import pipeline
import generator, pipeline
import keras.metrics
keras.metrics.mean_iou = pipeline.mean_iou
from keras import models
import os
import numpy as np
import pandas as pd

# def rle_encoding(x):
#
#     dots = np.where(x.T.flatten() == True)[0]
#     run_lengths = []
#     prev = -2
#     for b in dots:
#         if (b>prev+1): run_lengths.extend((b + 1, 0))
#         run_lengths[-1] += 1
#         prev = b
#     return run_lengths

def rle_encode(img):
    '''
    img: numpy array, 1 - mask, 0 - background
    Returns run length as string formated
    '''
    pixels = img.flatten()
    pixels = np.concatenate([[0], pixels, [0]])
    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
    runs[1::2] -= runs[::2]
    return ' '.join(str(x) for x in runs)

def out_dict_to_rle_dict(dict_with_arrays):
    rle_dict = dict.fromkeys([ids for ids in dict_with_arrays.keys()])
    for id, array_out in dict_with_arrays.items():
        rle = rle_encode(array_out)
        rle_dict[id] = rle
    return rle_dict

from skimage.morphology import label # label regions
def rle_encoding(x):
    '''
    x: numpy array of shape (height, width), 1 - mask, 0 - background
    Returns run length as list
    '''
    dots = np.where(x.T.flatten()==1)[0] # .T sets Fortran order down-then-right
    run_lengths = []
    prev = -2
    for b in dots:
        if (b>prev+1): run_lengths.extend((b+1, 0))
        run_lengths[-1] += 1
        prev = b
    return run_lengths

def prob_to_rles(x, cut_off = 0.5):
    lab_img = label(x>cut_off)
    if lab_img.max()<1:
        lab_img[0,0] = 1 # ensure at least one prediction per image
    for i in range(1, lab_img.max()+1):
        yield rle_encoding(lab_img==i)

if __name__ == '__main__':
    path_img = '../img'
    labels = os.listdir(path_img)[:]
    print(labels)
    prediction_ids = labels[:]

    model_x5 = models.load_model('C:/Users/huubh/Dropbox/DSB_MODEL/model_x88.h5')

    prediction_generator = generator.PredictDataGenerator(prediction_ids[:], path_img)
    predictions = model_x5.predict_generator(prediction_generator)

    out_square = generator.post_process_concat(prediction_ids[:], predictions, threshold=4)

    out_true = generator.post_process_original_size(out_square, path_img)

    # for ids, out_arra in out_true.items():
    #     generator.plot_image_true_mask(ids, out_arra, path_img)
    new_test_ids = []
    rles = []

    for id, arrayx_ in out_true.items():
        rle = list(prob_to_rles(arrayx_))
        rles.extend(rle)
        new_test_ids.extend([id] * len(rle))

    sub = pd.DataFrame()
    sub['ImageId'] = new_test_ids
    sub['EncodedPixels'] = pd.Series(rles).apply(lambda x: ' '.join(str(y) for y in x))
    sub.to_csv('sub.csv', index=False)


import unittest
from unittest.mock import patch, mock_open

from sdk.common.utils.file_utils import load_json_file, load_mongo_dump_file

FILE_UTILS_PATH = "sdk.common.utils.file_utils"

class FileUtilsTestCase(unittest.TestCase):
    @patch(f"{FILE_UTILS_PATH}.json")
    @patch(f"{FILE_UTILS_PATH}.Path")
    def test_load_json_file(self, mock_path, mock_json):
        path = "path_to_file"

        load_json_file(path=path)

        mock_json.loads.assert_called_once_with(mock_path().read_text())

    @patch(f"{FILE_UTILS_PATH}.open", mock_open())
    @patch(f"{FILE_UTILS_PATH}.logger")
    @patch(f"{FILE_UTILS_PATH}.json")
    @patch(f"{FILE_UTILS_PATH}.Database")
    def test_load_mongo_dump_file(self, mock_db, mock_json, mock_logger):
        user_1 = {"_id": 1, "name": "Name #1"}
        user_2 = {"_id": 2, "name": "Name #2"}

        mock_json.load.return_value = {0: [user_1], 1: [user_2]}

        file_path = "path_to_file"

        load_mongo_dump_file(file_path=file_path, database=mock_db)

        mock_db[2].update_one.assert_called_with(
            {"_id": user_2["_id"]}, {"$set": user_2}, upsert=True
        )
        mock_logger.info.assert_called()

if __name__ == "__main__":
    unittest.main()


import pickle
from typing import Tuple

import numpy as np

class SpatialPooler:
    def __init__(
        self,
        input_dimension: Tuple[int],
        column_dimension: Tuple[int],
        connection_sparsity: float,
        permanence_threshold: float,
        stimulus_threshold: float,
        permanence_increment: float,
        permanence_decrement: float,
        column_sparsity: float,
        potential_pool_radius: int,
        boost_strength: float,
        seed: int = 42,
    ):
        self.input_dimension = np.array(input_dimension)
        self.column_dimension = np.array(column_dimension)
        self.number_of_inputs = np.prod(input_dimension)
        self.number_of_columns = np.prod(column_dimension)

        self.synapse_connection_size = int(self.number_of_inputs * connection_sparsity)
        self.connection_sparsity = connection_sparsity
        self.potential_pool_radius = potential_pool_radius

        self.permanence_threshold = permanence_threshold
        self.stimulus_threshold = stimulus_threshold

        self.permanence_increment = permanence_increment
        self.permanence_decrement = permanence_decrement

        self.column_sparsity = column_sparsity
        self.number_of_active_columns = int(self.number_of_columns * column_sparsity)

        self.potential_pools = np.zeros(
            (self.number_of_columns, self.number_of_inputs), dtype=bool
        )

        self.permanences = np.zeros(
            (self.number_of_columns, self.number_of_inputs), dtype=float
        )

        self.connected_synapses = np.zeros(
            (self.number_of_columns, self.number_of_inputs), dtype=bool
        )

        self.boost_strength = boost_strength
        self.boost_factors = np.ones(self.number_of_columns, dtype=float)
        self.overlap_duty_cycles = np.zeros(self.number_of_columns, dtype=float)
        self.active_duty_cycle = np.zeros(self.number_of_columns, dtype=float)
        self.duty_cycle_period = 1000
        self.iteration = 1

        np.random.seed(seed)

        self._initialize()

    def get_potential_pool_center(self, column_idx: int) -> int:
        """
        this function returns the index of the center of the potential pool
        given a column index. It distributes the potential pool evenly over the
        input space.

        :param column_idx: index of the column

        :return: index of the center of the potential pool
        """

        column_coords = np.array(np.unravel_index(column_idx, self.column_dimension))

        # does this normalise the coords?
        ratios = column_coords / self.column_dimension
        input_coords = ratios * self.input_dimension
        input_coords += 0.5 * self.input_dimension / self.column_dimension
        inputs_coords = input_coords.astype(int)

        center_index = np.ravel_multi_index(  # type: ignore
            inputs_coords, self.input_dimension, mode="clip"
        )

        return center_index

    def get_neighborhood(self, center_index: int) -> np.ndarray:
        """
        Returns the indices of the neighborhood of a given center index by
        taking all indices within a radius of <self.potential_pool_radius>

        :param center_index: index of the center

        :return: indices of the neighborhood
        """

        center_coords = np.array(np.unravel_index(center_index, self.input_dimension))
        intervals = []
        for idx, dimension in enumerate(self.input_dimension):
            left = max(0, center_coords[idx] - self.potential_pool_radius)
            right = min(dimension, center_coords[idx] + self.potential_pool_radius)
            intervals.append(np.arange(left, right + 1))

        neighborhood = np.array(np.meshgrid(*intervals)).T.reshape(
            -1, len(self.input_dimension)
        )

        return neighborhood

    def get_potential_pool(self, column_idx: int) -> np.ndarray:
        """
        Returns the indices of the potential pool of a given column by
        calculating the center of the potential pool given a column index
        and then calculating the neighborhood of that center.

        :param column_idx: index of the column

        :return: indices of the potential pool
        """

        # check if potential_pool_radius is as large to cover whole area

        if ((self.potential_pool_radius * 2) >= self.input_dimension).all():
            indices = np.arange(self.number_of_inputs)
        else:
            center_index = self.get_potential_pool_center(column_idx)
            neighborhood = self.get_neighborhood(center_index)

            indices = np.ravel_multi_index(  # type: ignore
                neighborhood.T, self.input_dimension, mode="clip"
            )

        return indices

    def set_connected_synapses(self, permanences: np.ndarray):
        self.connected_synapses = permanences >= self.permanence_threshold

    def _init_potential_pools(self):
        """
        Initializes the potential pools of all columns.
        A potential pool is a set of input bits that a column can connect to.
        """

        for column in range(self.number_of_columns):
            potential_pool_indices = self.get_potential_pool(column)
            no_connections = int(
                len(potential_pool_indices) * self.connection_sparsity + 0.5
            )

            # get <no_connections> random indices from potential pool indices
            connections = np.random.choice(
                potential_pool_indices,
                size=no_connections,
                replace=False,
            )
            self.potential_pools[column, connections] = True

    def _init_permanences(self):
        for column in range(self.number_of_columns):
            potential_pool_size = np.sum(self.potential_pools[column, :])

            permanences = np.random.uniform(0, 1, potential_pool_size)

            self.permanences[column, self.potential_pools[column, :]] = permanences

    def _init_connected_synapses(self):
        self.set_connected_synapses(self.permanences)

    def _initialize(self):
        self._init_potential_pools()
        self._init_permanences()
        self._init_connected_synapses()

    def calculate_overlap(self, input_vector: np.ndarray) -> np.ndarray:
        """
        Calculates the overlap of the input vector with the columns.
        The overlap is defined as the number of on bits (1's) in the input vector
        that overlap with the connected synapses of a column.

        :param input_vector: the input vector

        :return: the overlap of the input vector with the columns shape: (number_of_columns,)
        """
        overlap = np.zeros(self.number_of_columns, dtype=float)
        input_flattened = input_vector.flatten()

        for column in range(self.number_of_columns):
            overlap[column] = np.sum(
                np.logical_and(
                    input_flattened, self.connected_synapses[column, :]
                ).astype(int)
            )

        return overlap

    def boost_columns(self, overlap: np.ndarray) -> np.ndarray:
        boosted_overlap = overlap * self.boost_factors
        return boosted_overlap

    def get_winning_columns(self, overlap: np.ndarray) -> np.ndarray:
        """
        Selects <number_of_active_columns> columns with the highest overlap
        which are above the stimulus threshold and returns their indices.

        :param overlap: the overlap of the input vector with the columns shape: (number_of_columns,)

        :return: the indices of the winning columns
        """

        # sort indices by overlap count in descending order and
        # select the first <number_of_active_columns> indices
        top_columns = np.argsort(overlap)[::-1][: self.number_of_active_columns]

        # select only the indices that are above the stimulus threshold
        winning_columns = top_columns[overlap[top_columns] >= self.stimulus_threshold]

        return winning_columns

    def top_columns_to_sdr(self, top_columns: np.ndarray) -> np.ndarray:
        """
        Converts the indices of the winning columns into an SDR.

        :param top_columns: the indices of the winning columns

        :return: SDR with shape (number_of_columns,)
        """

        sdr = np.zeros(self.number_of_columns, dtype=bool)
        sdr[top_columns] = True
        return sdr

    def update_permanences(self, input_vector: np.ndarray, top_columns: np.ndarray):
        flattened_input = input_vector.flatten()
        flipped_flattened_input = np.logical_not(flattened_input)

        for column_idx in top_columns:
            active = np.logical_and(
                flattened_input, self.potential_pools[column_idx, :]
            )

            inactive = np.logical_and(
                flipped_flattened_input, self.potential_pools[column_idx, :]
            )

            # increase active synapses
            self.permanences[column_idx, active == True] += self.permanence_increment

            # decrease inactive synapses
            self.permanences[column_idx, inactive == True] -= self.permanence_decrement

            # clip permanences to [0, 1] -> faster than np.clip
            self.permanences[column_idx, active > 1] = 1
            self.permanences[column_idx, inactive < 0] = 0

        self.set_connected_synapses(self.permanences)

    def calculate_moving_average(
        self, duty_cycles: np.ndarray, period: int, new_value: np.ndarray
    ) -> np.ndarray:
        moving_average = ((period - 1) * duty_cycles + new_value) / (period)
        return moving_average

    def update_duty_cycles(
        self, overlap_columns: np.ndarray, active_columns: np.ndarray
    ):

        overlap = np.zeros(self.number_of_columns, dtype=float)
        overlap[overlap_columns > 0] = 1

        active = np.zeros(self.number_of_columns, dtype=float)
        active[active_columns] = 1

        period = self.duty_cycle_period
        if period > self.iteration:
            period = self.iteration

        self.overlap_duty_cycles = self.calculate_moving_average(
            self.overlap_duty_cycles, period, overlap
        )
        self.active_duty_cycle = self.calculate_moving_average(
            self.active_duty_cycle, period, active
        )

    def exp_boost_function(
        self, boost_strength: np.ndarray, duty_cycle: np.ndarray, target_density: float
    ):
        return np.exp((target_density - duty_cycle) * boost_strength)

    def update_boost_factors(self):
        self.boost_factors = self.exp_boost_function(
            self.boost_strength, self.active_duty_cycle, self.column_sparsity
        )

    def save_state(self, path: str):
        with open(path, "wb") as f:
            pickle.dump(self, f)

    def load_state(self, path: str):
        with open(path, "rb") as f:
            temp = pickle.load(f)
            self.__dict__.update(temp.__dict__)

    def compute(self, input_vector: np.ndarray, learn: bool) -> np.ndarray:
        """
        Computes active columns for given input vector
        and applies boost and updates internal permanences if learning is on

        :param input_vector: input vector with shape <input_dimension>
        :param learn: if True, learning is applied

        :return: active columns with shape <number_of_columns>
        """
        assert (
            np.array(input_vector.shape) == self.input_dimension
        ).all(), f"Input vector has wrong shape. Expected {self.input_dimension}, got {input_vector.shape}"

        overlap = self.calculate_overlap(input_vector)

        if learn:
            overlap = self.boost_columns(overlap)

        winning_columns = self.get_winning_columns(overlap)

        if learn:
            self.update_permanences(input_vector, winning_columns)
            self.update_duty_cycles(overlap, winning_columns)
            # TODO bump weak columns
            self.update_boost_factors()

        self.iteration += 1

        return winning_columns


from __future__ import absolute_import
from __future__ import division

from __future__ import print_function

import abc
import collections
import logging
import numpy as np
import six
from tensorflow_data_validation import types
from tensorflow_data_validation.statistics.generators import stats_generator
from tensorflow_data_validation.utils import stats_util
from tensorflow_data_validation.types_compat import Dict, List, Text, Tuple

from tensorflow_metadata.proto.v0 import statistics_pb2

_IS_IMAGE_STATISTICS = 'is_image'
_MAX_IMAGE_WIDTH_STATISTICS = 'max_image_width'
_MAX_IMAGE_HEIGHT_STATISTICS = 'max_image_height'
_IMAGE_FORMAT_HISTOGRAM = 'image_format_histogram'

class ImageDecoderInterface(six.with_metaclass(abc.ABCMeta)):
  """Util class interface for getting image content metadata."""

  @abc.abstractmethod
  def get_format(self, content):
    """Returns the image type name if the content represents an image.

    Args:
      content: content in bytes to check the image format.

    Returns:
      Image type name (e.g. 'JPG'/'GIF'/etc) if the content represents an
      image. Otherwise returns an empty string.
    """
    raise NotImplementedError

  @abc.abstractmethod
  def get_size(self, content):
    """Returns the image size.

    Args:
      content: content in bytes to get the image size.

    Returns:
      A (image_height, image_width) tuple if the content represents an
      image.
    """
    raise NotImplementedError

class _PartialImageStats(object):
  """Partial statistics for computing the image statistics for a single feature.
  """

  def __init__(self):
    # A dict from image format string to the number of images in this format.
    self.counter_by_format = collections.Counter()
    # The total number of values processed for this feature.
    self.total_num_values = 0
    # The maximum image width among all the values for this feature.
    self.max_image_width = 0
    # The maximum image height among all the values for this feature.
    self.max_image_height = 0

def _update_partial_image_stats(
    image_stats,
    value,
    image_decoder):
  """Updates the partial image statistics using the input value."""
  for v in value:
    image_stats.total_num_values += 1
    image_type = image_decoder.get_format(v)
    image_stats.counter_by_format[image_type] += 1

    # If this is actually an image, update the max image height/width.
    if image_type:
      image_height, image_width = image_decoder.get_size(v)
      image_stats.max_image_height = max(image_stats.max_image_height,
                                         image_height)
      image_stats.max_image_width = max(image_stats.max_image_width,
                                        image_width)

def _merge_image_stats(
    left, right):
  """Merges two partial image statistics and return the merged statistics."""
  result = _PartialImageStats()
  result.total_num_values = left.total_num_values + right.total_num_values
  result.max_image_width = max(left.max_image_width, right.max_image_width)
  result.max_image_height = max(left.max_image_height, right.max_image_height)
  result.counter_by_format = left.counter_by_format + right.counter_by_format
  return result

def _make_feature_stats_proto(
    image_stats,
    feature_name):
  """Converts the partial image statistics into FeatureNameStatistics proto."""
  result = statistics_pb2.FeatureNameStatistics()
  result.name = feature_name

  # TODO(mingzhong): Need to add set any other fields?

  result.custom_stats.add(name=_IS_IMAGE_STATISTICS, num=1)

  # Max image width stats.
  result.custom_stats.add(
      name=_MAX_IMAGE_WIDTH_STATISTICS, num=image_stats.max_image_width)

  # Max image height stats.
  result.custom_stats.add(
      name=_MAX_IMAGE_HEIGHT_STATISTICS, num=image_stats.max_image_height)

  # Image type histogram.
  custom_stats = result.custom_stats.add()
  custom_stats.name = _IMAGE_FORMAT_HISTOGRAM

  # Add the buckets with sorted image type.
  for image_type in sorted(image_stats.counter_by_format):
    custom_stats.rank_histogram.buckets.add(
        label=image_type if image_type else 'UNKNOWN',
        sample_count=image_stats.counter_by_format[image_type])
  return result

class ImageStatsGenerator(stats_generator.CombinerStatsGenerator):
  """Computes the statistics for features of image type.

  """

  def __init__(self,
               image_decoder,
               name = 'ImageStatsGenerator',
               is_image_ratio_threshold = 0.8):
    """Initializes an image statistics generator.

    Args:
      image_decoder: ImageDecoderInterface instance for fetching image metadata.
      name: An optional unique name associated with the statistics generator.
      is_image_ratio_threshold: An optional threshold for checking if a feature
        should be treated as image feature. If the percentage of image features
        values for a feature is below this threshold, we won't generate the
        image statistics for this feature.
    """
    super(ImageStatsGenerator, self).__init__(name)
    self._image_decoder = image_decoder
    self._is_image_ratio_threshold = is_image_ratio_threshold

  # Creates an accumulator, which maps feature name to the partial image stats
  # associated with the feature.
  def create_accumulator(self):
    return {}

  # Incorporates the input (a Python dict whose keys are feature names and
  # values are numpy arrays representing a batch of examples) into the
  # accumulator.
  def add_input(self, accumulator,
                input_batch
               ):
    # Iterate through each feature and update the partial image stats.
    for feature_name, values in six.iteritems(input_batch):
      # TODO(mingzhong): Maybe skip features specified as categorical/numerical
      # features in schema.
      for value in values:
        # Check if we have a numpy arary with at least one value.
        if not isinstance(value, np.ndarray) or value.size == 0:
          continue

        # Check if the numpy array is of bytes type -- we skip checking image
        # statistics for numeric data.
        #
        # Note that it is intentional to not include count this in
        # total_num_values, as tfdv assumes that all values for the same feature
        # have the same numpy array dtype.
        # TODO(b/120138003): Run image stats gen for only a sample of examples.
        # TODO(b/118066476): Make image stas gen accept a function for filtering
        # in examples/features to run image stas gen on.
        if stats_util.get_feature_type(
            value.dtype) != statistics_pb2.FeatureNameStatistics.STRING:
          continue

        # If we encounter this feature for the first time, create a new partial
        # numeric stats.
        if feature_name not in accumulator:
          accumulator[feature_name] = _PartialImageStats()

        # Update the partial image stats.
        _update_partial_image_stats(accumulator[feature_name], value,
                                    self._image_decoder)
    return accumulator

  # Merges together a list of partial image statistics.
  def merge_accumulators(
      self, accumulators
  ):
    result = {}
    for accumulator in accumulators:
      for feature_name, image_stats in accumulator.items():
        if feature_name not in result:
          result[feature_name] = image_stats
        else:
          result[feature_name] = _merge_image_stats(result[feature_name],
                                                    image_stats)
    return result

  # Return final stats as a DatasetFeatureStatistics proto.
  def extract_output(self,
                     accumulator
                    ):
    # Create a new DatasetFeatureStatistics proto.
    result = statistics_pb2.DatasetFeatureStatistics()

    for feature_name, image_stats in six.iteritems(accumulator):
      # Only generate an image statistics proto if the ratio of image feature
      # values is above a threshold.
      if image_stats.total_num_values <= 0 or (
          1 - (image_stats.counter_by_format[''] /
               image_stats.total_num_values)) < self._is_image_ratio_threshold:
        logging.warning(
            'Ratio of image values for feature %s is below threshold',
            feature_name)
        continue

      feature_stats_proto = _make_feature_stats_proto(image_stats, feature_name)
      new_feature_stats_proto = result.features.add()
      new_feature_stats_proto.CopyFrom(feature_stats_proto)
    return result


def cached_make_env(make_env):
    """
    Only creates a new environment from the provided function if one has not yet already been
    created. This is useful here because we need to infer certain properties of the env, e.g.
    its observation and action spaces, without any intend of actually using it.
    """
    if make_env not in CACHED_ENVS:
        env = make_env()
        CACHED_ENVS[make_env] = env
    return CACHED_ENVS[make_env]


# advent of code day 1
# Input: Number of calories each elf is carrying
# each elf's inventory is separated by a line and each block is the calories of the items that an elf has brought
# Find how many calories are carried by the elf carrying the most calories

# open file in read mode
my_file = open("input1.txt", "r")

# read the file

data = my_file.read()

# split the data for each vertical space
calories = data.split("\n")

def max_calories(calories):
    # store each elfs inventory in current. If current is larger than max
    # set max equal to current
    current = 0
    max = 0
    for i in calories:
        if len(i) != 0:
            current += int(i)

        else:
            if current > max:
                max = current
            current = 0

    return max

# print(max_calories(calories))

def top_3_calories(calories):
    current = 0
    top_1 = 0
    top_2 = 0
    top_3 = 0

    for i in calories:
        if len(i) != 0:
            current += int(i)

        else:
            if current > top_1:
                top_2 = top_1
                top_1 = current
            elif current > top_2 and current < top_1:
                top_3 = top_2
                top_2 = current
            elif current > top_3 and current < top_2:
                top_3 = current
            current = 0
    return top_1 + top_2 + top_3

print(top_3_calories(calories))


import tkinter as tk
from tkinter import messagebox
import time
import sqlite3
import requests
import sys

##########################

def guardarEncargado(data):
    datosIn = (data["nombre"],data["ingreso"],"IN",0)
    datosOut = (data["nombre"],data["egreso"],"OUT",data["facturado"])
    conn = sqlite3.connect("comercio.sqlite")
    cursor = conn.cursor()
    try:
        cursor.execute("INSERT INTO registro VALUES (null,?,?,?,?)", datosIn)
        cursor.execute("INSERT INTO registro VALUES (null,?,?,?,?)", datosOut)
    except sqlite3.OperationalError:
        cursor.execute("""CREATE TABLE registro
        (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            encargado TEXT,
            fecha TEXT,
            evento TEXT,
            caja REAL
        )
        """)
        cursor.execute("INSERT INTO registro VALUES (null,?,?,?,?)", datosIn)
        cursor.execute("INSERT INTO registro VALUES (null,?,?,?,?)", datosOut)
    conn.commit()
    conn.close

def guardarVentas(data):
    datos = tuple(data)
    conn = sqlite3.connect("comercio.sqlite")
    cursor = conn.cursor()
    try:
        cursor.execute("INSERT INTO ventas VALUES (null,?,?,?,?,?,?,?)", datos)
    except sqlite3.OperationalError:
        cursor.execute("""CREATE TABLE ventas
        (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            cliente TEXT,
            fecha TEXT,
            ComboS INT,
            ComboD INT,
            ComboT INT,
            Flurby INT,
            total REAL
        )
        """)
        cursor.execute("INSERT INTO ventas VALUES (null,?,?,?,?,?,?,?)", datos)
    conn.commit()
    conn.close

def cotizar():
    try:
        r = requests.get("https://api-dolar-argentina.herokuapp.com/api/dolaroficial")
        valor = r.json()["venta"]
        valor = round(float(valor))
        return valor
    except:
        messagebox.showerror(title="Error grave", message="Sin internet para cotizar. Terminado")
        sys.exit()

def validar(dato):
	try:
		dato = int(dato)
		return dato
	except ValueError:
		return -1

def borrar():
    #no borramos el encargado, para no tener que estar reescribiendolo siempre
    ccomboUno.delete(0,tk.END)
    ccomboDos.delete(0,tk.END)
    ccomboTres.delete(0,tk.END)
    cpostre.delete(0,tk.END)
    ccliente.delete(0,tk.END)

def cancelar_pedido():
	respuesta = messagebox.askyesno(title="Pregunta", message="¿Desea cancelar el pedido?")
	if respuesta:
		borrar()

def pedir():
    cantUno= ccomboUno.get()
    cantUno = validar(cantUno)
    cantDos = ccomboDos.get()
    cantDos = validar(cantDos)
    cantTres = ccomboTres.get()
    cantTres = validar(cantTres)
    cantPostre = cpostre.get()
    cantPostre = validar(cantPostre)
    dolar = cotizar()
    if cantUno>=0 and cantDos>=0 and cantTres>=0 and cantPostre>=0:
        cliente = ccliente.get()
        encargado = cencargado.get()
        if cliente and encargado:
            respuesta = messagebox.askyesno(title="Pregunta", message="¿Confirma el pedido?")
            if respuesta:
                costot = ((cantUno*precios["ComboSimple"])+(cantDos*precios["ComboDoble"])+(cantTres*precios["ComboTriple"])+(cantPostre*precios["Flurby"]))
                totalPesos = costot * dolar
                fecha = time.asctime()
                pedido = [cliente,fecha,cantUno,cantDos,cantTres,cantPostre,totalPesos]
                messagebox.showinfo(title="A pagar", message="$"+str(totalPesos))
                guardarVentas(pedido)
                messagebox.showinfo(title="Información", message="Pedido Exitoso")
                if  datosEncargado["nombre"] != encargado and datosEncargado["egreso"] == "" : # cuando inicia la app egreso es vacio
                    datosEncargado["nombre"] = encargado
                    datosEncargado["egreso"] = "SinFecha" # es solo para que la proxima no cumpla la condición, es solo al inicio
                    datosEncargado["facturado"] += totalPesos #voy incrementando totales
                elif datosEncargado["nombre"] == encargado:
                    datosEncargado["facturado"] += totalPesos #voy incrementando totales
                else:
                    datosEncargado["egreso"] = fecha # al cambiar de encargado registro la fecha
                    guardarEncargado(datosEncargado) # guardo
                    #borramos el encargado anterior, en el diccionario ponemos el nuevo
                    datosEncargado["nombre"] = encargado # iniciamos el nuevo encargado
                    datosEncargado["Ingreso"] = fecha
                    datosEncargado["facturado"] = 0
                    datosEncargado["facturado"] += totalPesos
                borrar()
            else:
                messagebox.showinfo(title="Información", message="Pedido en pausa")
        else:
            messagebox.showwarning(title="Advertencia", message="Error, ingrese bien los datos")
    else:
        messagebox.showwarning(title="Advertencia", message="Error, ingrese datos correctos")

def salir():
    #salir seguro implica guardar el último encargado
    respuesta = messagebox.askyesno(title="Pregunta", message="¿Desea salir?")
    if respuesta:
        datosEncargado["egreso"] = time.asctime()
        guardarEncargado(datosEncargado)
        sys.exit()

##########################

precios = {"ComboSimple":5,"ComboDoble":6,"ComboTriple":7,"Flurby":2}
datosEncargado = {"nombre":"","ingreso":time.asctime(),"egreso":"","facturado":0}

##########################

ventana = tk.Tk()
ventana.config(width = 400, height = 400)
ventana.title("Delivery")

#####etiquetas######
ebienvenido = tk.Label(text="------ Pedidos -------")
ebienvenido.place(x = 140, y = 20)

enombreEncargado = tk.Label(text = "Nombre Encargado : ")
enombreEncargado.place(x = 50, y = 70)
ecomboUno = tk.Label(text = "Combo S cantidad : ")
ecomboUno.place(x = 50, y = 110)
ecomboDos = tk.Label(text = "Combo D cantidad : ")
ecomboDos.place(x = 50, y = 150)
ecomboTres = tk.Label(text = "Combo T cantidad : ")
ecomboTres.place(x = 50, y = 190)
ecliente = tk.Label(text = "Postre cantidad : ")
ecliente.place(x = 50, y = 230)
epostre = tk.Label(text = "Nombre del cliente : ")
epostre.place(x = 50, y = 270)

#####cajas#########

cencargado = tk.Entry()
cencargado.place(x = 230, y = 70)
ccomboUno = tk.Entry()
ccomboUno.place(x = 230, y = 110)
ccomboDos = tk.Entry()
ccomboDos.place(x = 230, y = 150)
ccomboTres = tk.Entry()
ccomboTres.place(x = 230, y = 190)
cpostre = tk.Entry()
cpostre.place(x = 230, y = 230)
ccliente = tk.Entry()
ccliente.place(x = 230, y = 270)

##### Botones #########

bpedido = tk.Button(text = "Hacer Pedido", command = pedir)
bpedido.place(x = 270 , y = 330, height=40, width = 100)

bcancelar = tk.Button(text = "Cancelar Pedido", command = cancelar_pedido)
bcancelar.place(x = 150 , y = 330, height=40, width = 100)

binfo = tk.Button(text = "Salir seguro",command=salir)
binfo.place(x = 30 , y = 330, height=40, width = 100)

ventana.mainloop()


from django.shortcuts import render, redirect
from .models import UserInput

# Create your views here.
def user_input_screen(request):
    if not request.user.is_authenticated:
        return redirect("/")

    if request.method == "POST":
        if request.POST.get("input_data"):
            high_blood_pressure = request.POST.get("high_blood_pressure")
            low_blood_pressure = request.POST.get("low_blood_pressure")
            date_recorded = request.POST.get("date_recorded")
            current_user = request.user

            print(high_blood_pressure)
            print(low_blood_pressure)
            print(date_recorded)
            print(current_user)

            # If user does not input a date, use current date
            if (not date_recorded):
                user_input = UserInput.objects.create(high_blood_pressure=high_blood_pressure,
                                                      low_blood_pressure=low_blood_pressure,
                                                      user=current_user)

            else:
                user_input = UserInput.objects.create(current_date=date_recorded,
                                                      high_blood_pressure=high_blood_pressure,
                                                      low_blood_pressure=low_blood_pressure,
                                                      user=current_user)
            user_input.save()

            user= request.user
            user_data = UserInput.objects.all().filter(user__username__contains=user.username)
            dates = []
            sys = []
            dia = []
            print(type(user_data[0].current_date))
            for data_point in user_data:
                sys.append(str(data_point.high_blood_pressure))
                dia.append(str(data_point.low_blood_pressure))
                dates.append(str(data_point.current_date)[:10])
            return render(request, "doctorpatient/patientdashboard.html",
            {'labels' : dates,
            'dia_data': dia,
            'sys_data': sys})

    return render(request, "input/user_input.html")


import re
import sys
from indic_romanizer_utils import convert_text

if __name__ == '__main__':
    if len(sys.argv) != 1:
        # We don't take arguments
        print("Usage: %s < indic.input > romanized.output" % sys.argv[0],
              file=sys.stderr)
        sys.exit(-1)

    comment_pattern = r'#.*$'
    comment_regex = re.compile(comment_pattern)

    for line in sys.stdin:
        line = comment_regex.sub("", line)
        line = line.strip()
        if not line:
            continue

        try:
            roman_form, indic_form = line.split('\t')
        except ValueError:
            print("Invalid line: %s" % line, file=sys.stderr)
            continue

        roman_form = roman_form.lower()
        phonetic_form = convert_text(indic_form)['phonetic_form']

        print(' : '.join([roman_form, phonetic_form]))


#!/usr/bin/env python3
# coding: utf-8

# @Time    : 2019/3/13 14:52
# @Author  : Zhanhui
# @File    : my_url.py

from django.core.validators import URLValidator

def check_valid_url(url):
    """
    检测传入的url是否正确的格式。
    :param url:
    :return:
    """

    check = False

    try:
        val_obj = URLValidator()
        val_obj(url)
    except Exception as e:
        del e

    return check


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time

start = time.clock()  #Program excution time
ims = []
fig = plt.figure()
data = np.ones((150, 150))

def dataInit():
    partyVotes = np.random.choice(
        [0, 1], [150, 150, 3], replace=True,
        p=[0.9, 0.1])  # 150*150 cells, 0 is supporting party 0, 1 is party1
    readNews = np.random.choice(
        [0, 1], [150, 150, 1], replace=True,
        p=[0.7, 0.3])  #Distribution of people who read political medias
    tolerance = np.random.choice(
        [5, 6, 7, 8], [150, 150, 1], replace=True, p=[1, 0, 0, 0]
    )  # How taugh for a person to change his opinion: level 5,6,7,8 from easy to difficult
    for x in range(partyVotes.shape[0]):
        for y in range(partyVotes.shape[1]):
            partyVotes[x][y][1] = readNews[x][y]
            partyVotes[x][y][2] = tolerance[x][y]
    return partyVotes

def runMajorityWin(partyVotes):
    for x in range(1, partyVotes.shape[0] - 1):
        for y in range(1, partyVotes.shape[1] - 1):
            data[x][y] = partyVotes[x][y][0]
            opinionChange(partyVotes, x, y)
    #print('data', data)

def opinionChange(partyVotes, x,
                  y):  #0(voting for party 0) -> 1(party 1) or 1 -> 0
    if partyVotes[x][y][0] == 0:
        if sumOfNeighbors(
                partyVotes, x, y
        ) >= partyVotes[x][y][2]:  # if the num of positive neighbors > tolerance, opinion changed
            partyVotes[x][y][0] = 1
    else:
        if 9 - sumOfNeighbors(
                partyVotes, x, y
        ) >= partyVotes[x][y][2]:  # if the num of negative neighbors > tolerance, opinion changed
            partyVotes[x][y][0] = 0

def sumOfNeighbors(partyVotes, x, y):  #calculate the sum of neighbours
    sum1 = 0
    sum2 = 0
    sum3 = 0
    firRowNeighbors = partyVotes[x - 1][y - 1:y + 2]
    secRowNeighbors = partyVotes[x][y - 1:y + 2]
    thrRowNeighbors = partyVotes[x + 1][y - 1:y + 2]

    for x in range(firRowNeighbors.shape[1]):
        sum1 += firRowNeighbors[x][0]
        sum2 += secRowNeighbors[x][0]
        sum3 += thrRowNeighbors[x][0]
    sumOfNeighbors = sum((sum1, sum2, sum3))
    return sumOfNeighbors

def animationDraw():  #Save video to working dir
    plt.legend()
    plt.axis('off')
    im_ani = animation.ArtistAnimation(
        fig, ims, interval=700, repeat_delay=2000, blit=True)
    plt.show()
    im_ani.save('votingmodel.mp4', writer=animation.FFMpegWriter())

days = 10
partyVotes = dataInit()
for day in range(days):
    runMajorityWin(partyVotes)
    ims.append((plt.imshow(data, cmap='YlOrBr', interpolation='nearest'), ))
print(partyVotes)
animationDraw()
minElapsed = (time.clock() - start) / 60
print(minElapsed, "mins are consumed")


import timeit
import gzip
from parse import dgidb, disgenet
from statistics import mean
import os

try:
    os.mkdir('../data/processed')
except FileExistsError:
    pass

start = timeit.default_timer()

print('Parsing DGIDB')
dgidb_ = dgidb.parse()

print('Parsing DISGENET')
disgenet_ = disgenet.parse()

dgidb_.interactions = {x: dgidb_.interactions[x]
                       for x in disgenet_.interactions.keys()}

print('Generating drugs')
with gzip.open('../data/processed/drugs.tsv.gz', 'wt') as f:
    f.write('Id\tName\n')
    for x_id, x in dgidb_.drug_names.items():
        f.write(f'{x_id}\t{x}\n')

print('Generating diseases')
with gzip.open('../data/processed/diseases.tsv.gz', 'wt') as f:
    f.write('Id\tName\tClass\n')
    for x_id, x in disgenet_.dis.items():
        f.write(f'{x_id}\t{x.name}\t{";".join(x.classes)}\n')

print('Generating interactions, evidences')
with gzip.open('../data/processed/interactions.tsv.gz', 'wt') as fi:
    with gzip.open('../data/processed/evidences.tsv.gz', 'wt') as fe:
        fi.write('Id\tDrugId\tDiseaseId\tScore\tGene\tType\n')
        fe.write('InteractionId\tPmid\tScore\n')

        ii = 0

        for g, dis_ls in disgenet_.interactions.items():
            drug_ls = dgidb_.interactions[g]

            for disi in dis_ls:
                for drugi in drug_ls:
                    disgenet_score = mean([evidence.score for evidence in disi.evidences])
                    score = drugi.score * disgenet_score
                    type = int(drugi.ty == disi.ty)

                    # Generate evidences

                    for pmid in drugi.pmids:
                        fe.write(f'{ii}\t{pmid}\t{drugi.score}\n')

                    for evidence in disi.evidences:
                        fe.write(f'{ii}\t{evidence.pmid}\t{evidence.score}\n')

                    fi.write(f'{ii}\t{drugi.drug}\t{disi.dis}\t{score}\t{type}\n')

                    ii += 1

print(f'Completed in {timeit.default_timer() - start:.1f} s')


'''Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

'''

class Solution:
    def lengthOfLastWord(self, s: str) -> int:

        length = 0
        i = 0
        while i < len(s):

            if s[i] == ' ':
                while i < len(s) and s[i] == ' ':
                    i += 1
                if i == len(s):
                    break
                else:
                    length = 0
            else:
                length += 1
                i += 1

        return length


import io
import tempfile
from unittest import mock

from PIL import Image
from django.core.files import File
from django.core.files.base import ContentFile
from django.test import TestCase, Client, override_settings
from django.urls import reverse
from posts.models import Post, Group, User
from django.core.cache import cache

class PostTests(TestCase):
    def setUp(self):
        cache.clear()
        self.no_auth_client = Client()
        self.auth_client = Client()
        self.auth_client2 = Client()
        self.auth_client3 = Client()
        self.user = User.objects.create_user(
            username='testuser',
            email='test@test.ru',
        )
        self.user2 = User.objects.create_user(
            username='testuser2',
            email='test2@test.ru',
        )
        self.user3 = User.objects.create_user(
            username='testuser3',
            email='test3@test.ru',
        )
        self.group = Group.objects.create(
            title='test',
            slug='test_group',
            description='empty'
        )
        self.auth_client.force_login(self.user)
        self.auth_client2.force_login(self.user2)
        self.auth_client3.force_login(self.user3)

    def create_post(self):
        return Post.objects.create(
            text='test text new post',
            author=self.user,
            group=self.group)

    def create_post_with_image(self, image):
        return Post.objects.create(
            text='test text new post with image',
            author=self.user,
            group=self.group,
            image=image)

    def check_text_in_url(self, text):
        author = self.post.author
        group = self.post.group
        for url in (
            reverse('index'),
            reverse('profile', kwargs={'username': self.user.username}),
            reverse('post_view', kwargs={'username': self.user.username,
                                         'post_id': self.post.id})):
            with self.subTest(url=url):
                response = self.auth_client.get(url)
                #  проверку паджинатора убрал - его нет на странице с постом
                self.assertContains(response, text),
                self.assertEqual(response.context['post'].author, author),
                self.assertEqual(response.context['post'].group, group)

    def test_profile(self):
        response = self.no_auth_client.get(
            reverse('profile', kwargs={'username': self.user.username}))
        self.assertEqual(response.status_code, 200)

    def test_no_auth_new_post(self):
        response = self.no_auth_client.post(
            reverse('new_post'), data={'text': 'test text'})
        self.assertNotEqual(response.status_code, 200)
        self.assertRedirects(response, '/auth/login/?next=/new')

    def test_auth_new_post(self):
        response = self.auth_client.post(
            reverse('new_post'),
            data={'text': 'test text new post', 'group': self.group.id},
            follow=True
        )
        self.assertEqual(response.status_code, 200)
        self.assertTrue(Post.objects.filter(
            text='test text new post', group=self.group.id).exists()
        )

    def test_view_auth_post(self):
        self.post = self.create_post()
        self.check_text_in_url('test text new post')

    def test_edit_auth_post(self):
        self.post = self.create_post()
        response = self.auth_client.get(reverse('post_edit', kwargs={
            'username': self.user.username, 'post_id': self.post.id}))
        self.assertEqual(response.status_code, 200)
        self.post.text = 'test edited text'
        self.post.save()
        self.check_text_in_url('test edited text')
        self.assertTrue(Post.objects.filter(
            text='test edited text',
            group=self.group.id,
            author=self.user).exists())

    def test_image_in_urls(self):
        self.post = self.create_post_with_image('test_img.png')
        self.check_text_in_url('<img')

    def test_post_with_image(self):
        with tempfile.TemporaryDirectory() as temp_directory:
            with override_settings(MEDIA_ROOT=temp_directory):
                byte_img = io.BytesIO()
                im = Image.new("RGB", size=(500, 500), color=(255, 0, 0, 0))
                im.save(byte_img, format='png')
                byte_img.seek(0)
                response = self.auth_client.post(
                    reverse('new_post'),
                    data={'text': 'image',
                          'group': self.group.id,
                          'image': ContentFile(byte_img.read(), name='t.png')},
                    follow=True
                )
                self.assertEqual(response.status_code, 200)
                self.assertContains(response, '<img')
                self.assertEqual(Post.objects.count(), 1)

    def test_not_image_upload(self):
        error_text = (
            'Загрузите правильное изображение.'
            ' Файл, который вы загрузили, поврежден'
            ' или не является изображением.'
        )
        file_mock = mock.MagicMock(spec=File, name='test.txt')
        response = self.auth_client.post(
            reverse('new_post'),
            data={'text': 'image', 'group': self.group.id, 'image': file_mock},
            follow=True
        )
        self.assertFormError(response, form='form', field='image',
                             errors=error_text)
        self.assertEqual(Post.objects.count(), 0)

    def test_cache_index(self):
        self.auth_client.get(reverse('index'))
        self.auth_client.post(
            reverse('new_post'),
            data={'text': 'test cache', 'group': self.group.id},
            follow=True)
        response = self.auth_client.get(reverse('index'))
        self.assertNotContains(response, 'test cache')

    def test_auth_follow(self):
        self.assertEqual(self.user.follower.count(), 0)
        self.auth_client.get(reverse('profile_follow',
                                     kwargs={'username': self.user2.username}))
        self.assertEqual(self.user.follower.count(), 1)

    def test_auth_unfollow(self):
        self.auth_client.get(reverse('profile_follow',
                                     kwargs={'username': self.user2.username}))
        self.assertEqual(self.user.follower.count(), 1)
        self.auth_client.get(reverse('profile_unfollow',
                                     kwargs={'username': self.user2.username}))
        self.assertEqual(self.user.follower.count(), 0)

    def test_add_comment(self):
        post = self.create_post()
        self.auth_client.post(reverse('add_comment',
                                      kwargs={'username': post.author.username,
                                              'post_id': post.id}),
                              data={'post': post,
                                    'author': post.author.username,
                                    'text': 'new test comment'}, follow=True)
        self.assertEqual(post.comments.count(), 1)

    def test_no_auth_add_comment(self):
        post = self.create_post()
        response = self.no_auth_client.post(
            reverse('add_comment', kwargs={'username': post.author.username,
                                           'post_id': post.id}),
            data={'post': post, 'author': post.author.username,
                  'text': 'new test comment'})
        self.assertEqual(post.comments.count(), 0)
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(
            response,
            f'/auth/login/?next=/{post.author.username}/{post.id}/comment')

    def test_follow_post(self):
        self.create_post()
        self.auth_client2.get(reverse(
            'profile_follow', kwargs={'username': self.user.username}))
        response = self.auth_client.get(reverse('follow_index'))
        response2 = self.auth_client2.get(reverse('follow_index'))
        response3 = self.auth_client3.get(reverse('follow_index'))
        self.assertNotContains(response, 'test text new post')
        self.assertContains(response2, 'test text new post')
        self.assertNotContains(response3, 'test text new post')

class ServerErrorsTest(TestCase):
    def setUp(self):
        self.client = Client()

    def test_404(self):
        response = self.client.get('/nohaveadminpage/posts')
        self.assertEqual(response.status_code, 404)


#!/usr/bin/python

import boto3

client = boto3.client('ses')

def send_email( send_to, send_bcc, subject, body_html ):
  response = client.send_email(
    Source='neolafia@neolafia.com',
    Destination={
      'ToAddresses' : send_to,
      'CcAddresses' : [],
      'BccAddresses': send_bcc
    },
    Message={
      'Subject': {
        'Data': subject,
        'Charset': 'utf-8'
      },
      'Body': {
        'Html': {
          'Data': body_html,
          'Charset': 'utf-8'
        }
      }
    },
    ReplyToAddresses=['neolafia@neolafia.com'],
    ReturnPath='neolafia@neolafia.com',
  )

  return response

send_email( ['ashwinchetty@gmail.com'], [], 'test email', '
this is bolded text.
')


"""
hello-restful api

Example file response
"""
from fastapi import APIRouter, status
from fastapi.responses import FileResponse

# file paths
HTML_FILE = "./api/static/index.html"
HTML_METADATA = "./api/static/html_metadata.json"
PNG_FILE = "./api/static/thoughtworks_flamingo_wave.png"
PNG_METADATA = "./api/static/png_metadata.json"

route = APIRouter()

@route.get("/html",
                 summary="Return html file.",
                 tags=["response formats"],
                 response_class=FileResponse,
                 status_code=status.HTTP_200_OK
                 )
async def get_html():
    """Return html file."""
    return HTML_FILE

@route.get("/png",
                 summary="Return png image file.",
                 tags=["response formats"],
                 response_class=FileResponse,
                 status_code=status.HTTP_200_OK
                 )
async def get_png():
    """Return png image file."""
    return PNG_FILE

@route.get("/html/metadata",
                 summary="Return file metadata.",
                 tags=["response formats"],
                 response_class=FileResponse,
                 status_code=status.HTTP_200_OK
                 )
async def get_html_metadata():
    """Return hmtl file metadata."""
    return HTML_METADATA

@route.get("/png/metadata",
                 summary="Return file metadata.",
                 tags=["response formats"],
                 response_class=FileResponse,
                 status_code=status.HTTP_200_OK
                 )
async def get_png_metadata():
    """Return png file metadata."""
    return PNG_METADATA


from django.db.models.fields import DateTimeField
from django.http import JsonResponse
from django.shortcuts import render, redirect
from login.models import DiscordUser
from .models import Store
import os
from datetime import datetime, timedelta
try:
    from ClinifyForest.local_settings import TZC
except:
    pass
# Create your views here.

def home(request):
    if request.method=='POST':
        current_user = DiscordUser.objects.get(discord_tag=request.user.discord_tag)
        prev_trees = current_user.trees
        prev_coins = current_user.coins
        prev_dead_trees = current_user.deadtrees
        hiddenval = int(request.POST['hidden'])
        rangec = int(request.POST['range'])
        if (current_user.in_session == True):
            current_user.in_session = False
            current_user.session_end = None
            current_user.session_end_time = None
            if (hiddenval == -1):
                coins = 20*int(rangec)
                new_dead_trees = int(prev_dead_trees) + int(rangec)
                new_coins = int(prev_coins) - int(coins)
                current_user.deadtrees = new_dead_trees
                current_user.coins = new_coins
                current_user.save()
                return redirect(home)
            elif (hiddenval == 0):
                if request.user.slowmode == True:
                    coins = 10*int(rangec)
                    new_coins = int(prev_coins) + int(coins)
                    current_user.coins = new_coins
                    current_user.save()
                    return redirect(home)
                coins = 25*int(rangec)
                new_coins = int(prev_coins) + int(coins)
                current_user.coins = new_coins
                new_trees = int(prev_trees) + int(rangec)
                current_user.trees = new_trees
                current_user.save()
                return redirect(home)
            elif (hiddenval == 1):
                current_user.save()
                return redirect(home)
        else:
            if (rangec > 0):
                current_user.in_session = True
                current_user.session_end = timedelta(seconds=(int(rangec)*30*60))
                try:
                    if TZC == 0:
                        tzcorrection = timedelta(seconds=((int(rangec)*30*60)))
                except:
                    tzcorrection = timedelta(seconds=((int(rangec)*30*60) + 19800))
                current_user.session_end_time = datetime.now() + tzcorrection
                current_user.save()
                return redirect(home)
    params = {}
    if request.user.is_authenticated:
        params = {'loginuser': request.user}
    return render(request, 'main/home.html', params)

def lb(request):
    users = DiscordUser.objects.order_by('-trees', 'deadtrees').all()
    params = {'users': users}
    if request.user.is_authenticated:
        params = {'loginuser': request.user, 'users': users}
    return render(request, 'main/lb.html', params)

def store(request):
    if request.method=='POST':
        hidden = request.POST['hidden']
        if hidden == "Room Access":
            request.user.room_access = True
            request.user.coins -= 199
            request.user.save()
            return redirect(store)
        if hidden == "Room Admin":
            request.user.room_admin = True
            request.user.coins -= 999
            request.user.save()
            return redirect(store)
        if hidden == "Water Your Trees":
            if request.user.deadtrees == 0:
                return redirect(store)
            request.user.deadtrees -= 1
            request.user.trees += 1
            request.user.coins -= 299
            request.user.save()
            return redirect(store)
    storeitems = Store.objects.all()
    params = {'store': storeitems}
    if request.user.is_authenticated:
        params = {'loginuser': request.user, 'store': storeitems}
    return render(request, 'main/store.html', params)

def reset(request):
    if request.user.is_authenticated:
        current_user = DiscordUser.objects.get(discord_tag=request.user.discord_tag)
        current_user.trees = 0
        current_user.deadtrees = 0
        current_user.coins = 0
        current_user.save()
    return redirect(home)

def rooms(request):
    params = {}
    if request.user.is_authenticated:
        params = {'loginuser': request.user}
        if request.user.room_access:
            return render(request, 'main/rooms.html', params)
        return redirect(home)
    return redirect(home)

def assetlinks(request):
    response_data = [
        {
            "relation": [
                "delegate_permission/common.handle_all_urls"
            ],
            "target": {
                "namespace": "android_app",
                "package_name": "com.herokuapp.clinifyforest.twa",
                "sha256_cert_fingerprints": [
                    "78:57:6E:D0:19:47:29:8A:07:A5:DB:4A:40:50:01:D2:A4:3E:9F:BC:EA:AF:A0:2E:96:CD:C5:F0:99:53:96:D2"
                ]
            }
        }
    ]
    return JsonResponse(response_data, safe=False)


from django.shortcuts import render
from .models import Product, Category

def products_view(request):
    context = {
        'categorys': Category.objects.all(),
        'products': Product.objects.all()
    }
    return render(request, "produtos.html", context)

def products_details(request, slug, pk):
    context = {
        'product': Product.objects.get(id=pk)
    }
    return render(request, "product_details.html", context)

def products_filter(request, pk):
    context = {
        'categorys': Category.objects.all(),
        'products': Product.objects.filter(category=pk),
        'category': Category.objects.get(id=pk),
    }
    return render(request, "produtos.html", context)


import matplotlib.pyplot as plt
# from scipy.ndimage import gaussian_filter
from skimage.io import imread
from filter import *

class universe:
    """
    Class to create disjoint component, using disjoint-set forest, union by rank and path compression
    """
    def __init__(self, n_elements):
        """
        Constructor, creates a list of nodes, wti a rank, a size and link, by default path is set to node
        :param n_elements:
        """
        self.num = n_elements
        self.elts = np.empty(shape=(n_elements, 3), dtype=int)
        for i in range(n_elements):
            self.elts[i, 0] = 0  # rank
            self.elts[i, 1] = 1  # size
            self.elts[i, 2] = i  # p

    def size(self, x):
        """
        Return the size of a node, the numbers of child
        :param x: the number of a node
        :return:
        """
        return self.elts[x, 1]

    def num_sets(self):
        """
        Return the number of edges by components
        :return:
        """
        return self.num

    def find(self, x):
        """
        Find a node
        :param x: the number of a node
        :return:
        """
        y = int(x)
        while y != self.elts[y, 2]:
            y = self.elts[y, 2]
        self.elts[x, 2] = y
        return y

    def join(self, x, y):
        """
        Join to nodes, itself
        :param x:
        :param y:
        :return:
        """
        if self.elts[x, 0] > self.elts[y, 0]:
            self.elts[y, 2] = x
            self.elts[x, 1] += self.elts[y, 1]
        else:
            self.elts[x, 2] = y
            self.elts[y, 1] += self.elts[x, 1]
            if self.elts[x, 0] == self.elts[y, 0]:
                self.elts[y, 0] += 1
        self.num -= 1

def random_rgb():
    """
    generate a random color for a disjoint component
    :return:
    """
    rgb = np.zeros(3, dtype=int)
    rgb[0] = np.random.randint(0, 255)
    rgb[1] = np.random.randint(0, 255)
    rgb[2] = np.random.randint(0, 255)
    return rgb

def compute_dissimilarity(x1, x2):
    """
    Compute dissimilarity between two nodes
    :param x1: a node or pixel
    :param x2: a node or pixel
    :return: a dissimilarity score, when score is 0, pixels are both the same
    """
    return np.sqrt(np.sum(np.power(x1 - x2, 2)))

def get_threshold(size, c):
    """
    :param size:
    :param c:
    :return:
    """
    return c / size

def segment_graph(num_vertices, num_edges, edges, c):
    """
    Segment a graph
    :param num_vertices: number of nodes
    :param num_edges: number of edges
    :param edges: list of edges
    :param c: a constant c
    :return: a universe object
    """
    edges = edges[edges[:, 2].argsort()]
    u = universe(num_vertices)
    threshold = np.zeros(shape=num_vertices, dtype=float)

    for i in range(num_vertices):
        threshold[i] = get_threshold(1, c)

    for i in range(num_edges):
        a = u.find(edges[i, 0])
        b = u.find(edges[i, 1])

        if a != b:
            if (edges[i, 2] <= threshold[a]) and (edges[i, 2] <= threshold[b]):
                u.join(a, b)
                a = u.find(a)
                threshold[a] = edges[i, 2] + get_threshold(u.size(a), c)
    return u

def segment(in_image, sigma, k, min_size):
    """
    segment method, create graph from an image and laucnh segment graph_methods, show the result
    :param in_image: source image a numpy array
    :param sigma: sigma, which is the variance for gaussian smooth
    :param k:
    :param min_size: min nodes by component
    :return:
    """
    height, width, band = in_image.shape
    in_image_smooth = np.zeros((height, width, band))
    in_image_smooth[:, :, 0] = smooth(in_image[:, :, 0], sigma)
    in_image_smooth[:, :, 1] = smooth(in_image[:, :, 1], sigma)
    in_image_smooth[:, :, 2] = smooth(in_image[:, :, 2], sigma)

    if band != 3:
        raise Exception("This library accept only RGB images at this time")

    edges_size = width * height * 4 - (4*2) - ((height-2)*2) - ((width-2)*2)
    edges = np.zeros(shape=(edges_size, 3), dtype=object)
    num = 0
    for y in range(height):
        for x in range(width):
            node = int(y * width + x)
            if y > 0:
                edges[num, 0] = node
                edges[num, 1] = int((y-1)*width+x)
                edges[num, 2] = compute_dissimilarity(in_image_smooth[y, x], in_image_smooth[y-1, x])
                num += 1
            if y < height-1:
                edges[num, 0] = node
                edges[num, 1] = int((y+1)*width+x)
                edges[num, 2] = compute_dissimilarity(in_image_smooth[y, x], in_image_smooth[y+1, x])
                num += 1
            if x < width-2:
                edges[num, 0] = node
                edges[num, 1] = int(y*width+(x+1))
                edges[num, 2] = compute_dissimilarity(in_image_smooth[y, x], in_image_smooth[y, x+1])
                num += 1
            if x > 0:
                edges[num, 0] = node
                edges[num, 1] = int(y*width+(x-1))
                edges[num, 2] = compute_dissimilarity(in_image_smooth[y, x], in_image_smooth[y, x-1])
                num += 1
    u = segment_graph(width*height, num, edges, k)
    for i in range(num):
        a = u.find(edges[i, 0])
        b = u.find(edges[i, 1])
        if (a != b) and ((u.size(a) < min_size) or (u.size(b) < min_size)):
            u.join(a, b)

    num_cc = u.num_sets()
    output = np.zeros(shape=(height, width, 3))

    colors = np.zeros(shape=(height * width, 3))
    for i in range(height * width):
        colors[i, :] = random_rgb()

    for y in range(height):
        for x in range(width):
            comp = u.find(y * width + x)
            output[y, x, :] = colors[comp, :]

    fig = plt.figure()
    a = fig.add_subplot(1, 2, 1)
    plt.imshow(in_image)
    a.set_title('Original Image')
    a = fig.add_subplot(1, 2, 2)
    output = output.astype(int)
    plt.imshow(output)
    a.set_title('Segmented Image')
    plt.show()

if __name__ == '__main__':
    sigma = 0.9
    k = 500
    min = 20
    in_image = imread("paris.jpg")
    segment(in_image, sigma, k, min)


#!/usr/bin/env python

import os
import argparse
import sys
import glob
import shutil
from termcolor import colored
from shutil import copyfile

import am_config as amc

__author__ = 'amuls'

class logging_action(argparse.Action):
    def __call__(self, parser, namespace, log_actions, option_string=None):
        choices = ['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET']
        for log_action in log_actions:
            if log_action not in choices:
                raise argparse.ArgumentError(self, "log_actions must be in {!s}".format(choices))
        setattr(namespace, self.dest, log_actions)

def treatCmdOpts(argv):
    """
    Treats the command line options and sets the global variables according to the CLI args

    :param argv: the options (without argv[0])
    :type argv: list of string
    """
    helpTxt = os.path.basename(__file__) + ' creates a daily SBF file based on (six) hourly SBF files found in given directory'

    # create the parser for command line arguments
    parser = argparse.ArgumentParser(description=helpTxt)

    parser.add_argument('-d', '--dir', help='Directory of SBF file (defaults to .)', required=False, default='.')
    parser.add_argument('-o', '--overwrite', help='overwrite daily SBF file (default False)', action='store_true', required=False)

    parser.add_argument('-l', '--logging', help='specify logging level console/file (default {:s})'.format(colored('INFO DEBUG', 'green')), nargs=2, required=False, default=['INFO', 'DEBUG'], action=logging_action)

    args = parser.parse_args()

    return args.dir, args.overwrite, args.logging

def main(argv):
    """
    creates a combined SBF file from hourly or six-hourly SBF files
    """
    amc.cBaseName = colored(os.path.basename(__file__), 'yellow')
    cFuncName = colored(os.path.basename(__file__), 'yellow') + ' - ' + colored(sys._getframe().f_code.co_name, 'green')

    # treat command line options
    dirSBF, overwrite, logLevels = treatCmdOpts(argv)

    # create logging for better debugging
    logger, log_name = amc.createLoggers(os.path.basename(__file__), dir=dirSBF, logLevels=logLevels)

    # change to the directory dirSBF if it exists
    workDir = os.getcwd()
    if dirSBF != '.':
        workDir = os.path.normpath(os.path.join(workDir, dirSBF))
    logger.info('{func:s}: working directory is {dir:s}'.format(func=cFuncName, dir=workDir))

    if not os.path.exists(workDir):
        logger.error('{func:s}: directory {dir:s} does not exists.'.format(func=cFuncName, dir=colored(workDir, 'red')))
        sys.exit(amc.E_DIR_NOT_EXIST)
    else:
        os.chdir(workDir)
        logger.info('{func:s}: changed to directory {dir:s}'.format(func=cFuncName, dir=workDir))

    # find the files corresponsing to hourly SBF logged data, else serach for 6-hourly data
    hourlySBFs = sorted(glob.glob(r"????[0-9][0-9][0-9][A-X].[0-9][0-9]_"))
    sixHourlySBFs = sorted(glob.glob(r"????[0-9][0-9][0-9][1-4].[0-9][0-9]_"))

    # combine the files to create the daily SBF file
    logger.info('{func:s}: combine SBF (six-)hourly files to daily SBF file'.format(func=cFuncName))
    if len(hourlySBFs) > 0:
        dailySBF = hourlySBFs[0][:7] + '0' + hourlySBFs[0][8:]

        if not os.path.isfile(dailySBF) or overwrite:
            logger.info('{func:s}: creating daily SBF file {daily:s}'.format(func=cFuncName, daily=colored(dailySBF, 'green')))

            fDaily = open(dailySBF, 'wb')
            for i, hourlySBF in enumerate(hourlySBFs):
                fHourly = open(hourlySBF, 'rb')
                shutil.copyfileobj(fHourly, fDaily, 65536)
                fHourly.close()
            fDaily.close()
        else:
            logger.info('{func:s}: reusing daily SBF file {daily:s}'.format(func=cFuncName, daily=colored(dailySBF, 'green')))
    elif len(sixHourlySBFs) > 0:
        dailySBF = sixHourlySBFs[0][:7] + '0' + sixHourlySBFs[0][8:]

        if not os.path.isfile(dailySBF) or overwrite:
            logger.info('{func:s}: creating daily SBF file {daily:s}'.format(func=cFuncName, daily=colored(dailySBF, 'green')))

            fDaily = open(dailySBF, 'wb')
            for i, sixHourlySBF in enumerate(sixHourlySBFs):
                fSixHourly = open(sixHourlySBF, 'rb')
                shutil.copyfileobj(fSixHourly, fDaily, 65536)
                fSixHourly.close()
            fDaily.close()
        else:
            logger.info('{func:s}: reusing daily SBF file {daily:s}'.format(func=cFuncName, daily=colored(dailySBF, 'green')))
    else:
        logger.info('{func:s}: No SBF files found with syntax STATDOYS.YY_'.format(func=cFuncName))

    # copy temp log file to the YYDOY directory
    copyfile(log_name, os.path.join(workDir, 'pysbfdaily.log'))
    os.remove(log_name)

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


import pygame
from player import Player

pygame.init()

pygame.display.set_caption("JimmyG Adventures")
screen = pygame.display.set_mode((1000, 563))

# Load Player
playerX, playerY = 99, 468
player = Player(playerX, playerY, screen)

# Set Background Image
bg = pygame.image.load("bg\\2_game_background.png")
# Set and Load Player Variables
# Load background and Player

screen.blit(bg, (0, 0))

clock = pygame.time.Clock()
pressed_right = False
pressed_left = False

# Game loop
while 1:
    for event in pygame.event.get():
        print(event)
        if event.type == pygame.QUIT:
            break

        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            playerX -= 10
        if keys[pygame.K_d]:
            playerX += 10

        screen.blit(bg, (0, 0))
        player.update_player(playerX, playerY)
        pygame.display.update()
        clock.tick(120)