import asyncio
import re
import logging

from redbot.core.bot import Red
from redbot.core import checks, Config, commands

log = logging.getLogger("red.mod")

class Giveaway(commands.Cog):
    def __init__(self, bot: Red, dao):
        self.bot = bot
        self.dao = dao
        self.config = Config.get_conf(self, identifier=835127642323413791, force_registration=True)
        default_global = {
        }
        self.config.register_global(**default_global)
        self.server_config = None
        self.lock = False
        self.ready = False

    async def on_ready(self):
        await self.dao.on_ready()
        self.server_config = self.load_server_config()
        self.ready = True

    @commands.guild_only()
    @commands.command(pass_context=True, no_pm=True, help="Join the current giveaway")
    async def giveaway(self, ctx):
        if self.lock:
            return

        this_author = ctx.message.author
        this_channel_id = ctx.message.channel.id
        regular_role = None
        server = self.bot.get_guild(111772771016515584)
        stats = self.dao.get_member_stats("111772771016515584", str(this_author.id))

        # get the regular role
        for r in server.roles:
            if r.id == 345877423142731778:  # Regular
                regular_role = r
                break

        if this_channel_id != 312973523066814467:
            return

        if (
                self.server_config["other"]["giveaway_item"]
                and self.server_config["other"]["giveaway_deadline"]
        ):
            if not self.dao.get_sub_in_giveaway(str(this_author.id)):
                if "luckboost_3" in stats and stats["luckboost_3"] and regular_role in this_author.roles:
                    self.dao.append_sub_to_giveaway(str(this_author.id), 5)
                    stats["luckboost_3"] = False
                    self.dao.update_member_stats(
                        "111772771016515584", str(this_author.id), stats
                    )
                    await ctx.send(
                        this_author.mention
                        + " You joined the giveaway for **{}** with **5x** winning chance for being regular and using a luck ticket! The giveaway will end **{}** and you will be notified if you win. Good Luck! :wink:".format(
                            self.server_config["other"]["giveaway_item"],
                            self.server_config["other"]["giveaway_deadline"],
                        )
                    )
                elif regular_role in this_author.roles:
                    self.dao.append_sub_to_giveaway(str(this_author.id), 2)
                    await ctx.send(this_author.mention +
                                   " You joined the giveaway for **{}** with **double** winning chance for being regular! The giveaway will end **{}** and you will be notified if you win. Good Luck! :wink:".format(
                                       self.server_config["other"]["giveaway_item"],
                                       self.server_config["other"]["giveaway_deadline"]))
                else:
                    self.dao.append_sub_to_giveaway(str(this_author.id), 1)
                    await ctx.send(
                        this_author.mention
                        + " You joined the giveaway for **{}**. The giveaway will end **{}** and you will be notified if you win. Good Luck! :wink:".format(
                            self.server_config["other"]["giveaway_item"],
                            self.server_config["other"]["giveaway_deadline"],
                        )
                    )
            else:
                await ctx.send(
                    this_author.mention + " you already joined the giveaway."
                )
        else:
            await ctx.send("There is no giveaway running right now.")

    @commands.guild_only()
    @checks.admin_or_permissions(manage_roles=True)
    @commands.command(pass_context=True, no_pm=True, help="Start a new giveaway")
    async def startgiveaway(self, ctx):
        if (
                self.server_config["other"]["giveaway_item"]
                and self.server_config["other"]["giveaway_deadline"]
        ):
            await ctx.send(
                "There is already a giveaway running. Please use !wipegiveaway before you start a new one. (Don't forget to chose a winner before you end!)"
            )
            return
        desc_array = re.findall(r'"([^"]*)"', ctx.message.content)

        if not len(desc_array) == 2:
            await ctx.send(
                'Please set 2 arguments between quotation marks. `!startgiveaway "<item>" "<deadline>"`\nExample: `!startgiveaway "a new GTX2900" "10 days"`'
            )
            return

        self.server_config["other"]["giveaway_item"] = desc_array[0]
        self.server_config["other"]["giveaway_deadline"] = desc_array[1]
        self.dao.update_server_config("111772771016515584", self.server_config)

        await ctx.send(
            "New giveaway was started! Use !giveawaywinner to chose a winner when the time has passed."
        )

    @commands.guild_only()
    @checks.admin_or_permissions(manage_roles=True)
    @commands.command(pass_context=True, no_pm=True, help="Wipe the giveaway")
    async def wipegiveaway(self, ctx):
        self.dao.wipe_giveaway()
        self.server_config["other"]["giveaway_item"] = ""
        self.server_config["other"]["giveaway_deadline"] = ""
        self.dao.update_server_config("111772771016515584", self.server_config)
        await ctx.send(
            "The giveaway was wiped. You can start a new one with !startgiveaway"
        )

    @commands.guild_only()
    @checks.admin_or_permissions(manage_roles=True)
    @commands.command(
        pass_context=True, no_pm=True, help="Chose a winner for the current giveaway"
    )
    async def giveawaywinner(self, ctx):
        print("Fetching giveaway winner...")
        if (
                self.server_config["other"]["giveaway_item"]
                and self.server_config["other"]["giveaway_deadline"]
        ):
            win_user = None
            while not win_user:
                winner_id = self.dao.get_random_sub_from_giveaway()
                print("chosen winner id: " + winner_id)
                win_user = self.bot.get_user(int(winner_id))
                print("chosen winner user: " + win_user.name)
            await ctx.send("Shuffling giveaway list...")
            await asyncio.sleep(5)
            await ctx.send("*Shuffling intensifies...*")
            await asyncio.sleep(5)
            await ctx.send("**And the winner is...**")
            await asyncio.sleep(5)
            await ctx.send(
                "Congatulations "
                + win_user.mention
                + " you won **{}**!!!".format(
                    self.server_config["other"]["giveaway_item"]
                )
            )
        else:
            await ctx.send(
                'You have to start a giveaway before you can chose a winner. Please use !startgiveaway "<item>" "<deadline>"'
            )

    @commands.guild_only()
    @checks.mod_or_permissions(manage_messages=True)
    @commands.command(pass_context=True, no_pm=True, help="Lock the giveaway")
    async def lockgiveaway(self, ctx):
        self.lock = True
        await ctx.send(
            "The giveaway has been locked. Unlock again with !unlockgiveaway"
        )

    @commands.guild_only()
    @checks.mod_or_permissions(manage_messages=True)
    @commands.command(pass_context=True, no_pm=True, help="Unlock the giveaway")
    async def unlockgiveaway(self, ctx):
        self.lock = False
        await ctx.send("The giveaway has been unlocked.")

    def load_server_config(self):
        try:
            server_config = self.dao.get_server_config(111772771016515584)
            if not server_config:
                self.dao.add_new_server("111772771016515584")
                server_config = self.dao.get_server_config(111772771016515584)
            return server_config
        except:
            print("Failed reading server_id and/or config")


import os
import shlex

from .git_access import GitHubRepo, GitRepo

class LibretroSuper:
    """ Represents the libretro-super repository with info files """
    def __init__(self, working_directory):
        self._working_directory = working_directory

    def fetch_and_reset(self):
        """ Fetch and reset libretro-super repo """
        print("Fetching libretro-super repo")
        gitrepo = GitRepo(
            GitHubRepo('libretro-super',
                       'https://github.com/libretro/libretro-super.git', ''),
            self._working_directory)
        gitrepo.fetch_and_reset()

    def parse_info_file(self, library_soname):
        """ Load info file from libretro-super repository """
        path = os.path.join(self._working_directory, 'libretro-super', 'dist',
                            'info', '{}.info'.format(library_soname))
        result = {
            'license': 'Unlicensed',
        }

        if os.path.isfile(path):
            with open(path, 'r') as info_ctx:
                for line in info_ctx.readlines():
                    if '=' in line:
                        name, var = line.partition('=')[::2]
                        result[name.strip()] = shlex.split(var)[0]
        return result


import math
import sdtoolbox as sd
import numpy as np
import matplotlib.pyplot as plt
import scipy
import cantera

p_0_min =100000 ;
p_0_max =1000000 ;
T_0_min =300 ;
T_0_max =1000 ;
PHI_0_min = 0.5;
PHI_0_max = 1.5;
p_imax =5 ;
T_jmax = 7;
PHI_kmax = 5;

mech = 'gri30.cti';

p0 = np.zeros(p_imax);
p0bar = np.zeros(p_imax);
T0 = np.zeros(T_jmax);
PHI = np.zeros(PHI_kmax);
U_CJ = np.zeros((p_imax, T_jmax, PHI_kmax));

for i in range(0,p_imax):
    p0[i] = p_0_min + i*(p_0_max - p_0_min)/(p_imax - 1);
    p0bar[i] = p0[i]/100000;
    for j in range(0,T_jmax):
        T0[j] = T_0_min + j*(T_0_max - T_0_min)/(T_jmax - 1);
        for k in range(0,PHI_kmax):
            PHI[k] = PHI_0_min + k*(PHI_0_max - PHI_0_min)/(PHI_kmax - 1);
            x = 'H2:%.2f O2:1 N2:3.76' % PHI[k];
            U_CJ[i , j , k] = sd.postshock.CJspeed(p0[i] , T0[j], x , mech);
        k = 0;
    j = 0;

font = {'family' : 'DejaVu Sans',
        'weight' : 'normal',
        'size'   : 18}

plt.rc('font', **font)

plt.figure(figsize=(20,10))
for l in range(int(p_imax)):
    plt.plot(PHI, U_CJ[l,0,:], label = 'p0 = %.1f bar' % p0bar[l])
    plt.plot()
plt.xlabel('Equivalence ratio $\phi$ [-]')
plt.ylabel('CJ detonation speed [m/s]')
plt.title("")
plt.legend()
plt.show()
#plt.savefig('CJU_phi_p1var.png')

plt.figure(figsize=(20,10))
for l in range(int(T_jmax)):
    plt.plot(PHI, U_CJ[0,l,:], label = 'T0 = %.0f K' % T0[l])
    plt.plot()
plt.xlabel('Equivalence ratio $\phi$ [-]')
plt.ylabel('CJ detonation speed [m/s]')
plt.title("")
plt.legend()
plt.show()
#plt.savefig('CJU_phi_T1var.png')

plt.figure(figsize=(20,10))
for l in range(int(T_jmax)):
    plt.plot(p0bar, U_CJ[:,l,3], label = 'T0 = %.0f K' % T0[l])
plt.xlabel('Preassure [bar]')
plt.ylabel('CJ detonation speed [m/s]')
plt.title("")
plt.legend()
plt.show()
#plt.savefig('CJU_p1_T1var.png')

plt.figure(figsize=(20,10))
for l in range(int(PHI_kmax)):
    plt.plot(p0bar, U_CJ[:,0,l], label = '$\phi$ = %.1f' % PHI[l])
plt.xlabel('Preassure [bar]')
plt.ylabel('CJ detonation speed [m/s]')
plt.title("")
plt.legend()
plt.show()
#plt.savefig('CJU_p1_phivar.png')

plt.figure(figsize=(20,10))
for l in range(int(p_imax)):
    plt.plot(T0, U_CJ[l,:,3], label = 'p0 = %.1f bar' % p0bar[l])
plt.xlabel('Temperature [K]')
plt.ylabel('CJ detonation speed [m/s]')
plt.title("")
plt.legend()
plt.show()
#plt.savefig('CJU_T1_p1var.png')

plt.figure(figsize=(20,10))
for l in range(int(PHI_kmax)):
    plt.plot(T0, U_CJ[0,:,l], label = '$\phi$ = %.1f' % PHI[l])
plt.xlabel('Temperature [K]')
plt.ylabel('CJ detonation speed [m/s]')
plt.title("")
plt.legend()
plt.show()
#plt.savefig('CJU_T1_phivar.png')


 #encoding:utf-8
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum
from django.db import connections
from django.db.models import Q
from decimal import *
import datetime, time

