import os
from flask import Flask,session,flash, render_template,redirect, url_for, json, request,jsonify
import random
from flaskext.mysql import MySQL
from flask_cors import CORS, cross_origin
from werkzeug.utils import secure_filename
#from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__,static_folder='static', static_url_path='/static')

APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT,'static/img/cats')
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

CORS(app, origins='*')
mysql = MySQL(app)
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'bfc1f7492709c0'
app.config['MYSQL_DATABASE_PASSWORD'] = '42121e97'
app.config['MYSQL_DATABASE_DB'] = 'ad_1fde3f7e20bc37f'
app.config['MYSQL_DATABASE_HOST'] = 'us-cdbr-iron-east-03.cleardb.net'
mysql.init_app(app)

#FUNÇÃO PARA VERIFICAR SE O ARQUIVO É VALIDO
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#-------------------------------------------------------------------------------------------------------------
#FUNÇÃO PARA LISTAR TODAS AS CATEGORIAS
def lista_categorias():
	con=mysql.connect()
	cursor=con.cursor()
	cursor.execute("SELECT nome from categorias")
	categorias=cursor.fetchall()
	cursor.close()
	return categorias
#-------------------------------------------------------------------------------------------------------------
def lista_anuncios():
	con=mysql.connect()
	cursor=con.cursor()
	cursor.execute("SELECT categoria,expiracao,texto_tras,imagem_frente FROM anuncios order by expiracao ASC")
	anuncios=cursor.fetchall()
	cursor.close()
	con.close()
	return anuncios
#--------------------------------------------------------------------------------------------------------------
# Rota Index
@app.route('/')
def index():
	if session.get('logado') == True:
		return redirect(url_for("admin"))
	return render_template("login.html")
#-------------------------------------------------------------------------------------------------------------
# Rota Logout
@app.route('/logout')
def logout():
    session.pop('logado', None)
    return redirect(url_for('index'))
#-------------------------------------------------------------------------------------------------------------
# Rota Login
@app.route('/login',methods=['POST'])
def login():
	usr=str(request.form['user'])
	psw=str(request.form['password'])
	con=mysql.connect()
	cursor=con.cursor()
	cursor.execute("SELECT usuario,senha from usuarios WHERE usuario ='"+usr+"'")
	user=cursor.fetchall()
	con.close()

	if len(user) is 1:
		if (str(user[0][1])==psw):
			session['logado']=True #Setando a sessão
			return redirect(url_for("admin"))
		else:
			return "falhou"
	else:
		return "Usuario invalido"
#-------------------------------------------------------------------------------------------------------------
#Rota página Admin
@app.route('/admin')
def admin():
	if session.get('logado') != True:
		return redirect(url_for("index"))
	categorias = lista_categorias()
	return render_template("admin.html",categorias=categorias)
#-------------------------------------------------------------------------------------------------------------
#Rota lista anuncio
@app.route('/listar-anuncio')
def listanunc():
	if session.get('logado') != True:
		return redirect(url_for("index"))
	anuncios = lista_anuncios()
	return render_template("listar-anuncio.html",anuncios=anuncios)
#-------------------------------------------------------------------------------------------------------------
#Rota lista cliente
@app.route('/listar-cliente')
def listacliente():
	if session.get('logado') != True:
		return redirect(url_for("index"))
	return render_template("listar-cliente.html")
#-------------------------------------------------------------------------------------------------------------
#Rota lista categoria
@app.route('/listar-categoria')
def listacategoria():
	if session.get('logado') != True:
		return redirect(url_for("index"))
	categorias = lista_categorias()
	return render_template("listar-categoria.html", categorias=categorias)

#-------------------------------------------------------------------------------------------------------------
#Função cadastrar cliente
@app.route('/cadcliente',methods=['POST'])
def cadcliente():
	razao=str(request.form['razao'])
	cnpj=str(request.form['cnpj'])
	tel=str(request.form['telefone'])
	email=str(request.form['email'])
	resp=str(request.form['responsavel'])
	con=mysql.connect()
	cursor=con.cursor()
	try:
		cursor.callproc('cadcliente',(razao,cnpj,tel,email,resp))
		con.commit()
		flash('Cliente inserido com sucesso!')
	except:
		con.rollback()
		flash('Cliente não inserido!')
	cursor.close()
	con.close()

	return redirect(url_for("admin"))
#-------------------------------------------------------------------------------------------------------------
#FUNÇÃO CADASTRAR ANUNCIOS
@app.route('/cadanuncio',methods=['POST'])
def cadanuncio():
	categoria=str(request.form['categoria'])
	expiracao=request.form['expiracao']
	descricao = str(request.form['descricao'])
	img=request.files['imagem']
	name=str(random.randrange(1,1000000))+".png"
	img.save(os.path.join(app.config['UPLOAD_FOLDER'],name))
	con=mysql.connect()
	cursor=con.cursor()
	try:
		cursor.callproc('cadanuncio',(categoria,expiracao,descricao,name))
		con.commit()
		flash('Anuncio inserido com sucesso!')
	except:
		con.rollback()
		flash('Anuncio não inserido!')
	cursor.close()
	con.close()

	return redirect(url_for("admin"))

#------------------------------------------------------------------------------------------------------------
#Função cadastrar categoria
@app.route('/cadcat',methods=['POST'])
def cadcat():
	cate=request.form['cat']
	con=mysql.connect()
	cursor=con.cursor()
	try:
		cursor.callproc('cadcat',[cate,])
		con.commit()
		flash('Categoria inserida com sucesso!')
	except (ValueError, KeyError, TypeError) as error:
	    con.rollback()
	    flash(error)
	cursor.close()
	con.close()

	return redirect(url_for("admin"))
#-------------------------------------------------------------------------------------------------------------
@app.route('/tst')
def viewteste():
	return render_template("teste2.html")
#-------------------------------------------------------------------------------------------------------------
@app.route('/teste',methods=['POST'])
def testeimg():
	img=request.files['imagem']
	name=str(random.randrange(1,1000000))+".png"
	img.save(os.path.join(app.config['UPLOAD_FOLDER'],name))
	teste = print(img)
	return "blablabla"
#-------------------------------------------------------------------------------------------------------------
#API retorna os anuncios da HOME
@app.route('/api/home')
def home():
	tipo=request.args.get("tipo")
	con=mysql.connect()
	cursor=con.cursor()
	cursor.callproc('ListaIndex',(tipo,))
	ret = cursor.fetchall()
	anuncios=[]
	for anuncio in ret:
		i={
			'id':anuncio[0],
			'imagem':anuncio[1],
			'texto':anuncio[2],
			'categoria':anuncio[3]
		}
		anuncios.append(i)
	return jsonify(anuncios)
#-------------------------------------------------------------------------------------------------------------
# API Retorna os anuncios da categoria
@app.route('/api/list', methods=['GET'])
def list():

	cat = request.args.get("categoria")
	con=mysql.connect()
	cursor=con.cursor()
	cursor.callproc('ListaAnuncios',(cat,))
	categorias = cursor.fetchall()
	anuncios=[]
	for anuncio in categorias:
		i={
			'id':anuncio[0],
			'imagem':anuncio[1],
			'texto':anuncio[2],
			'categoria':anuncio[3]
		}
		anuncios.append(i)
	return jsonify(anuncios)
#-------------------------------------------------------------------------------------------------------------
# API Retorna todas as categorias
@app.route('/api/categorias',methods=['POST'])
def list_cats():
	con=mysql.connect()
	cursor=con.cursor()
	cursor.callproc('ListaCategorias')
	list_categorias = cursor.fetchall()
	cat=[]
	for nome in list_categorias:
		i={
			'nome':nome[0]
		}
		cat.append(i)
	return jsonify(cat)
#-------------------------------------------------------------------------------------------------------------

if __name__ == '__main__':
	app.config['SECRET_KEY'] = "koakoakoqews"
	port = int(os.environ.get('PORT', 5000))
	#app.debug= True
	#toolbar = DebugToolbarExtension(app)
	app.run(host='127.0.0.1', port=port)  #usar se for testar localmente
	#app.run(host='0.0.0.0', port=port)	#usar no herokuc


import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
import ssl
import json

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter location: ')
if len(url) < 1:
  url = 'http://py4e-data.dr-chuck.net/comments_42.json'
print('Retrieving', url)
uh = urllib.request.urlopen(url, context=ctx)
data = uh.read().decode()
print('Retrieved', len(data), 'characters')
js = json.loads(data)
sum = 0
counts = len(js['comments'])
print('Count:', counts)
for i in range(counts):
  sum += js['comments'][i]['count']
print('Sum:', sum)


from pathlib import Path
import pytest
import yaml

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from shopping_cart import data_model as m
from shopping_cart.store.operations import populate

directory = Path(__file__).parent

@pytest.fixture(name="session")
def make_store_session():
    """
    Make a new empty store database session

    """
    engine = create_engine('sqlite://')
    session = sessionmaker(bind=engine)()
    m.Base.metadata.create_all(engine)
    yield session
    session.close()

@pytest.fixture(name="product")
def make_product():
    """
    Pytest fixture to generate a product instance

    """

    def _generate(
            product_id: int,
            name: str,
            price: float
    ):
        return m.Product(
            id=product_id,
            name=name,
            unit_price=price
        )

    return _generate

@pytest.fixture(name="store")
def make_store_database(session):
    """
    Pytest fixture to add list of products
    to the store database from a mock store configuration

    """

    with open(directory / "mock_data/store.yaml") as f:
        product_dict = yaml.safe_load(f)

    populate(
        product_dict,
        session
    )

    return session


# This file is part of pyunicorn.
# Copyright (C) 2008--2023 Jonathan F. Donges and pyunicorn authors
# URL: <http://www.pik-potsdam.de/members/donges/software>
# License: BSD (3-clause)
#
# Please acknowledge and cite the use of this software and its authors
# when results are used in publications or published elsewhere.
#
# You can use the following reference:
# J.F. Donges, J. Heitzig, B. Beronov, M. Wiedermann, J. Runge, Q.-Y. Feng,
# L. Tupikina, V. Stolbova, R.V. Donner, N. Marwan, H.A. Dijkstra,
# and J. Kurths, "Unified functional network and nonlinear time series analysis
# for complex systems science: The pyunicorn package"

"""
Simple tests for the timeseries class.
"""

import numpy as np
from numpy.testing import assert_array_almost_equal

from pyunicorn.timeseries import CrossRecurrencePlot, VisibilityGraph, \
    Surrogates
from pyunicorn.core.data import Data
from pyunicorn.core._ext.types import DFIELD

# turn off for weave compilation & error detection
parallel = False

def create_test_data():
    # Create test time series
    tdata = Data.SmallTestData().observable()
    n_index, n_times = tdata.shape
    # subtract means form the input data
    tdata -= np.mean(tdata, axis=1)[:, None]
    # normalize the data
    tdata /= np.sqrt(np.sum(tdata*tdata, axis=1))[:, None]
    return tdata

# -----------------------------------------------------------------------------
# cross_recurrence_plot
# -----------------------------------------------------------------------------

def testCrossRecurrencePlot():
    tdata = create_test_data()
    CrossRecurrencePlot(x=tdata, y=tdata, threshold=0.2)

def testDistanceMatrix():
    tdata = create_test_data()
    crp = CrossRecurrencePlot(x=tdata, y=tdata, threshold=1.0)
    crp.distance_matrix(tdata.T, tdata.T, metric='manhattan')

def testManhattanDistanceMatrix():
    tdata = create_test_data()
    n_index, n_times = tdata.shape
    crp = CrossRecurrencePlot(x=tdata, y=tdata, threshold=1.0)
    manh_dist_1 = crp.manhattan_distance_matrix(tdata.T, tdata.T)
    manh_dist_2 = crp.manhattan_distance_matrix(tdata.T, tdata.T)
    assert np.allclose(manh_dist_1, manh_dist_2, atol=1e-04)

def testEuclideanDistanceMatrix():
    tdata = create_test_data()
    n_index, n_times = tdata.shape
    crp = CrossRecurrencePlot(x=tdata, y=tdata, threshold=1.0)
    eucl_dist_1 = crp.euclidean_distance_matrix(tdata.T, tdata.T)
    eucl_dist_2 = crp.euclidean_distance_matrix(tdata.T, tdata.T)
    assert np.allclose(eucl_dist_1, eucl_dist_2, atol=1e-04)

