from collections import namedtuple, Counter
import warnings
from math import sqrt

import numpy as np
from scipy.stats import special_ortho_group
import pytest

import kwant
from ... import lattice
from ...builder import HoppingKind, Builder, Site
from ...system import NoSymmetry
from .. import gauge

## Utilities

square_lattice = lattice.square(norbs=1, name='square')
honeycomb_lattice = lattice.honeycomb(norbs=1, name='honeycomb')
cubic_lattice = lattice.cubic(norbs=1, name='cubic')

def rectangle(W, L):
    return (
        lambda s: 0 <= s.pos[0] < L and 0 <= s.pos[1] < W,
        (L/2, W/2)
    )

def ring(r_inner, r_outer):
    return (
        lambda s: r_inner <= np.linalg.norm(s.pos) <= r_outer,
        ((r_inner + r_outer) / 2, 0)
    )

def wedge(W):
    return (
        lambda s: (0 <= s.pos[0] < W) and (0 <= s.pos[1] <= s.pos[0]),
        (0, 0)
    )

def half_ring(r_inner, r_outer):
    in_ring, _ = ring(r_inner, r_outer)
    return (
        lambda s: s.pos[0] <= 0 and in_ring(s),
        (-(r_inner + r_outer) / 2, 0)
    )

def cuboid(a, b, c):
    return (
        lambda s: 0 <= s.pos[0] < a and 0 <= s.pos[1] < b and 0 <= s.pos[2] < c,
        (a/2, b/2, c/2)
    )

def hypercube(dim, W):
    return (
        lambda s: all(0 <= x < W for x in s.pos),
        (W / 2,) * dim
    )

def circle(r):
    return (
        lambda s: np.linalg.norm(s.pos) < r,
        (0, 0)
    )

def ball(dim, r):
    return (
        lambda s: np.linalg.norm(s.pos) < r,
        (0,) * dim
    )

def model(lat, neighbors):
    syst = Builder(lattice.TranslationalSymmetry(*lat.prim_vecs))
    if hasattr(lat, 'sublattices'):
        for l in lat.sublattices:
            zv = (0,) * len(l.prim_vecs)
            syst[l(*zv)] = None
    else:
        zv = (0,) * len(l.prim_vecs)
        syst[lat(*zv)] = None
    for r in range(neighbors):
        syst[lat.neighbors(r + 1)] = None
    return syst

def check_loop_kind(loop_kind):
    (_, first_fam_a, prev_fam_b), *rest = loop_kind
    for (_, fam_a, fam_b) in rest:
        if prev_fam_b != fam_a:
            raise ValueError('Invalid loop kind: does not close')
        prev_fam_b = fam_b
    # loop closes
    net_delta = np.sum([hk.delta for hk in loop_kind])
    if first_fam_a != fam_b or np.any(net_delta != 0):
        raise ValueError('Invalid loop kind: does not close')

def available_loops(syst, loop_kind):

    def maybe_loop(site):
        loop = [site]
        a = site
        for delta, family_a, family_b in loop_kind:
            b = Site(family_b, a.tag + delta, True)
            if family_a != a.family or (a, b) not in syst:
                return None
            loop.append(b)
            a = b
        return loop

    check_loop_kind(loop_kind)

    return list(filter(None, map(maybe_loop, syst.sites())))

def loop_to_links(loop):
    return list(zip(loop, loop[1:]))

def no_symmetry(lat, neighbors):
    return NoSymmetry()

def translational_symmetry(lat, neighbors):
    return lattice.TranslationalSymmetry(int((neighbors + 1)/2) * lat.prim_vecs[0])

## Tests

# Tests that phase around a loop is equal to the flux through the loop.
# First we define the loops that we want to test, for various lattices.
# If a system does not support a particular kind of loop, they will simply
# not be generated.

Loop = namedtuple('Loop', ('path', 'flux'))

square_loops = [([HoppingKind(d, square_lattice) for d in l.path], l.flux)
        for l in [
    # 1st nearest neighbors
    Loop(path=[(1, 0), (0, 1), (-1, 0), (0, -1)], flux=1),
    # 2nd nearest neighbors
    Loop(path=[(1, 0), (0, 1), (-1, -1)], flux=0.5),
    Loop(path=[(1, 0), (-1, 1), (0, -1)], flux=0.5),
    # 3rd nearest neighbors
    Loop(path=[(2, 0), (0, 1), (-2, 0), (0, -1)], flux=2),
    Loop(path=[(2, 0), (-1, 1), (-1, 0), (0, -1)], flux=1.5),
]]

a, b = honeycomb_lattice.sublattices
honeycomb_loops = [([HoppingKind(d, a, b) for *d, a, b in l.path], l.flux)
        for l in [
    # 1st nearest neighbors
    Loop(path=[(0, 0, a, b), (-1, 1, b, a), (0, -1, a, b), (0, 0, b, a),
               (1, -1, a, b), (0, 1, b, a)],
         flux=sqrt(3)/2),
    # 2nd nearest neighbors
    Loop(path=[(-1, 1, a, a), (0, -1, a, a), (1, 0, a, a)],
         flux=sqrt(3)/4),
    Loop(path=[(-1, 0, b, b), (1, -1, b, b), (0, 1, b, b)],
         flux=sqrt(3)/4),
]]

cubic_loops = [([HoppingKind(d, cubic_lattice) for d in l.path], l.flux)
        for l in [
    # 1st nearest neighbors
    Loop(path=[(1, 0, 0), (0, 1, 0), (-1, 0, 0), (0, -1, 0)], flux=1),
    Loop(path=[(0, 1, 0), (0, 0, 1), (0, -1, 0), (0, 0, -1)], flux=0),
    Loop(path=[(1, 0, 0), (0, 0, 1), (-1, 0, 0), (0, 0, -1)], flux=0),
    # 2nd nearest neighbors
    Loop(path=[(1, 0, 0), (-1, 1, 0), (0, -1, 0)], flux=0.5),
    Loop(path=[(1, 0, 0), (0, 1, 0), (-1, -1, 0)], flux=0.5),
    Loop(path=[(1, 0, 0), (-1, 0, 1), (0, 0, -1)], flux=0),
    Loop(path=[(1, 0, 0), (0, 0, 1), (-1, 0, -1)], flux=0),
    Loop(path=[(0, 1, 0), (0, -1, 1), (0, 0, -1)], flux=0),
    Loop(path=[(0, 1, 0), (0, 0, 1), (0, -1, -1)], flux=0),
    # 3rd nearest neighbors
    Loop(path=[(1, 1, 1), (0, 0, -1), (-1, -1, 0)], flux=0),
    Loop(path=[(1, 1, 1), (-1, 0, -1), (0, -1, 0)], flux=0.5),
]]

square = (square_lattice, square_loops)
honeycomb = (honeycomb_lattice, honeycomb_loops)
cubic = (cubic_lattice, cubic_loops)

def _test_phase_loops(syst, phases, loops):
    for loop_kind, loop_flux in loops:
        for loop in available_loops(syst, loop_kind):
            loop_phase = np.prod([phases(a, b) for a, b in loop_to_links(loop)])
            expected_loop_phase = np.exp(1j * np.pi * loop_flux)
            assert np.isclose(loop_phase, expected_loop_phase)

@pytest.mark.parametrize("neighbors", [1, 2, 3])
@pytest.mark.parametrize("symmetry", [no_symmetry, translational_symmetry],
                         ids=['finite', 'infinite'])
@pytest.mark.parametrize("lattice, loops", [square, honeycomb, cubic],
                         ids=['square', 'honeycomb', 'cubic'])
def test_phases(lattice, neighbors, symmetry, loops):
    """Check that the phases around common loops are equal to the flux, for
    finite and infinite systems with uniform magnetic field.
    """
    W = 4
    dim = len(lattice.prim_vecs)
    field = np.array([0, 0, 1]) if dim == 3 else 1

    syst = Builder(symmetry(lattice, neighbors))
    syst.fill(model(lattice, neighbors), *hypercube(dim, W))

    this_gauge = gauge.magnetic_gauge(syst.finalized())
    phases = this_gauge(field)

    _test_phase_loops(syst, phases, loops)

@pytest.mark.parametrize("neighbors", [1, 2, 3])
@pytest.mark.parametrize("lat, loops", [square, honeycomb],
                         ids=['square', 'honeycomb'])
def test_phases_composite(neighbors, lat, loops):
    """Check that the phases around common loops are equal to the flux, for
    composite systems with uniform magnetic field.
    """
    W = 4
    dim = len(lat.prim_vecs)
    field = np.array([0, 0, 1]) if dim == 3 else 1

    lead = Builder(lattice.TranslationalSymmetry(-lat.prim_vecs[0]))
    lead.fill(model(lat, neighbors), *hypercube(dim, W))

    # Case where extra sites are added and fields are same in
    # scattering region and lead.
    syst = Builder()
    syst.fill(model(lat, neighbors), *ball(dim, W + 1))
    extra_sites = syst.attach_lead(lead)
    assert extra_sites  # make sure we're testing the edge case with added sites

    this_gauge = gauge.magnetic_gauge(syst.finalized())
    # same field in scattering region and lead
    phases, lead_phases = this_gauge(field, field)

    # When extra sites are added to the central region we need to select
    # the correct phase function.
    def combined_phases(a, b):
        if a in extra_sites or b in extra_sites:
            return lead_phases(a, b)
        else:
            return phases(a, b)

    _test_phase_loops(syst, combined_phases, loops)
    _test_phase_loops(lead, lead_phases, loops)

@pytest.mark.parametrize("neighbors", [1, 2])
def test_overlapping_interfaces(neighbors):
    """Test composite systems with overlapping lead interfaces."""

    lat = square_lattice

    def _make_syst(edge, W=5):

        syst = Builder()
        syst.fill(model(lat, neighbors), *rectangle(W, W))

        leadx = Builder(lattice.TranslationalSymmetry((-1, 0)))
        leadx[(lat(0, j) for j in range(edge, W - edge))] = None
        for n in range(1, neighbors + 1):
            leadx[lat.neighbors(n)] = None

        leady = Builder(lattice.TranslationalSymmetry((0, -1)))
        leady[(lat(i, 0) for i in range(edge, W - edge))] = None
        for n in range(1, neighbors + 1):
            leady[lat.neighbors(n)] = None

        assert not syst.attach_lead(leadx)  # sanity check; no sites added
        assert not syst.attach_lead(leady)  # sanity check; no sites added

        return syst, leadx, leady

    # edge == 0: lead interfaces overlap
    # edge == 1: lead interfaces partition scattering region
    #            into 2 disconnected components
    for edge in (0, 1):
        syst, leadx, leady = _make_syst(edge)
        this_gauge = gauge.magnetic_gauge(syst.finalized())
        phases, leadx_phases, leady_phases = this_gauge(1, 1, 1)
        _test_phase_loops(syst, phases, square_loops)
        _test_phase_loops(leadx, leadx_phases, square_loops)
        _test_phase_loops(leady, leady_phases, square_loops)

def _make_square_syst(sym, neighbors=1):
    lat = square_lattice
    syst = Builder(sym)
    syst[(lat(i, j) for i in (0, 1) for j in (0, 1))] = None
    for n in range(1, neighbors + 1):
        syst[lat.neighbors(n)] = None
    return syst