#Modelos de modulos
from microsip_web.apps.punto_de_venta.models import *

#libs
from custom_db.main import next_id, first_or_none, runsql_rows

def new_factura_global( **kwargs ):
    ''' Genera una factura global '''

    #Parametros
    connection_name = kwargs.get('connection_name', None)
    username = kwargs.get('username', None)
    fecha_inicio = kwargs.get('fecha_inicio', None)
    fecha_fin = kwargs.get('fecha_fin', None)

    almacen = kwargs.get('almacen', None)
    cliente = kwargs.get('cliente', None)
    cliente_direccion = kwargs.get('cliente_direccion', None)
    cliente_clave = first_or_none( ClienteClave.objects.filter( cliente=cliente ) )

    factura_tipo = kwargs.get('factura_tipo', None)
    modalidad_facturacion = kwargs.get('modalidad_facturacion', None)

    detalles_list =[]
    ventas_list = []
    # Ventas facturadas
    ventas_facturadas = PuntoVentaDocumentoLiga.objects.filter(docto_pv_fuente__fecha__gte = fecha_inicio, docto_pv_fuente__fecha__lte = fecha_fin)
    if almacen:
        ventas_facturadas = ventas_facturadas.filter(docto_pv_fuente__almacen= almacen)
    ventas_facturadas_list =  list( set( ventas_facturadas.values_list( 'docto_pv_fuente__id', flat = True ) ) )

    # Ventas sin facturar
    ventas_sinfacturar =  PuntoVentaDocumento.objects.exclude( id__in = ventas_facturadas_list).exclude(estado='C').filter(tipo= 'V', fecha__gte = fecha_inicio, fecha__lte = fecha_fin)

    detalles_factura = PuntoVentaDocumentoDetalle.objects.exclude(documento_pv__estado='C').exclude(documento_pv__id__in = ventas_facturadas_list)\
       .filter(documento_pv__tipo = 'V',documento_pv__fecha__gte= fecha_inicio, documento_pv__fecha__lte=fecha_fin)
    if almacen:
        ventas_sinfacturar = ventas_sinfacturar.filter(almacen = almacen)
        detalles_factura = detalles_factura.filter(documento_pv__almacen = almacen)

    ventas_sinfacturar_list =  list( set( ventas_sinfacturar.order_by('folio',).values_list( 'id', flat = True ) ) )

    # Totales factura global
    totales = ventas_sinfacturar.aggregate(
            importe_neto=Sum('importe_neto',),
            total_impuestos=Sum('total_impuestos',),
            importe_donativo=Sum('importe_donativo',),
            total_fpgc=Sum('total_fpgc',),
            importe_descuento=Sum('importe_descuento',),
        )

    importe_neto = totales['importe_neto']
    total_impuestos = totales['total_impuestos']
    importe_donativo = totales['importe_donativo']
    total_fpgc = totales['total_fpgc']
    importe_descuento = totales['importe_descuento']

    message =''
    impuestos = []

    # si hay ventas por facturar
    if ventas_sinfacturar.count() > 0:
        for venta in ventas_sinfacturar:
            # detalles_venta = list( set( PuntoVentaDocumentoDetalle.objects.filter(documento_pv=venta).values_list( 'id', flat = True ) ) )
            ventas_list.append({
                    'id':venta.id,
                    'folio': venta.folio,
                    'fecha':str(venta.fecha),
                    'importe_neto':str(venta.importe_neto),
                    # 'detalles': detalles_venta,
                })

        impuestos_doc =  PuntoVentaDocumentoImpuesto.objects.filter(documento_pv__in=ventas_sinfacturar_list).filter(venta_neta__gt=0).values('impuesto','porcentaje_impuestos').annotate(
                venta_neta = Sum('venta_neta'),
                otros_impuestos = Sum('otros_impuestos'),
                importe_impuesto = Sum('importe_impuesto'),
            )

        if factura_tipo == 'P':

            articulo_ventaspg_id = Registry.objects.get( nombre = 'ARTICULO_VENTAS_FG_PV_ID' ).valor
            articulo = Articulo.objects.get(pk=articulo_ventaspg_id)
            articulo_clave = first_or_none(ArticuloClave.objects.filter(articulo=articulo))
            if articulo_clave:
                articulo_clave = articulo_clave.clave
            articulo_nombre = articulo.nombre
            articulo_id = articulo.id
            detalles_list.append({
                    'articulo_nombre':articulo_nombre,
                    'articulo_id': articulo_id,
                    'articulo_clave': articulo_clave,
                    'precio': str(importe_neto),
                    'porcentaje_descuento': 0,
                    'unidades':1,
                    'precio_total_neto': str(importe_neto),
                })

        for impuesto in impuestos_doc:
            impuestos.append({
                    'venta_neta': str(impuesto['venta_neta']),
                    'otros_impuestos': str(impuesto['otros_impuestos']),
                    'importe_impuesto': str(impuesto['importe_impuesto']),
                    'porcentaje_impuestos': str(impuesto['porcentaje_impuestos']),
                    'impuestos_ids': str(impuesto['impuesto'])
                })

        if factura_tipo == 'C':
            detalles_factura_concentrada = detalles_factura.values('articulo').annotate(
                    sum_unidades = Sum('unidades'),
                    sum_precio_total_neto = Sum('precio_total_neto'),
                )

            for detalle in detalles_factura_concentrada:
                articulo = Articulo.objects.get(pk=detalle['articulo'])
                detalles_relacion = list( set( detalles_factura.filter(articulo=articulo).values_list( 'id', flat = True ) ) )

                articulo_clave = first_or_none(ArticuloClave.objects.filter(articulo=articulo))
                if articulo_clave:
                    articulo_clave = articulo_clave.clave

                unidades = detalle['sum_unidades']
                precio_total_neto = detalle['sum_precio_total_neto']

                precio = precio_total_neto / unidades

                detalles_list.append({
                        'articulo_nombre':articulo.nombre,
                        'articulo_id': articulo.id,
                        'articulo_clave': articulo_clave,
                        'precio': str(precio),
                        'porcentaje_descuento': 0,
                        'unidades':str(unidades),
                        'precio_total_neto': str(precio_total_neto),
                        'detalles_relacion': detalles_relacion,
                    })
        elif factura_tipo == 'D':
            for detalle_factura in detalles_factura:
                detalles_list.append({
                        'articulo_nombre':detalle_factura.articulo.nombre,
                        'articulo_id': detalle_factura.articulo.id,
                        'articulo_clave': detalle_factura.clave_articulo,
                        'precio': str(detalle_factura.precio_unitario),
                        'porcentaje_descuento':str(detalle_factura.porcentaje_descuento),
                        'unidades':str(detalle_factura.unidades),
                        'precio_total_neto': str(detalle_factura.precio_total_neto),
                    })
    else:
        message = 'No hay ventas por facturar'

    totales_factura = {
        'importe_neto': str(importe_neto),
        'total_impuestos': str(total_impuestos),
        'importe_donativo': str(importe_donativo),
        'total_fpgc': str(total_fpgc),
        'importe_descuento': str(importe_descuento),
    }

    data = {
        'totales':totales_factura,
        'detalles': detalles_list,
        'ventas_facturadas':ventas_list,
        'message': message,
        'fecha_inicio':str(fecha_inicio),
        'fecha_fin':str(fecha_fin),
        'impuestos': impuestos,
    }

    return data


import os
import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np
from astropy.coordinates import EarthLocation, SkyCoord
from astropy.io import fits
from astropy.time import Time

def hjd_calc(alpha,delta,cat,loc):
    obj_coo = SkyCoord(alpha, delta, unit=(u.deg, u.deg), frame='icrs')
    date_obs=fits.open(cat[:-3]+'new')[0].header['DATE-OBS']
    exptime=fits.open(cat[:-3]+'new')[0].header['EXPTIME']
    t = Time(date_obs, format='isot', scale='utc', location=loc)
    ltt_helio = t.light_travel_time(obj_coo, 'heliocentric')
    hjd=(t+ltt_helio+exptime/2/86400).jd
    return hjd

def phase_calc(coords,obj,hjd):
    ind=np.where(coords[:,0]==obj)[0][0]
    P=np.float(coords[ind,3])
    T0=np.float(coords[ind,4])
    ph=(hjd-T0)/P-int((hjd-T0)/P)
    if ph<0:
        ph=1+ph
    if ph>0.5:
        ph=ph-1
    return ph

def k_objfromcat(alpha0,delta0,cat,r_arcsec):
    k0=-1
    for k in range(len(cat)):
        alpha=cat[k,12]
        delta=cat[k,13]
        r=np.sqrt((alpha-alpha0)**2+(delta-delta0)**2)
        if r<=r_arcsec/3600:
            k0=k
    return k0

def Is_Obj_OnOfImage(alpha0,delta0,cat):
    alpha_min=np.min(cat[:,12])
    alpha_max=np.max(cat[:,12])
    delta_min=np.min(cat[:,13])
    delta_max=np.max(cat[:,13])
    onImage=((alpha0>=alpha_min) and (alpha0<=alpha_max) and (delta0>=delta_min) and (delta0<=delta_max))
    return onImage

def limit_mag_estimation(cat,thresh_w, k_ref, mag_ref, errmag_ref):
    threshold=cat[0,-1]
    fwhms=cat[:,14]
    fwhm=np.median(fwhms)
    h=threshold*np.exp(4*np.log10(2)*thresh_w**2/fwhm**2)
    V=2*np.pi*h*(fwhm/2.35482)**2
    limit_mag_cat=-2.5*np.log10(V)
    limitmag=limit_mag_cat-cat[k_ref,6]+mag_ref
    errlimitmag=np.sqrt(cat[k_ref,8]**2+errmag_ref**2)
    return limitmag, errlimitmag

def rel_phot(alpha_obj, delta_obj, alpha_ref, delta_ref, mag_ref, errmag_ref, cat, r_arcsec):
    k_ref=k_objfromcat(alpha_ref, delta_ref, cat, r_arcsec); k_obj=k_objfromcat(alpha_obj, delta_obj, cat, r_arcsec)
    if k_ref!=-1 and k_obj!=-1: #the reference and the object are detected
        mag_obj=cat[k_obj,6]-cat[k_ref,6]+mag_ref
        errmag_obj=np.sqrt(cat[k_obj,8]**2+cat[k_ref,8]**2+errmag_ref**2)
        SNR_obj=cat[k_obj,5]/cat[k_obj,7]
    elif k_ref==-1: # the reference is not detected
        refOnImage=Is_Obj_OnOfImage(alpha_ref,delta_ref,cat)
        if refOnImage:
            mag_obj=1000; errmag_obj=0; SNR_obj=0   # the reference is inside the frame
        else:
            mag_obj=10000; errmag_obj=0; SNR_obj=-1  # the reference is outside the frame
    elif k_obj==-1: # the object is not detected
        objOnImage=Is_Obj_OnOfImage(alpha_obj,delta_obj,cat)
        if objOnImage:
            mag_obj=None; errmag_obj=0; SNR_obj=0 # the object is inside the frame
        else:
            mag_obj=0; errmag_obj=0; SNR_obj=0 # the object is outside the frame
    return mag_obj, errmag_obj, SNR_obj

def writeTable_date(obj, date,Filter,res, code):
    res_table=open('result_'+obj+'_'+code+'_'+date+'_'+Filter+'.txt', 'w')
    h,w=np.shape(res)
    for i in range(h):
        for j in range(w):
            res_table.write(str(round(res[i,j],5))+'\t')
        res_table.write('\n')
    res_table.close()

obj='EX_Dra'; Filter='Green'

path='...'