def testSupremumDistanceMatrix():
    tdata = create_test_data()
    n_index, n_times = tdata.shape
    crp = CrossRecurrencePlot(x=tdata, y=tdata, threshold=1.0)
    supr_dist_1 = crp.supremum_distance_matrix(tdata.T, tdata.T)
    supr_dist_2 = crp.supremum_distance_matrix(tdata.T, tdata.T)
    assert np.allclose(supr_dist_1, supr_dist_2, atol=1e-04)

# -----------------------------------------------------------------------------
# surrogates
# -----------------------------------------------------------------------------

def testNormalizeTimeSeriesArray():
    ts = Surrogates.SmallTestData().original_data
    Surrogates.SmallTestData().normalize_time_series_array(ts)
    res = ts.mean(axis=1)
    exp = np.array([0., 0., 0., 0., 0., 0.])
    assert np.allclose(res, exp, atol=1e-04)

    res = ts.std(axis=1)
    exp = np.array([1., 1., 1., 1., 1., 1.])
    assert np.allclose(res, exp, atol=1e-04)

def testEmbedTimeSeriesArray():
    ts = Surrogates.SmallTestData().original_data
    res = Surrogates.SmallTestData().embed_time_series_array(
        time_series_array=ts, dimension=3, delay=2)[0, :6, :]
    exp = np.array([[0., 0.61464833, 1.14988147],
                    [0.31244015, 0.89680225, 1.3660254],
                    [0.61464833, 1.14988147, 1.53884177],
                    [0.89680225, 1.3660254, 1.6636525],
                    [1.14988147, 1.53884177, 1.73766672],
                    [1.3660254, 1.6636525, 1.76007351]])
    assert np.allclose(res, exp, atol=1e-04)

def testWhiteNoiseSurrogates():
    ts = Surrogates.SmallTestData().original_data
    surrogates = Surrogates.SmallTestData().white_noise_surrogates(ts)

    assert(np.allclose(np.histogram(ts[0, :])[0],
                       np.histogram(surrogates[0, :])[0]))

def testCorrelatedNoiseSurrogates():
    ts = Surrogates.SmallTestData().original_data
    surrogates = Surrogates.SmallTestData().correlated_noise_surrogates(ts)
    assert np.allclose(np.abs(np.fft.fft(ts, axis=1))[0, 1:10],
                       np.abs(np.fft.fft(surrogates, axis=1))[0, 1:10])

def testTwinSurrogates():
    tdata = create_test_data()
    n_index, n_times = tdata.shape
    s = Surrogates(tdata)
    tsurro = s.twin_surrogates(tdata, 1, 0, 0.2)
    corrcoef = np.corrcoef(tdata, tsurro)[n_index:, :n_index]
    for i in range(n_index):
        corrcoef[i, i] = 0.0
    assert (corrcoef >= -1.0).all() and (corrcoef <= 1.0).all()

def testPearsonCorrelation():
    tdata = create_test_data()
    n_index, n_times = tdata.shape
    norm = 1.0 / float(n_times)
    c = Surrogates.test_pearson_correlation(tdata, tdata)
    corrcoef = np.corrcoef(tdata, tdata)[n_index:, :n_index]*norm
    for i in range(n_index):
        corrcoef[i, i] = 0.0

    assert c.shape == (n_index, n_index)
    assert_array_almost_equal(c, corrcoef, decimal=5)

def testMutualInformation():
    tdata = create_test_data()
    test_mi = Surrogates.test_mutual_information(tdata[:1], tdata[-1:],
                                                 n_bins=32)
    assert (test_mi >= -1.0).all() and (test_mi <= 1.0).all()

# -----------------------------------------------------------------------------
# visibility_graph
# -----------------------------------------------------------------------------

def create_test_timeseries():
    """
    Return test time series including random values and timings
    with 10 sampling points.

    :rtype: 2D array
    :return: a timeseries for testing purposes
    """
    #  Create time series
    ts = np.zeros((2, 10))

    for i in range(2):
        ts[i, :] = np.random.rand(10)

    ts[1, :].sort()

    return ts

# def testVisibility():
#     x, t = create_test_timeseries()
#     n_times = len(t)
#     vg = VisibilityGraph(x, timings=t)
#     # Choose two different, not neighbouring random nodes i, j
#     node1, node2 = 0, 0
#     while (abs(node2-node1)<=1):
#         node1 = np.int32(np.floor(np.random.rand()*n_times))
#         node2 = np.int32(np.floor(np.random.rand()*n_times))

#     # the following returns incorrect results, assertion therefore failing
#     i, j = min(node1, node2), max(node1, node2)
#     test = np.zeros((j-(i+1)))
#     for k in range(i+1,j):
#         test[k-(i+1)] = np.less((x[k]-x[i]) / (t[k]-t[i]),
#                                 (x[j]-x[i]) / (t[j]-t[i]))

#     assert np.invert(bool(np.sum(test))) == vg.visibility(node1, node2)

def testVisibility():
    x, t = create_test_timeseries()
    vg = VisibilityGraph(x, timings=t)
    A = vg.adjacency

    assert A.shape == (len(x), len(x))
    assert A.dtype == np.int16

def testVisibilityHorizontal():
    x, t = create_test_timeseries()
    vg = VisibilityGraph(x, timings=t, horizontal=True)
    A = vg.adjacency

    assert A.shape == (len(x), len(x))
    assert A.dtype == np.int16

def testRetardedLocalClustering():
    x, t = create_test_timeseries()
    vg = VisibilityGraph(x, timings=t)
    C_ret = vg.retarded_local_clustering()

    assert C_ret.shape == x.shape
    assert C_ret.dtype == DFIELD

def testAdvancedLocalClustering():
    x, t = create_test_timeseries()
    vg = VisibilityGraph(x, timings=t)
    C_adv = vg.advanced_local_clustering()

    assert C_adv.shape == x.shape
    assert C_adv.dtype == DFIELD


import pygame
from Settings import Settings
from Ship import Ship
from Bullet import Bullet
from pygame.sprite import Group

class Game():
    def __init__(self):
        """Initialize game."""

        self.settings = Settings()
        self.initScreen()

        self.ship = Ship(self.screen)

        self.bullets = Group()

        # Startup app sound
        pygame.mixer.music.load('sounds/start.mp3')
        pygame.mixer.music.play(0)

    def draw(self):
        # Draw Background & a rectangle
        self.screen.fill(self.settings.bg_color)
        pygame.draw.rect(self.screen, (60, 60, 180), self.small_screen_rect )

        # Draw Ship
        self.ship.draw()

        for bullet in self.bullets:
            bullet.draw()

        # Make the most recently Drawn screen visible.
        pygame.display.flip()

    def update(self):
        # Draw Background
        self.ship.update()
        for bullet in self.bullets:
            bullet.update()

        for bullet in self.bullets.copy():  # .copy() is used in order to use bullets.remove above
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

    def processKeyDown(self, key):
        if key == pygame.K_RIGHT:
            self.ship.moveRight(True)
        if key == pygame.K_LEFT:
            self.ship.moveLeft(True)
        if key == pygame.K_SPACE:
            new_bullet = Bullet(self.settings, self.screen, self.ship)
            self.bullets.add(new_bullet)

    def processKeyUp(self, key):
        if key == pygame.K_RIGHT:
            self.ship.moveRight(False)
        if key == pygame.K_LEFT:
            self.ship.moveLeft(False)

    def initScreen(self):
        self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
        self.screen_rect = self.screen.get_rect()
        self.small_screen_rect = pygame.Rect(30, 30, self.settings.screen_width - 60, self.settings.screen_height - 60 )


import torch
import torch.nn as nn
import torch.nn.functional as F

class AlexNet(nn.Module):
    def __init__(self):
        super(AlexNet, self).__init__()
        # convolution part
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=96, kernel_size=11, stride=4, padding=0)
        self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2)
        self.conv2 = nn.Conv2d(in_channels =96, out_channels=256, kernel_size=5, stride=1, padding=2)
        self.pool2 = nn.MaxPool2d(kernel_size=3, stride=2)
        self.conv3 = nn.Conv2d(in_channels =256, out_channels=384, kernel_size=3, stride=1, padding=1)
        self.conv4 = nn.Conv2d(in_channels =384, out_channels=384, kernel_size=3, stride=1, padding=1)
        self.conv5 = nn.Conv2d(in_channels =384, out_channels=256, kernel_size=3, stride=1, padding=1)
        self.pool3 = nn.MaxPool2d(kernel_size=3, stride=2)
        # dense part
        self.fc1 = nn.Linear(in_features=9216, out_features = 4096)
        self.dropout1 = nn.Dropout(0.5)
        self.fc2 = nn.Linear(in_features=4096, out_features = 4096)
        self.dropout2 = nn.Dropout(0.5)
        self.fc3 = nn.Linear(in_features=4096, out_features=1000)

    def forward(self, image):
        # get the batch size, channels, height and width
        # original size (bs, 3, 227, 227)
        bs, c, h, w = image.size()
        x = F.relu(self.conv1(image)) # size (bs, 96, 55, 55) ((w-f+2p)/s) + 1)
        x = self.pool1(x) # (bs, 96, 27, 27) ((w-f+2p)/s) + 1)
        x = F.relu(self.conv2(x)) # size (bs, 256, 27, 27
        x= self.pool2(x) # size (bs, 256, 13, 13)
        x = F.relu(self.conv3(image)) # size (bs, 384, 13, 13)
        x = F.relu(self.conv4(image)) # size (bs, 384, 13, 13)
        x = F.relu(self.conv5(image)) # size (bs, 256, 13, 13)
        x = self.pool3(x) # size (bs, 256, 6, 6)
        x = x.view(bs, -1) # size (bs, 9216)
        x = F.relu(self.fc1(x)) # size (bs, 4096)
        x = self.dropout1(x) # size (bs, 4096)
        x = self.fc2(x) # size (bs, 4096)
        x = self.dropout2(x) # size (bs, 4096)
        x = F.relu(self.fc3(x)) # size (bs, 1000)
        # 1000 is number of classes in ImageNet dataset
        # softmax is an activation function that converts linear output to praobabilities that add upto 1
        # for each sample in the batch
        x = torch.softmax(x, axis=1) # size (bs, 1000)
        return x


import numpy as np
from classes.basic_classes import DatasetType, DataSet
from typing import NamedTuple
import torch
import os.path as osp
from torch_geometric.datasets import Planetoid

import sys
sys.path.append("../")
from rgnn.utils import sparse_tensor

# run command for 2nd paper:
"""
python experiment_train.py with "dataset=pubmed" "seed=5" "model_params={\"label\": \"Soft Medoid GDC (T=1.0)\", \"model\": \"RGNN\", \"do_cache_adj_prep\": True, \"n_filters\": 64, \"dropout\": 0.5, \"mean\": \"soft_k_medoid\", \"mean_kwargs\": {\"k\": 32, \"temperature\": 1.0}, \"svd_params\": None, \"jaccard_params\": None, \"gdc_params\": {\"alpha\": 0.15, \"k\": 32}}" "artifact_dir=cache" "binary_attr=False"
"""

import sys
sys.path.append("../code")
from helpers.getGitPath import getGitPath

class Masks(NamedTuple):
    train: torch.tensor
    val: torch.tensor
    test: torch.tensor

def loadDataset(dataset, device):
        dataset_path = osp.join(getGitPath(), 'datasets')

        if type(dataset) == type(""):
            if dataset == "pubmed":
                dataset = DataSet.PUBMED
            else:
                raise(Exception("Unrecognized dataset name: {}".format(dataset)))

        if dataset is DataSet.PUBMED or dataset is DataSet.CORA or dataset is DataSet.CITESEER:
            dataset = Planetoid(dataset_path, dataset.string())
        elif dataset is DataSet.TWITTER:
            twitter_glove_path = osp.join(dataset_path, 'twitter', 'glove.pkl')
            if not osp.exists(twitter_glove_path):
                quit("Go to README and follow the download instructions to the TWITTER dataset")
            else:
                dataset = TwitterDataset(osp.dirname(twitter_glove_path))
                with open(twitter_glove_path, 'rb') as file:
                    glove_matrix = pickle.load(file)
                self.glove_matrix = torch.tensor(glove_matrix, dtype=torch.float32).to(device)

        data = dataset[0].to(device)
        setattr(data, 'num_classes', dataset.num_classes)

        return data, dataset.num_classes, dataset.num_features