def test_unfixable_gauge():
    """Check error is raised when we cannot fix the gauge."""

    leadx = _make_square_syst(lattice.TranslationalSymmetry((-1, 0)))
    leady = _make_square_syst(lattice.TranslationalSymmetry((0, -1)))

    # 1x2 line with 2 leads
    syst = _make_square_syst(NoSymmetry())
    del syst[[square_lattice(1, 0), square_lattice(1, 1)]]
    syst.attach_lead(leadx)
    syst.attach_lead(leadx.reversed())
    with pytest.raises(ValueError):
        gauge.magnetic_gauge(syst.finalized())

    # 2x2 square with leads attached from all 4 sides,
    # and nearest neighbor hoppings
    syst = _make_square_syst(NoSymmetry())
    # Until we add the last lead we have enough gauge freedom
    # to specify independent fields in the scattering region
    # and each of the leads. We check that no extra sites are
    # added as a sanity check.
    assert not syst.attach_lead(leadx)
    gauge.magnetic_gauge(syst.finalized())
    assert not syst.attach_lead(leady)
    gauge.magnetic_gauge(syst.finalized())
    assert not syst.attach_lead(leadx.reversed())
    gauge.magnetic_gauge(syst.finalized())
    # Adding the last lead removes our gauge freedom.
    assert not syst.attach_lead(leady.reversed())
    with pytest.raises(ValueError):
        gauge.magnetic_gauge(syst.finalized())

    # 2x2 square with 2 leads, but 4rd nearest neighbor hoppings
    syst = _make_square_syst(NoSymmetry())
    del syst[(square_lattice(1, 0), square_lattice(1, 1))]
    leadx = _make_square_syst(lattice.TranslationalSymmetry((-1, 0)))
    leadx[square_lattice.neighbors(4)] = None
    for lead in (leadx, leadx.reversed()):
        syst.attach_lead(lead)

    with pytest.raises(ValueError):
        gauge.magnetic_gauge(syst.finalized())

def _test_disconnected(syst):
    with pytest.raises(ValueError) as excinfo:
        gauge.magnetic_gauge(syst.finalized())
        assert 'unit cell not connected' in str(excinfo.value)

def test_invalid_lead():
    """Check error is raised when a lead unit cell is not connected
       within the unit cell itself.

       In order for the algorithm to work we need to be able to close
       loops within the lead. However we only add a single lead unit
       cell, so not all paths can be closed, even if the lead is
       connected.
    """
    lat = square_lattice

    lead = _make_square_syst(lattice.TranslationalSymmetry((-1, 0)),
                             neighbors=0)
    # Truly disconnected system
    # Ignore warnings to suppress Kwant's complaint about disconnected lead
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        _test_disconnected(lead)

    # 2 disconnected chains (diagonal)
    lead[(lat(0, 0), lat(1, 1))] = None
    lead[(lat(0, 1), lat(1, 0))] = None
    _test_disconnected(lead)

    lead = _make_square_syst(lattice.TranslationalSymmetry((-1, 0)),
                             neighbors=0)
    # 2 disconnected chains (horizontal)
    lead[(lat(0, 0), lat(1, 0))] = None
    lead[(lat(0, 1), lat(1, 1))] = None
    _test_disconnected(lead)

    # System has loops, but need 3 unit cells
    # to express them.
    lead[(lat(0, 0), lat(1, 1))] = None
    lead[(lat(0, 1), lat(1, 0))] = None
    _test_disconnected(lead)

# Test internal parts of magnetic_gauge

@pytest.mark.parametrize("shape",
                         [rectangle(5, 5), circle(4),
                          half_ring(5, 10)],
                         ids=['rectangle', 'circle', 'half-ring']
    )
@pytest.mark.parametrize("lattice", [square_lattice, honeycomb_lattice],
                         ids=['square', 'honeycomb'])
@pytest.mark.parametrize("neighbors", [1, 2, 3])
def test_minimal_cycle_basis(lattice, neighbors, shape):
    """Check that for lattice models on genus 0 shapes, nearly
       all loops have the same (minimal) length. This is not an
       equality, as there may be weird loops on the edges.
    """
    syst = Builder()
    syst.fill(model(lattice, neighbors), *shape)
    syst = syst.finalized()

    loops = gauge._loops_in_finite(syst)
    loop_counts = Counter(map(len, loops))
    min_loop = min(loop_counts)
    # arbitrarily allow 1% of slightly longer loops;
    # we don't make stronger guarantees about the quality
    # of our loop basis
    assert loop_counts[min_loop] / len(loops) > 0.99, loop_counts

def random_loop(n, max_radius=10, planar=False):
    """Return a loop of 'n' points.

    The loop is in the x-y plane if 'planar is False', otherwise
    each point is given a random perturbation in the z direction
    """
    theta = np.sort(2 * np.pi * np.random.rand(n))
    r = max_radius * np.random.rand(n)
    if planar:
        z = np.zeros((n,))
    else:
        z = 2 * (max_radius / 5) * (np.random.rand(n) - 1)
    return np.array([r * np.cos(theta), r * np.sin(theta), z]).transpose()

def test_constant_surface_integral():
    field_direction = np.random.rand(3)
    field_direction /= np.linalg.norm(field_direction)
    loop = random_loop(7)

    integral = gauge._surface_integral

    I = integral(lambda r: field_direction, loop)
    assert np.isclose(I, integral(field_direction, loop))
    assert np.isclose(I, integral(lambda r: field_direction, loop, average=True))

def circular_field(r_vec):
    return np.array([r_vec[1], -r_vec[0], 0])

def test_invariant_surface_integral():
    """Surface integral should be identical if we apply a random
       rotation to loop and vector field.
    """
    integral = gauge._surface_integral
    # loop with random orientation
    orig_loop = loop = random_loop(7)
    I = integral(circular_field, loop)
    for _ in range(4):
        rot = special_ortho_group.rvs(3)
        loop = orig_loop @ rot.transpose()
        assert np.isclose(I, integral(lambda r: rot @ circular_field(rot.transpose() @ r), loop))

@pytest.fixture
def system_and_gauge():
    def hopping(a, b, peierls):
        return -1 * peierls(a, b)

    syst = Builder()
    syst[(square_lattice(i, j) for i in range(3) for j in range(10))] = 4
    syst[square_lattice.neighbors()] = hopping

    lead = Builder(lattice.TranslationalSymmetry((-1, 0)))
    lead[(square_lattice(0, j) for j in range(10))] = 4
    lead[square_lattice.neighbors()] = hopping

    syst.attach_lead(lead.substituted(peierls='peierls_left'))
    syst.attach_lead(lead.reversed().substituted(peierls='peierls_right'))

    syst = syst.finalized()

    magnetic_gauge = gauge.magnetic_gauge(syst)

    return syst, magnetic_gauge

@pytest.mark.parametrize('B',[0, 0.1, lambda r: 0.1 * np.exp(-r[1]**2)])
def test_uniform_magnetic_field(system_and_gauge, B):
    syst, gauge = system_and_gauge

    peierls, peierls_left, peierls_right = gauge(B, B, B)

    params = dict(peierls=peierls, peierls_left=peierls_left,
                  peierls_right=peierls_right)

    s = kwant.smatrix(syst, energy=0.6, params=params)
    t = s.submatrix(1, 0)

    assert t.shape > (0, 0)  # sanity check
    assert np.allclose(np.abs(t)**2, np.eye(*t.shape))

def test_phase_sign(system_and_gauge):
    syst, gauge = system_and_gauge

    peierls, peierls_left, peierls_right = gauge(0.1, 0.1, 0.1)

    params = dict(peierls=peierls, peierls_left=peierls_left,
                  peierls_right=peierls_right)

    cut = [(square_lattice(1, j), square_lattice(0, j))
            for j in range(10)]
    J = kwant.operator.Current(syst, where=cut)
    J = J.bind(params=params)

    psi = kwant.wave_function(syst, energy=0.6, params=params)(0)[0]

    # Electrons incident from the left travel along the *top*
    # edge of the Hall bar in the presence of a magnetic field
    # out of the plane
    j = J(psi)
    j_bottom = sum(j[0:5])
    j_top = sum(j[5:10])

    assert np.isclose(j_top + j_bottom, 1)  # sanity check
    assert j_top > 0.9


from django.contrib.auth import get_user_model
from django.utils import timezone
from django.core.mail import send_mail

User = get_user_model()

def wish_birthday():
    today = timezone.now().date()
    user_list = User.objects.filter(birthday__day=today.day, birthday__month=today.month)

    for item in user_list:
        subject = 'Birthday Wish!'
        body = 'Hi {},\n Happy Birthday!!!'.format(item.username)
        send_mail(subject, body, 'contact@yourdomain.com', [item.email])


with open("26data/26-J1.txt", "r") as f:
    data = list(map(int, f.readlines()))[1:]

res = 0
for n in range(len(data)):
    for k in range(n + 1, len(data)):
        if data[n] + data[k] == 100:
            res += 1
            del data[k]
            break

print(res)

# 3845 - CORRECT


# just a seperate file for handling the logging
# of sanic to use with logging
from sanic.log import DefaultFilter
import sys

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
    'accessFilter': {
        '()': DefaultFilter,
        'param': [0, 10, 20]
    },
    'errorFilter': {
        '()': DefaultFilter,
        'param': [30, 40, 50]
    }
},
'formatters': {
    'simple': {
        'format': '%(asctime)s - (%(name)s)[%(levelname)s]: %(message)s',
        'datefmt': '%Y-%m-%d %H:%M:%S'
    },
    'access': {
        'format': '%(asctime)s - (%(name)s)[%(levelname)s][%(host)s]: ' +
                  '%(request)s %(message)s %(status)d %(byte)d',
        'datefmt': '%Y-%m-%d %H:%M:%S'
    }
},
'handlers': {
    'internalFile': {
        'class': 'logging.FileHandler',
        'filters': ['accessFilter'],
        'formatter': 'simple',
        'filename': "temp/clickinternal.log"
    },
    'accessFile': {
        'class': 'logging.FileHandler',
        'filters': ['accessFilter'],
        'formatter': 'access',
        'filename': "temp/clickaccess.log"
    },
    'errorFile': {
        'class': 'logging.FileHandler',
        'filters': ['errorFilter'],
        'formatter': 'simple',
        'filename': "temp/clickerr.log"
    },
    'internal': {
        'class': 'logging.StreamHandler',
        'filters': ['accessFilter'],
        'formatter': 'simple',
        'stream': sys.stderr
    },
    'accessStream': {
        'class': 'logging.StreamHandler',
        'filters': ['accessFilter'],
        'formatter': 'access',
        'stream': sys.stderr
    },
    'errorStream': {
        'class': 'logging.StreamHandler',
        'filters': ['errorFilter'],
        'formatter': 'simple',
        'stream': sys.stderr
    }
},
'loggers': {
    'sanic': {
        'level': 'DEBUG',
        'handlers': ['internal','errorStream','internalFile', 'errorFile']
    },
    'network': {
        'level': 'DEBUG',
        'handlers': ['accessStream','errorStream','accessFile', 'errorFile']
    }
}
}


def inputWitdhlong( ) :
    wi = float( input('กว้าง : ') )
    lo = float( input('ยาว : ') )
    return wi, lo

def inputBaseHigh( ) :
    ba = float( input('ฐาน : ') )
    hi = float( input('สูง : ') )
    return ba, hi