r_arcsec=6
DETECT_MINAREA=12
thresh_w=np.sqrt(DETECT_MINAREA/np.pi)
loc = EarthLocation(lon="41:25:33", lat="+43:38:59", height=2026)
d_o=np.loadtxt(path+'Dates_Objects.txt',dtype=np.str)  #table with columns: Date_c	Object	Green (number of frames)	Red(number of frames)
coords=np.loadtxt(path+'Coords_Ephemeris.dat', dtype=np.str) #table with columns:obj	aplha 	delta	P_orb	T0
j=np.where(coords[:,0]==obj)[0]
alpha_obj=float(coords[j,1]); delta_obj=float(coords[j,2])
dates=np.sort(d_o[np.where(d_o[:,1]==obj)[0],0])

checks=np.loadtxt(path+'CataclChecks/'+obj+'_checks.txt') # table with columns: n	alpha	delta	V	errV	R	errR
# alpha_ref, delta_ref, mag_ref are parameters of reference star
alpha_ref=checks[0,1]; delta_ref=checks[0,2]
if Filter=='Green':
    mag_ref=checks[0,3]; errmag_ref=checks[0,4]
if Filter=='Red':
    mag_ref=checks[0,5]; errmag_ref=checks[0,6]

os.chdir(path+'/relPhotResults')
result_obj=open('result_'+obj+'_obj_'+Filter+'.txt', 'w')

dates_no0=[]
hjds=[]; phases=[]
res_obj=[]
limitmags=[]; limitmagerrs=[]

for date in dates:
    hjds_date=[]; phases_date=[]
    limitmags_date=[]; limitmagerrs_date=[]
    date_o=d_o[np.where(d_o[:,0]==date)[0], :]
    if Filter=='Green':
        n=2
    if Filter=='Red':
        n=3
    n_img=int(date_o[np.where(date_o[:,1]==obj)[0][0],n])
    if n_img==0:
        continue
    dates_no0.append(date)
    res_obj_date=np.zeros((n_img,3))
    os.chdir(path+date+'/'+obj)
    k=0
    cats=[]
    for f in np.sort(os.listdir()):
        if f.endswith('_WCS.cat'):
            os.chdir(path+date+'/'+obj)
            cats.append(f)
            filt=fits.open(f[:-3]+'new')[0].header['FILTER']
            if filt==Filter:
                cat=np.loadtxt(f)
                hjd=hjd_calc(alpha_obj,delta_obj,f,loc)
                hjds_date.append(hjd)
                phase=phase_calc(coords,obj,hjd)
                phases_date.append(phase)
                mag_obj, errmag_obj, SNR_obj=rel_phot(alpha_obj, delta_obj, alpha_ref, delta_ref, mag_ref, errmag_ref, cat, r_arcsec)
                res_obj_date[k,:]=[mag_obj, errmag_obj, SNR_obj]
                if mag_obj==None: # the object is inside the frame, but not detected
                    limitmag, limitmagerr=limit_mag_estimation(cat, thresh_w, k_objfromcat(alpha_ref, delta_ref, cat, r_arcsec), mag_ref, errmag_ref)
                    limitmags_date.append(limitmag); limitmagerrs_date.append(limitmagerr)
                    mag_obj=100
                else:
                    limitmag=0; limitmagerr=0
                    limitmags_date.append(0); limitmagerrs_date.append(0)
                result_obj.write(date+'\t'+f+'\t'+str(round(hjd,5))+'\t'+str(round(phase,5))+'\t'+str(round(mag_obj,3))+'\t'+str(round(errmag_obj,3))+'\t'+str(round(SNR_obj,3))+'\t')
                if limitmag!=0:
                    result_obj.write('# limit_mag= '+str(round(limitmag,3))+'\t'+str(round(limitmagerr,3)))
                result_obj.write('\n')
                k=k+1

    os.chdir(path+'/relPhotResults')
    writeTable_date(obj,date,Filter,res_obj_date, 'obj')
    result_obj.write('# '+date+'\t'+str(round(np.mean(hjds_date),5))+'\t'+str(round(np.mean(phases_date),5))+'\tmean mag= '+str(round(np.nanmean(res_obj_date[:,0]),3))+'\t'+str(round(np.nanstd(res_obj_date[:,0]),3))+'\t')
    if len(limitmags_date)>0:
        result_obj.write('limitmag= '+str(round(np.mean(limitmags_date),3))+'\t'+str(round(np.std(limitmags_date),3)))
    result_obj.write('\n')
    limitmags.append(limitmags_date); limitmagerrs.append(limitmagerrs_date)
    phases.append(phases_date)
    hjds.append(hjds_date)
    res_obj.append(res_obj_date)

os.chdir(path+'/relPhotResults')
args=phases # or args=hjds

plt.figure(figsize=(6,6))
plt.title(obj+' '+Filter)
for i in range(len(dates_no0)):
    plt.scatter(args[i],res_obj[i][:,0],linestyle='solid', label=dates_no0[i][:-2], s=50)
    plt.errorbar(args[i],res_obj[i][:,0],yerr=res_obj[i][:,1],fmt='o')
    plt.scatter(args[i],limitmags[i], marker='v',label='limitmag_'+dates_no0[i][:-2])
plt.legend()
plt.gca().invert_yaxis()
plt.show()


from flask import render_template, flash, request, send_from_directory
from app import app
from flask import request
from wtforms import Form, validators, TextField, SelectField, TextAreaField, SelectMultipleField, SubmitField
from wtforms.fields.html5 import DateField
from wtforms_components import DateIntervalField, DateRange
from app import getdata
import json, os
import datetime
from flask_admin.form.widgets import DatePickerWidget

class ReusableForm(Form):
    name = TextField(validators=[validators.required()])
    date = TextField('Start', default='Select date', validators=[validators.required()])
    languages = SelectMultipleField('Languages', choices=[('en', 'English'), ('it', 'Italian'),('de','German'),('fr', 'French'),('es','Spanish')], validators=[validators.required()])
    dataBtn = SubmitField(label='Get Data')

class TrendsForm(Form):
    languages = SelectField('Languages', choices=[('en', 'English'), ('it', 'Italian'),('de','German'),('fr', 'French'),('es','Spanish')], validators=[validators.required()])
    trendBtn = SubmitField(label='Get Last Trends')

@app.route('/', methods=['GET', 'POST'])
@app.route('/index')
def index():

    supported_languages = ['en','it','de','fr','es']
    langs = []
    langs.append(request.accept_languages.best_match(supported_languages))
    if langs == [] or not langs or langs == [None]:
        langs = ['en']

    form = ReusableForm(request.form)
    trendForm = TrendsForm(request.form)

    data, form_input, name = getdata.acquireTrends(langs)
    articles_desc = getdata.enrichArticles(form_input.split(','), langs[0])

    if trendForm.validate() and trendForm.trendBtn.data:
        if trendForm.validate():
            langs =  [trendForm.languages.data]
            data, form_input, name = getdata.acquireTrends(langs)
            articles_desc = getdata.enrichArticles(form_input.split(','), langs[0])
        else:
            name = 'All the form fields are required'
            data = []

    if form.validate() and form.dataBtn.data:

        if form.validate():
            start, end = request.form['date'].split("-")
            name = request.form['name']
            langs =  form.languages.data
            s = start.replace("/", "")
            e = end.replace("/", "")
            startDate = s[-5:-1]+s[:2]+s[2:4]
            endDate = e[-4:]+e[1:3]+e[3:5]
            form_input = name
            data, errors = getdata.launchQuery(name, startDate, endDate, langs)
            articles_desc = getdata.enrichArticles(name.split(','), langs[0])
            name = name.replace(",", " - ")
        else:
            name = 'All the form fields are required'
            data = []

    return render_template('index.html', form=form, trendForm=trendForm, data=data, name=name.replace('_',' '), query=form_input, articles_desc=articles_desc)

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')


import json
from scripts.infoForpy import *
import random

@commands.command(pass_context=True)
async def bankget(ctx, sum):
    global useridauthor
    try:
        with open(f'{path}{ctx.message.author.id}.json', 'r') as f:
            useridauthor = json.load(f)
    except:
        print(f"{cur_lang['db_created']}{ctx.message.author.id}")
        dictionary = {
            "xp": 0,
            "access": 1,
            "bank": 0,
            "money": 0
        }
        userid_write = json.dumps(dictionary, indent=4)
        with open(f'{path}{ctx.message.author.id}.json', 'w') as f:
            f.write(userid_write)
    if(int(useridauthor['bank']) >= int(sum)):

        try:
            dictionary = {
                "xp": useridauthor["xp"],
                "access": useridauthor["access"],
                "bank" : int(useridauthor["bank"]) - int(sum),
                "money" : int(useridauthor['money']) + int(sum)
            }
        except:
            dictionary = {
                "xp": 0,
                "access": 1,
                "bank": 0,
                "money": 0
            }

        userid_write = json.dumps(dictionary, indent=4)

        with open(f"{path}{ctx.message.author.id}.json", "w") as f:
            f.write(userid_write)

        embed = discord.Embed(title="Банкомат (Приват Банк (ДС))",
                              description=f"***Успішно знято з картки: {ctx.message.author.id} - {sum}₴***",
                              color=0xFF5733)
        embed.set_author(name=ctx.message.author.name, icon_url=ctx.message.author.avatar.url)
        embed.add_field(name="Знято з картки",
                        value=f"***{ctx.message.author.id}***",
                        inline=False)
        embed.add_field(name="Сумму", value=f"{sum}₴",

                        inline=False)
        embed.add_field(name="При комісії", value=f"0₴",
                        inline=False)

        await ctx.send(embed=embed)
        try:
            with open(f'{path}{ctx.message.author.id}.json', 'r') as f:
                useridauthor = json.load(f)
        except:
            print(f"{cur_lang['db_created']}{ctx.message.author.id}")
            dictionary = {
                "xp": 0,
                "access": 1,
                "bank": 0,
                "money": 0
            }
            userid_write = json.dumps(dictionary, indent=4)
            with open(f'{path}{ctx.message.author.id}.json', 'w') as f:
                f.write(userid_write)
    else:
        embed = discord.Embed(title="Банкомат (Приват Банк (ДС))",
                              description=f"***Вибачте, але на картці: {ctx.message.author.id} немає необхідних коштів, а саме: {sum}₴.***",
                              color=0xFF5733)
        await ctx.send(embed=embed)


from scipy.spatial import distance as dist
from collections import OrderedDict
import numpy as np