def GetPrepGraph(dataset_name, device):
    """
    Calculates the properties returned by prep_graph from Ben-style dataset
    """
    dataset_path = osp.join(getGitPath(), 'datasets')
    dataset_string = {"pubmed" : "PubMed"}[dataset_name]

    dataset = Planetoid(dataset_path, dataset_string)

    n_vertices = dataset.data.to_dict()['y'].shape[0]

    adj_matrix = torch.zeros((n_vertices, n_vertices))
    edges = dataset.data.to_dict()['edge_index']
    for e in edges.t():
        adj_matrix[e[0], e[1]] = 1

    ### HAVE n_vertices, adj_matrix

    attr = dataset.data.to_dict()['x']
    labels = dataset.data.to_dict()['y']

    # adj_sparse = sparse_tensor(adj_matrix.tocoo())

    adj_sparse = torch.sparse_coo_tensor(edges, torch.ones(edges.shape[1]),
     size=(n_vertices,n_vertices), dtype=torch.uint8)

    return attr.to(device), adj_sparse.coalesce().to(device), labels.to(device)

def Get_Masks(dataset):
    if hasattr(dataset, 'train_mask') and hasattr(dataset, 'val_mask') and hasattr(dataset, 'test_mask'):
        masks = Masks(dataset.train_mask, dataset.val_mask, dataset.test_mask)
        train_mask = [idx for idx in range(masks.train.shape[0]) if masks.train[idx]]
        val_mask = [idx for idx in range(masks.val.shape[0]) if masks.val[idx]]
        test_mask = [idx for idx in range(masks.test.shape[0]) if masks.test[idx]]
        # print(train_mask)

        # print(val_mask)

        # print(test_mask)
        # input("wait Get_Masks")

        return masks
    else:
        raise NotImplementedError("The current datadet doesn't have default masking")


from feedReader.models import SiteInfo
import feedparser
import hashlib
from feedReader.mongoFunctions import Mongo
from time import mktime
from datetime import datetime
from django.utils.html import strip_tags
import time
from bs4 import BeautifulSoup
#from urllib2 import Request, urlopen
import urllib3
import re

class ParsingFuncs:

    '''
    Contains all functions to get and parse the feeds
    '''

    def __init__(self):
        '''
        Initialise mongodb connection
        '''
        self.mongo = Mongo()

    def fetchFeeds(self):
        '''
        Fetches all the entries in the table siteInfo and fetches its feeds ..
        Stores to the database
        '''
        siteList = SiteInfo.objects.all()
        for site in siteList:
            modifiedStr = self.createLastModifiedStr(site.lastModified, site.etag)
            if modifiedStr is not None:
                feeds = feedparser.parse(site.feedUrl, modifiedStr)
            else:
                feeds = feedparser.parse(site.feedUrl)
            # find the last modified date. This value will be in feed.updated, feed.last_modified
            lastModified = self.findLastModifiedDate(feeds.feed)
            try:
                etag = feeds.feed.etag
            except:
                etag = None

            feedsHash = self.md5Feeds(feeds)  # calculating the hash of entire feeds
            if(site.feedHash == feedsHash):
                continue  # if no change in feeds ignore it.
            site.feedHash = feedsHash  # if changed save it in db
            if etag is None:
                site.lastModified = lastModified
            else:
                site.etag = etag
            site.save()
            for entry in feeds.entries:
                dt = datetime.fromtimestamp(mktime(entry.published_parsed))  # the format of published_parsed is not..
                entry['published_parsed'] = dt                              # compactible with mongodb
                try:
                    mediaContnet = entry['media_content']
                except:
                    mediaContnet = None
                try:
                    content = entry['content'][0]['value']
                except:
                    content = None
                entry['image_link'] = self.getImage(media_content=mediaContnet,
                                                    summary=entry['summary'],
                                                    content=content,
                                                    link=entry['link'])
                self.mongo.insertFeeds(entry, site.id)

    def allFeeds(self,user_id, lastDate=None):
        if lastDate is not None:
            return self.mongo.selectFeeds(user_id=user_id,dateOfLastItem=lastDate)
        return self.mongo.selectFeeds(user_id=user_id)

    def md5Feeds(self, feed):
        '''
        find md5 of feed
        '''
        md5 = hashlib.md5(str(feed).encode('utf-8'))
        return md5.hexdigest()

    def selectFeedById(self, id):
        return self.mongo.selectFeedById(id)

    def getSiteTitle(self, siteId):
        siteObject = SiteInfo.objects.filter(id=siteId)
        for site in siteObject:
            return site.title

    def getSummary(self, summary):
        summary1000wds = strip_tags(summary)
        summary1000wds = summary1000wds[:300] + "..."
        return summary1000wds

    def getFullPost(self, summaryDetail):
        post = strip_tags(summaryDetail)
        return post

    def createLastModifiedStr(self, last_modified=None, etag=None):
        modiStr = None
        if etag is not None:
            modiStr = "etag = " + str(etag)
        if last_modified is not None:
            modiStr = "modified = " + str(last_modified.utctimetuple())
        return modiStr

    def findLastModifiedDate(self, feed):
        try:
            last_modified = datetime.fromtimestamp(mktime(feed.updated_parsed))  # if updated date is present
        except:
            try:
                last_modified = datetime.fromtimestamp(mktime(feed.date_parsed))  # if date field is present
            except:
                try:
                    # if published_parsed is present
                    last_modified = datetime.fromtimestamp(mktime(feed.published_parsed))
                except:
                    structTime = time.localtime()
                    last_modified = datetime(*structTime[:6])
        return last_modified

    def getFullPostURLOpen(self, link, summary):
        http = urllib3.PoolManager()
        #req = Request(link, headers={'User-Agent': "ireadr"})
        try:
            page = http.request('GET', link)
            page = page.data
            #page = urlopen(req)
        except:
            page = None
        if page is not None:
            soup = BeautifulSoup(page)
            summary = summary[:25]
            # modify this like check match for entire summary.
            #if not found find a substring of length 50 and check again
            # if again not found then reduce the length and try again
            element = soup.find(text=re.compile(summary))
            post = element.findParent('div')
            return post
        return None

    def findImgsrcFromHtml(self, content):
        soup = BeautifulSoup(content)
        img_links = soup.findAll('img')
        if len(img_links) > 0:
            for link in img_links:
                try:
                    if link['height'] == '1' or link['width'] == '1':
                        continue
                    else:
                        return (link['src'])
                except:
                    return (link['src'])
        return None

    def getImage(self, media_content=None, summary=None, content=None, link=None):
        if media_content is not None:
            return (media_content[0]['url'])
        # if media_content is None
        if summary is not None:
            return (self.findImgsrcFromHtml(summary))
        # if no matching image is found in summary
        if content is not None:
            return (self.findImgsrcFromHtml(content))
        # if image is not found in content then fetch the original page and extract the image
        if link is not None:
            post = self.getFullPostURLOpen(link, summary)
            if post is not None:
                return(self.findImgsrcFromHtml(post))
        return None


import datetime
from odoo import models, fields, http, api
from odoo.http import request
from odoo.addons.website.models.ir_http import sitemap_qs2dom
from odoo.osv.expression import FALSE_DOMAIN
SITEMAP_CACHE_TIME = datetime.timedelta(hours=12)
LOC_PER_SITEMAP = 45000

class Website(models.Model):
    _inherit = "website"

    @api.multi
    def enumerate_pages_2(self, query_string=None, force=False):
        """ Available pages in the website/CMS. This is mostly used for links
            generation and can be overridden by modules setting up new HTML
            controllers for dynamic pages (e.g. blog).
            By default, returns template views marked as pages.
            :param str query_string: a (user-provided) string, fetches pages
                                     matching the string
            :returns: a list of mappings with two keys: ``name`` is the displayable
                      name of the resource (page), ``url`` is the absolute URL
                      of the same.
            :rtype: list({name: str, url: str})
        """

        router = request.httprequest.app.get_db_router(request.db)
        # Force enumeration to be performed as public user
        url_set = set()

        sitemap_endpoint_done = set()

        for rule in router.iter_rules():
            if 'sitemap' in rule.endpoint.routing:
                if rule.endpoint in sitemap_endpoint_done:
                    continue
                sitemap_endpoint_done.add(rule.endpoint)

                func = rule.endpoint.routing['sitemap']
                if func is False:
                    continue
                for loc in func(self.env, rule, query_string):
                    new_loc = self.check_loc(loc)
                    if new_loc:
                        yield new_loc
                continue

            if not self.rule_is_enumerable(rule):
                continue

            converters = rule._converters or {}
            if query_string and not converters and (query_string not in rule.build([{}], append_unknown=False)[1]):
                continue
            values = [{}]
            # converters with a domain are processed after the other ones
            convitems = sorted(
                converters.items(),
                key=lambda x: (hasattr(x[1], 'domain') and (x[1].domain != '[]'), rule._trace.index((True, x[0]))))

            for (i, (name, converter)) in enumerate(convitems):
                newval = []
                for val in values:
                    query = i == len(convitems) - 1 and query_string
                    if query:
                        r = "".join([x[1] for x in rule._trace[1:] if not x[0]])  # remove model converter from route
                        query = sitemap_qs2dom(query, r, self.env[converter.model]._rec_name)
                        if query == FALSE_DOMAIN:
                            continue
                    for value_dict in converter.generate(uid=self.env.uid, dom=query, args=val):
                        newval.append(val.copy())
                        value_dict[name] = value_dict['loc']
                        del value_dict['loc']
                        newval[-1].update(value_dict)
                values = newval

            for value in values:
                domain_part, url = rule.build(value, append_unknown=False)
                if not query_string or query_string.lower() in url.lower():
                    page = {'loc': url}
                    for key, val in value.items():
                        if key.startswith('__'):
                            page[key[2:]] = val
                    if url in ('/sitemap.xml',):
                        continue
                    if url in url_set:
                        continue
                    url_set.add(url)
                    new_loc = self.check_loc(page)
                    if new_loc:
                        yield new_loc

        # '/' already has a http.route & is in the routing_map so it will already have an entry in the xml
        domain = [('url', '!=', '/')]
        if not force:
            domain += [('website_indexed', '=', True)]
            # is_visible
            domain += [('website_published', '=', True), '|', ('date_publish', '=', False),
                       ('date_publish', '<=', fields.Datetime.now())]

        if query_string:
            domain += [('url', 'like', query_string)]

        pages = self.get_website_pages(domain)

        for page in pages:

            record = {'loc': page['url'], 'id': page['id'], 'name': page['name']}
            if page.view_id and page.view_id.priority != 16:
                record['__priority'] = min(round(page.view_id.priority / 32.0, 1), 1)
            if page['write_date']:
                record['__lastmod'] = page['write_date'].date()

            new_loc = self.check_loc(record)
            if new_loc:
                yield new_loc

    def check_loc(self, data):
        # Exclude
        if self and self.sitemap_exclude_urls:
            urls = self.sitemap_exclude_urls.split('\n')
            urls = [x.strip() for x in urls if x.strip()]
            if data['loc'] in urls:
                return False
        return data


# -*- coding: utf-8 -*-
import argparse, json, sys, re, os, datetime, struct, copy, pylab