def calAndShowAreaSquare( ba, hi ) :
    area = ba * hi / 2
    print(f'สามเหลี่ยมฐาน {ba} สูง {hi} มีพื้นที่ {area}')

wi, lo = inputWitdhlong( )
calAndShowAreaSquare(wi, lo)
print('--------------------------')
ba, hi = inputBaseHigh( )
calAndShowAreaSquare(ba, hi)


# Create your views here.
id = int()
iditemcourant = int()
#-*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render , redirect
from utilisateur.forms import *
from utilisateur.models import *
#import time
from django.core.urlresolvers import reverse
def utilisateur(request):
	if request.method == 'POST':
		form = formuser(request.POST)
		if form.is_valid():

			global id
			id = int(form.cleaned_data['idUtilisateur'])
			listeid = list()
			for i in utilisateurtable.objects.all():
				listeid.append(i.id)
			if id in listeid:
				return redirect("index")#ici lien vers acceuil du site
			else:
				return redirect("authentification")#ici lien vers acceuil du site

	else:
		form = formuser()
	#return render(request, 'index.html', locals())
	return render(request, 'index2.html', locals())

def index(request):
	return render(request, 'index.html', {})

def genereid(request):
	#iduser = str(time.time())
	#list = iduser.split('.')
	#iduser = "".join(list)
	#iduser = 'votre nouveau id est :' + iduser
	connecte = utilisateurtable.objects.create()
	connecte.id = str(connecte.id)

	return HttpResponse(connecte.id)

def listitemmath(request):
	return render(request, 'listitemmath.html', locals())

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

def equation_du_premier_degre(request):
	a = pedagogic_item.objects.get(id = iditemcourant)
	exo = reverse(a.link_to_exo)
	return render(request, 'eq1.html', locals())

def equation_du_second(request):
	a = pedagogic_item.objects.get(id = iditemcourant)
	exo = reverse(a.link_to_exo)
	return render(request, 'eq2.html', locals())

def derivee(request):
	a = pedagogic_item.objects.get(id = iditemcourant)
	exo = reverse(a.link_to_exo)

	return render(request, 'derivee.html', locals())

def primitive(request):
	a = pedagogic_item.objects.get(id = iditemcourant)
	exo = reverse(a.link_to_exo)

	return render(request, 'primitive.html', locals())

def equation_differentiel(request):
	a = pedagogic_item.objects.get(id = iditemcourant)
	exo = reverse(a.link_to_exo)

	return render(request, 'eqdiff.html', locals())

def equation_du_premier_degreexo(request  ):
	if request.method == 'POST':
		form = formexo(request.POST)
		if form.is_valid():
			oui = form.cleaned_data['oui']
			non = form.cleaned_data['non']
			reussite = bool()
			if oui is True and non is False:
				reussite = True
			else:
				reussite = False
			if reussite:#il a reussi lexercice ce qui veut dire deja qu'il a fini un item
				#chargeons les informations de la base utilisateur
				utilisateur = utilisateurtable.objects.get(id = id)
				#decalage   on a 4 items car 4 neuds constituent un chemin de 3arretes a retribuer
				utilisateur.id_ante_ante_penultimate_item = utilisateur.id_ante_penultimate_item
				utilisateur.id_ante_penultimate_item = utilisateur.id_penultimate_item
				utilisateur.id_penultimate_item	= utilisateur.id_last_item
				utilisateur.id_last_item = iditemcourant
				utilisateur.save()

				#verifions que utilisateur.id_penultimate_item n'est pas nul
				if utilisateur.id_penultimate_item != None :
					last_link = link_to_next_possible_pi.objects.get(iditemfk=utilisateur.id_penultimate_item, iditemnextfk=utilisateur.id_last_item)
					if last_link.d_a_pos_ph != None:
						var = float(last_link.d_a_pos_ph)
						var += 3
						last_link.d_a_pos_ph = str(var)
						last_link.save()

					else:
						var = 3.0
						last_link.d_a_pos_ph = str(var)
						last_link.save()

				if utilisateur.id_ante_penultimate_item != None :
					penultimate_link = link_to_next_possible_pi.objects.get(iditemfk=utilisateur.id_ante_penultimate_item, iditemnextfk=utilisateur.id_penultimate_item)

					if penultimate_link.d_a_pos_ph != None:
						var = float(penultimate_link.d_a_pos_ph)
						var += 2
						penultimate_link.d_a_pos_ph = str(var)
						penultimate_link.save()

					else:
						var = 2.0
						penultimate_link.d_a_pos_ph = str(var)
						penultimate_link.save()

				if utilisateur.id_ante_ante_penultimate_item != None and utilisateur.id_penultimate_item != None :
					ante_penultimate_link = link_to_next_possible_pi.objects.get(iditemfk=utilisateur.id_ante_ante_penultimate_item, iditemnextfk=utilisateur.id_ante_penultimate_item)

					if ante_penultimate_link.d_a_pos_ph != None:
						var = float(ante_penultimate_link.d_a_pos_ph)
						var += 1
						ante_penultimate_link.d_a_pos_ph = str(var)
						ante_penultimate_link.save()

					else:
						var = 1.0
						ante_penultimate_link.d_a_pos_ph = str(var)
						ante_penultimate_link.save()
				return redirect("proposelien")

			else: #c'est a dire il na valider le test
	#chargeons les informations de la base utilisateur
				utilisateur = utilisateurtable.objects.get(id = id)
				#decalage   on a 4 items car 4 neuds constituent un chemin de 3arretes a retribuer
				utilisateur.id_ante_ante_penultimate_item = utilisateur.id_ante_penultimate_item
				utilisateur.id_ante_penultimate_item = utilisateur.id_penultimate_item
				utilisateur.id_penultimate_item	= utilisateur.id_last_item
				utilisateur.id_last_item = iditemcourant
				utilisateur.save()

				#verifions que utilisateur.id_penultimate_item n'est pas nul
				if utilisateur.id_penultimate_item != None :
					last_link = link_to_next_possible_pi.objects.get(iditemfk=utilisateur.id_penultimate_item, iditemnextfk=utilisateur.id_last_item)
					if last_link.d_a_neg_ph != None:
						var = float(last_link.d_a_neg_ph)
						var -= 3
						last_link.d_a_neg_ph = str(var)
						last_link.save()

					else:
						var = -3.0
						last_link.d_a_neg_ph = str(var)
						last_link.save()

				if utilisateur.id_ante_penultimate_item != None :
					penultimate_link = link_to_next_possible_pi.objects.get(iditemfk=utilisateur.id_ante_penultimate_item, iditemnextfk=utilisateur.id_penultimate_item)

					if penultimate_link.d_a_neg_ph != None:
						var = float(penultimate_link.d_a_neg_ph)
						var -= 2
						penultimate_link.d_a_neg_ph = str(var)
						penultimate_link.save()

					else:
						var = -2.0
						penultimate_link.d_a_neg_ph = str(var)
						penultimate_link.save()

				if utilisateur.id_ante_ante_penultimate_item != None and utilisateur.id_penultimate_item != None :
					ante_penultimate_link = link_to_next_possible_pi.objects.get(iditemfk=utilisateur.id_ante_ante_penultimate_item, iditemnextfk=utilisateur.id_ante_penultimate_item)

					if ante_penultimate_link.d_a_neg_ph != None:
						var = float(ante_penultimate_link.d_a_neg_ph)
						var -= 1
						ante_penultimate_link.d_a_neg_ph = str(var)
						ante_penultimate_link.save()

					else:
						var = -1.0
						ante_penultimate_link.d_a_neg_ph = str(var)
						ante_penultimate_link.save()
				return redirect("proposelien")

	else:
		form = formexo()

	return render(request, 'exoeq1.html', locals())

def viewitem(request , iditem):
	#il vient de clicquer sur un item independamment ou pas on sait pas mais on va regarder sil existe deja un chemin entre le dernier item parcouru et l'item courant

	#gestion template
	a = pedagogic_item.objects.get(id = iditem)
	lien = reverse(a.link_to_courses)

	global iditemcourant
	iditemcourant = iditem#donc voila le nouveau item

		#verifions si un chemin entre le dernier lien et le nouveau lien
	utilisateur = utilisateurtable.objects.get(id = id)
	#pour pouvoir avoir un chemin il faut qu'il y ait un noeud precedent au moins
	if utilisateur.id_last_item != None :#on est sur notre premier item
		precedent = utilisateur.id_last_item
		suivant = iditemcourant
		#si le chemin n'existe pas elle sera creer
		i , boole = link_to_next_possible_pi.objects.get_or_create(iditemfk=precedent, iditemnextfk= suivant)

		#return HttpResponse(boole)#reussite ,
		listepossiblite = link_to_next_possible_pi.objects.filter(iditemfk = precedent)#si
		for chemin in listepossiblite:

			if chemin.d_a_pos_ph != None:#on ne dimunue pas
				var = float(chemin.d_a_pos_ph)
				var -= 1
				chemin.d_a_pos_ph = str(var)
				chemin.save()

			else:
				chemin.d_a_pos_ph = '-1'
				chemin.save()

	return render(request, 'viewitem.html', locals())

def proposelien(request):
	#algorithme de trie des liens
	utilisateur = utilisateurtable.objects.get(id = id)
	liste = link_to_next_possible_pi.objects.filter(iditemfk = utilisateur.id_last_item)#si
	nombrelien = len(liste)
	if nombrelien == 1:
		lienlist = pedagogic_item.objects.filter(id = liste[0].iditemnextfk)
		nom_cour = lienlist[0].link_to_courses
		lien = reverse(nom_cour)

	return render(request, 'proposelien.html', locals())


import contextlib
import datetime
import unittest

from traits.api import Date, HasTraits, List
from traitsui.api import DateEditor, View, Item
from traitsui.editors.date_editor import CellFormat

from traitsui.tests._tools import (
    BaseTestMixin,
    create_ui,
    requires_toolkit,
    reraise_exceptions,
    ToolkitName,
)

class Foo(HasTraits):

    dates = List(Date)

    single_date = Date()

def single_select_custom_view():
    view = View(
        Item(
            name="single_date",
            style="custom",
            editor=DateEditor(multi_select=False),
        )
    )
    return view

def multi_select_custom_view():
    view = View(
        Item(
            name="dates", style="custom", editor=DateEditor(multi_select=True)
        )
    )
    return view

def multi_select_selected_color_view():
    view = View(
        Item(
            name="dates",
            style="custom",
            editor=DateEditor(
                multi_select=True,
                selected_style=CellFormat(bold=True, bgcolor=(128, 10, 0)),
            ),
        )
    )
    return view