class CentroidTracker():
    def __init__(self, maxDisappeared=50):
        self.nextObjectID = 0
        self.objects = OrderedDict()
        self.originRects = OrderedDict()
        self.disappeared = OrderedDict()

        self.maxDisappeared = maxDisappeared

    def register(self, centroid, rect):
        self.originRects[self.nextObjectID] = rect
        self.objects[self.nextObjectID] = centroid
        self.disappeared[self.nextObjectID] = 0
        self.nextObjectID += 1

    def deregister(self, objectID):
        del self.originRects[objectID]
        del self.objects[objectID]
        del self.disappeared[objectID]

    def get_id(self, rect):
        (x, y, eX, eY) = rect
        cX = ((x + eX) / 2.0)
        cY = ((y + eY) / 2.0)

        objectIDs = list(self.objects.keys())
        objectCentroids = list(self.objects.values())

        D = dist.cdist(np.array(objectCentroids), [(cX, cY)])

        rows = D.min(axis=1).argsort()
        cols = D.argmin(axis=1)[rows]
        objectID = None

        for (row, col) in zip(rows, cols):
            objectID = objectIDs[row]
            break
        return objectID

    def update(self, rects):

        if(len(rects) == 0):
            for objectID in list(self.disappeared.keys()):
                self.disappeared[objectID] += 1

                if(self.disappeared[objectID] > self.maxDisappeared):
                    self.deregister(objectID)
            return self.objects, self.originRects

        inputCentroids = np.zeros((len(rects), 2), dtype="int")

        for(i, (startX, startY, endX, endY)) in enumerate(rects):
            cX = int((startX + endX) / 2.0)
            cY = int((startY + endY) / 2.0)
            inputCentroids[i] = (cX, cY)

        if(len(self.objects) == 0):
            for i in range(0, len(inputCentroids)):
                centroid = inputCentroids[i]
                rect = rects[i]
                self.register(centroid, rect)

        else:
            objectIDs = list(self.objects.keys())
            objectCentroids = list(self.objects.values())

            D = dist.cdist(np.array(objectCentroids), inputCentroids)

            rows = D.min(axis=1).argsort()
            cols = D.argmin(axis=1)[rows]

            usedRows = set()
            usedCols = set()

            for (row, col) in zip(rows, cols):

                if row in usedRows or col in usedCols:
                    continue

                objectID = objectIDs[row]
                self.objects[objectID] = inputCentroids[col]
                self.originRects[objectID] = rects[col]
                self.disappeared[objectID] = 0

                usedRows.add(row)
                usedCols.add(col)

            unusedRows = set(range(0, D.shape[0])).difference(usedRows)
            unusedCols = set(range(0, D.shape[1])).difference(usedCols)

            if D.shape[0] >= D.shape[1]:

                for row in unusedRows:
                    objectID = objectIDs[row]
                    self.disappeared[objectID] += 1

                    if self.disappeared[objectID] > self.maxDisappeared:
                        self.deregister(objectID)

            else:

                for col in unusedCols:
                    centroid = inputCentroids[col]
                    rect = rects[col]
                    self.register(centroid, rect)

        return self.objects, self.originRects


from __future__ import absolute_import
from typing import Optional, Sequence
from oneflow.python.oneflow_export import oneflow_export

import oneflow.python.framework.session_context as session_ctx
import oneflow.python.framework.compile_context as compile_context
import oneflow.python.framework.remote_blob as remote_blob_util
import oneflow.python.framework.distribute as distribute_util
import oneflow.python.experimental.name_scope as name_scope
import oneflow.core.operator.op_conf_pb2 as op_conf_util
import oneflow.core.register.logical_blob_id_pb2 as logical_blob_id_util
import oneflow.python.framework.c_api_util as c_api_util
import oneflow.python.framework.hob as hob
import oneflow.python.framework.dtype as dtype_util
import oneflow.python.eager.vm_util as vm_util
import oneflow.python.eager.gradient_util as gradient_util
import oneflow.python.eager.op_executor as op_executor
import oneflow.python.lib.core.enable_if as enable_if
import oneflow
import os

@oneflow_export("get_variable")
def api_get_variable(
    name: str,
    shape: Optional[Sequence[int]] = None,
    dtype: Optional[dtype_util.dtype] = dtype_util.float32,
    initializer: Optional[op_conf_util.InitializerConf] = None,
    regularizer: Optional[op_conf_util.RegularizerConf] = None,
    trainable: Optional[bool] = None,
    model_name: Optional[str] = None,
    random_seed: Optional[int] = None,
    distribute: distribute_util.Distribute = distribute_util.broadcast(),
    reuse: bool = True,
) -> remote_blob_util.BlobDef:
    r"""Create a variable or retrieve an existing one.

    Args:
        name: Name of this variable. One variable could be shared by multiple OneFlow functions. `None` by defauilt
        shape: Shape of the variable. `None` by defauilt
        dtype: Data type of the variable. `None` by defauilt
        initializer: A initializer object. For instance, a :func:`~oneflow.ones_initializer`. `None` by defauilt
        trainable: A `bool` to indicate if this variable is trainable. `True` by defauilt
        model_name: A `string`. `'weight'` or `'bias'`. `None` by defauilt
        random_seed: Random seed for random initializers. `None` by defauilt
    """
    api = enable_if.unique([get_lazy_variable, get_eager_variable])
    return api(
        name,
        shape=shape,
        dtype=dtype,
        initializer=initializer,
        regularizer=regularizer,
        trainable=trainable,
        model_name=model_name,
        random_seed=random_seed,
        distribute=distribute,
        reuse=reuse,
    )

@enable_if.condition(hob.in_global_mode & hob.eager_execution_enabled)
def get_eager_variable(
    name,
    shape=None,
    dtype=None,
    initializer=None,
    regularizer=None,
    trainable=None,
    model_name=None,
    random_seed=None,
    distribute=distribute_util.broadcast(),
    reuse=True,
):
    assert isinstance(name, str)
    assert isinstance(
        shape, (list, tuple)
    ), "param shape should be a list or tuple of dimension"

    job_name = c_api_util.JobBuildAndInferCtx_GetCurrentJobName()
    name = name_scope.GetJobNameScopePrefix(job_name) + name
    sess = session_ctx.GetDefaultSession()
    var_blob, job_var_blob = sess.TryGetVariableBlobOfJobFromStash(job_name, name)

    if reuse is False:
        assert job_var_blob is None, (
            "varaible '{}' already exists, "
            "getting the same variable is not allowed "
            "when reuse is False".format(name)
        )

    if job_var_blob is None:
        op_conf = _GenerateVariableOpConf(
            name=name,
            shape=shape,
            dtype=dtype,
            initializer=initializer,
            regularizer=regularizer,
            trainable=trainable,
            model_name=model_name,
            random_seed=random_seed,
            distribute=distribute,
        )
        op_attribute = compile_context.CurJobAddConsistentOp(op_conf)
        if var_blob is None:
            var_blob = _CreateEagerVariableBlob(op_attribute)
            op_executor.EagerInitVariableBlob(op_conf, var_blob)

        assert isinstance(var_blob, remote_blob_util.EagerConsistentBlob)
        sess.StashVariableBlob4Job(job_name, op_conf.name, var_blob)
    else:
        assert isinstance(job_var_blob, remote_blob_util.EagerConsistentBlob)
        assert isinstance(var_blob, remote_blob_util.EagerConsistentBlob)
        assert var_blob.IdenticalTo(job_var_blob)

    bw_blob_register = gradient_util.GetDefaultBackwardBlobRegister()
    bw_blob_register.TrySetObject4BlobName(
        var_blob.logical_blob_name, var_blob.blob_object
    )
    return var_blob

@enable_if.condition(hob.in_global_mode & ~hob.eager_execution_enabled)
def get_lazy_variable(
    name,
    shape=None,
    dtype=None,
    initializer=None,
    regularizer=None,
    trainable=None,
    model_name=None,
    random_seed=None,
    distribute=distribute_util.broadcast(),
    reuse=True,
):
    assert isinstance(name, str)
    assert isinstance(
        shape, (list, tuple)
    ), "param shape should be a list or tuple of dimension"

    job_name = c_api_util.JobBuildAndInferCtx_GetCurrentJobName()
    name = name_scope.GetJobNameScopePrefix(job_name) + name
    sess = session_ctx.GetDefaultSession()
    var_blob, job_var_blob = sess.TryGetVariableBlobOfJobFromStash(job_name, name)

    if reuse is False:
        assert job_var_blob is None, (
            "varaible '{}' already exists, "
            "getting the same variable is not allowed "
            "when param reuse is False".format(name)
        )

    if job_var_blob is None:
        op_conf = _GenerateVariableOpConf(
            name=name,
            shape=shape,
            dtype=dtype,
            initializer=initializer,
            regularizer=regularizer,
            trainable=trainable,
            model_name=model_name,
            random_seed=random_seed,
            distribute=distribute,
        )
        job_var_blob = _CreateVariableBlob(op_conf)
        assert isinstance(job_var_blob, remote_blob_util.LazyConsistentBlob)
        sess.StashVariableBlob4Job(job_name, op_conf.name, job_var_blob)
        if var_blob is not None:
            assert isinstance(var_blob, remote_blob_util.LazyConsistentBlob)
            assert var_blob.IdenticalTo(job_var_blob)
    else:
        assert isinstance(job_var_blob, remote_blob_util.LazyConsistentBlob)
        assert isinstance(var_blob, remote_blob_util.LazyConsistentBlob)
        assert var_blob.IdenticalTo(job_var_blob)

    return job_var_blob

def _GenerateVariableOpConf(
    name,
    shape,
    dtype=None,
    initializer=None,
    regularizer=None,
    trainable=None,
    model_name=None,
    random_seed=None,
    distribute=distribute_util.broadcast(),
):
    op_conf = op_conf_util.OperatorConf()
    op_conf.name = name
    op_conf.variable_conf.shape.dim.extend(shape)

    assert dtype is not None
    op_conf.variable_conf.data_type = dtype.oneflow_proto_dtype

    root_path = (
        compile_context.GetCurJobConfigProto().default_initialize_with_snapshot_path
    )
    dir_path = os.path.join(root_path, name)
    file_path = os.path.join(dir_path, "out")
    if root_path and os.path.isfile(file_path):
        op_conf.variable_conf.initialize_with_snapshot.path = dir_path
        op_conf.variable_conf.initialize_with_snapshot.key = "out"
    else:
        if root_path:
            print("{} not found, will be initialized".format(file_path))
        if initializer is not None:
            op_conf.variable_conf.initializer.CopyFrom(initializer)

    if regularizer is not None:
        op_conf.variable_conf.regularizer.CopyFrom(regularizer)

    if trainable is not None:
        op_conf.trainable = trainable

    if model_name is not None:
        op_conf.variable_conf.model_name = model_name

    if type(distribute) is distribute_util.SplitDistribute:
        op_conf.variable_conf.split_axis.value = distribute.axis
    else:
        op_conf.variable_conf.split_axis.ClearField("value")

    if random_seed is not None:
        op_conf.variable_conf.random_seed = random_seed

    op_conf.variable_conf.out = "out"
    return op_conf

def _CreateVariableBlob(op_conf):
    compile_context.CurJobAddConsistentOp(op_conf)
    lbi = logical_blob_id_util.LogicalBlobId()
    lbi.op_name = op_conf.name
    lbi.blob_name = op_conf.variable_conf.out
    return remote_blob_util.RemoteBlob(lbi)

def _CreateEagerVariableBlob(op_attribute):
    bn_in_op2blob_object = {}

    def BuildInstruction(builder):
        parallel_conf = oneflow.placement.current_scope().default_parallel_conf
        builder.StatelessCall(
            op_attribute, parallel_conf, bn_in_op2blob_object=bn_in_op2blob_object
        )

    vm_util.LogicalRun(BuildInstruction)
    lbi = logical_blob_id_util.LogicalBlobId()
    lbi.op_name = op_attribute.op_conf.name
    lbi.blob_name = op_attribute.op_conf.variable_conf.out
    return remote_blob_util.EagerLogicalBlob(
        lbi, blob_object=bn_in_op2blob_object["out"]
    )


import numpy as np
from grabscreen import grab_screen
import cv2
import time
from getkeys import key_check
import os
import win32gui
import win32api, win32con

class self_window():
    character = None
    def __init__(self):
        self.differenceX, self.differenceY = seek_for_window()
        self.window_region = (self.differenceX,self.differenceY,800+self.differenceX-1,600+self.differenceY-1)
        self.running = True
    def cursor_pos(self):
        tup = win32api.GetCursorPos()
        x = tup[0] - self.differenceX
        y = tup[1] - self.differenceY
        return (x,y)
    def right_click_without_move(self):
        x,y = win32api.GetCursorPos()[0], win32api.GetCursorPos()[1]
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
        time.sleep(0.07)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
    def click(self,x,y):
        x = x + self.differenceX
        y = y + self.differenceY

        # add slight move!
        # print(win32api.GetCursorPos())
        win32api.SetCursorPos((x,y))
        time.sleep(0.2)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
        time.sleep(0.07)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
    def screenshot(self):
        img_rgb = grab_screen(region=(self.differenceX,self.differenceY,800+self.differenceX-1,600+self.differenceY-1))
        cv2.imwrite('screen.png',img_rgb)