kAuPerAngstrom = 1.8897259885789
kPsecPerAu = 2.418884326505e-5  # Time

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='')
    parser.add_argument('eigenvalue_vs_ipratio_paths', metavar='JSON', type=str, nargs='+',
                        help='')
    parser.add_argument('--xmin', metavar='XMIN', dest='x_min', type=float, default=None,
                        help='')
    parser.add_argument('--xmax', metavar='XMAX', dest='x_max', type=float, default=None,
                        help='')
    parser.add_argument('--ymin', metavar='YMIN', dest='y_min', type=float, default=None,
                        help='')
    parser.add_argument('--ymax', metavar='YMAX', dest='y_max', type=float, default=None,
                        help='')
    parser.add_argument('-t', metavar='TITLE', dest='title', type=str, default='',
                        help='')
    parser.add_argument('-s', metavar='TIME_START', dest='time_start', type=float, default=None,
                        help='')  # in ps.
    parser.add_argument('-e', metavar='TIME_END', dest='time_end', type=float, default=None,
                        help='')  # in ps.
    parser.add_argument('-o', metavar='OUT', dest='fig_path', type=str, default=None,
                        help='')
    parser.add_argument('-l', metavar='LABELS', dest='labels', type=str, default=None,
                        help='')
    args = parser.parse_args()

    if args.title == '':
        title = args.eigenvalue_vs_ipratio_paths[0]
    else:
        title = args.title

    if args.fig_path is None:
        fig_path = re.sub(r'(_eigenvalue_vs_ipratio)?\.[^.]+$', '', args.eigenvalue_vs_ipratio_paths[0]) + \
                   '_eigenvalue_vs_ipratio.png'
    else:
        fig_path = args.fig_path

    if args.labels is None:
        labels = ['sample %d' % i for i in range(len(args.eigenvalue_vs_ipratio_paths))]
    else:
        labels = args.labels.split(',')

    vsss = []
    for path in args.eigenvalue_vs_ipratio_paths:
        with open(path, 'r') as fp:
            vsss.append(json.load(fp))

    header = re.sub('\.[^.]+$', '', fig_path)

    min_eigenvalue = 1e100
    min_ipratio = 1e100
    max_eigenvalue = -1e100
    max_ipratio = -1e100
    for vss in vsss:
        for vs in vss:
            min_eigenvalue = min(min_eigenvalue, min(vs['eigenvalues']))
            min_ipratio = min(min_ipratio, min(vs['ipratios']))
            max_eigenvalue = max(max_eigenvalue, max(vs['eigenvalues']))
            max_ipratio = max(max_ipratio, max(vs['ipratios']))

    if args.x_min is None:
        x_min = min_eigenvalue
    else:
        x_min = args.x_min
    if args.x_max is None:
        x_max = max_eigenvalue
    else:
        x_max = args.x_max
    if args.y_min is None:
        y_min = 0.
    else:
        y_min = args.y_min
    if args.y_max is None:
        y_max = 1. / min_ipratio
    else:
        y_max = args.y_max

    for step in range(len(vsss[0])):
        output_filename = '%s_%06d.png' % (header, step)
        pylab.title(title + ' %.4f [ps]' % (vsss[0][step]['time'] * kPsecPerAu))
        pylab.xlabel('Eigenvalue [au]')
        pylab.ylabel('Pratio')
        pylab.grid()
        pylab.xlim(x_min, x_max)
        pylab.ylim(y_min, y_max)
        for sample in range(len(vsss)):
            pratios = [1. / ipratio for ipratio in vsss[sample][step]['ipratios']]
            pylab.plot(vsss[sample][step]['eigenvalues'], pratios, '+-', label=labels[sample])
        pylab.legend(loc='upper left')
        pylab.savefig(output_filename)
        pylab.clf()


import random
import math
import time
from util import Queue
class User:
    def __init__(self, name):
        self.name = name

class SocialGraph:
    def __init__(self):
        self.lastID = 0
        self.users = {}
        self.friendships = {}

    def addFriendship(self, userID, friendID):
        """
        Creates a bi-directional friendship
        """
        if userID == friendID:
            return False
        elif friendID in self.friendships[userID] or userID in self.friendships[friendID]:
            return False
        else:
            self.friendships[userID].add(friendID)
            self.friendships[friendID].add(userID)
            return True

        """
        For a one directional Friendship
        elif friendID in self.friendships[userID]:
            print("WARNING: YOU ARE ALREADY FOLLOWING USER")
        else:
            self.friendships[userID].add(friendID)
        """

    def addUser(self, name):
        """
        Create a new user with a sequential integer ID
        """
        self.lastID += 1  # automatically increment the ID to assign the new user
        self.users[self.lastID] = User(name)
        self.friendships[self.lastID] = set()

    def populateGraphLinear(self, numUsers, avgFriendships):
        # Reset graph
        self.lastID = 0
        self.users = {}
        self.friendships = {}

        # Add users
        # loop over a range of 0 to numUsers
        for i in range(numUsers):
            # add user to the graph
            self.addUser(f"User {i + 1}")

        # friendships

        # get the target friendships via (numUsers * avgFriendships)
        targetFriendships = (numUsers * avgFriendships)
        # set a counter for total friendships
        totalFriendships = 0
        # set a counter for collisions
        collisions = 0

        # while total friendships is less than the target friendships
        while totalFriendships < targetFriendships:
            # set userID to a random number between 1 and the lastID
            userID = random.randint(1, self.lastID)
            # set friendID to a random number between 1 and the lastID
            friendID = random.randint(1, self.lastID)
            # if the return of add friendship of userID and friendID is true
            if self.addFriendship(userID, friendID):
                # increment total friendships
                totalFriendships += 2
            # otherwise
            else:
                # increment collisions
                collisions += 1
        # print collision
        print(f"COLLISIONS: {collisions}")

    def populateGraph(self, numUsers, avgFriendships):
        """
        Takes a number of users and an average number of friendships
        as arguments

        Creates that number of users and a randomly distributed friendships
        between those users.

        The number of users must be greater than the average number of friendships.
        """
        # Reset graph
        self.lastID = 0
        self.users = {}
        self.friendships = {}
        # !!!! IMPLEMENT ME
        for i in range(0, numUsers):
            self.addUser(f"User {i}")

        # Add users

        # Create friendships
        possibleFriendships = []

        for userID in self.users:
            for friendID in range(userID +1,self.lastID + 1):
            #why not for friendID in range(0, self.lastID + 1):
            # if friendID == userID:
            #because starting from zero it means thats the zeroth user is already friends with the 1th user and automatically when you do addfriendship 1th will become friend with the zeroth
            #this is for two way connections but in the case of following like in twitter, i think your solution can work
                possibleFriendships.append((userID, friendID))
        random.shuffle(possibleFriendships)
        #dividing by 2 because each friendship adds 2 frienships
        # if its for one directional we wont be dividing by 2
        for i in range(0,math.floor(numUsers * avgFriendships / 2)):
            friendship = possibleFriendships[i]
            self.addFriendship(friendship[0], friendship[1])

    def getAllSocialPaths(self, userID):
        """
        Takes a user's userID as an argument
        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.
        """
        visited = {}
        # Note that this is a dictionary, not a set
        # !!!! IMPLEMENT ME
        q = Queue()

        q.enqueue([userID])

        while q.size() > 0:
            path = q.dequeue()
            newUserID = path[-1]

            if newUserID not in visited:
                # set the new user ids path in visited
                visited[newUserID] = path
                # loop over each friend id in the friendships at the index of new user id
                for friendID in self.friendships[newUserID]:
                    # check that the friend id is not in visited
                    if friendID not in visited:
                        # create a copy of the path
                        new_path = list(path)
                        # append the friend id to the copy of the path
                        new_path.append(friendID)
                        # enqueue the copy of the path
                        q.enqueue(new_path)

        return visited

if __name__ == '__main__':
    sg = SocialGraph()
    sg.populateGraphLinear(10, 2)
    print(sg.friendships)
    connections = sg.getAllSocialPaths(1)
    print(connections)

# if __name__ == '__main__':
#     sg = SocialGraph()
#     start_time = time.time()
#     numUsers = 2000
#     avgFriendships = 190
#     # sg.populateGraph(numUsers, avgFriendships)

#     sg.populateGraphLinear(numUsers, avgFriendships)
#     end_time = time.time()
#     print(f"Linear runtime: {end_time - start_time} seconds")

#     start_time = time.time()
#     sg.populateGraph(numUsers, avgFriendships)
#     end_time = time.time()
#     print(f"Quadratic runtime: {end_time - start_time} seconds")


from random import shuffle, randrange
from mdpstate import MDPState
from copy import deepcopy

class Maze:

    """
    Creates a maze of specified size.
    Output is a list of lists, to be used as a matrix with coordinates.
    '#' = wall
    ' ' = empty space

    Adapted from http://rosettacode.org/wiki/Maze_generation#Python
    """

    def __init__(self, w=10, h=10):

        self.vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
        self.ver = [["# "] * w + ['#'] for _ in range(h)] + [[]]
        self.hor = [["##"] * w + ['#'] for _ in range(h + 1)]

        self.matrix = self.make_maze(w, h)

        #self.grid = self.maze_to_mdp()

    def make_maze(self, w, h):

        self.walk(randrange(w), randrange(h))

        cells = ""

        for (a, b) in zip(self.hor, self.ver):
            cells += ''.join(a + ['\n'] + b + ['\n'])

        cells = cells.split('\n')
        cells = [list(row) for row in cells]
        del cells[len(cells)-1]
        del cells[len(cells)-1]

        return [row for row in cells]

    def walk(self, x, y):
        self.vis[y][x] = 1

        d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
        shuffle(d)
        for (xx, yy) in d:
            if self.vis[yy][xx]: continue
            if xx == x: self.hor[max(y, yy)][x] = "# "
            if yy == y: self.ver[y][max(x, xx)] = "  "
            self.walk(xx, yy)

    def __repr__(self):
        strlst = [''.join(row) for row in self.matrix]
        return '\n'.join(strlst)

if __name__ == '__main__':
    new_maze = Maze(w=3,h=3)
    print(new_maze.matrix)

Policy iteration and Value iteration/maze.py


"""
     计算一组数据中能构成三角形的最大周长
"""

# 输出数据列表
str = input("输入一组数字：")
xstr = str.split(',')
xlist = list(map(lambda x: int(x), xstr))

# 排序
xlist.sort(reverse=True)

# 从大到小，三边为一组，判断是否能构成三角形并算出数据
perimeter = 0
for i in range(len(xlist)-2):
    a = xlist[i]
    b = xlist[i+1]
    c = xlist[i+2]
    if b+c > a:
        perimeter = a+b+c
        break

if perimeter == 0:
    print("无数据构成三角形")
else:
    print("三角形的周长最大为：", perimeter)


from django.shortcuts import render, HttpResponse, redirect
from .models import *
from django.contrib import messages

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

def register(request):
    if request.method == 'POST':
        post_data = request.POST
        response = User.objects.register(post_data)
        if response['valid']:
            request.session['uid'] = response['user'].id
            return redirect('/success')
        else:
            for error in response['errors']:
                messages.add_message(request, messages.ERROR, error)
            return redirect('/')

def login(request):
    if request.method == 'POST':
        post_data = request.POST
        response = User.objects.login(post_data)
        if response['valid']:
            request.session['uid'] = response['user'].id
            return redirect('/success')
        else:
            for error in response['errors']:
                messages.add_message(request, messages.ERROR, error)
            return redirect('/')

def success(request):
    if 'uid' in request.session:
        user = User.objects.get(id=request.session['uid'])
        return render(request, 'success.html', {'user': user})
    else:
        return redirect('/')

def logout(request):
    request.session.clear()
    return redirect('/')


from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.utils.callback_data import CallbackData

files_call = CallbackData('file_btns', 'format_file', 'link')

def get_formats(formats_lst: list, link: str):
    markup = InlineKeyboardMarkup()

    for elem in formats_lst:
        markup.insert(
            InlineKeyboardButton(
                text=elem,
                callback_data=files_call.new(format_file=elem, link=link)
            )
        )
    return markup

languages_call = CallbackData('languages', 'language', 'link', 'abbr')

def get_language(languages_lst: list, link: str, abbr_lst):
    markup = InlineKeyboardMarkup()

    for elem in range(len(languages_lst)):
        lang = languages_lst[elem]
        abbr = abbr_lst[elem]
        markup.insert(
            InlineKeyboardButton(
                text=lang,
                callback_data=languages_call.new(language=elem, link=link, abbr=abbr)
            )
        )
    return markup


import numpy as np
import keras.models
from scipy.misc import imread, imresize

json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = keras.models.model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model.h5")
print("Loaded Model from disk")