@requires_toolkit([ToolkitName.qt])
class TestDateEditorCustomQt(BaseTestMixin, unittest.TestCase):
    def setUp(self):
        BaseTestMixin.setUp(self)

    def tearDown(self):
        BaseTestMixin.tearDown(self)

    def test_single_select_qt(self):
        with self.launch_editor(single_select_custom_view) as (foo, editor):
            date = datetime.date(2018, 2, 3)
            self.click_date_on_editor(editor, date)
            self.assertEqual(foo.single_date, date)

    def test_multi_select_dates_on_editor(self):
        with self.launch_editor(multi_select_custom_view) as (foo, editor):
            dates = [datetime.date(2018, 2, 3), datetime.date(2018, 2, 1)]
            for date in dates:
                self.click_date_on_editor(editor, date)

            for date in dates:
                self.check_select_status(
                    editor=editor, date=date, selected=True
                )

            self.assertEqual(foo.dates, sorted(dates))

    def test_multi_select_qt_styles_reset(self):
        with self.launch_editor(multi_select_custom_view) as (foo, editor):
            date = datetime.date(2018, 2, 1)
            self.click_date_on_editor(editor, date)
            self.check_select_status(editor=editor, date=date, selected=True)

            self.click_date_on_editor(editor, date)
            self.check_select_status(editor=editor, date=date, selected=False)

    def test_multi_select_qt_set_model_dates(self):
        # Test setting the dates from the model object.
        with self.launch_editor(multi_select_custom_view) as (foo, editor):
            foo.dates = [datetime.date(2010, 1, 2), datetime.date(2010, 2, 1)]

            for date in foo.dates:
                self.check_select_status(
                    editor=editor, date=date, selected=True
                )

    def test_custom_selected_color(self):
        view_factory = multi_select_selected_color_view
        with self.launch_editor(view_factory) as (foo, editor):
            date = datetime.date(2011, 3, 4)
            foo.dates = [date]

            self.check_date_bgcolor(editor, date, (128, 10, 0))

    # --------------------
    # Helper methods
    # --------------------

    @contextlib.contextmanager
    def launch_editor(self, view_factory):
        foo = Foo()
        with create_ui(foo, dict(view=view_factory())) as ui:
            (editor,) = ui._editors
            yield foo, editor

    def check_select_status(self, editor, date, selected):
        from pyface.qt import QtCore, QtGui

        qdate = QtCore.QDate(date.year, date.month, date.day)
        textformat = editor.control.dateTextFormat(qdate)
        if selected:
            self.assertEqual(
                textformat.fontWeight(),
                QtGui.QFont.Weight.Bold,
                "{!r} is not selected.".format(date),
            )
            self.check_date_bgcolor(editor, date, (0, 128, 0))
        else:
            self.assertEqual(
                textformat.fontWeight(),
                QtGui.QFont.Weight.Normal,
                "{!r} is not unselected.".format(date),
            )
            self.assertEqual(
                textformat.background().style(),
                QtCore.Qt.BrushStyle.NoBrush,
                "Expected brush to have been reset.",
            )
            self.check_date_bgcolor(editor, date, (0, 0, 0))

    def click_date_on_editor(self, editor, date):
        from pyface.qt import QtCore

        # QCalendarWidget.setSelectedDate modifies internal state
        # instead of triggering the click signal.
        # So we call update_object directly
        editor.update_object(QtCore.QDate(date.year, date.month, date.day))

    def check_date_bgcolor(self, editor, date, expected):
        from pyface.qt import QtCore

        qdate = QtCore.QDate(date.year, date.month, date.day)
        textformat = editor.control.dateTextFormat(qdate)

        color = textformat.background().color()
        actual = (color.red(), color.green(), color.blue())
        self.assertEqual(
            actual,
            expected,
            "Expected color: {!r}. Got color: {!r}".format(expected, actual),
        )

# Run this test case against wx too once enthought/traitsui#752 is fixed.
@requires_toolkit([ToolkitName.qt])
class TestDateEditorInitDispose(unittest.TestCase):
    """Test the init and dispose of date editor."""

    def check_init_and_dispose(self, view):
        with reraise_exceptions(), create_ui(Foo(), dict(view=view)):
            pass

    def test_simple_date_editor(self):
        view = View(
            Item(
                name="single_date",
                style="simple",
            )
        )
        self.check_init_and_dispose(view)

    def test_custom_date_editor(self):
        view = View(
            Item(
                name="single_date",
                style="custom",
            )
        )
        self.check_init_and_dispose(view)


import healsparse as hs
import healpy as hp
import numpy as np
from optparse import OptionParser

def main():
    usage = "%prog [options]"
    parser = OptionParser(usage=usage)
    parser.add_option("--input_file",type="string",dest="infilename",help="Input file",default='/pool/cosmo01_data1/des/y6_sp_maps/mangle_maps/SPmaps/band_g/y6a2_g_o.4096_t.32768_AIRMASS.MAX_EQU.fits.fz')
    parser.add_option("--nside_coverage",type="int",dest="nside_coverage",help="nside coverage value",default=32)
    parser.add_option("--nside_out",type="int",dest="nside_out",help="nside of output file",default=4096)
    parser.add_option("--nest",action="store_true",dest="isnest",help="Toggle NEST to True",default=False)
    parser.add_option("--healpix",action="store_true",dest="ishealpix",help="Toggle healpix format to True",default=False)
    parser.add_option("--mask",action="store_true",dest="applymask",help="Toggle mask application to True",default=False)
    parser.add_option("--input_file_maskname",type="string",dest="maskname",help="Mask file",default='/pool/cosmo01_data1/des/y6_sp_maps/official_v1/outliers_analysis/bao_mask/jointmasks/Y6LSSBAO_V2_MASK_WITHDEPTH_up_to_22.5_jointmask_0.01percent_sb_mean_0.5max_val_neb_mean_gcs_bit64.fits.gz')
    parser.add_option("--output_healsparse",action="store_true",dest="ouths",help="Toggle healsparse output",default=False)
    parser.add_option("--output_dir",type="string",dest="outdir",help="Output directory",default='./')
    parser.add_option("--output_file_mapname",type="string",dest="mapname",help="Output file map name",default='MAPNAME')
    parser.add_option("--output_file_statname",type="string",dest="statname",help="Output file stat name",default='STATNAME')
    parser.add_option("--output_file_bandname",type="string",dest="bandname",help="Output file band name",default=None)
    (options, args) = parser.parse_args()

    print('Selected NEST',options.isnest)
    print('nside',options.nside_out)

    #read a map
    print('Reading map',options.infilename)
    print('Selected input format as Healpix',options.ishealpix)
    if options.applymask:
        print('Applying mask',options.maskname)
    if options.ishealpix:
        inmap = hp.read_map(options.infilename, nest = options.isnest)
        if options.applymask:
            maskmap = hp.read_map(options.maskname,nest=False,partial=True)
            mask = np.where(maskmap == hp.UNSEEN) #masked out regions assumed to be assigned UNSEEN
            inmap[mask[0]] = hp.UNSEEN
    else:
        inmap = hs.HealSparseMap.read(options.infilename, options.nside_coverage)

    #build string with file name
    if options.isnest:
        nestring = 'NEST'
    else:
        nestring = 'RING'

    if options.bandname is None:
        outfilename_noext = '_'.join(('y6',options.mapname,options.statname,str(options.nside_out),nestring))
    else:
        outfilename_noext = '_'.join(('y6',options.mapname,options.statname,options.bandname,str(options.nside_out),nestring))

    if options.ouths:
        extension = '.hs'
    else:
        extension = '.fits'

    outfilename = options.outdir + outfilename_noext + extension

    #write maps
    print('Writing map',outfilename)
    if options.ishealpix: #input is healpix
        if options.ouths: #output in healsparse format
            conv_map = hs.HealSparseMap(nside_coverage=options.nside_coverage, healpix_map=inmap)
            conv_map.write(outfilename, clobber=True)
        else: #output in healpix
            if options.isnest:
                order = 'NESTED'
            else:
                order = 'RING'
            lores_map = hp.ud_grade(inmap, options.nside_out, order_in = order, order_out = order)
            hp.write_map(outfilename, lores_map, nest = options.isnest, overwrite=True)
    else: #input is healsparse
        if options.ouths: #output in healsparse format
            inmap.write(outfilename, clobber=True)
        else: #output in healpix
            conv_map = inmap.generate_healpix_map(nside=options.nside_out, reduction='mean', nest = options.isnest)
            hp.write_map(outfilename, conv_map, nest = options.isnest, overwrite=True)

if __name__ == "__main__":
    main()


"""

Creating keyspaces in Cassandra:

CREATE KEYSPACE my_keyspace WITH replication = {'class':'SimpleStrategy', 'replication_factor':1};

"""

from faker import Faker

faker = Faker()

def get_registered_user():
	return faker.name()+"$"+faker.address()+"$"+faker.year()
	"""return {
		"name": faker.name(),
		"address":faker.address(),
		"created_at": faker.year()
	}"""

if __name__ == "__main__":
	print(get_registered_user())


from unittest import TestCase
from sqlite3 import IntegrityError
import os
from shutil import copytree, rmtree
from random import randint, random
import uuid
from tempfile import gettempdir
from shapely.geometry import Point
import shapely.wkb
from aequilibrae.project import Project

from ...data import siouxfalls_project

class TestNode(TestCase):
    def setUp(self) -> None:
        os.environ["PATH"] = os.path.join(gettempdir(), "temp_data") + ";" + os.environ["PATH"]

        self.proj_dir = os.path.join(gettempdir(), uuid.uuid4().hex)
        copytree(siouxfalls_project, self.proj_dir)

        self.project = Project()
        self.project.open(self.proj_dir)
        self.network = self.project.network
        self.curr = self.project.conn.cursor()

    def tearDown(self) -> None:
        self.curr.close()
        self.project.close()
        try:
            rmtree(self.proj_dir)
        except Exception as e:
            print(f"Failed to remove at {e.args}")

    def test_save_and_assignment(self):
        nodes = self.network.nodes
        nd = randint(1, 24)
        node = nodes.get(nd)

        with self.assertRaises(AttributeError):
            node.modes = "abc"

        with self.assertRaises(AttributeError):
            node.link_types = "default"

        with self.assertRaises(AttributeError):
            node.node_id = 2

        with self.assertRaises(ValueError):
            node.is_centroid = 2

        node.is_centroid = 0
        self.assertEqual(0, node.is_centroid, "Assignment of is_centroid did not work")

        x = node.geometry.x + random()
        y = node.geometry.y + random()

        node.geometry = Point([x, y])

        node.save()

        self.curr.execute("Select is_centroid, asBinary(geometry) from nodes where node_id=?;", [nd])
        flag, wkb = self.curr.fetchone()
        self.assertEqual(flag, 0, "Saving of is_centroid failed")

        geo = shapely.wkb.loads(wkb)
        self.assertEqual(geo.x, x, "Geometry X saved wrong")
        self.assertEqual(geo.y, y, "Geometry Y saved wrong")

        self.curr.execute("Select asBinary(geometry) from links where a_node=?;", [nd])
        wkb = self.curr.fetchone()[0]

        geo2 = shapely.wkb.loads(wkb)
        self.assertEqual(geo2.xy[0][0], x, "Saving node geometry broke underlying network")
        self.assertEqual(geo2.xy[1][0], y, "Saving node geometry broke underlying network")

    def test_data_fields(self):
        nodes = self.network.nodes

        node1 = nodes.get(randint(1, 24))
        node2 = nodes.get(randint(1, 24))

        self.assertEqual(node1.data_fields(), node2.data_fields(), "Different nodes have different data fields")

        fields = sorted(node1.data_fields())
        self.curr.execute("pragma table_info(nodes)")
        dt = self.curr.fetchall()

        actual_fields = sorted([x[1] for x in dt if x[1] != "ogc_fid"])

        self.assertEqual(fields, actual_fields, "Node has unexpected set of fields")

    def test_renumber(self):
        nodes = self.network.nodes

        node = nodes.get(randint(2, 24))

        x = node.geometry.x
        y = node.geometry.y

        with self.assertRaises(IntegrityError):
            node.renumber(1)

        num = randint(25, 2000)
        node.renumber(num)

        self.curr.execute("Select asBinary(geometry) from nodes where node_id=?;", [num])
        wkb = self.curr.fetchone()[0]

        geo = shapely.wkb.loads(wkb)
        self.assertEqual(geo.x, x, "Renumbering failed")
        self.assertEqual(geo.y, y, "Renumbering failed")