def callback(hwnd, extra):
    # if win32gui.GetWindowText(hwnd) == 'Path of Exile':
    rect = win32gui.GetWindowRect(hwnd)
    x = rect[0]
    y = rect[1]
    return (x+8, y+31)
    w = rect[2] - x
    h = rect[3] - y
    print("Window %s:" % win32gui.GetWindowText(hwnd))
    print("\tLocation: (%d, %d)" % (x, y))
    print("\t    Size: (%d, %d)" % (w, h))
    #img_rgb = grab_screen(region=(x+8,y+31,800+x+7,600+y+30))
    # print_img(img_rgb)

def seek_for_window():
    hwnd = win32gui.FindWindow(None, "Path of Exile")
    print('window found')
    difference = callback(hwnd,None)
    return difference[0], difference[1]
    import pdb; pdb.set_trace()

def zseek_for_login_page():
    while True:
        last_time = time.time()
        # img_rgb = grab_screen(region=(33,31,832,630)) 833 631
        img_rgb = grab_screen(region=(0,0,1024,768))
        img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
        # back_img = img_rgb[60:110, 390:440]
        # (Pdb) cv2.imwrite('obj.png',back_img)
        template = cv2.imread('clue.png',0)
        w, h = template.shape[::-1]
        res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
        threshold = 0.8
        loc = np.where( res >= threshold)
        for pt in zip(*loc[::-1]):
#             width_difference, height_difference = (pt[0]-390,pt[1]-60)
            cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 1)
            # pt[0] + 10        pt[0] + w
            #cv2.line(img_rgb, (540, pt[1] + round(h/2) ), (540, pt[1] + round(h/2) ), (255,0,0), 4)
        print_img(img_rgb)
        cv2.imwrite('res.png',img_rgb)
        import pdb; pdb.set_trace()
        # print('loop took {} seconds'.format(time.time()-last_time))

def print_img(img):
    cv2.imshow("test", img); cv2.waitKey(0); cv2.destroyAllWindows()
# # def test():
#     last_time = time.time()
#     img_rgb = cv2.imread('main_menu.png')
#     img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
#     template = cv2.imread('login_button.png',0)
#     w, h = template.shape[::-1]
#     res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
#     threshold = 0.8
#     loc = np.where( res >= threshold)
#     counter = 1
#     for pt in zip(*loc[::-1]):
#         # cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
#         import pdb; pdb.set_trace()# pt[0] + 10        pt[0] + w
#         cv2.line(img_rgb, (540, pt[1] + round(h/2) ), (540, pt[1] + round(h/2) ), (255,0,0), 4)
#     print_img(img_rgb)
#     cv2.imwrite('res.png',img_rgb)
#     # print('loop took {} seconds'.format(time.time()-last_time))
def save_img(img,name):
    cv2.imwrite( str(name)+".jpg",img)
def create_backup_img(width,height):
    file_name = 'backup_data.npy'
    region = (0,0,1024,768)#x = 1024, y = 768
    screen = grab_screen(region=(0,0,1024,768))
    print_img(screen)
    if os.path.isfile(file_name):
        print('File exists, loading previous data!')
        training_data = list(np.load(file_name))
    else:
        print('File does not exist, starting fresh!')
        training_data = []
    screen = grab_screen(region=region)
    #print_img(screen)
    training_data.append([screen])
    np.save(file_name,training_data)

def load_arr():
    return list(np.load('backup_data.npy'))

def utils_main():
    screen = grab_screen(region=(0,0,1024,768))
    screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
    logo_part = screen[100:200, 400:500]

    #click(log_in)

    import pdb; pdb.set_trace()
# test()


from __future__ import print_function
from __future__ import with_statement

import os
import logging.config

logging.config.fileConfig(os.path.dirname(__file__)+"/logger.conf")
logger = logging.getLogger("pgclient")

class BaseSession(object):

    def __init__(self, transport, oprot_factory, container, timeout):
        self._transport = transport                     # TPegasusTransport
        self._oprot_factory = oprot_factory
        self._container = container
        self._seqid = 0
        self._requests = {}
        self._default_timeout = timeout

    def __del__(self):
        self.close()

    def operate(self, op, timeout=None):
        if not isinstance(timeout, int) or timeout <= 0:
            timeout = self._default_timeout


def bucketSort(nli):
    temp = max(nli)
    k = 0
    while temp:
        temp /= 10
        k += 1

    lLen = len(nli)
    q=1
    while k > 0:
        tli = [0 for i in range(10)]

        for i in nli:   #统计当前位的词频
            index=int(i % (q*10) / q)
            tli[index] += 1

        for i in range(1,10):   #将词频数组中的每一位都计算出前缀和
            tli[i] += tli[i-1]

        cli=[0 for i in range(lLen)]    #准备一个和元素组长度相等的数组,初始化为0
        i = lLen-1
        while i >= 0:
            index = tli[int(nli[i] % (q*10) / q)]-1
            cli[index] = nli[i]
            tli[int(nli[i] % (q*10) / q)] -= 1
            i-=1
        nli = cli
        q *= 10
        k-=1

    return nli

import random
times=100
lLen=10
for i in range(times):
    nList=[]
    for j in range(lLen):
        temp = random.randint(0,1000)
        nList.append(temp)
    r1 = sorted(nList)
    r2 = bucketSort(nList)

    if r1 != r2:
        break

if i == times-1:
    print("NICE!!!!")
else:
    print("Fucking Fucked!")

003桶排序优雅处理.py


from abc import abstractmethod

import numpy as np

from pymoo.core.population import Population

# ---------------------------------------------------------------------------------------------------------
# Survival
# ---------------------------------------------------------------------------------------------------------

class Survival:

    def __init__(self, filter_infeasible=True):
        super().__init__()
        self.filter_infeasible = filter_infeasible

    def do(self,
           problem,
           pop,
           *args,
           n_survive=None,
           return_indices=False,
           **kwargs):

        # make sure the population has at least one individual
        if len(pop) == 0:
            return pop

        if n_survive is None:
            n_survive = len(pop)

        n_survive = min(n_survive, len(pop))

        # if the split should be done beforehand
        if self.filter_infeasible and problem.has_constraints():

            # split feasible and infeasible solutions
            feas, infeas = split_by_feasibility(pop, sort_infeas_by_cv=True)

            if len(feas) == 0:
                survivors = Population()
            else:
                survivors = self._do(problem, pop[feas], *args, n_survive=min(len(feas), n_survive), **kwargs)

            # calculate how many individuals are still remaining to be filled up with infeasible ones
            n_remaining = n_survive - len(survivors)

            # if infeasible solutions needs to be added
            if n_remaining > 0:
                survivors = Population.merge(survivors, pop[infeas[:n_remaining]])

        else:
            survivors = self._do(problem, pop, *args, n_survive=n_survive, **kwargs)

        if return_indices:
            H = {}
            for k, ind in enumerate(pop):
                H[ind] = k
            return [H[survivor] for survivor in survivors]
        else:
            return survivors

    @abstractmethod
    def _do(self, problem, pop, *args, n_survive=None, **kwargs):
        pass

class ToReplacement(Survival):

    def __init__(self, survival):
        super().__init__(False)
        self.survival = survival

    def _do(self, problem, pop, off, **kwargs):
        merged = Population.merge(pop, off)
        I = self.survival.do(problem, merged, n_survive=len(merged), return_indices=True, **kwargs)
        merged.set("__rank__", I)

        for k in range(len(pop)):
            if off[k].get("__rank__") < pop[k].get("__rank__"):
                pop[k] = off[k]

        return pop

def split_by_feasibility(pop, sort_infeas_by_cv=True, sort_feas_by_obj=False, return_pop=False):
    F, CV, b = pop.get("F", "CV", "feasible")

    feasible = np.where(b)[0]
    infeasible = np.where(~b)[0]

    if sort_infeas_by_cv:
        infeasible = infeasible[np.argsort(CV[infeasible, 0])]

    if sort_feas_by_obj:
        feasible = feasible[np.argsort(F[feasible, 0])]

    if not return_pop:
        return feasible, infeasible
    else:
        return feasible, infeasible, pop[feasible], pop[infeasible]


# Author: Zhang Huangbin <zhb@iredmail.org>

import web
import settings

from libs import iredutils, form_utils
from libs.l10n import TIMEZONES

from libs.sqllib import SQLWrap, decorators, sqlutils
from libs.sqllib import user as sql_lib_user
from libs.sqllib import admin as sql_lib_admin
from libs.sqllib import domain as sql_lib_domain
from libs.sqllib import utils as sql_lib_utils
from libs.sqllib import general as sql_lib_general

session = web.config.get('_session')

class List:
    @decorators.require_global_admin
    def GET(self, domain, cur_page=1, disabled_only=False):
        domain = str(domain).lower()
        cur_page = int(cur_page) or 1

        form = web.input(_unicode=False)
        order_name = form.get('order_name')
        order_by_desc = (form.get('order_by', 'asc').lower() == 'desc')

        records = []

        # Real-time used quota.
        used_quotas = {}

        all_first_chars = []
        first_char = None
        if 'starts_with' in form:
            first_char = form.get('starts_with')[:1].upper()
            if not iredutils.is_valid_account_first_char(first_char):
                first_char = None

        _wrap = SQLWrap()
        conn = _wrap.conn

        total = sql_lib_user.num_users_under_domains(conn=conn,
                                                     domains=[domain],
                                                     disabled_only=disabled_only,
                                                     first_char=first_char)

        if total:
            _qr = sql_lib_general.get_first_char_of_all_accounts(domain=domain,
                                                                 account_type='user',
                                                                 conn=conn)
            if _qr[0]:
                all_first_chars = _qr[1]

            qr = sql_lib_user.get_paged_users(conn=conn,
                                              domain=domain,
                                              cur_page=cur_page,
                                              order_name=order_name,
                                              order_by_desc=order_by_desc,
                                              first_char=first_char,
                                              disabled_only=disabled_only)

            if qr[0]:
                records = qr[1]
            else:
                raise web.seeother('/domains?msg=%s' % web.urlquote(qr[1]))

            # Get list of email addresses
            mails = []
            for r in records:
                mails += [str(r.get('username')).lower()]

            if mails:
                # Get real-time mailbox usage
                if settings.SHOW_USED_QUOTA:
                    try:
                        used_quotas = sql_lib_general.get_account_used_quota(accounts=mails, conn=conn)
                    except Exception:
                        pass

        if session.get('is_global_admin'):
            days_to_keep_removed_mailbox = settings.DAYS_TO_KEEP_REMOVED_MAILBOX_FOR_GLOBAL_ADMIN
        else:
            days_to_keep_removed_mailbox = settings.DAYS_TO_KEEP_REMOVED_MAILBOX

        return web.render('sql/user/list.html',
                          cur_domain=domain,
                          cur_page=cur_page,
                          total=total,
                          users=records,
                          used_quotas=used_quotas,
                          order_name=order_name,
                          order_by_desc=order_by_desc,
                          all_first_chars=all_first_chars,
                          first_char=first_char,
                          disabled_only=disabled_only,
                          days_to_keep_removed_mailbox=days_to_keep_removed_mailbox,
                          msg=form.get('msg', None))

    @decorators.csrf_protected
    @decorators.require_global_admin
    def POST(self, domain, page=1):
        form = web.input(_unicode=False, mail=[])
        page = int(page)
        if page < 1:
            page = 1

        domain = str(domain).lower()

        # Filter users not under the same domain.
        mails = [str(v)
                 for v in form.get('mail', [])
                 if iredutils.is_email(v) and str(v).endswith('@' + domain)]

        action = form.get('action', None)
        msg = form.get('msg', None)

        redirect_to_admin_list = False
        if 'redirect_to_admin_list' in form:
            redirect_to_admin_list = True

        _wrap = SQLWrap()
        conn = _wrap.conn

        if action == 'delete':
            keep_mailbox_days = form_utils.get_single_value(form=form,
                                                            input_name='keep_mailbox_days',
                                                            default_value=0,
                                                            is_integer=True)
            result = sql_lib_user.delete_users(conn=conn,
                                               accounts=mails,
                                               keep_mailbox_days=keep_mailbox_days)
            msg = 'DELETED'
        elif action == 'disable':
            result = sql_lib_utils.set_account_status(conn=conn,
                                                      accounts=mails,
                                                      account_type='user',
                                                      enable_account=False)
            msg = 'DISABLED'
        elif action == 'enable':
            result = sql_lib_utils.set_account_status(conn=conn,
                                                      accounts=mails,
                                                      account_type='user',
                                                      enable_account=True)
            msg = 'ENABLED'
        elif action == 'markasglobaladmin':
            result = sql_lib_user.mark_user_as_admin(conn=conn,
                                                     domain=domain,
                                                     users=mails,
                                                     as_global_admin=True)
            msg = 'MARKASGLOBALADMIN'
        elif action == 'unmarkasglobaladmin':
            result = sql_lib_user.mark_user_as_admin(conn=conn,
                                                     domain=domain,
                                                     users=mails,
                                                     as_global_admin=False)
            msg = 'UNMARKASGLOBALADMIN'
        else:
            result = (False, 'INVALID_ACTION')

        if result[0] is True:
            if redirect_to_admin_list:
                raise web.seeother('/admins/%s/page/%d?msg=%s' % (domain, page, msg))
            else:
                raise web.seeother('/users/%s/page/%d?msg=%s' % (domain, page, msg))
        else:
            if redirect_to_admin_list:
                raise web.seeother('/admins/%s/page/%d?msg=%s' % (domain, page, web.urlquote(result[1])))
            else:
                raise web.seeother('/users/%s/page/%d?msg=%s' % (domain, page, web.urlquote(result[1])))