# compile and evaluate loaded model
loaded_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# loss,accuracy = model.evaluate(X_test,y_test)
# print('loss:', loss)
# print('accuracy:', accuracy)
x = imread('output.png', mode='L')
x = np.invert(x)
x = imresize(x, (28, 28))
import matplotlib.pyplot as plt

plt.imshow(x)
plt.show()
# imshow(x)
x = x.reshape(1, 28, 28, 1)

out = loaded_model.predict(x)
print(out)
print(np.argmax(out, axis=1))


"""对称密码.

demo:
  - P47 编码 midnight. `encode_midnight`
  - P47 测验一, 凯撒密码平移 3 个字母. `caesar_cipher`
  - P47 XOR 运算规则. `xor_rule`
  - P48 比特序列的 XOR. `bit_xor`
  - P50 一次性密码本. `OneTimePad`
  - P54 Feistel 网络. `Feistel`
  - P61 三重 DES. `TripleDES`

AES 的最终实现涉及第四章内容, 而且 AES 可以用于生产环境所以放到了:
https://github.com/dyq666/sanji/blob/master/util/third_cryptography.py
"""

__all__ = (
    'Feistel',
    'OneTimePad',
    'TripleDES',
)

import secrets
from typing import Tuple

from nami.util import Binary

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

def encode_midnight():
    """编码 midnight demo."""
    s = 'midnight'
    for c in s:
        print(f'{c} -> {Binary.int_2_str(ord(c))}')

def caesar_cipher():
    """凯撒密码 demo."""
    map_ = {i: (i + 3) % 26 for i in range(26)}
    for k, v in map_.items():
        print(f'{k} -> {v}')

def xor_rule():
    """XOR 运算规则 demo."""
    group = (
        ('0', '0'),
        ('0', '1'),
        ('1', '0'),
        ('1', '1'),
    )
    for l, r in group:
        print(f'{l} XOR {r} = {Binary.str_xor(l, r)}')

def bit_xor():
    """比特序列的 XOR demo."""
    top = '01001100'
    bot = '10101010'
    line = '-' * 29
    re1 = Binary.str_xor(top, bot)
    re2 = Binary.str_xor(re1, bot)

    print(f'{" ".join(top)}  ... A')
    print(f'{" ".join(bot)}  ...       B')
    print(line)
    print(f'{" ".join(re1)}  ... A XOR B')
    print()
    print(f'{" ".join(re1)}  ... A XOR B')
    print(f'{" ".join(bot)}  ...       B')
    print(line)
    print(f'{" ".join(re2)}  ... A')

class OneTimePad:
    """一次性密码本.

    密钥长度必须与消息长度相同.
    """

    def __init__(self, key: bytes):
        self.key = key

    def encrypt(self, msg: bytes) -> bytes:
        if len(msg) != len(self.key):
            raise ValueError
        return Binary.bytes_xor(self.key, msg)

    decrypt = encrypt

    @staticmethod
    def generate_key(length) -> bytes:
        return secrets.token_bytes(length)