# 从列表中找出某个值第一个匹配项的索引位置

# list.index(obj)

# 参数
    # obj -- 查找的对象。

# 返回值： 该方法返回查找对象的索引位置，如果没有找到对象则抛出异常。

Array = [1, 2, 3, 4, 5]

print(Array.index(2)) # 1

Array2 = [
    {
        "name": "Tom",
        "age": 18
    },
    {
        "name": "Yang",
        "age": 22
    }
]

print(Array2.index({
    "name": "Yang",
    "age": 22
})) # 1

# 对象 也可以检测

print(Array.index(6)) # ValueError: 6 is not in list


#!/usr/bin/env python
#===============================================================================
# objdump2vmh.py
#===============================================================================
#
#  -h --help     Display this message
#  -v --verbose  Verbose mode
#  -f --file     Objdump file to parse
#
# Author : Ji Kim
# Date   : April 13, 2011
#

import optparse
import fileinput
import sys
import re

#-------------------------------------------------------------------------------
# Command line processing
#-------------------------------------------------------------------------------

class OptionParserWithCustomError(optparse.OptionParser):
  def error( self, msg = "" ):
    if ( msg ): print("\n ERROR: %s" % msg)
    print("")
    for line in fileinput.input(sys.argv[0]):
      if ( not re.match( "#", line ) ): sys.exit(msg != "")
      if ((fileinput.lineno() == 3) or (fileinput.lineno() > 4)):
        print( re.sub( "^#", "", line.rstrip("\n") ) )

def parse_cmdline():
  p = OptionParserWithCustomError( add_help_option=False )
  p.add_option( "-v", "--verbose", action="store_true", dest="verbose" )
  p.add_option( "-h", "--help",    action="store_true", dest="help" )
  p.add_option( "-f", "--file",    action="store", type="string", dest="file" )
  (opts,args) = p.parse_args()
  if ( help == True ): p.error()
  if args: p.error("found extra positional arguments")
  return opts

#-------------------------------------------------------------------------------
# Main
#-------------------------------------------------------------------------------

def main():
  opts = parse_cmdline()

  # Open vmh file for writing
  file_out = open( opts.file[0:opts.file.find( "." )] + ".vmh", "w" )

  try:

    file_out.write( "\n" )

    # Open objdump file for reading
    file_in = open( opts.file, "r" )

    try:

      in_block = False

      # Iterate through lines in the file
      for line in file_in:

        # Parse the line into a list of words
        split_line = line.split()

        # Check if line is the beginning of an instruction block
        if ( line.find( ">:" ) >= 0 ):

          in_block = True

          # Convert block virtual address to physical address
          block_addr = hex( int( split_line[0], 16 ) )[2:]

          # Name of current block
          block_name = split_line[1][:-1]

          # Number of spaces between address and comment, offset from left edge = 10
          space_amt = ( 10 - ( len( block_addr ) + 1 ) )

          # Construct vmh line to write
          buffer = "@" + block_addr + ( " " * space_amt ) + "// " + block_name + "\n"

          # Write to vmh file
          file_out.write( buffer )

        # Check if line is within an instruction block
        elif ( in_block ):

          # Unset in_block if there's a break
          if ( line == "\n" ):

            in_block = False
            file_out.write( "\n" )

          else:

            # Parse instruction fields
            inst_bits = split_line[1]
            PC_raw = split_line[0][:-1]
            zero_amt = 8 - len( PC_raw )
            PC = ( "0" * zero_amt ) + PC_raw

            # Iterate through bytes in current data word
            bytes = range(4)
            bytes.reverse()

            for i in bytes:

              # Construct vmh line to write
              buffer = inst_bits[i*2:i*2+2]

              if ( i == 3 ):
                buffer = buffer + "        // " + PC + "\n"
              else:
                buffer = buffer + "\n"

              # Write line to file
              file_out.write( buffer )

    finally:

      file_in.close()

  finally:

    file_out.close()

main()


from OpenGL.GL import *
from common import get_namekey
import numpy as np
import pyglet

# #---badway
# vaoidx = VAO( {0:3,1:2},
#     #np.array([0,0,0, 0,0,  0.5,0,0, 1,0,  0.5,0.5,0, 1,1,  0,0.5,0, 0,1, ]).astype('float32'),
#     #np.array([0,0,0, 0,0,  1,0,0, 1,0,  1,1,0, 1,1,  0,1,0, 0,1, ]).astype('float32'),
#     np.array([ [0,0,0, 0,0],  [1,0,0, 1,0],  [1,1,0, 1,1],  [0,1,0, 0,1] ]).astype('float32'),
#     np.array([0,1,2,0,2,3,]).astype('uint')
#     )

#hard to parse. we take thisway.
# vaoidx = VAO(
#     {
#     'position' : [ 0,0,0, 1,0,0, 1,1,0, 0,1,0,],
#     'uv' : [ 0,0,  1,0,  1,1,  0,1 ],
#     },
#     indices = [0,1,2,0,2,3,]
#     )#name

#hard to parse.
# vaoidx = VAO(
#     position= [ 0,0,0, 1,0,0, 1,1,0, 0,1,0,],
#     uv = [ 0,0,  1,0,  1,1,  0,1 ],
#     indices = [0,1,2,0,2,3,]
#     )#name

vao_attrs={
    'position' : np.array([ 0,0,0, 1,0,0, 1,1,0, 0,1,0,]).astype('float32'),
    'uv' : np.array([ 0,0,  1,0,  1,1,  0,1 ]).astype('float32'),
    }
vao_indices = np.array([0,1,2,0,2,3,]).astype('uint')

# for i,nparr in vao_attrs.items():
#     a = len(nparr)
#     print(a)

class VAO:
    """indexed actually. hope we not use vao_notindexed."""
    last = -1

    #---namedict ver 0.2
    namedict = {}
    @classmethod
    def get(cls, name):
        if not 'default' in cls.namedict:
            cls.default()
        return cls.namedict.get(name)
    @classmethod
    def set(cls, name: str, item) -> str:
        name = get_namekey(cls.namedict,name)
        cls.namedict[name]=item
        return name
    @classmethod
    def default(cls):
        cls(vao_attrs,vao_indices,name='default')

    def __repr__(self):
        return f"vao name:{self.name}"

    def __init__(self, attrdict,indices, name='vao'):
        """we need attrdict{'position':ndarr(f32)} !"""
        #attrlist=[]
        #for attrname, nparr in attrdict.items():
        #    attrlist.append(nparr)
        #vertices = np.concatenate( attrlist ).astype('float32')
        assert list(attrdict.keys())[0]=='position'

        vert_count = len(attrdict['position'])//3

        #attr_size_dict = {0:3,1:2}
        attr_size_dict = {}
        attridx = -1
        for attrname, nparr in attrdict.items():
            attridx+=1
            attrN = len(nparr)//vert_count
            attr_size_dict[attridx] = attrN
        stride = sum(attr_size_dict.values())#5, of 3+2

        vertices = []
        for idx, nparr in enumerate(attrdict.values()):
            vertlen = attr_size_dict[idx]
            verted = nparr.reshape(-1,vertlen)
            vertices.append(verted)
        vertices = np.hstack(vertices).flatten().astype('float32')

        #---old way
        #vertices = np.array([ [0,0,0, 0,0],  [1,0,0, 1,0],  [1,1,0, 1,1],  [0,1,0, 0,1] ]).astype('float32')
        #indices = np.array([0,1,2,0,2,3,]).astype('uint')
        #attr_size_dict = {0:3,1:2}
        #stride = sum(attr_size_dict.values())#5, of 3+2

        #pos 12, indices,,
        #vert_count = len(indices)

        datatype = GL_FLOAT
        normalized = GL_FALSE #GL_TRUE
        fsize = np.float32(0.0).nbytes #to ensure namespace-safe.

        VAO = glGenVertexArrays(1) # create a VA. if 3, 3of VA got. #errs if no window.
        VBO = glGenBuffers(1) #it's buffer, for data of vao.fine.
        EBO = glGenBuffers(1) #indexed, so EBO also. yeah.

        glBindVertexArray(VAO) #gpu bind VAO

        glBindBuffer(GL_ARRAY_BUFFER, VBO) #gpu bind VBO in VAO
        glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)

        pre_offset = 0
        for attr_index, size in attr_size_dict.items():
            if pre_offset==0:
                offset = None
                offset = ctypes.c_void_p(0)#maybe it seems works.
                glVertexAttribPointer(attr_index, size, datatype, normalized, stride * fsize, offset)
                glEnableVertexAttribArray(attr_index)
                pre_offset = size
            else:
                offset = ctypes.c_void_p( pre_offset *fsize)
                glVertexAttribPointer(attr_index, size, datatype, normalized, stride * fsize, offset)
                glEnableVertexAttribArray(attr_index)
                pre_offset +=size

        self.ID = VAO
        self.ID_VBO = VBO
        self.ID_EBO = EBO
        self.stride = stride
        self.points = len(indices)
        self.vertices = vertices
        self.name = self.__class__.set(name,self)

    def update_position(self,position):
        vertices = self.vertices

        #assume 0,1,2 is posxyz.
        vertices[0::self.stride] = position[0::3]
        vertices[1::self.stride] = position[1::3]
        vertices[2::self.stride] = position[2::3]

        VAO = self.ID
        VBO = self.ID_VBO
        glBindVertexArray(VAO)
        glBindBuffer(GL_ARRAY_BUFFER, VBO) #gpu bind VBO in VAO
        glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
        #GL_STREAM_DRAW for little change, if you want someday..
        self.vertices = vertices

    def update(self,vertices):
        """requires same shape kinds.."""
        VAO = self.ID
        VBO = self.ID_VBO
        glBindVertexArray(VAO)
        glBindBuffer(GL_ARRAY_BUFFER, VBO) #gpu bind VBO in VAO
        glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
        #GL_STREAM_DRAW for little change, if you want someday..
        #self.points = len(vertices)//self.stride #donno why do this..

    def update_indices(self,vertices, indices):
        """hope we not use this.."""
        VAO = self.ID
        VBO = self.ID_VBO
        EBO = self.ID_EBO
        glBindVertexArray(VAO)
        glBindBuffer(GL_ARRAY_BUFFER, VBO) #gpu bind VBO in VAO
        glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)
        self.points = len(indices)#now we can really change it..

    def bind(self):
        if VAO.last != self.ID:
            glBindVertexArray(self.ID)
            VAO.last = self.ID
    def unbind(self):
        glBindVertexArray(0)
        VAO.last = -1

    def draw(self, MODE = 'triangles'):
        """requires bind first. it just draw command of VAO bound gpu."""
        #simple mode changeable draw. we not prefer partial draw which is slow.
        draw_dict = {'points':GL_POINTS,
        'lines':GL_LINE_STRIP,
        'triangles':GL_TRIANGLES,
        }
        MODE = draw_dict[MODE]
        glDrawElements(MODE, self.points, GL_UNSIGNED_INT, None)

if __name__ == "__main__":
    window = pyglet.window.Window()
    VAO.default()
    a = VAO.get('default')
    print(a)