class ListDisabled:
    @decorators.require_global_admin
    def GET(self, domain, cur_page=1):
        _instance = List()
        return _instance.GET(domain=domain, cur_page=cur_page, disabled_only=True)

class Profile:
    @decorators.require_global_admin
    def GET(self, profile_type, mail):
        mail = str(mail).lower()
        domain = mail.split('@', 1)[-1]

        _wrap = SQLWrap()
        conn = _wrap.conn

        form = web.input()
        msg = form.get('msg', '')

        # profile_type == 'general'
        used_quota = {}

        qr = sql_lib_user.profile(mail=mail, conn=conn)
        if qr[0]:
            user_profile = qr[1]
        else:
            raise web.seeother('/users/{}?msg={}'.format(domain, web.urlquote(qr[1])))
        del qr

        # Get per-user settings
        user_settings = {}
        qr = sql_lib_general.get_user_settings(conn=conn,
                                               mail=mail,
                                               existing_settings=user_profile['settings'])
        if qr[0]:
            user_settings = qr[1]
        del qr

        # Get used quota.
        if settings.SHOW_USED_QUOTA:
            used_quota = sql_lib_general.get_account_used_quota(accounts=[mail], conn=conn)

        # Get per-domain disabled user profiles.
        qr = sql_lib_domain.simple_profile(conn=conn,
                                           domain=domain,
                                           columns=['settings'])

        if qr[0]:
            domain_profile = qr[1]
            domain_settings = sqlutils.account_settings_string_to_dict(domain_profile['settings'])

            min_passwd_length = domain_settings.get('min_passwd_length', settings.min_passwd_length)
            max_passwd_length = domain_settings.get('max_passwd_length', settings.max_passwd_length)

        return web.render(
            'sql/user/profile.html',
            cur_domain=domain,
            mail=mail,
            profile_type=profile_type,
            profile=user_profile,
            timezones=TIMEZONES,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length,
            store_password_in_plain_text=settings.STORE_PASSWORD_IN_PLAIN_TEXT,
            password_policies=iredutils.get_password_policies(),
            user_settings=user_settings,
            used_quota=used_quota,
            languagemaps=iredutils.get_language_maps(),
            msg=msg,
        )

    @decorators.require_global_admin
    @decorators.csrf_protected
    def POST(self, profile_type, mail):
        form = web.input(
            enabledService=[],
            shadowAddress=[],
            telephoneNumber=[],
            domainName=[],      # Managed domains
        )

        mail = str(mail).lower()

        _wrap = SQLWrap()
        conn = _wrap.conn

        result = sql_lib_user.update(conn=conn,
                                     mail=mail,
                                     profile_type=profile_type,
                                     form=form)

        if result[0]:
            raise web.seeother('/profile/user/{}/{}?msg=UPDATED'.format(profile_type, mail))
        else:
            raise web.seeother('/profile/user/{}/{}?msg={}'.format(profile_type, mail, web.urlquote(result[1])))

class Create:
    @decorators.require_global_admin
    def GET(self, domain):
        domain = str(domain).lower()

        form = web.input()

        # Get all managed domains.
        _wrap = SQLWrap()
        conn = _wrap.conn

        if session.get('is_global_admin'):
            qr = sql_lib_domain.get_all_domains(conn=conn, name_only=True)
        else:
            qr = sql_lib_admin.get_managed_domains(conn=conn,
                                                   admin=session.get('username'),
                                                   domain_name_only=True)

        if qr[0] is True:
            all_domains = qr[1]
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(qr[1]))

        # Get domain profile.
        qr_profile = sql_lib_domain.simple_profile(domain=domain, conn=conn)
        if qr_profile[0] is True:
            domain_profile = qr_profile[1]
            domain_settings = sqlutils.account_settings_string_to_dict(domain_profile['settings'])
        else:
            raise web.seeother('/domains?msg=%s' % web.urlquote(qr_profile[1]))

        # Cet total number and allocated quota size of existing users under domain.
        num_users_under_domain = sql_lib_general.num_users_under_domain(domain=domain, conn=conn)

        min_passwd_length = domain_settings.get('min_passwd_length', settings.min_passwd_length)
        max_passwd_length = domain_settings.get('max_passwd_length', settings.max_passwd_length)

        return web.render(
            'sql/user/create.html',
            cur_domain=domain,
            allDomains=all_domains,
            profile=domain_profile,
            domain_settings=domain_settings,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length,
            store_password_in_plain_text=settings.STORE_PASSWORD_IN_PLAIN_TEXT,
            num_existing_users=num_users_under_domain,
            languagemaps=iredutils.get_language_maps(),
            password_policies=iredutils.get_password_policies(),
            msg=form.get('msg'),
        )

    @decorators.csrf_protected
    @decorators.require_global_admin
    def POST(self, domain):
        domain = str(domain).lower()
        form = web.input()

        domain_in_form = form_utils.get_domain_name(form)
        if domain != domain_in_form:
            raise web.seeother('/domains?msg=PERMISSION_DENIED')

        # Get domain name, username, cn.
        username = form_utils.get_single_value(form,
                                               input_name='username',
                                               to_string=True)

        qr = sql_lib_user.add_user_from_form(domain=domain, form=form)

        if qr[0]:
            raise web.seeother('/profile/user/general/{}@{}?msg=CREATED'.format(username, domain))
        else:
            raise web.seeother('/create/user/{}?msg={}'.format(domain, web.urlquote(qr[1])))


#!/usr/bin/python3
"""
Function that prints the square
with the character #
"""

def print_square(size):
    """
    Defines a function
    Takes an integer as an argument
    """
    # Check if size is an integer
    if not isinstance(size, int):
        raise TypeError("size must be an integer")
    # Check if size is greater than 0
    if size < 0:
        raise ValueError("size must be >= 0")
    # Check if size is not a float
    if type(size) is float and size < 0:
        raise TypeError("size must be an integer")
    if size == 0:
        print("", end="")
    # Prints the square with the character #
    else:
        print("\n".join("#"*size for rows in range(size)))


#collatz calculator 3n + 1 until it reaches 1.

def collatz():

    n = int(input("Enter a starting number: "))
    lst = list()
    lst.append(n)

    while n > 1:
        if n % 2 == 0:
            n = int(n / 2)
            lst.append(n)
        else:
            n = 3*n + 1
            lst.append(n)

    return(lst)

result = collatz()
print(result,"\n\nThere are {} elements in the list.".format(len(result)),"\n\nThe highest number in the list is {}.".format(max(result)))


from scapy.all import *

def sniffPckt(pkt):
	pkt.show()

def start_sniff():
	scapy_sniff = sniff(prn=sniffPckt,timeout=50,iface='eth0',stop_filter = lambda x:x.haslayer(ICMP))
	wrpcap('btkakademi.pcap',scapy_sniff)

def start_read():
	scapy_cap=rdpcap('btkakademi.pcap')
	ip_list = []
	for pckt in scapy_cap:
		if IP in pckt:
			if pckt[IP].src not in ip_list:
				ip_list.append(pckt[IP].src)
		else:
			pckt.show()
	print(ip_list)

print("""
	1: sniff
	2: read
	""")

choice = input(">> ")

if(choice=="1"):
	start_sniff()
elif(choice=="2"):
	start_read()
else:
	print("Hatalı Giriş")


from django.db import models
from django.contrib.auth.models import User
from django.core.validators import RegexValidator