class Feistel:
    """Feistel 网络的简化版.

    在简化版中有如下的规则:
      1. 明文长度必须被 2 整除.
      2. 密钥长度是明文长度的一半.
      3. 轮转算法 `algorithm` 必须返回 `bytes` 类型, 并且输出的长度必须大于等于明文长度的一半.
      4. 所有子密钥相同.
    """

    def __init__(self, key: bytes, count: int, algorithm: callable):
        self.count = count
        self.key = key
        self.algorithm = algorithm

    def round(self, l: bytes, r: bytes) -> Tuple[bytes, bytes]:
        """一轮."""
        new_l = Binary.bytes_xor(self.algorithm(self.key, r), l)
        return new_l, r

    def encrypt(self, msg: bytes) -> bytes:
        if len(msg) % 2 != 0:
            raise ValueError

        # 由于每次循环都会 `reverse`, 但第一轮是不需要 `reverse`,
        # 因此第一轮前先 `reverse` 一次, 抵消掉循环中的 `reverse`.
        group = msg[len(msg) // 2:], msg[:len(msg) // 2]
        for i in range(self.count):
            group = reversed(group)
            group = self.round(*group)
        return b''.join(group)

    decrypt = encrypt

    @staticmethod
    def generate_key(length: int) -> bytes:
        return secrets.token_bytes(length)

class TripleDES:
    """三重 DES."""

    BLOCK_SIZE = 8  # algorithms.TripleDES.block_size / 8

    def __init__(self, key: bytes, iv: bytes):
        self.cipher = Cipher(
            algorithm=algorithms.TripleDES(key),
            mode=modes.CBC(iv),
            backend=default_backend(),
        )
        self.padding = padding.PKCS7(algorithms.AES.block_size)

    def encrypt(self, msg: bytes) -> bytes:
        encryptor = self.cipher.encryptor()
        padder = self.padding.padder()
        msg = padder.update(msg) + padder.finalize()
        return encryptor.update(msg) + encryptor.finalize()

    def decrypt(self, msg: bytes) -> bytes:
        decryptor = self.cipher.decryptor()
        unpadder = self.padding.unpadder()
        msg = decryptor.update(msg) + decryptor.finalize()
        return unpadder.update(msg) + unpadder.finalize()

    @classmethod
    def generate_key(cls) -> Tuple[bytes, bytes]:
        return secrets.token_bytes(24), secrets.token_bytes(cls.BLOCK_SIZE)


"""
Program : COVID_19___Confirmed_Cases_Simple_Map_Animation.ipynb

(c) 2020
"""

import time
import pandas as pd
import numpy as np
from bokeh.plotting import figure, show, curdoc
from bokeh.io import output_notebook, push_notebook, output_file
from bokeh.palettes import Spectral6
from bokeh.transform import linear_cmap
from bokeh.models import ColumnDataSource, HoverTool

from bokeh.tile_providers import get_provider, Vendors
from pyproj import Proj, transform

from bokeh.layouts import row, column, grid, gridplot
from bokeh.models import CustomJS
from bokeh.models.widgets import Button, RadioGroup, Select, Slider

#output_file("MyLayout.html")

iSelect=0           # Index of Select (Afganisthan, dll)
nSum = [0,0,0,0,0,0,0]
nMinMax = [0,0,0,0,0,0,0]

# ------------------------------------------------------------------------------
# Database
# ------------------------------------------------------------------------------
df1=pd.read_csv('https://raw.githubusercontent.com/valiandafh/Tubes-/master/time_series_covid19_confirmed_global.csv')    # Confirmed
df2=pd.read_csv('https://raw.githubusercontent.com/valiandafh/Tubes-/master/time_series_covid19_recovered_global.csv')    # Recovered
df3=pd.read_csv('https://raw.githubusercontent.com/valiandafh/Tubes-/master/time_series_covid19_death_global.csv')        # Death

df1.rename(columns={'Province/State':'Province', 'Country/Region':'Country'}, inplace=True)
maxBaris=len(df1.iloc[:,0])     # 264
maxKolom=len(df1.iloc[0,:])     # 96

df1['Total'] = df1.iloc[:,-1]
df2['Total'] = df2.iloc[:,-1]
df3['Total'] = df3.iloc[:,-1]

dCountry=df1['Country']
dProvince=df1['Province']
lCountry=dCountry.values.tolist()
lProvince=dProvince.values.tolist()
# List of Select
L1 = lCountry
L2 = lProvince
L3 = L1

y1=df1.iloc[iSelect,4:maxKolom]
y2=df2.iloc[iSelect,4:maxKolom]
y3=df3.iloc[iSelect,4:maxKolom]
x1=[x1 for x1 in range(0,len(y1))]
mydates=y2.index.values
nBaris=len(lCountry)-1
nKolom=len(x1)-1

#print(z1)
# ------------------------------------------------------------------------------
# A = Button + Radio Grup
# ------------------------------------------------------------------------------
mybtn11 = Button(label="Confirmed Case", name="11", height=70, width=150)
mybtn12 = Button(label="Country = 1", name="12", width=120)

def myhandler1a(attr,old,new):
  mybtn12.label = "Country = " + str(nSum[new])

mylabels=["1-99", "100-999", "1.000-9.999", " 10.000-99.999", "100.000-499.999", " > 500.000", "ALL"]
myradio_group = RadioGroup(labels=mylabels, active=5, width=150)
myradio_group.on_change('active', myhandler1a)

mybtn15 = Button(label="Confirmed = 1176", name="12", width=120)
mybtn16 = Button(label="Recovered = 166", name="12", width=120)
mybtn17 = Button(label="Death = 140", name="12", width=120)

# ------------------------------------------------------------------------------
# B = Peta + Data
# ------------------------------------------------------------------------------
mydf=df1
mytitle="Covid-19 Pandemic World Data Distribution"
x=mydf['Long']
y=mydf['Lat']
z=mydf['Total']
myC=mydf['Country']

#"""
mysizes=np.abs(z)
myWarna=np.abs(z)

# Konversi WGS84 to Mercator
in_wgs = Proj('epsg:4326')
out_mercator = Proj('epsg:3857')

mX = np.abs(x)
mY = np.abs(y)
for ii in range(len(x)):
  mX[ii], mY[ii] = transform(in_wgs, out_mercator, y[ii], x[ii])

# Size of Circle
for ii in range(len(z)):
  mysizes[ii]=(5 if (z[ii]<1000) else
              (10 if z[ii]<10000 else
              (16 if z[ii]<100000 else
              (28 if z[ii]<500000 else
              42))))

for ii in range(len(z)):
  myWarna[ii]=(0 if (z[ii]<10) else
              (1 if z[ii]<100 else
              (3 if z[ii]<1000 else
              (5 if z[ii]<10000 else
              (7 if z[ii]<100000 else
              (9 if z[ii]<500000 else
              12))))))

for ii in range(len(z)):
  if (z[ii]<100): nSum[0]=nSum[0]+1
  elif (z[ii]<1000): nSum[1]=nSum[1]+1
  elif (z[ii]<10000): nSum[2]=nSum[2]+1
  elif (z[ii]<100000): nSum[3]=nSum[3]+1
  elif (z[ii]<500000): nSum[4]=nSum[4]+1
  else: nSum[5]=nSum[5]+1
nSum[6]=len(z)
#print(nSum)
#print("---------")

nMin=5000000
nMax=0
iMin=0
iMax=0
for ii in range(len(z)):
  if (z[ii]>nMax):
    nMax=z[ii]
    iMax=ii

for ii in range(len(z)):
  if (z[ii]<nMin):
    if (z[ii]>0):
      nMin=z[ii]
      iMin=ii

nMinMax[0]=iMin
nMinMax[1]=nMin
nMinMax[2]=iMax
nMinMax[3]=nMax

mydf['E']=mX
mydf['N']=mY
mydf['Size'] = mysizes
mydf['Warna'] = myWarna

myfillcolors = linear_cmap(field_name='Warna', palette=Spectral6, low=min(myWarna), high=max(myWarna))

mysource = ColumnDataSource(mydf)
myhover = HoverTool(tooltips=[("Country ", "@Country"),
                              ("Province ", "@Province"),
                              ("Long ", "@Long"),
                              ("Lat ", "@Lat"),
                              ("Total ", "@Total")])

# range bounds supplied in web mercator coordinates
M1 = figure (plot_width=600, plot_height=440,
  x_range=(-16000000, 16000000), y_range=(-8000000, 8000000),
  x_axis_type='mercator', y_axis_type='mercator',
  title=mytitle, tools=[myhover, 'pan', 'wheel_zoom', 'zoom_in', 'zoom_out','save', 'reset']
)

mytile_provider = get_provider(Vendors.CARTODBPOSITRON)
# tile_provider = get_provider(Vendors.STAMEN_TONER_BACKGROUND)

M1.add_tile(mytile_provider)
M1.circle(x='E', y='N', source=mysource, line_color=myfillcolors, fill_color=myfillcolors, size='Size')

mybtn21 = Button(label="Min : ", width=240)
mybtn22 = Button(label="Click here", width=80)
mybtn23 = Button(label="Max : ", width=240)

def myhandler2b():
  i=nMinMax[0]
  mybtn21.label = L1[i]+" = "+str(z[i])+", "+str(df2['Total'][i])+", "+str(df3['Total'][i])
  i=nMinMax[2]
  mybtn23.label = L1[i]+" = "+str(z[i])+", "+str(df2['Total'][i])+", "+str(df3['Total'][i])

mybtn22.on_click(myhandler2b)

B22 = row(mybtn21, mybtn22, mybtn23)
B = column(M1, B22)

#"""
#B = Button(label="Data = 3", name="23", width=600)
# ------------------------------------------------------------------------------
# C = Select + Plotter + Slider
# ------------------------------------------------------------------------------
iSlider = nKolom      # Index of Slider (0-91 days)

x1c = x1
y1c = df1.iloc[iSelect,4:maxKolom]
y2c = df2.iloc[iSelect,4:maxKolom]
y3c = df3.iloc[iSelect,4:maxKolom]

x1d=[x1 for x1 in range(0,len(y1))]
y1d=[x1 for x1 in range(0,len(y1))]
y2d=[x1 for x1 in range(0,len(y1))]
y3d=[x1 for x1 in range(0,len(y1))]

def PDailyCase(iNum):
  for i in range(1, nKolom):
    y1d[i]=y1c[i]-y1c[i-1]
    y2d[i]=y2c[i]-y2c[i-1]
    y3d[i]=y3c[i]-y3c[i-1]

PDailyCase(iSelect)
#print(x1c)
#print(y1c)
#print(y2c)
#print(x1d)
#print(y1d)
#print(y2d)

mybtn31 = Button(label=mydates[nKolom], width=75)
mybtn32 = Button(label=str(y1d[nKolom]), width=75)
mybtn33 = Button(label=str(y2d[nKolom]), width=60)
mybtn34 = Button(label=str(y3d[nKolom]), width=60)

source3 = ColumnDataSource(data=dict(x1c=x1c, y1c=y1c, y2c=y2c, y3c=y3c))
source3b = ColumnDataSource(data=dict(x1d=x1d, y1d=y1d, y2d=y2d, y3d=y3d))

plot3 = figure(plot_width=300, plot_height=200, title="Accumulated Report", toolbar_location=None)
plot3.x_range.start = 0
plot3.y_range.start = 0

plot3b = figure(plot_width=300, plot_height=200, title="Daily Case Report", toolbar_location=None)
plot3b.x_range.start = 0
plot3b.y_range.start = 0

r1 = plot3.line('x1c', 'y1c', source=source3, line_width=3, line_color='red')
r2 = plot3.line('x1c', 'y2c', source=source3, line_width=3, line_color='green')
r3 = plot3.line('x1c', 'y3c', source=source3, line_width=3, line_color='black')

r1b = plot3b.line('x1d', 'y1d', source=source3b, line_width=3, line_color='red')
r2b = plot3b.line('x1d', 'y2d', source=source3b, line_width=3, line_color='green')
r3b = plot3b.line('x1d', 'y3d', source=source3b, line_width=3, line_color='black')

# Cek NaN variable
def isNaN(num):
  return num!= num

for i in range(nBaris):
  L3[i]=(L1[i] if isNaN(L2[i]) else (L1[i]+L2[i]))

# Event : Select
def myhandler3a(attr,old,new):
  iSelect=-1
  for i in range(0, nBaris):
    iSelect=(i if (L1[i]==new) else iSelect)

  mybtn31.label = mydates[nKolom]
  y3c = df3.iloc[iSelect,4:maxKolom]
  y2c = df2.iloc[iSelect,4:maxKolom]
  y1c = df1.iloc[iSelect,4:maxKolom]
  mybtn15.label = "Confirmed = " + str(y1c[nKolom])
  mybtn16.label = "Recovered = " + str(y2c[nKolom])
  mybtn17.label = "Death = " + str(y3c[nKolom])
  r1.data_source.data["y1c"] = y1c
  r2.data_source.data["y2c"] = y2c
  r3.data_source.data["y3c"] = y3c
#  print(iSelect)
#  PDailyCase(iSelect)
  for i in range(1, nKolom+1):
    y1d[i]=y1c[i]-y1c[i-1]
    y2d[i]=y2c[i]-y2c[i-1]
    y3d[i]=y3c[i]-y3c[i-1]
  r1b.data_source.data["y1d"] = y1d
  r2b.data_source.data["y2d"] = y2d
  r3b.data_source.data["y3d"] = y3d
  mybtn32.label = str(y1d[nKolom])
  mybtn33.label = str(y2d[nKolom])
  mybtn34.label = str(y3d[nKolom])

# Event : Slider
def myhandler3b(attr,old,new):
  iSlider = new
  plot3.x_range.end = iSlider*1.01
  plot3.y_range.end = r1.data_source.data["y1c"][iSlider]*1.01
  mybtn31.label = mydates[iSlider]
  mybtn32.label = str(r1b.data_source.data["y1d"][iSlider])
  mybtn33.label = str(r2b.data_source.data["y2d"][iSlider])
  mybtn34.label = str(r3b.data_source.data["y3d"][iSlider])

  plot3b.x_range.end = iSlider*1.01
  plot3b.y_range.end = r1b.data_source.data["y1d"][iSlider]*1.01

opsiSelect=L3
myselect3 = Select(value=opsiSelect[0], options=opsiSelect, title="Country/Province ", width=150)
myselect3.on_change('value', myhandler3a)

slider3 = Slider(start=0, end=nKolom, value=nKolom, step=1, height=45, title="Slider Day ", width=300)
slider3.on_change('value', myhandler3b)

print(nBaris)
print(nKolom)
print(L1[nBaris])
print(y1c[nKolom])
print(y2c[nKolom])
print(y3c[nKolom])

# ------------------------------------------------------------------------------
# All = A + B + C
# ------------------------------------------------------------------------------
A = column(mybtn11, myradio_group, mybtn12, myselect3, mybtn15, mybtn16, mybtn17)

C33 = row(mybtn31, mybtn32, mybtn33, mybtn34)
C = column(plot3, C33, plot3b, slider3)

MyLayout = row(A, B, C)
#show(MyLayout)
curdoc().add_root(MyLayout)
curdoc().title = "COVID19 Pandemic World Data Distribution"


from jawaf.exceptions import ServerError

async def create_pool(**connection_settings):
    """Create a pool using the `engine` to call the right db backend.
    :param connection_settings: Kwargs.
    :return: Pool.
    """
    engine = connection_settings.pop('engine')
    if engine == 'postgresql':
        from jawaf.adapters.db.postgresql import PostgreSQLBackend
        return await PostgreSQLBackend().create_pool(**connection_settings)
    raise ServerError(f'Unsupported DB Backend {engine}')


import sys
sys.path.append("notebooks/")

import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import accuracy_score
from sentiment import PCA, KNNClassifier
import matplotlib
import matplotlib.pyplot as plt
import time
import argparse

# para un dataset `df`
# obtiene instancias de train y test
# crea el modelo de bolsa de palabras
# y poda los datos desde el `min_df` al `max_df`
def get_instances(df, max_df=0.90, min_df=0.1):
  text_train = df[df.type == 'train']["review"]
  label_train = df[df.type == 'train']["label"]

  text_test = df[df.type == 'test']["review"]
  label_test = df[df.type == 'test']["label"]

  vectorizer = CountVectorizer(max_df=max_df, min_df=min_df, max_features=5000)

  vectorizer.fit(text_train)

  X_train, y_train = vectorizer.transform(text_train), (label_train == 'pos').values
  X_test, y_test = vectorizer.transform(text_test), (label_test == 'pos').values

  return X_train, y_train, X_test, y_test

def main(args):
  # datasets de train y test
  df = pd.read_csv("data/imdb_small.csv")

  #recortando data set para pruebas chiquitas
  if(args.elem > 0):
    df = df[:args.elem]

  X_train, y_train, X_test, y_test = get_instances(df)

  alpha = args.alpha_Start

  # rango de k
  k_range = np.arange(args.k_Start, args.k_Stop, args.k_Step)

  # rango de alpha
  alpha_range = np.arange(alpha, args.alpha_Stop, args.alpha_Step)

  # resultados de accuaracies para cada k
  results = []
  for i in range(len(k_range)):
    results.append([])

  for alpha in alpha_range:
    pca = PCA(alpha)
    pca.fit(X_train.toarray())
    X_train_aux = pca.transform(X_train)
    X_test_aux = pca.transform(X_test)

    # kNN
    for i in range(len(k_range)):
      k = k_range[i]

      clf = KNNClassifier(k)
      clf.fit(X_train, y_train)
      y_pred = clf.predict(X_test)
      t = accuracy_score(y_test, y_pred)

      results[i].append(t)

  for i, result in enumerate(results):
    plt.plot(alpha_range, result, label='k = {0}'.format(k_range[i]))

  plt.xlabel('alpha')
  plt.ylabel('accuaracy')
  plt.legend()
  plt.savefig('results/k_vs_accuaracy-{}'.format(time.strftime("%Y%m%d-%H%M%S")))
  plt.show()

  '''
  fig, ax = plt.subplots()
  ax.plot(its, accs)

  _title = 'k vs. accuracy' if alpha == 0 else 'k vs. accuracy - Alpha = {0}'.format(alpha)
  ax.set(xlabel='k', ylabel='accuracy',title='title=_title')
  ax.grid()

  fig.savefig("results/k_vs_accuaracy_{0}.png".format(time.strftime("%Y%m%d-%H%M%S")))
  plt.show()
  '''

def positive_integer(value):
  ivalue = int(value)
  if ivalue < 0:
    raise argparse.ArgumentTypeError("%s Valor inválido, tiene que ser un numero natural." % value)
  return ivalue

if __name__ == '__main__':
  description = 'Acuraccy.'

  parser = argparse.ArgumentParser(description=description)

  parser.add_argument(
    '--k_Start',
    type=positive_integer,
    default=20,
    help='Valor minimo de k'
  )
  parser.add_argument(
    '--k_Stop',
    type=positive_integer,
    default=41,
    help='Valor maximo de k'
  )
  parser.add_argument(
    '--k_Step',
    type=positive_integer,
    default=10,
    help='Salto de k'
  )
  parser.add_argument(
    '--alpha_Start',
    type=positive_integer,
    default=50,
    help='Valor minimo de alpha'
  )
  parser.add_argument(
    '--alpha_Stop',
    type=positive_integer,
    default=201,
    help='Valor maximo de alpha'
  )
  parser.add_argument(
    '--alpha_Step',
    type=positive_integer,
    default=30,
    help='Salto de alpha'
  )
  parser.add_argument(
    '--elem',
    type=int,
    default=1000,
    help='Poda bruta de comentarios'
  )
  parser.add_argument(
    '--reps',
    type=positive_integer,
    default=10,
    help='Repeticiones de kNN'
  )
  args = parser.parse_args()

  assert args.k_Start > 0
  #assert args.k_Stop < args.elem
  assert args.k_Start <= args.k_Stop

  main(args)


H, W, K = map(int, input().split())

S = [list(map(int, input())) for _ in range(H)]
accS = [[0] * (W + 1) for _ in range(H + 1)]

for h in range(H):
    for w in range(W):
        accS[h + 1][w + 1] = accS[h + 1][w] + accS[h][w + 1] - accS[h][w] + S[h][w]

def isOk(L, left, right):
    for top, bot in zip(L, L[1:]):
        if accS[bot][right] - accS[bot][left] - accS[top][right] + accS[top][left] > K:
            return False
    return True

ans = 10**18

for mask in range(1 << H):
    L = [0] + [d + 1 for d in range(H - 1) if (mask & (1 << d)) > 0] + [H]

    cnt = len(L) - 2
    left = 0
    while left < W:
        right = left
        while right < W and isOk(L, left, right + 1):
            right += 1

        if left == right:
            cnt = 10**18
            break

        cnt += 1
        left = right

    ans = min(ans, cnt - 1)

print(ans)


# pylint: disable=W0614,W0401
'''
One off program to initialize and set up the Customer database as shown in the
video lesson/code
'''

import logging
from customer_db_model import *

logging.basicConfig(level=logging.INFO)
LOGGER = logging.getLogger(__name__)

LOGGER.info('One off program to set up the customer database')

DATABASE.create_tables([Customer])

DATABASE.close()


def stringToArray(string):
    string=string[2:len(string)-2]
    temp=string.split("],[")
    length=len(temp)
    array=[[0]*2]*length
    for i in range (0,length):
        array[i]=temp[i].split(',')
    return array
def move(player,row,line,array):
    array[int(row)][int(line)]=player
    return array
def check(array):
    for i in range(3):
        if array[i][0]==array[i][1] and array[i][0]==array[i][2] and array[i][0]!=0:
            return True
        elif array[0][i]==array[1][i] and array[0][i]==array[2][i] and array[0][i]!=0:
            return True
    if array[0][0]==array[1][1] and array[0][0]==array[2][2] and array[0][0]!=0:
        return True
    elif array[0][2]==array[1][1] and array[0][2]==array[2][0] and array[0][2]!=0:
        return True
    else:
        return False
array=stringToArray(input())
table=[[0 for _ in range(3)] for _ in range(3)]
for i in range(len(array)):
    if i % 2==0:
        array=move("A",array[i][0],array[i][1],table)
        flag=check(table)
        if flag :
            print("A")
            break
    else:
        array=move("B",array[i][0],array[i][1],table)
        flag=check(table)
        if flag :
            print("B")
            break
if not flag:
    if len(array)==9:
        print("Draw")
    else:
        print("Pending")


# Matplotlib imports
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.axis
from matplotlib import cm, rc
from matplotlib.ticker import LinearLocator, FormatStrFormatter, ScalarFormatter
import numpy as np
import math

def plot(results, key, titles):
    """Produce surface plot of the flow results as function of PD and coolant
    channel diameter.
    """
    # get parametric sweep data
    N = int(math.sqrt(len(results.data)))
    M = results.data[key].reshape(N, N)
    R = results.data['r'].reshape(N, N)
    PD = results.data['pd'].reshape(N, N)

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(R, PD, M,
                           cmap=cm.viridis, linewidth=0,
                           vmin=0, vmax=np.nanmax(M),
                           antialiased=False)

    # set x/y axis labels, ticks
    ax.set_xlabel("Coolant Channel Diameter [m]", fontsize=7)
    plt.xticks(rotation=25, fontsize=6)
    ax.set_ylabel("Fuel Pitch to Coolant D Ratio [-]", fontsize=7)
    plt.yticks(rotation=25, fontsize=6)
    ax.set_zlabel(titles[key][1], fontsize=7)

    # Customize the z axis.
    ax.set_zlim(np.nanmin(M), np.nanmax(M))
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    # edit z tick labels
    for t in ax.zaxis.get_major_ticks():
        t.label.set_fontsize(6)
    niceMathTextForm = ScalarFormatter(useMathText=True)
    ax.w_zaxis.set_major_formatter(niceMathTextForm)
    ax.ticklabel_format(axis="z", style="sci", scilimits=(0, 0))
    plt.title(titles[key][0])

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5, format='%.0e')

    return plt