import numpy as np
import keras
from keras.datasets import mnist

class Dataset:

    def __init__(self, path, local):
        """
        Initialize the MNIST dataset.
        Parameters path and local are only included to fit the interface of Dataset
        :param path: Ignored
        :param local: Ignored
        """

        (x, y), (_, _) = mnist.load_data()

        # Configure input
        x = (x.astype(np.float32) - 127.5) / 127.5
        x = np.expand_dims(x, axis=3)
        x_padding = np.zeros((x.shape[0], 64, 64, 1)) - 1
        x_padding[:, :28, :28, :] = x
        x = x_padding
        y = keras.utils.np_utils.to_categorical(y, 10)

        self.x = x
        self.y = y

        print('Loaded dataset')
        print('X:', self.x.shape)
        print('Y:', self.y.shape)


class Monitors:

    name = 'Samsung'
    matrix = 'VA'
    res = 'WQHD'
    freq = 60

class Headphones:
    name = 'Sony'
    sensitivity = 108
    micro = True

monitor_1 = Monitors()
monitor_2 = Monitors()
monitor_2.freq = 144
monitor_3 = Monitors()
monitor_3.freq = 70
monitor_4 = Monitors()

headphone_1 = Headphones()
headphone_1.micro = False
headphone_2 = Headphones()
headphone_3 = Headphones()

print(monitor_1.freq, monitor_2.freq, monitor_3.freq, monitor_4.freq)
print(headphone_1.micro, headphone_2.micro, headphone_2.micro,)


'''
Escribir una funcion para ingresar desde el teclado una serie de numeros entre 1
y 20 guardarlos en una lista. En caso de ingresar un valor fuera de rango el
programa mostrara un mensaje de error solicitara un nuevo numero. Para finalizar
la carga se debera ingresar -1. La funcion no recibe ningun parametro, y
devuelve la lista cargada (o vacia, si el usuario no ingreso nada) como valor de
retorno.
'''

def cargar_lista(lista,num):
    while(num != -1):
        if(num < 1 or num > 20):
            print("Ingrese un valor valido entre 1 y 20")
        else:
            lista.append(num)

        num = int(input("Ingrese un numero entre 1 y 20 (Termina con -1): "))

    return lista

lista = []

num = int(input("Ingrese un numero entre 1 y 20 (Termina con -1): "))

print(cargar_lista(lista,num))

input()


import logging
import requests

from io import BytesIO
from django.core.management import BaseCommand

from places.models import Place, PlaceImage

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = 'Load information about places with media files'

    def add_arguments(self, parser):
        parser.add_argument('resource_url', type=str)

    def handle(self, *args, **options):
        resource_url = options['resource_url']

        logger.info(f'START LOADING DATA FROM RESOURCE {resource_url}')

        try:
            response = requests.get(resource_url)
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            logger.error(f'UNABLE TO LOAD DATA FROM RESOURCE {resource_url}, details: {e}')
            return

        place_data = response.json()
        place, created = Place.objects.get_or_create(
            title=place_data['title'],
            defaults={
                'short_title': place_data['title'],
                'short_description': place_data['description_short'],
                'long_description': place_data['description_long'],
                'lng': place_data['coordinates']['lng'],
                'lat': place_data['coordinates']['lat'],
                'place_id': place_data['title'],
            }
        )
        if created:
            for i, img_url in enumerate(place_data['imgs'], start=1):
                try:
                    img_response = requests.get(img_url)
                    img_response.raise_for_status()
                except requests.exceptions.HTTPError as e:
                    logger.error(f'UNABLE TO SAVE IMAGE FROM FROM RESOURCE {img_url}, details: {e}')
                    continue

                img = BytesIO(img_response.content)
                place_image, img_created = PlaceImage.objects.get_or_create(
                    place=place,
                    position=i
                )
                place_image.image.save(f'place-{place.id}-img-{i}', img, save=True)

        action = 'CREATED' if created else 'UPDATED'
        logger.info(f'{action} PLACE {place}')

        logger.info(f'END LOADING DATA FROM RESOURCE {resource_url}')


import ops
import iopc

TARBALL_FILE="drbd-utils-8.9.10.tar.gz"
TARBALL_DIR="drbd-utils-8.9.10"
INSTALL_DIR="drbd-utils-bin"
pkg_path = ""
output_dir = ""
tarball_pkg = ""
tarball_dir = ""
install_dir = ""
install_tmp_dir = ""
cc_host = ""

def set_global(args):
    global pkg_path
    global output_dir
    global tarball_pkg
    global install_dir
    global install_tmp_dir
    global tarball_dir
    global cc_host
    pkg_path = args["pkg_path"]
    output_dir = args["output_path"]
    tarball_pkg = ops.path_join(pkg_path, TARBALL_FILE)
    install_dir = ops.path_join(output_dir, INSTALL_DIR)
    install_tmp_dir = ops.path_join(output_dir, INSTALL_DIR + "-tmp")
    tarball_dir = ops.path_join(output_dir, TARBALL_DIR)
    cc_host_str = ops.getEnv("CROSS_COMPILE")
    cc_host = cc_host_str[:len(cc_host_str) - 1]

def MAIN_ENV(args):
    set_global(args)

    ops.exportEnv(ops.setEnv("CC", ops.getEnv("CROSS_COMPILE") + "gcc"))
    ops.exportEnv(ops.setEnv("CXX", ops.getEnv("CROSS_COMPILE") + "g++"))
    ops.exportEnv(ops.setEnv("CROSS", ops.getEnv("CROSS_COMPILE")))
    ops.exportEnv(ops.setEnv("DESTDIR", install_tmp_dir))

    return False

def MAIN_EXTRACT(args):
    set_global(args)

    ops.unTarGz(tarball_pkg, output_dir)
    #ops.copyto(ops.path_join(pkg_path, "finit.conf"), output_dir)

    return True

def MAIN_PATCH(args, patch_group_name):
    set_global(args)
    for patch in iopc.get_patch_list(pkg_path, patch_group_name):
        if iopc.apply_patch(tarball_dir, patch):
            continue
        else:
            sys.exit(1)

    return True

def MAIN_CONFIGURE(args):
    set_global(args)

    extra_conf = []
    extra_conf.append("--with-distro=generic")
    extra_conf.append("--without-manual")
    extra_conf.append("--without-udev")
    extra_conf.append("--without-83support")
    extra_conf.append("--with-initscripttype=sysv")
    #extra_conf.append("--prefix=" + install_dir)
    extra_conf.append("--host=" + cc_host)
    iopc.configure(tarball_dir, extra_conf)

    return True

def MAIN_BUILD(args):
    set_global(args)

    ops.mkdir(install_dir)
    ops.mkdir(install_tmp_dir)
    iopc.make(tarball_dir)
    iopc.make_install(tarball_dir)
    return False

def MAIN_INSTALL(args):
    set_global(args)

    ops.mkdir(install_dir)
    ops.copyto(ops.path_join(install_tmp_dir, "lib"), install_dir)

    ops.mkdir(ops.path_join(install_dir, "sbin"))
    ops.copyto(ops.path_join(install_tmp_dir, "usr/local/sbin/drbdadm"), ops.path_join(install_dir, "/sbin"))
    ops.copyto(ops.path_join(install_tmp_dir, "usr/local/sbin/drbdsetup"), ops.path_join(install_dir, "/sbin"))
    ops.copyto(ops.path_join(install_tmp_dir, "usr/local/sbin/drbdmeta"), ops.path_join(install_dir, "/sbin"))

    ops.mkdir(ops.path_join(install_dir, "usr/"))
    ops.rm_file(ops.path_join(install_dir, "var"))
    ops.ln(install_dir, "/var", ops.path_join(install_dir, "var"))
    iopc.installBin(args["pkg_name"], ops.path_join(install_dir, "lib/."), "lib")
    iopc.installBin(args["pkg_name"], ops.path_join(install_dir, "sbin/."), "sbin")
    iopc.installBin(args["pkg_name"], ops.path_join(install_dir, "var"), "usr/local")
    #iopc.installBin(args["pkg_name"], ops.path_join(output_dir, "finit.conf"), "etc")

    return False

def MAIN_SDKENV(args):
    set_global(args)
    return False

def MAIN_CLEAN_BUILD(args):
    set_global(args)

    return False

def MAIN(args):
    set_global(args)


import pymongo
from data_handlers import import_from_csv

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
core_db = myclient["core"]
indices_col = core_db["indices"]
historical_data_col = core_db["historical_data"]

instruments_file = "C:\\Users\\Prathiksha\\Documents\\Prashanth\\Trading\\instruments_nse.csv"
market_cap_file = "C:\\Users\\Prathiksha\\Documents\\Prashanth\\Trading\\MCAP31032021_0.csv"
mis_data_file = "C:\\Users\\Prathiksha\\Documents\\Prashanth\\Trading\\Zerodha - Intraday margins - EQ- MIS_CO leverages.csv"
instruments_df = import_from_csv(instruments_file)
market_cap_df = import_from_csv(market_cap_file)
mis_df = import_from_csv(mis_data_file)
print(mis_df.columns)

def insert_to_db(df, db_col):
    indices = df.columns
    for ind in df.index:
        input_dict = {}
        for index in indices:
            input_dict[index] = str(df[index][ind])
        db_col.insert_one(input_dict)

def update_to_db(df, db_col, indices, field):
    for ind in df.index:
        for i in range(0, len(indices)):
            try:
                db_col.update_one({"tradingsymbol":df[indices[i]][ind]},{"$set":{field:"true"}})
            except Exception as e:
                print(e)
            # try:
            #     db_col.update_one({"tradingsymbol":df[indices[i]][ind]+"-BE"},{"$set":{"rank":df['Sr. No.'][ind], "market_cap":df['market_cap'][ind]}})
            # except Exception as e:
            #     print(e)

update_to_db(mis_df, indices_col, ['Symbol'], "mis_status")
#insert_to_db(instruments_df, indices_col)


import warnings
from functools import partial
from multiprocessing import Pool

import pandas as pd
import textacy
import textacy.preprocessing
import textacy.representations
import textacy.tm
from tqdm import tqdm

tqdm.pandas()

warnings.simplefilter(action="ignore", category=FutureWarning)

preproc = textacy.preprocessing.make_pipeline(
    textacy.preprocessing.normalize.unicode,
    textacy.preprocessing.normalize.bullet_points,
    textacy.preprocessing.normalize.quotation_marks,
    textacy.preprocessing.normalize.whitespace,
    textacy.preprocessing.normalize.hyphenated_words,
    textacy.preprocessing.remove.brackets,
    textacy.preprocessing.replace.currency_symbols,
    textacy.preprocessing.remove.html_tags,
)

def from_dict_to_frame(indexed_dict):
    data = {k: [v] for k, v in indexed_dict.items()}
    df = pd.DataFrame.from_dict(data).T
    df.columns = ["text"]
    df = df.explode("text")
    return df