# Create your models here.
class Contact(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    first_name = models.CharField(max_length=20, verbose_name="First Name")
    last_name = models.CharField(max_length=30, verbose_name="Last Name")
    address = models.CharField(max_length=255, verbose_name="Address", blank=True)
    email = models.EmailField(max_length=50, verbose_name="Email", blank=True)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Correct format: '+999999999'. Up to 15 digits allowed.")
    phone = models.CharField(validators=[phone_regex], max_length=17, blank=True, verbose_name="Phone Number") # validators should be a list
    date = models.DateTimeField(auto_now_add=True, verbose_name='Created Date')

    def __str__(self,):
        return self.first_name + self.last_name

    class Meta:
        ordering = ['first_name']


# 1.- DEFINIR VARIABLES
subTotal = 0
opcion = "0"
# 2.- SOLICITAR LOS DATOS
print("\n ********* Panadería ********")
while opcion != "6":
    print("==== Menu principal ====")
    print("1.- Pan amasado")
    print("2.- Pan Molde")
    print("3.- Pan Baguette")
    print("4.- Pan Integral")
    print("5.- Total venta")
    print("6.- Salir")
    opcion = input("Ingrese una opción:")

    if opcion not in ("1","2","3","4","5","6"):
        input("La opción no es válida")
    elif opcion == "6":
        print("Adios!!!")
    elif opcion == "5":
        if subTotal < 5000:
            subTotal*=1.1
            print("La venta paga envío")
        else:
            print("El envío es gratis")
        print("El total de la venta es", int(subTotal))
        subTotal = 0
    else:
        cantidad = int(input("Ingrese cantidad de pan a llevar:"))
        if opcion == "1":
            subTotal += cantidad * 1500
        elif opcion == "2":
            subTotal += cantidad * 1000
        elif opcion == "3":
            subTotal += cantidad * 2000
        elif opcion == "4":
            subTotal += cantidad * 3000
        print("El sub total es:", subTotal)


from sim.concrete import db
from sim.nova.scheduler import filters
from sim.nova.scheduler import weights
from oslo.config import cfg

CONF = cfg.CONF
CONF.import_opt('default_filters', 'sim.nova.scheduler.filters')

class FilterScheduler(object):
	"""FilterScheduler simulator"""

	def _select_filters(self, filters):
		if not filters:
			selected_filters = CONF.default_filters
		else:
			selected_filters = filters
		return selected_filters

	def _schedule(self, all_hosts, selected_filters, flavor):
		def _filter(host, filters, flavor):
			for f in filters:
				if not f.host_passes(host, flavor):
					return False
			return True

		selected_hosts = []
		filters = []

		from sim import utils
		for sf in selected_filters:
			filterClass = utils.class_for_name(sf)
			filters.append(filterClass())

		for h in all_hosts:
			if _filter(h, filters, flavor):
				selected_hosts.append(h)

		return selected_hosts

	#We don't consider the possibility to pass a bundle of instances to be spawned
	def select_destinations(self, flavor, filters=None):
		""""Returns a list of destinations ordered from the best suitable to the worst"""

		all_hosts = db.Host.get_all()
		selected_filters = self._select_filters(filters)

		#Filtering
		selected_destinations = self._schedule(all_hosts, selected_filters, flavor)
		#Weighing
		weighted_destinations = weights.get_weighed_hosts(selected_destinations)
		return weighted_destinations


from database import Database
from validation import Validation
import random

class Product:
    def __init__(
        self,
        product_id,
        product_name,
        description,
        price,
        seller,
        amount_sold,
        rating,
        stock_quanitity,
        category,
    ):
        self.product_id = product_id
        self.product_name = product_name
        self.description = description
        self.price = price
        self.seller = seller
        self.rating = rating
        self.amount_sold = amount_sold
        self.stock_quanitity = stock_quanitity
        self.category = category

    @classmethod
    def list_products(cls):
        return [Product(*prod) for prod in Database.get_all_products()]

    @classmethod
    def list_purchases(cls):
        return Database.get_all_purchases()

    @classmethod
    def get_product(cls, idd):
        return Product(*Database.get_product_from_id(idd))

    @classmethod
    def add_product(
        cls,
        product_id,
        product_name,
        description,
        price,
        seller,
        rating,
        amount_sold,
        stock_quanitity,
        category,
    ):
        Database.add_product(
            product_id,
            product_name,
            description,
            price,
            seller,
            rating,
            amount_sold,
            stock_quanitity,
            category,
        )

    def purchase_product(self, buyer):
        idd = random.randint(0, 1000000000)
        print("!===Product Successfully Purchased===!")
        print("Product Name: {0}".format(self.product_name))
        print("Billing Amount: Rs. {0}".format(self.price))
        print("---Seller info---")
        seller_user = Database.get_user_details(self.seller, "seller", False)
        print("Name: {0} {1}".format(seller_user[0], seller_user[1]))
        print("Username: {0}".format(seller_user[2]))
        print("Address: {0}".format(seller_user[5]))
        i = Validation.get_int_input(input("Enter Rating between 1 to 5:"), 5)
        self.rating = int(self.rating) + i
        self.stock_quanitity = int(self.stock_quanitity) - 1
        self.amount_sold = int(self.amount_sold) + 1
        buyer.my_products.append(idd)
        Database.purchase_product(
            idd,
            self.product_id,
            buyer.username,
            self.rating,
            self.stock_quanitity,
            buyer.my_products,
            self.amount_sold,
            self.seller,
        )
        print("Enter any key to continue...")
        input()

    @classmethod
    def search_products(cls, search_term, p_type):
        return [
            Product(*prod) for prod in Database.search_products(search_term, p_type)
        ]

    def __repr__(self):
        return """
Name : {0}
Catergory : {6}
Description : {1}
Price : Rs. {2}
Seller : {3}
Rating : {4}
Amount Sold : {5}
Stocks : {7}
=====================================================
            \n
        """.format(
            self.product_name,
            self.description,
            self.price,
            self.seller,
            "N/A"
            if self.amount_sold == "0"
            else round(int(self.rating) / int(self.amount_sold), 2),
            self.amount_sold,
            self.category,
            self.stock_quanitity if int(self.stock_quanitity) > 0 else "Out Of Stock",
        )


import requests
from bs4 import BeautifulSoup
from db import News, session

def extract_news(parser):
    """ Extract news from a given web page """
    news_list = []

    table = (parser.find('table', {'class': 'itemlist'}))
    trs = table.find_all("tr")
    count = 0
    dict_add = {
        'author': None,
        'comments': 0,
        'points': 0,
        'title': None,
        'url': None
    }

    for i, elem in enumerate(trs):
        if i < 90:
            if count == 0:
                dict_add["title"] = elem.find('a', {'class': 'storylink'}).get_text()
                dict_add['url'] = (elem.find('a', {'class': 'storylink'}))['href']
            if count == 1:
                str_point=(elem.find('span', {'class': 'score'})).get_text()
                dict_add['points'] = int(str_point[:str_point.find(" ")])
                dict_add['author'] = elem.find('a', {'class': 'hnuser'}).get_text()
                a_els = elem.find_all("a")
                if a_els[-1].get_text() == "discuss":
                    dict_add['comments'] = 0
                else:
                    str_comm = a_els[-1].get_text()
                    dict_add['comments'] = int(str_comm[:str_comm.find(" ")])
            if count == 2:
                news_list.append(dict_add)
                count = -1
                dict_add = {
                    'author': None,
                    'comments': 0,
                    'points': 0,
                    'title': None,
                    'url': None
                }
            count += 1

    return news_list

def extract_next_page(parser):
    """ Extract next page URL """
    table = (parser.find('table', {'class': 'itemlist'}))
    trs = table.find_all("tr")
    return trs[-1].find('a', {'class': 'morelink'})['href']

def get_news(url, n_pages=1):
    """ Collect news from a given web page """
    news = []
    while n_pages:
        print("Collecting data from page: {}".format(url))
        response = requests.get(url)
        soup = BeautifulSoup(response.text, "html.parser")
        news_list = extract_news(soup)
        next_page = extract_next_page(soup)
        url = "https://news.ycombinator.com/" + next_page
        news.extend(news_list)
        n_pages -= 1
        print(len(news))

    return news


from table_games.common.cards import *
from table_games.blackjack.blackjack import PlayerPolicy, PlayerState, SpotState, SpotSplitAction, SpotDoubleAction, SpotHitAction, SpotStandAction, soft_total, hard_total

class Wrapper:
    def __init__(self, value) -> None:
        self.value = value

class PlayerPolicyMonitor(PlayerPolicy):

    policy = {
        'hard':  { idx: ['']*10 for idx in range(8, 18)  },
        'soft':  { idx: ['']*10 for idx in range(13, 21) },
        'pairs': { idx: ['']*10 for idx in range(1, 11)  },
    }

    observing: PlayerPolicy = None

    @classmethod
    def Action(cls, player: PlayerState, spot: SpotState, up_card: Card, submit):

        attempted_double = Wrapper(False)

        def m_submit(action):

            is_pair = True
            is_pair &= len(spot._cards) == 2
            is_pair &= spot._cards[0]._value == spot._cards[1]._value

            soft = soft_total(spot._cards)
            hard = hard_total(spot._cards)

            column = min(10, up_card._value) - 2
            if column == -1: column = 9

            m_action = ''
            if   type(action) is SpotSplitAction:  m_action = 'V'
            elif type(action) is SpotDoubleAction: m_action = 'D'
            elif type(action) is SpotHitAction:    m_action = 'H'
            elif type(action) is SpotStandAction:  m_action = 'S'
            else: raise Exception('Unknown action type')

            if attempted_double.value:
                m_action = 'D' + m_action

            if submit(action):
                if is_pair:
                    row = min(10, spot._cards[0]._value)
                    if type(action) is SpotSplitAction:
                        cls.policy['pairs'][row][column] = 'Y'
                        return True
                    else:
                        cls.policy['pairs'][row][column] = 'N'

                if soft != hard:
                    row = min(20, soft)
                    cls.policy['soft'][row][column] = m_action
                else:
                    row = max(8, min(17, hard))
                    cls.policy['hard'][row][column] = m_action

                return True

            elif type(action) is SpotDoubleAction:
                attempted_double.value = True
                return False

            else:
                raise Exception('Unknown action type')

        cls.observing.Action(player, spot, up_card, m_submit)

    @classmethod
    def ToCsv(cls, filename):
        header = 'total,2,3,4,5,6,7,8,9,10,A'
        with open(filename, 'w') as f:
            f.write(header + '\n')
            f.write('\n')

            # Write the hard policy to the csv
            for row in reversed(range(8, 18)):
                f.write(f'{ row },')
                f.write(','.join(cls.policy['hard'][row]))
                f.write('\n')

            f.write('\n')

            # Write the soft policy to the csv
            for row in reversed(range(13, 21)):
                f.write(f'{ row },')
                f.write(','.join(cls.policy['soft'][row]))
                f.write('\n')

            f.write('\n')

            # Write the pair policy to the csv
            f.write('A,')
            f.write(','.join(cls.policy['pairs'][1]))
            f.write('\n')
            for row in reversed(range(2, 11)):
                f.write(f'{ row },')
                f.write(','.join(cls.policy['pairs'][row]))
                f.write('\n')

    @classmethod
    def PrebetAction(cls, player: PlayerState, submit):
        return cls.observing.PrebetAction(player, submit)

    @classmethod
    def Bet(cls, game: 'Blackjack', player: PlayerState, submit):
        return cls.observing.Bet(game, player, submit)

    @classmethod
    def InsuranceAction(cls, player: PlayerState) -> bool:
        return cls.observing.InsuranceAction(player)


def hitung_BMI(bb,tb):
    return bb/(tb*tb)

def cek_status_BMI(bmi):
    if(bmi >= 35):
        return "OBESITAS MORBID"
    elif(bmi >= 27):
        return "OBESITAS"
    elif(bmi >= 23):
        return "GEMUK"
    elif(bmi >= 18):
        return "IDEAL"
    else:
        return "KURUS"

berat  = int(input("Masukkan berat badan (Kg)  :"))
tinggi = int(input("Masukkan tinggi badan (cm) : "))

if(berat > 0) and (tinggi > 0):
    bmi = hitung_BMI(berat,tinggi/100)
    print("Status berat badan anda adalah", cek_status_BMI(bmi))
else:
    print("Input yang dimasukkan tidak valid")


class Solution:
    def mostWordsFound(self, sentences: List[str]) -> int:

        def find_words(s):
            count = 0
            ans = 0
            i = 0
            while(i < len(s)):
                if s[i]==" ":
                    ans+=1
                i+=1
            ans +=1
            return ans

        max_words = 0

        for sentence in sentences:
            number_of_words = find_words(sentence)
            max_words = max(max_words, number_of_words)
        return max_words


import logging
import time
from copy import deepcopy

import torch
from torch import nn
import traceback
from mpi4py import MPI

from algorithms.baseDecent.decentralized_worker import BaseDecentralizedWorker

from utils.data_utils import (
    get_data,
    apply_gradient
)
from utils.tensor_buffer import (
    TensorBuffer
)

class DecentralizedWorker(BaseDecentralizedWorker):
    def __init__(self, client_index, topology_manager, train_data_global, test_data_global, train_data_num,
                train_data_local_dict, test_data_local_dict, train_data_local_num_dict, worker_number,
                device, model, args, model_trainer, perf_timer, metrics):
        super().__init__(client_index, topology_manager, train_data_global, test_data_global, train_data_num,
                train_data_local_dict, test_data_local_dict, train_data_local_num_dict, worker_number,
                device, model, args, model_trainer, perf_timer, metrics)
        """
            The `compression` method should be specified in `args`.
        """
        # =================================================
        # Specilaized for CHOCO_SGD
        # ============================================================
        self.param_groups = self.model_trainer.param_groups
        self.param_names = self.model_trainer.param_names
        self.topology_manager = topology_manager
        self.neighbors_info = self.topology_manager.topology

        # will be initialized in init_neighbor_hat_params()
        self.neighbor_hat_params = None
        self.shapes = None
        self.init_neighbor_hat_params()

        # used for CHOCO_SGD
        # self.consensus_stepsize = 0.9  # 0.5
        self.consensus_stepsize = args.consensus_stepsize

    def aggregate(self, compressor, selected_shapes):
        start_time = time.time()
        model_list = []
        training_num = 0

        for neighbor_idx in self.in_neighbor_idx_list:

            msg_params = self.worker_result_dict[neighbor_idx]
            compressor.uncompress(msg_params,
                self.neighbor_hat_params["memory"],
                selected_shapes, self.shapes
            )

        logging.debug("len of self.worker_result_dict[idx] = " + str(len(self.worker_result_dict)))

        end_time = time.time()
        logging.debug("aggregate time cost: %d" % (end_time - start_time))
        # return averaged_params

    # ==============================================================================

    # Specilaized for CHOCO_SGD
    def init_neighbor_hat_params(self):
        params, params_shapes = get_data(
            self.param_groups, self.param_names, is_get_grad=False
        )
        flatten_params = TensorBuffer(params)
        flatten_params.buffer = torch.zeros_like(flatten_params.buffer).to(self.device)

        # init the neighbor_params.
        self.neighbor_hat_params = {
                self.client_index: deepcopy(flatten_params),
                "memory": deepcopy(flatten_params),
                # "receive_cache": deepcopy(flatten_params),
            }
        self.neighbor_hat_params[self.client_index].buffer = \
            self.neighbor_hat_params[self.client_index].buffer.to(flatten_params.buffer.device)
        self.neighbor_hat_params["memory"].buffer = \
            self.neighbor_hat_params["memory"].buffer.to(flatten_params.buffer.device)
        # self.neighbor_hat_params["receive_cache"].buffer = \
        #     self.neighbor_hat_params["receive_cache"].buffer.to(flatten_params.buffer.device)

        self.shapes = params_shapes


import json

import pygame
import socket
import os

from client.main_menu import MainMenu
from common.socketwrapper import SocketWrapper
from client.game_screen import GameScreen
from common import preferences

class Client:

    running = False
    socket = None
    alt_down = False

    def __init__(self, dimensions):
        pygame.init()
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        if preferences.preferences['fullscreen']:
            self.fullscreen = True
            self.display = pygame.display.set_mode(dimensions, pygame.FULLSCREEN)
        else:
            self.fullscreen = False
            self.display = pygame.display.set_mode(dimensions)
        pygame.display.set_caption('Snakes')
        self.dimensions = dimensions

        self.clock = pygame.time.Clock()
        self.screen = MainMenu(dimensions, self)

    def toggle_fullscreen(self):
        self.fullscreen = not self.fullscreen
        if self.fullscreen:
            self.display = pygame.display.set_mode(preferences.preferences['resolution'], pygame.FULLSCREEN)
        else:
            self.display = pygame.display.set_mode(preferences.preferences['resolution'])

    def start(self):
        self.running = True
        self.run()

    def start_game(self, single_player):
        if not single_player:
            self.connect((preferences.preferences['server'], preferences.preferences['port']))

        self.screen = GameScreen(self.dimensions, self.socket)

    def connect(self, address):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect(address)
        self.socket = SocketWrapper(sock)
        self.socket.start_listening()
        self.socket.send(json.dumps({'type': 'change_username', 'payload': preferences.preferences['username']}))

    def stop(self):
        self.running = False
        if self.socket:
            self.socket.stop_listening()
        pygame.quit()

    def render(self):
        self.screen.render()
        self.display.blit(self.screen, (0, 0))
        pygame.display.flip()

    def update(self, events):
        self.screen.update(events)

    def run(self):

        while self.running:
            self.clock.tick(30)

            events = pygame.event.get()

            self.update(events)

            for event in events:
                if event.type == pygame.QUIT:
                    self.stop()
                    return
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LALT or event.key == pygame.K_RALT:
                        self.alt_down = True
                    elif self.alt_down and event.key == pygame.K_F4:
                        self.stop()
                        return
                    elif self.alt_down and event.key == pygame.K_RETURN:
                        self.toggle_fullscreen()
                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_LALT or event.key == pygame.K_RALT:
                        self.alt_down = False

            self.render()


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# random_info.py

desc = """This project uses AIKIF to handle a random series of data collection
tasks to solve an everyday problem.

1. Request for solution
Someome has a request to solve an issue
- document details

2. Identify Problem
- map the reqest to a series of information that needs collecting

3. Find Tools to solve the problem
- work out what is needed for a solution

4. Run the tools to find possible solutions
- run the tools and keep all results

5. Test results and pick most likely solution
- for all the test results, find the most appropraite matching result

"""

import os
import sys

proj_fldr = os.getcwd()
src_fldr = os.path.join(proj_fldr, '..','..', 'aikif')
sys.path.append(src_fldr)

import project as prj

import transpose

from dataTools import cls_datatable as dt

def main():

    # define the project
    prj_random = prj.Project(name='Random Information Request', desc=desc, fldr=proj_fldr)

    # add sources of data
    prj_random.add_source('Root Ontology', os.path.abspath(os.path.join(src_fldr, 'data','ref', 'ontology.yaml')))
    #prj_random.add_source('Toolboxes', os.path.abspath(os.path.join(src_fldr, 'data','ref', 'toolbox.csv')))

    # parse the request for possible toolboxes to use based on local ontology
    keywords = []
    for s in prj_random.data_sources:
        with open(s[1], 'r') as f:
            for line in f:
                print(s[1], ' = ' , line)
                for word in line.split(' '):
                    keywords.append(word.strip('\n').strip(' '))

    # a. split request into words
    # b. lookup local ontology of words to concepts
    # c. lookup toolboxes that match the concepts
    print(list(set(keywords)))
    # test the matching toolboxes on the source data
    # a. run the test on each toolboxes
    # b. compare test results and attempt to rank results

    all_projects = prj.Projects()
    all_projects.add_ontology('researcher')
    all_projects.add_project(prj_random)

    print(prj_random)

if __name__ == '__main__':
    main()


import sys, itertools, re, functools, operator

with open('input.txt') as f:
    lines = f.readlines()  # read complete file, create list of lines with CRs

ints = []
for line in lines:
    line = str.rstrip(line, '\n')
    if len(line) == 0: continue
    ints.append(int(line))

w = 50
for p in range(w, len(ints)):
    i = ints[p]
    combis = itertools.combinations(ints[p - w:p], 2)
    if not functools.reduce((lambda a, b: a or b), (a + b == i for (a, b) in combis)):
        print("error:", i)
        break

# 258585477

2020/09/Teil 1 - V02 - iterate over positions - max functional.py


import urllib.request as urllib2
from pyspark.sql.window import Window
from pyspark.sql.functions import when, col, rank, lag, lead, row_number, dense_rank, percent_rank, ntile, cume_dist, \
    first, last, regexp_extract, regexp_replace, explode, explode_outer, posexplode, posexplode_outer, flatten
from pyspark.sql.session import SparkSession
from pyspark.sql.types import DoubleType, StructType, StructField, StringType, TimestampType, IntegerType
from pyspark.sql.functions import broadcast

# Create Spark Session
spark = SparkSession.builder.appName("Flights_SparkSql").master("local[*]").getOrCreate()

# Create Sample Dataframe
empDF = spark.createDataFrame([
    (7369, "SMITH", "CLERK", 7902, "17-Dec-80", 800, 20, 10),
    (7499, "ALLEN", "SALESMAN", 7698, "20-Feb-81", 1600, 300, 30),
    (7521, "WARD", "SALESMAN", 7698, "22-Feb-81", 1250, 500, 30),
    (7566, "JONES", "MANAGER", 7839, "2-Apr-81", 2975, 0, 20),
    (7654, "MARTIN", "SALESMAN", 7698, "28-Sep-81", 1250, 1400, 30),
    (7698, "BLAKE", "MANAGER", 7839, "1-May-81", 2850, 0, 30),
    (7782, "CLARK", "MANAGER", 7839, "9-Jun-81", 2450, 0, 10),
    (7788, "SCOTT", "ANALYST", 7566, "19-Apr-87", 3000, 0, 20),
    (7839, "KING", "PRESIDENT", 0, "17-Nov-81", 5000, 0, 10),
    (7844, "TURNER", "SALESMAN", 7698, "8-Sep-81", 1500, 0, 30),
    (7844, "DIWAKAR", "SALESMAN", 7698, "9-Sep-81", 1000, 0, 30),
    (7876, "ADAMS", "CLERK", 7788, "23-May-87", 1100, 0, 20)
]).toDF("empno", "ename", "job", "mgr", "hiredate", "sal", "comm", "deptno")

# partitionWindow = Window.partitionBy(col("deptno")).orderBy(col("sal").desc())
dfs = empDF.where("mgr in (7698, 7788)")
dfs.show(50)

arrayArrayData = [
    ("James", [["Java", "Scala", "C++"], ["Spark", "Java"]]),
    ("Michael", [["Spark", "Java", "C++"], ["Spark", "Java"]]),
    ("Robert", [["CSharp", "VB"], ["Spark", "Python"]])
]

df = spark.createDataFrame(data=arrayArrayData, schema=['name', 'subjects'])
df.printSchema()
df.show(truncate=False)
df.select(df.name, explode(df.subjects).alias("Exploded_ListSubject")).show(truncate=False)
df.select(df.name, flatten(df.subjects).alias("Flatten_Subjects")).show()

arrayData = [
    ('James', ['Java', 'Scala'], {'hair': 'black', 'eye': 'brown'}),
    ('Michael', ['Spark', 'Java', None], {'hair': 'brown', 'eye': None}),
    ('Robert', ['CSharp', ''], {'hair': 'red', 'eye': ''}),
    ('Washington', None, None),
    ('Jefferson', ['1', '2'], {})]

df = spark.createDataFrame(data=arrayData, schema=['name', 'knownLanguages', 'properties'])
df.printSchema()
df.show()

df2 = df.select(df.name, explode(df.knownLanguages).alias("knownLanguages"))
df2.printSchema()
df2.show()

df3 = df.select(df.name, explode(df.properties))
df3.printSchema()
df3.show()

""" with list """
df.select(df.name, explode_outer(df.knownLanguages)).show()
""" with dict """
df.select(df.name, explode_outer(df.properties)).show()

""" with list """
df.select(df.name, posexplode(df.knownLanguages)).show()
""" with dict """
df.select(df.name, posexplode(df.properties)).show()

""" with list """
df.select(col("name"), posexplode_outer(col("knownLanguages"))).show()

""" with dict """
df.select(df.name, posexplode_outer(df.properties)).show()


# 딕셔너리 이용하여 학번, 이름 출력
myName_dic = { 20194146: "이승진" }
for myID in myName_dic.keys() :
    print(myID, myName_dic[myID], "\n")

# 2차원 튜플 초기화(학점 포)
student_tup = (('211101', '최성훈', '010-1234-4500', '4.3'),
               ('211102', '김은지', '010-2230-6540', '3.9'),
               ('211103', '이세은', '010-3232-7788', '4.25') )

# 빈 딕셔너리 초기화
student_dic = {}

# 튜플의 요소를 딕셔너리에 추가
for student in student_tup :
    number, name, phone, grade = student
    student_dic[number] = [name, phone, grade]  # key는 학번, value는 [이름, 연락처, 학점]

# 딕셔너리의 (key, value) 쌍을 순서대로 출력
print("학생의 정보 목록")
for key, value in student_dic.items() :
    print("{'" + key + "' : ", value, "}")

# 학점 평균 구하여 출력
avg = 0
for key_id in student_dic.keys() :
    avg += float(student_dic[key_id][2])	# 각 리스트(value)의 2번째 요소
avg /= 3
print("전체 학생의 학점 평균 : %.2f" % avg)

# key(입력한 학번)에 해당하는 value(이름, 연락처) 출력
key_id = input("\n학번을 입력하시오 : ")
print("이름 : ", student_dic[key_id][0])
print("연락처 : ", student_dic[key_id][1])