from SAMANTHA.Speak.LibrarySpeakWithExport import *

voiceSAM = SpeakSAM()

import telebot

class ComandReceivedTelegram():
    tb = None

    def __init__(self, Token):
        self.tb = telebot.TeleBot(Token)

        @self.tb.message_handler(commands=['start'])
        def send_welcome(message):
            cid = message.chat.id
            self.tb.reply_to(message, "Hola!, soy el bot de la FCV, "
                                 "por favor digite su numero de documento "
                                 "despues del comando /DOC para registrarlo en la DB")

        @self.tb.message_handler(commands=['DOC'])
        def comando_doc(mensaje):
            chat_id = mensaje.chat.id
            unique_code = self.extract_unique_code(mensaje.text)
            print(unique_code)

        @self.tb.message_handler(function=lambda message:True)
        def message(message):
            nombreArchivoResultante = voiceSAM.convertirTextoVoz(message.chat.id, message.text)
            print(nombreArchivoResultante)
            if nombreArchivoResultante != None:
                self.tb.sendAudio(chat_id=message, audio=open(nombreArchivoResultante, 'rb'))
                voiceSAM.borrarAudio()
            else:
                self.tb.reply_to(message, message.text)

        def listener(message):
            for m in message:
                chat_id = m.chat.id
                texto = m.text
                respuestaChatBot = texto

                nombreArchivoResultante = voiceSAM.convertirTextoVoz(str(chat_id), respuestaChatBot)

                print(nombreArchivoResultante)
                if nombreArchivoResultante != None:
                    self.tb.send_audio(chat_id=chat_id, audio=open(nombreArchivoResultante, 'rb'))
                    voiceSAM.borrarAudio()
                    print("audio")
                else:
                    print("no audio")
                    self.tb.reply_to(m, respuestaChatBot)

        print("Sistema listo para recibir mensajes")
        self.tb.set_update_listener(listener)
        self.tb.polling()

    def extract_unique_code(self, text):
        mensaje_filtrado = text.split()
        contadorItemsLista = 0
        for item in mensaje_filtrado:
            contadorItemsLista += 1

        if contadorItemsLista > 1:
            return mensaje_filtrado[1]
        else:
            return " "


#!/usr/bin/env python

import rospy
from std_msgs.msg import String
import sys
import time
import re
import RPi.GPIO as GPIO
import smbus
import math

bus = smbus.SMBus(1)
address = 0x1e