def extract_terms_df(
    data,
    text_var,
    index_var,
    ngs=True,
    ents=True,
    ncs=False,
    sample_size=100000,
    drop_emoji=True,
    ngrams=(2, 2),
    remove_punctuation=True,
    include_pos=["NOUN"],
    include_types=["PERSON", "ORG"],
    language="en_core_web_sm",
):
    load_lang = textacy.load_spacy_lang(language, disable=())

    def extract_terms(
        tuple,  # (index, text)
        ngs=True,
        ents=True,
        ncs=False,
        ngrams=(2, 2),
        drop_emoji=True,
        remove_punctuation=False,
        include_pos=["NOUN", "PROPN", "ADJ"],
        include_types=["PERSON", "ORG"],
    ):
        index = tuple[0]
        text = tuple[1]

        prepro_text = preproc(str(text))
        if drop_emoji == True:
            prepro_text = textacy.preprocessing.replace.emojis(prepro_text, repl="")

        if remove_punctuation == True:
            prepro_text = textacy.preprocessing.remove.punctuation(prepro_text)

        doc = textacy.make_spacy_doc(prepro_text, lang=load_lang)

        terms = []

        if ngs:
            ngrams_terms = list(
                textacy.extract.terms(
                    doc,
                    ngs=partial(
                        textacy.extract.ngrams,
                        n=ngrams,
                        filter_punct=True,
                        filter_stops=True,
                        include_pos=include_pos,
                    ),
                    dedupe=False,
                )
            )

            terms.append(ngrams_terms)

        if ents:
            ents_terms = list(
                textacy.extract.terms(
                    doc,
                    ents=partial(textacy.extract.entities, include_types=include_types),
                    dedupe=False,
                )
            )
            terms.append(ents_terms)

        if ncs:
            ncs_terms = list(
                textacy.extract.terms(
                    doc,
                    ncs=partial(textacy.extract.noun_chunks, drop_determiners=True),
                    dedupe=False,
                )
            )

            noun_chunks = [x for x in ncs_terms if len(x) >= 3]
            terms.append(noun_chunks)

        final = [item for sublist in terms for item in sublist]
        final = list(set(final))

        df = [
            (term.text, term.lemma_.lower(), term.label_, term.__len__())
            for term in final
        ]
        df = pd.DataFrame(df, columns=["text", "lemma", "ent", "ngrams"])
        df["text_index"] = index

        return df

    """
    This function extracts terms from a column in a DataFrame. It can extract in a multiprocessing way
    It outputs a dataframe with the list of terms and a table with the indexed terms
    """

    data = data[data[text_var].notna()]
    data = data.sample(min(sample_size, len(data)))

    sentences = data[text_var].to_list()
    indexes = data[index_var].to_list()
    inputs = [(x, y) for x, y in zip(indexes, sentences)]

    # else:
    res = list(
        tqdm(
            map(
                partial(
                    extract_terms,
                    ngs=ngs,
                    ents=ents,
                    ncs=ncs,
                    drop_emoji=drop_emoji,
                    remove_punctuation=remove_punctuation,
                    ngrams=ngrams,
                    include_pos=include_pos,
                    include_types=include_types,
                ),
                inputs,
            ),
            total=len(inputs),
        )
    )

    final_res = pd.concat([x for x in res])

    terms = (
        final_res.groupby(["text", "lemma", "ent", "ngrams"])
        .agg(count_terms=("text_index", "count"))
        .reset_index()
    )

    # duplicates to get rid of
    terms = terms.sort_values(["text", "ent"]).reset_index(drop=True)
    terms = terms.drop_duplicates(["text"], keep="first")
    terms = terms.sort_values("count_terms", ascending=False)
    terms = terms.rename(columns={"text": "terms_indexed"})
    terms = terms.set_index("terms_indexed")

    terms_indexed = final_res[["text", "text_index"]].drop_duplicates()
    terms_indexed = terms_indexed.rename(columns={"text_index": index_var})
    terms_indexed = terms_indexed.groupby(index_var)["text"].apply(list)
    terms_indexed = terms_indexed.reset_index()
    terms_indexed = terms_indexed.rename(columns={"text": "terms_indexed"})
    terms_indexed = terms_indexed.set_index(index_var)

    return terms, terms_indexed


import json

import numpy as np
import pandas as pd
import tensorflow as tf

class BalancedGroupSoftmax:
  def __init__(self,
               dataset_json,
               category_map,
               empty_class_id,
               selected_locations=None,
               n_groups=4,
               sl_max_groups=[0, 10, 100, 1000, 2**100],
               beta_others=8.0):
    self.n_groups = n_groups
    self.sl_max_groups = sl_max_groups
    self.beta_others = beta_others
    self.category_map = category_map
    self.empty_class_id = empty_class_id
    self.label2binlabel = {}
    self.groups_counts = [1] * (n_groups + 1)
    self.predict_tables = []

    dataset_df = self._load_dataset(dataset_json, selected_locations)
    self._generate_binlabel_idx(dataset_df)
    self._generate_predict_tables()

  def _load_dataset(self, dataset_json, selected_locations):
    with tf.io.gfile.GFile(dataset_json, 'r') as json_file:
      json_data = json.load(json_file)
    images = pd.DataFrame(json_data['images'])
    annotations = pd.DataFrame(json_data['annotations'])
    images = pd.merge(images,
                        annotations[["image_id", "category_id"]],
                        how='left',
                        left_on='id',
                        right_on='image_id')

    if selected_locations is not None:
      images = images[images.location.isin(selected_locations)]
      images = images.copy()

    return images

  def _get_group(self, instances_count):
    for group, group_max in enumerate(self.sl_max_groups):
      if instances_count < group_max:
        return group
    return 0

  def _generate_binlabel_idx(self, dataset_df):
    categories = list(range(self.category_map.get_num_classes()))

    #group 0 is only bg/fg
    self.groups_counts[0] = 2
    empty_class = self.category_map.category_to_index(self.empty_class_id)
    self.label2binlabel[empty_class] = [1] + [0] * (self.n_groups)
    categories.remove(empty_class)

    #nonempty categories
    for categ in categories:
      categ_id = self.category_map.index_to_category(categ)
      instances_count = len(dataset_df[dataset_df.category_id == categ_id])
      group_id = self._get_group(instances_count)

      binlabel = [0] * (self.n_groups + 1)
      binlabel[group_id] = self.groups_counts[group_id]
      self.groups_counts[group_id] += 1
      self.label2binlabel[categ] = binlabel

  def _generate_predict_tables(self):
    for i in range(self.n_groups + 1):
      self.predict_tables.append(
        np.zeros(shape=(self.groups_counts[i],
                        self.category_map.get_num_classes())))

    for label, binlabel in self.label2binlabel.items():
      group = np.asarray(binlabel).argmax()
      self.predict_tables[group][binlabel[group]][label] = 1.0

  def create_classif_header(self, head_features):
    outputs = []

    for group_count in self.groups_counts:
      output = tf.keras.layers.Dense(group_count,
                                     activation='softmax')(head_features)
      outputs.append(output)

    return outputs

  def _create_map_layer(self, inputs, n_inputs, n_outputs, weights):
    map_layer = tf.keras.layers.Dense(n_outputs, use_bias=False)
    map_layer(tf.convert_to_tensor(np.ones((1, n_inputs)), dtype=tf.float32))
    map_layer.set_weights([weights])

    return map_layer(inputs)

  def create_prediction_model(self, trained_model):
    fg_prob_map = np.array([np.ones(self.category_map.get_num_classes()),
                            np.zeros(self.category_map.get_num_classes())])
    fg_prob = self._create_map_layer(trained_model.outputs[0],
                                     self.groups_counts[0],
                                     self.category_map.get_num_classes(),
                                     fg_prob_map)

    mapped_predictions = []
    for output, group_size, predict_tbl in zip(trained_model.outputs,
                                               self.groups_counts,
                                               self.predict_tables):
      layer_map = self._create_map_layer(output,
                                          group_size,
                                          self.category_map.get_num_classes(),
                                          predict_tbl)
      mapped_predictions.append(layer_map)

    scaled_mapped_predictions = [mapped_predictions[0]]
    for map_pred in mapped_predictions[1:]:
      scaled_map_pred = tf.keras.layers.Multiply()([map_pred, fg_prob])
      scaled_mapped_predictions.append(scaled_map_pred)

    preds = tf.keras.layers.Add()(scaled_mapped_predictions)
    model = tf.keras.models.Model(inputs=trained_model.inputs, outputs=preds)

    return model

  def process_label(self, label):
    def _get_idx_label(label):
      categ_id = self.category_map.category_to_index(label.numpy())
      binlabels = self.label2binlabel[categ_id]
      binlabels_one_hot = []

      for idx, binlabel in enumerate(binlabels):
        one_hot = np.zeros(self.groups_counts[idx])
        one_hot[binlabel] = 1
        binlabels_one_hot.append(one_hot)

      return binlabels_one_hot
    labels = tf.py_function(func=_get_idx_label,
                            inp=[label],
                            Tout=([tf.float32]*(self.n_groups+1)))
    labels = [tf.ensure_shape(label, shape=(self.groups_counts[i],))
              for i, label in enumerate(labels)]

    return tuple(labels)

  def generate_balancing_mask(self, labels):
    batch_size = tf.shape(labels[0])[0]
    masks = []

    #for the bg/fg group we use all instances
    mask0 = tf.ones(shape=(batch_size,))
    masks.append(mask0)

    def _get_max(labels, batch_size):
      labels = labels.numpy()
      others = labels[:,0]
      fg = 1.0 - others
      fg_num = np.sum(fg)

      if fg_num == 0:
        return np.zeros(batch_size)

      others_num = batch_size - fg_num
      others_sample_num = int(fg_num * self.beta_others)

      if others_sample_num > others_num:
        return np.ones(batch_size)
      else:
        sample_idx = np.random.choice(others.nonzero()[0],
                                      (others_sample_num, ), replace=False)
        fg[sample_idx] = 1.0

      return fg

    for i in range(1, self.n_groups + 1):
      mask = tf.py_function(func=_get_max,
                            inp=[labels[i], batch_size],
                            Tout=tf.float32)
      masks.append(mask)

    return tuple(masks)


def caminho_hamiltoniano(grafo, size, ponto, path=[]):
    if ponto not in set(path):
        path.append(ponto)
        if len(path) == size:
            return path
        todos_candidatos = []
        for prox_ponto in grafo.get(ponto, []):
            res_path = [i for i in path]
            candidatos = caminho_hamiltoniano(grafo, size, prox_ponto, res_path)
            if candidatos is not None:
                todos_candidatos.extend(candidatos)
            else:
                pass
        return todos_candidatos
    else:
        return None

if __name__ == '__main__':
    ponto = 1
    size = 4

    grafo = {1: [2, 3], 2: [1, 3, 4], 3: [1, 2, 4], 4: [2, 3]}

    grafo2 = {1:[2,4],2:[1,3],3:[2,4],4:[1,3]}

    grafo3 = {0:[1,2],1:[3,4],2:[0,5,6],3:[1],4:[1],5:[2],6:[2]}

    path = caminho_hamiltoniano(grafo, size, ponto)
    lista_candidados = []
    for j in range(size):
        while j*size < len(path):
            start = int(j*size)
            end = int((j+1)*size)
            lista_candidados.append(path[start:end])
            break
    print('Candidatos a ciclos hamiltonianos: '%(lista_candidados))

    if len(lista_candidados) == 0:
        print('Não há caminho hamiltoniano, então, não há ciclo hamiltoniano')
    else:
        for candidato in lista_candidados:
            if ponto in grafo[candidato[-1]]:
                print('O caminho %s é um ciclo hamiltoniano'%(candidato))
            else:
                print('O caminho %s não é um ciclo hamiltoniano'%(candidato))


import logging
from typing import List

from DAL.ItemDAL.ItemDALInterface import ItemDALInterface
from Database.DBConnection import DBConnection
from Entities.Item import Item

class ItemDALImplementation(ItemDALInterface):

    def create_item(self, item: Item) -> Item:
        logging.info("Beginning DAL method create item with item: " + str(item))
        sql = "INSERT INTO Designs.Item (item_name) VALUES (%s) RETURNING item_id;"
        connection = DBConnection.db_connection()
        cursor = connection.cursor()
        cursor.execute(sql, (item.item_name,))
        item.item_id = cursor.fetchone()[0]
        cursor.close()
        connection.commit()
        connection.close()
        logging.info("Finishing DAL method create item with item: " + str(item))
        return item

    def get_item(self, item_id: int) -> Item:
        logging.info("Beginning DAL method get item with item ID: " + str(item_id))
        sql = "SELECT * FROM Designs.Item WHERE item_id=%s;"
        connection = DBConnection.db_connection()
        cursor = connection.cursor()
        cursor.execute(sql, (item_id,))
        item_info = cursor.fetchone()
        cursor.close()
        connection.close()
        if item_info is None:
            item = Item(0, "")
            logging.info("Finishing DAL method get item, item not found")
            return item
        else:
            item = Item(*item_info)
            logging.info("Finishing DAL method get item with item: " + str(item.convert_to_dictionary()))
            return item

    def get_all_items(self) -> List[Item]:
        logging.info("Beginning DAL method get all items")
        sql = "SELECT * FROM Designs.Item;"
        connection = DBConnection.db_connection()
        cursor = connection.cursor()
        cursor.execute(sql)
        item_records = cursor.fetchall()
        cursor.close()
        connection.close()
        item_list = []
        for item in item_records:
            item = Item(*item)
            item_list.append(item)
            logging.info("Finishing DAL method get all items with items: " + str(item.convert_to_dictionary()))
        return item_list

    def update_item(self, item: Item) -> bool:
        logging.info("Beginning DAL method update item with item: " + str(item.convert_to_dictionary()))
        sql = "Update Designs.Item SET item_name=%s WHERE item_id=%s;"
        connection = DBConnection.db_connection()
        cursor = connection.cursor()
        cursor.execute(sql, (item.item_name, item.item_id))
        cursor.close()
        connection.commit()
        connection.close()
        logging.info("Finishing DAL method update item")
        return True

    def delete_item(self, item_id: int) -> bool:
        logging.info("Beginning DAL method delete item with item ID: " + str(item_id))
        sql = "DELETE FROM Designs.Item WHERE item_id=%s;"
        connection = DBConnection.db_connection()
        cursor = connection.cursor()
        cursor.execute(sql, (item_id,))
        cursor.close()
        connection.commit()
        connection.close()
        logging.info("Finishing DAL method delete item")
        return True


def getval(A, i, j, L, H):
    if (i < 0 or i >= L or j < 0 or j >= H):
        return 0
    else:
        return A[i][j]

def find_max_block(A, r, c, L, H, size, cntarr, maxsize):
    if (r >= L or c >= H):
        return
    cntarr[r][c] = True
    size += 1
    if (size > maxsize):
        maxsize = size
    directions = [[-1,0], [-1,-1], [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1]]
    for direction in directions:
        new_i = r + direction[0]
        new_j = c + direction[1]
        val = getval(A, new_i, new_j, L, H)
        if (val > 0 and cntarr[new_i][new_j] is False):
            maxsize = find_max_block(A, new_i, new_j, L, H, size, cntarr, maxsize)
    cntarr[r][c] = False
    return maxsize

def get_max_ones(A, rmax, colmax):
    maxsize = 0
    size = 0
    cntarr = [[False for j in range(0,colmax)] for i in range(0,rmax) ]
    for i in range(0, rmax):
        for j in range(0, colmax):
            if (A[i][j] == 1):
                maxsize = find_max_block(A, i, j, L, H, size, cntarr, maxsize)
    return maxsize

if __name__ == '__main__':
    A = [
            [1, 1, 0, 0, 0],
            [0, 1, 1, 0, 0],
            [0, 0, 1, 0, 1],
            [1, 0, 0, 0, 1],
            [0, 1, 0, 1, 1]
        ]

    L = len(A)
    H = len(A[0])
    print(get_max_ones(A, L, H))


# Importeren modules
import copy
import math

ERROR_MARGIN = 0.01

def build_Best_Graph(n_dict, c_dict): # main function
    #  n_dict = Nodes Dict
    #  c_dict = Connections Dict
    #  f_nid = First Node Id
    #  o_nid_list = Ordered Nodes Ids List
    solutions_list = []
    for f_nid in n_dict: # for each node in node_list
        print('Creating list of node ' + str(f_nid))
        o_nid_list = ordered_Node_List(f_nid, c_dict, n_dict)
        nodes_list = [n_dict[nid] for nid in o_nid_list] # list of noodes with coordinates
        nodes_list[0]['coor'] = coor_0() # add the first node with coordinates
        nodes_list[1]['coor'] = coor_1(nodes_list[0], nodes_list[1]) # add the second node with coordinates
        for index in range(2, len(nodes_list)):
            print('Evaluating node ' + str(index))
            nodes_list[index]['coor'] = get_Coordinates(nodes_list[index], nodes_list[:index], c_dict)
        solutions_list.append(nodes_list)
    print('Evaluating lists')
    best_solution = min(solutions_list, key=lambda nodes_list: solution_Stress(nodes_list, c_dict)) # get list of nodes with lowest stress
    return best_solution

def ordered_Node_List(f_nid, c_dict, n_dict): # Sort Nodes Ids
    #  nid_l_list = Nodes Ids Left List
    #  s_nid_dict = Score Nodes Ids-To-List Dict
    o_nid_list = [f_nid]
    nid_l_list = list(n_dict.keys())
    nid_l_list.remove(f_nid)
    while len(nid_l_list) > 0:
        print('Done in ' +str(len(nid_l_list)))
        s_nid_dict = {}
        for nid in nid_l_list:
            s_nid_dict[nid] = score_Node_To_List(nid, o_nid_list, c_dict, n_dict)
        max_nid = max(s_nid_dict.keys(), key=lambda nid: s_nid_dict[nid])
        o_nid_list.append(max_nid)
        nid_l_list.remove(max_nid)
    return o_nid_list

def score_Node_To_List(nid1, o_nid_list, c_dict, n_dict):
    score_sum = 0
    for nid2 in o_nid_list:
        score_sum += get_Score(c_dict[nid1][nid2], n_dict[nid1]['lenght'], n_dict[nid2]['lenght'])
    return score_sum

def get_Score(n_connections, lenght_1, lenght_2):
    score = n_connections / (lenght_1*lenght_2)
    return score

def coor_0(): # first node coordinate
    return (0, 0)

def coor_1(node_1, node_2): # second node coordinate
    magnitude_in_X = node_1['radius'] + node_2['radius']
    return ((magnitude_in_X), 0)

def get_Coordinates(node, prior_nodes_list, c_dict):
    stress_list = []
    for prior_pair in pairs_Nodes(prior_nodes_list):
        p_n1 = prior_pair[0]
        p_n2 = prior_pair[1]
        c_1 = {'x': p_n1['coor'][0], 'y': p_n1['coor'][1], 'r': p_n1['radius'] + node['radius'] + ERROR_MARGIN}
        c_2 = {'x': p_n2['coor'][0], 'y': p_n2['coor'][1], 'r': p_n2['radius'] + node['radius'] + ERROR_MARGIN}
        if do_Overlaps(c_1, c_2): #  If circles overlap
            #print('Calculate intersection')
            int_coordinates = coor_Inter(c_1, c_2) # intersection coordinates
            for coordinate in int_coordinates:
                c_3 = {'x': coordinate[0], 'y': coordinate[1], 'r': node['radius']}
                #print('Calculate overlaping wiht any')
                if not overlaps_Any(c_3, prior_nodes_list): #  If nodes don't overlap
                    #print('Node Stress')
                    stress = node_Stress(node['id'], c_3['x'], c_3['y'], prior_nodes_list, c_dict)
                    stress_list.append({'coor': coordinate, 'stress': stress})
                else:
                    pass
        else:
            pass
    best_coordinate = min(stress_list, key=lambda coordinate: coordinate['stress'])['coor']
    return best_coordinate

def overlaps_Any(circle, nodes_list):
    overlaps = False
    index = 0
    while not overlaps and index < len(nodes_list):
        #print('iteration ' + str(index))
        #print('Calculate individual overlaping')
        new_circle = {'x': nodes_list[index]['coor'][0], 'y': nodes_list[index]['coor'][1], 'r': nodes_list[index]['radius']}
        overlaps = do_Overlaps(circle, new_circle)
        index += 1
    return overlaps

def pairs_Nodes(nodes_list): # order-independent combinaton without repetition
    pairs_list  = []
    for n1 in nodes_list:
        for n2 in nodes_list:
            if n1['id'] > n2['id']:
                pairs_list.append((n1, n2))
    return pairs_list

def do_Overlaps(c_1, c_2): # if overlaps return true
    x1 = c_1['x']
    x2 = c_2['x']
    y1 = c_1['y']
    y2 = c_2['y']
    r1 = c_1['r']
    r2 = c_2['r']
    #print(c_1)
    #print(c_2)
    circles_distance = math.sqrt((x2-x1)**2 + (y2-y1)**2)
    sum_radius = r1 + r2
    overlaps = sum_radius > circles_distance
    #print(overlaps)
    return overlaps

def coor_Inter(c_1, c_2): # intersection points between circles
    # reference: https://math.stackexchange.com/questions/256100/how-can-i-find-the-points-at-which-two-circles-intersect
    # https://gist.github.com/jupdike/bfe5eb23d1c395d8a0a1a4ddd94882ac
    x1 = c_1['x']
    x2 = c_2['x']
    y1 = c_1['y']
    y2 = c_2['y']
    r1 = c_1['r']
    r2 = c_2['r']
    R2 = (x2-x1)**2 + (y2-y1)**2
    R4 = R2**2
    r2r2 = r1**2 - r2**2
    a = r2r2 / (2 * R2)
    c = math.sqrt(2 * (r1**2 + r2**2) / R2 - (r2r2) / R4 - 1)
    fx = (x1+x2) / 2 + a * (x2 - x1)
    gx = c * (y2 - y1) / 2
    ix1 = fx + gx
    ix2 = fx - gx
    fy = (y1+y2) / 2 + a * (y2 - y1)
    gy = c * (x1 - x2) / 2
    iy1 = fy + gy
    iy2 = fy - gy
    int_coordinates = [(ix1, iy1), (ix2, iy1)]
    return int_coordinates

def node_Stress(nid, x1, y1, nodes_list, c_dict): # stress of a node against the graph
    stress = 0
    for p_n in nodes_list:
        p_nid = p_n['id']
        if nid != p_nid:
            x2 = p_n['coor'][0]
            y2 = p_n['coor'][1]
            R2 = (x2-x1)**2 + (y2-y1)**2
            n_edges = c_dict[nid][p_nid]
            stress += n_edges*R2
    return stress

def solution_Stress(nodes_list, c_dict): # total stress of the graph
    solution_stress = 0
    for node in nodes_list:
        node_stress = node_Stress(node['id'], node['coor'][0], node['coor'][1], nodes_list, c_dict)
    solution_stress = solution_stress / 2
    return solution_stress