clk = 4
dt = 22
GPIO.setmode(GPIO.BCM)
GPIO.setup(clk, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(dt, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

pub = rospy.Publisher('bear_encd', String, queue_size=5)
rospy.init_node('bear_encoder', anonymous=True)
rate=rospy.Rate(10)

counter = 0
clkLastState = GPIO.input(clk)

def readEncoderl():
    global clkLastState
    global counter
    clkState = GPIO.input(clk)
    dtState = GPIO.input(dt)
    if clkState != clkLastState:
            if dtState != clkState:
                    counter += 1
            else:
                    counter -= 1
    clkLastState = clkState
    return counter

def read_byte(adr):
    return bus.read_byte_data(address, adr)

def read_word(adr):
    high = bus.read_byte_data(address, adr)
    low = bus.read_byte_data(address, adr+1)
    val = (high << 8) + low
    return val

def read_word_2c(adr):
    val = read_word(adr)
    if (val >= 0x8000):
        return -((65535 - val) + 1)
    else:
        return val

def write_byte(adr, value):
    bus.write_byte_data(address, adr, value)

write_byte(0, 0b01110000) # Set to 8 samples @ 15Hz
write_byte(1, 0b00100000) # 1.3 gain LSb / Gauss 1090 (default)
write_byte(2, 0b00000000) # Continuous sampling

scale = 0.92

def getBearingData():
    x_out = read_word_2c(3) * scale
    y_out = read_word_2c(7) * scale
    z_out = read_word_2c(5) * scale

    bearing  = math.atan2(y_out, x_out)
    if (bearing < 0):
        bearing += 2 * math.pi

    return math.degrees(bearing)

def callbackencd(data):
    bear = str(getBearingData())
    encd = data.data
    rospy.loginfo(repr(bear+" "+encd))
    pub.publish(bear+" "+encd)
    rate.sleep()

def bearingPublish():

    # while not rospy.is_shutdown():
    subencd=rospy.Subscriber('encoderl', String, callbackencd)
    rospy.sleep(0.1)
    rospy.spin()

if __name__ == '__main__':
    try:
        bearingPublish()
    except rospy.ROSInterruptException:
        pass


from django.shortcuts import render, redirect, get_object_or_404
from clientes.models import Person
from .forms import PersonForm
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

@login_required
def listar_clientes(request):
    people = Person.objects.all()
    return render(request, "listar_clientes.html", {"people": people})

@login_required
def incluir_cliente(request):
    form = PersonForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
        return redirect('listar_clientes')
    return render(request, "incluir_alterar_clientes.html", {"form": form})

@login_required
def alterar_cliente(request, cliente_id):
    try:
        person = get_object_or_404(Person, pk=cliente_id)
        form = PersonForm(request.POST or None, request.FILES or None, instance=person)

        if form.is_valid():
            form.save()
            return redirect('listar_clientes')
        return render(request, "incluir_alterar_clientes.html", {"form": form})
    except Person.DoesNotExist:
        return HttpResponse("nao existi o objeto com este id: {}".format(cliente_id))

@login_required
def deletar_cliente(request, cliente_id):
    try:
        person = get_object_or_404(Person, pk=cliente_id)
        person.delete()
        return redirect('listar_clientes')
    except Person.DoesNotExist:
        return HttpResponse("nao existi o objeto com este id: {}".format(cliente_id))


# coding: utf-8
#########################################################################
# 网站: 疯狂Java联盟               #
# author yeeku.H.lee kongyeeku@163.com                                  #
#                                                                       #
# version 1.0                                                           #
#                                                                       #
# Copyright (C), 2001-2018, yeeku.H.Lee                                 #
#                                                                       #
# This program is protected by copyright laws.                          #
#                                                                       #
# Program Name:                                                         #
#                                                                       #
#
Date:                                                             #
#########################################################################
import selectors, socket, threading

# 创建默认的selectors对象
sel = selectors.DefaultSelector()
# 负责监听“有数据可读”事件的函数
def read(conn, mask):
    data = conn.recv(1024)  # Should be ready
    if data:
        print(data.decode('utf-8'))
    else:
        print('closing', conn)
        sel.unregister(conn)
        conn.close()
# 创建socket对象
s = socket.socket()
# 连接远程主机
s.connect(('192.168.1.88', 30000))
# 设置该socket是非阻塞的
s.setblocking(False)
# 使用sel为s的EVENT_READ事件注册read监听函数
sel.register(s, selectors.EVENT_READ, read)    # ①
# 定义不断读取用户键盘输入的函数
def keyboard_input(s):
    while True:
        line = input('')
        if line is None or line == 'exit':
            break
        # 将用户的键盘输入内容写入socket
        s.send(line.encode('utf-8'))
# 采用线程不断读取用户的键盘输入
threading.Thread(target=keyboard_input, args=(s, )).start()
while True:
    # 获取事件
    events = sel.select()
    for key, mask in events:
        # key的data属性获取为该事件注册的监听函数
        callback = key.data
        # 调用监听函数, key的fileobj属性获取被监听的socket对象
        callback(key.fileobj, mask)


#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import os
import pandas as pd

def process_data(select):
    '''
    按照一级标签做分类
    :return: texts,labels
    '''
    ann_filename = r'label_text.csv'
    df = pd.read_csv(ann_filename, encoding='utf-8')  # pandas读取csv数据
    print('step1: 读取标注文本及标签信息', select)  # 显示当前处理的二级标签类别
    make_label(df)
    X = df[['Content']]
    Y = df.multilabel
    print(df.head())  # 查看前5行
    classes_num = 0
    if select == 'all':
        anntxt = X.values.tolist()
        label = Y.tolist()
        # label = [x - 1 for x in label]
        content, tag = [], []
        for i in range(len(label)):
            if label[i] in [1,2,3]:
                content.append(anntxt[i])
                tag.append(0)
            if label[i] in [4,5, 6,7]:
                content.append(anntxt[i])
                tag.append(1)
            if label[i] in [8,9, 10]:
                content.append(anntxt[i])
                tag.append(2)
            if label[i] in [13,14, 15]:
                content.append(anntxt[i])
                tag.append(3)
            if label[i] in [16,17, 18, 19, 20,21]: #抑郁 焦虑问题合并
                content.append(anntxt[i])
                tag.append(4)
            if label[i] in [22, 23, 24,25]:#学习问题
                content.append(anntxt[i])
                tag.append(5)
            if label[i] in [26, 27, 28]:
                content.append(anntxt[i])
                tag.append(6)
            if label[i] in [12, 29, 30]: #特殊问题
                content.append(anntxt[i])
                tag.append(7)
            if label[i] in [34, 35]: #健康状况
                content.append(anntxt[i])
                tag.append(8)
            if label[i] in [36, 37, 38]: #所属群体	一般儿童，留守儿童，流动儿童，孤困儿童
                content.append(anntxt[i])
                tag.append(9)
            if label[i] in [39, 40, 41]: #家庭结构	寄养家庭，重组家庭，单亲家庭，完整家庭
                content.append(anntxt[i])
                tag.append(10)
            if label[i] in [42, 43, 44, 45]: #教养方式	权威型教养方式，专制型教养方式，溺爱型教养方式，忽视型教养方式
                content.append(anntxt[i])
                tag.append(11)
            if label[i] in [46, 47, 48, 49]: #家庭气氛	平静型家庭气氛，和谐型家庭气氛，冲突型家庭气氛，离散型家庭气氛
                content.append(anntxt[i])
                tag.append(12)
            if label[i] in [50, 51]:  # 成员健康状况
                content.append(anntxt[i])
                tag.append(13)
            if label[i] in [54, 55]:  # 成员经济状况
                content.append(anntxt[i])
                tag.append(14)
            if label[i] in [56, 57, 58]:  # 教师领导方式	权威型领导方式，民主型领导方式，放任型领导方式
                content.append(anntxt[i])
                tag.append(15)
            if label[i] in [59, 60, 61, 62, 63]:  #同伴接纳	受欢迎，一般型，被拒绝，被忽视，矛盾型
                content.append(anntxt[i])
                tag.append(16)
            if label[i] in [66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81]:
                content.append(anntxt[i])
                tag.append(17)
            if label[i] in [82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95]:
                content.append(anntxt[i])
                tag.append(18)

        train_x_list = content
        train_y_list = tag
        print('获取all ann 数据规模：', len(train_y_list))
        classes_num = 19
    return train_x_list, train_y_list, classes_num

def make_label(df):
    '''把label22，转换为22；字符截取 转为int。'''
    df["multilabel"] = df["Label"].apply(lambda x: int(x[5:]))

if __name__ == '__main__':
    select = 'all'
    anntxt, label, classes_num = process_data(select)
    print('获取数据完成', select)


#!/usr/bin python
# -*- coding: utf-8 -*-

import wave

import pyaudio

FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 50
WAVE_OUTPUT_FILENAME = "teste.wav"

audio = pyaudio.PyAudio()

def main():
    # começa a gravação

    stream = audio.open(format=FORMAT, channels=CHANNELS,
                        rate=RATE, input=True,
                        frames_per_buffer=CHUNK)
    frames = []

    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)

    # termina a gravação

    stream.stop_stream()
    stream.close()
    audio.terminate()

    waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    waveFile.setnchannels(CHANNELS)
    waveFile.setsampwidth(audio.get_sample_size(FORMAT))
    waveFile.setframerate(RATE)
    waveFile.writeframes(b''.join(frames))
    waveFile.close()

if __name__ == "__main__":
    main()


from .modules import ThreadCreator
from .utils import emit

class Customer(ThreadCreator):
    target = 'customer'
    def initialize(self, name):
        def customer_func():
            self.trigger('enter', name=name)
            # Do not block thread activity.
            can_seat = self.seat_semaphore.acquire(blocking=False)
            if not can_seat:
            # Exit the thread because the seat is full.
                self.trigger('full', name=name)
            else:
                # Signal barber that a customer has been added into waiting queue.
                self.customer_queue.put(name)
                self.customer_semaphore.release()
                self.trigger('waiting', name=name)
                self.barber_semaphore.acquire()
                self.trigger('serving', name=name)
        return customer_func


# -*- coding: UTF-8 -*-

from predict_1_5 import *
from predict_5_12 import *
from predict_no import *
from predict_12_23_yf import *
from predict_max_23 import *
from predict_circle import *
from predict_no_yf import *
from util.get_dis3_circle import *
from util.pro_is_flag import *
from util.get_no_tred import *

circle = pd.read_csv('../pro_data/circle.csv', index_col=0)
train_district3 = pd.read_csv('../pro_data/train_district3.csv', index_col=0)
product_info = pd.read_csv('../data/product_info.txt', index_col=0)
train_month = pd.read_csv('../pro_data/train_month.csv', index_col=0)
predict = pd.read_csv('../data/prediction_lilei.txt', index_col=[0, 1])
predict['ciiquantity_month'] = 0
predict = predict.unstack()
length = len(train_month.columns)
l = get_dis3_circle()
dic = get_no_trend()

for i in predict.index:
    if i in train_month.index:
        s = train_month.loc[i]
        flag = length  # flag代表开始具有销量时的月份下标
        for j in range(0, length):
            if s[j] > 0:
                flag = j
                break
        if i in circle.index:  # 如果其具有强烈的周期性，则进行周期性预测
            s = circle.loc[i]
            predict.loc[i] = predict_cricle(s)
            continue
        if length - flag == 23:  # 对历史销量都存在的出行产品进行预测
            r1 = predict_max_23(s)
            predict.loc[i] = np.array(r1)
        elif length - flag >= 12:  # 对历史销量在12到23个月之间的出行产品进行预测
            d = product_info.at[i, 'district_id3']
            flag1 = isflag(d, l)
            predict.loc[i] = predict_12_23_yf(s, flag1)
        elif length - flag > 4:  # 对历史销量在5到12个月之间的出行产品进行预测
            predict.loc[i] = predict_5_12(s, flag, product_info.at[i, 'voters'])
        elif length - flag > 0:  # 对历史销量在1到5个月之间的出行产品进行预测
            predict.loc[i] = predict_1_5(s, flag, product_info.at[i, 'voters'])
        else:  # 对只有预订单而没有历史销量的出行产品进行预测
            d = product_info.at[i, 'district_id3']
            trend = None
            if d in dic:
                trend = dic[d]
            predict.loc[i] = np.array(give_value_startdate(product_info.at[i, 'voters'], 0, trend))
    else:  # 对没有订单数据的出行产品进行预测
        d = product_info.at[i, 'district_id3']
        trend = None
        if d in dic:
            trend = dic[d]
        r1 = predict_no(product_info.at[i, 'voters'],
                        product_info.at[i, 'startdate'], product_info.at[i, 'cooperatedate'], trend)
        r2 = predict_no_yf(product_info.at[i, 'voters'],
                           product_info.at[i, 'startdate'], product_info.at[i, 'cooperatedate'], trend)
        predict.loc[i] = (0.5 * np.array(r1) + 0.5 * np.array(r2))
predict.columns = ['2015-12-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-04-01', '2016-05-01', '2016-06-01',
                   '2016-07-01', '2016-08-01', '2016-09-01', '2016-10-01', '2016-11-01', '2016-12-01', '2017-01-01']
predict = predict.unstack()
predict.name = 'ciiquantity_month'
predict.index.names = ['product_month', 'product_id']
predict = predict.swaplevel()
predict.to_csv('../result/prediction_lemonace_final.txt', header=True)


# _*_ coding: utf-8 _*_
# Author: Monica( nikochild@gmail.com)
from odoo import models, fields, api, _

class JptipExam(models.Model):
    _name = 'jt.exam'

    # @api.model
    # def _getCourseTime(self):
    #     return [('id', 'in', 'batch_id.class_time')]

    name = fields.Char('測驗', size=256)
    batch_id = fields.Many2one(
        'jt.batch', '班級名稱', store=True, required=True)
    course_id = fields.Many2one(
        'jt.course', '級數', store=True)
    batch_course_id = fields.Many2one('jt.course.line', string='選擇級數')
    timetable_id = fields.Many2one(
        'class.timetable', '課堂', store=True)
    start_time = fields.Many2many('jt.time.session.manager',  string='上課時間')
    lines_id = fields.One2many(
        'jt.exam.lines', 'exam_id')
    exam_category = fields.Selection([('a', '平時考'), ('b', '期中考'), ('c', '期末考')], string='考試類別', required=True)
    company_id = fields.Many2one(related='batch_id.company_id', string='Company', store=True, readonly=True)

    def exam_lines(self):
        lines = []
        for exam in self:
            if any(exam.batch_id.st_batch_id):
                for st in exam.batch_id.st_batch_id.filtered(lambda x: x.state == 'ing' and x.course_line_id.id == self.batch_course_id.id):
                    line = self.env['jt.exam.lines'].create({
                        'exam_id': exam.id,
                        'student_id': st.student_id.id,
                    })
                    lines.append(line.id)
        return lines

    @api.onchange('batch_course_id')
    def onchange_student(self):
        if not self.batch_id:
            self.lines_id.unlink()
        else:
            lines = self.exam_lines()
            course = sorted(self.batch_id.course_id.course_ids, key=lambda x: x.id)
            if self.batch_id.name and self.batch_course_id.code and dict(self._fields['exam_category'].selection).get(self.exam_category):
                self.name = self.batch_id.name + '-' + self.batch_course_id.code + '-' + dict(self._fields['exam_category'].selection).get(self.exam_category)
            self.update({
                'start_time': [(6, 0, self.batch_id.class_time.ids)],
                'lines_id': [(6, 0, lines)],
            })

    @api.onchange('exam_category')
    def onchange_exam_category(self):
        if self.batch_id.name and self.batch_course_id.code and dict(self._fields['exam_category'].selection).get(self.exam_category):
            self.name = self.batch_id.name + '-' + self.batch_course_id.code + '-' + dict(self._fields['exam_category'].selection).get(self.exam_category)
            if not self.batch_id:
                self.lines_id.unlink()
            else:
                lines = self.exam_lines()
                course = sorted(self.batch_id.course_id.course_ids, key=lambda x: x.id)
                self.update({
                    'start_time': [(6, 0, self.batch_id.class_time.ids)],
                    'lines_id': [(6, 0, lines)]
                })

    # @api.onchange('timetable_id')
    # def onchange_name(self):
    #     if not self.timetable_id:
    #         self.name = False
    #     else:
    #         self.name = '%s' % self.timetable_id.name
    #         self.course_id = self.timetable_id.course_line_id.id

    @api.model
    def create(self, values):
        # if not values.get('name', False) or values['name'] == _('New'):
        #     values['name'] = '%s' % self.env['class.timetable'].browse(values.get('timetable_id')).name
        if not values.get('lines_id', False):
            values['lines_id'] = [(6, 0, self.exam_lines())]
        Exam = super(JptipExam, self).create(values)
        return Exam

class JptipExamLines(models.Model):
    _name = 'jt.exam.lines'

    exam_id = fields.Many2one('jt.exam', ondelete="cascade")
    student_id = fields.Many2one('jt.student')
    exam_code = fields.Char(string='分數')
    note = fields.Text('Note')
    company_id = fields.Many2one(related='exam_id.company_id', string='Company', store=True, readonly=True)

    @api.multi
    def unlink(self):
        return super(JptipExamLines, self).unlink()


# Author: Deendayal Kumawat
""" Date: 22/12/19
Descriptions: Loop"""
'''
While Loop ----> Conditions check first and
if condition true then loop execute and if condition is false then break the loop
'''
i = 0
while (i < 50):
    print("Hello")
    i = i+1


from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba

path_txt = 'file.txt'
f = open(path_txt, 'r', encoding='UTF-8').read()

cut_text = " ".join(jieba.cut(f))

wordcloud = WordCloud(
    font_path="/Users/Jason/Library/Fonts/msyh.ttf",
    background_color="white", width=1000, height=880).generate(cut_text)

plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()


"""
	Helper functions and list to the PBG module. Mostly here to cut down length of PBG file.
"""

lineNo = []

def objType(obj):
	if obj: return obj.__class__.__name__
	else: return str(None)

def getAttribute(attrObj, fromCall):
	stack = []
	ctx = ["Call"] if fromCall else ["Attr"]
	calls = [attrObj] if fromCall else[]
	#this simply finds the string that is the attribute e.g. math.sqrt
	def attrDive(obj):
		nonlocal stack, ctx, calls
		stack.append(obj.attr)
		if "Attribute" == objType(obj.value):
			ctx.append("Attr"); attrDive(obj.value)
		elif "Call" == objType(obj.value):
			ctx.append("Call"); calls.append(obj.value)
			if "Attribute" == objType(obj.value.func): attrDive(obj.value.func)
			elif "Name" == objType(obj.value.func):stack.append(obj.value.func.id)
		elif "Name" == objType(obj.value):
			ctx.append("Attr"); stack.append(obj.value.id);
	if fromCall: attrDive(attrObj.func)
	else: attrDive(attrObj)
	attr = ''; realctx = []; realcalls = []
	while stack:
		attr += stack.pop()+"."
		realctx.append(ctx.pop())
	while calls: realcalls.append(calls.pop())
	attr = attr[:-1]; attr = attr.split(".")
	return attr, realctx, realcalls