from odoo import api, fields, models

class AccountPaymentLine(models.Model):
    _inherit = "account.payment.line"

    priority = fields.Selection(
        [("NORM", "Normal"), ("HIGH", "High")],
        string="Priority",
        default="NORM",
        help="This field will be used as 'Instruction Priority' in "
        "the generated PAIN file.",
    )
    # local_instrument is used for instant credit transfers which
    # will begin on November 2017, cf account_banking_sepa_credit_transfer
    # It is also used in some countries such as switzerland,
    # cf l10n_ch_pain_base that adds some entries in the selection field
    local_instrument = fields.Selection([], string="Local Instrument")
    category_purpose = fields.Selection(
        [
            # Full category purpose list found on:
            # https://www.iso20022.org/external_code_list.page
            # Document "External Code Sets spreadsheet" version Feb 8th 2017
            ("BONU", "Bonus Payment"),
            ("CASH", "Cash Management Transfer"),
            ("CBLK", "Card Bulk Clearing"),
            ("CCRD", "Credit Card Payment"),
            ("CORT", "Trade Settlement Payment"),
            ("DCRD", "Debit Card Payment"),
            ("DIVI", "Dividend"),
            ("DVPM", "Deliver Against Payment"),
            ("EPAY", "ePayment"),
            ("FCOL", "Fee Collection"),
            ("GOVT", "Government Payment"),
            ("HEDG", "Hedging"),
            ("ICCP", "Irrevocable Credit Card Payment"),
            ("IDCP", "Irrevocable Debit Card Payment"),
            ("INTC", "Intra-Company Payment"),
            ("INTE", "Interest"),
            ("LOAN", "Loan"),
            ("OTHR", "Other Payment"),
            ("PENS", "Pension Payment"),
            ("RVPM", "Receive Against Payment"),
            ("SALA", "Salary Payment"),
            ("SECU", "Securities"),
            ("SSBE", "Social Security Benefit"),
            ("SUPP", "Supplier Payment"),
            ("TAXS", "Tax Payment"),
            ("TRAD", "Trade"),
            ("TREA", "Treasury Payment"),
            ("VATX", "VAT Payment"),
            ("WHLD", "WithHolding"),
        ],
        string="Category Purpose",
        help="If neither your bank nor your local regulations oblige you to "
        "set the category purpose, leave the field empty.",
    )
    purpose = fields.Selection(
        # Full category purpose list found on:
        # https://www.iso20022.org/external_code_list.page
        # Document "External Code Sets spreadsheet" version 31 August, 2018
        selection=[
            ("ACCT", "Account Management"),
            ("CASH", "Cash Management Transfer"),
            ("COLL", "Collection Payment"),
            ("INTC", "Intra Company Payment"),
            ("LIMA", "Liquidity Management"),
            ("NETT", "Netting"),
            ("AGRT", "Agricultural Transfer"),
            ("BEXP", "Business Expenses"),
            ("COMC", "Commercial Payment"),
            ("CPYR", "Copyright"),
            ("GDDS", "Purchase Sale Of Goods"),
            ("LICF", "License Fee"),
            ("ROYA", "Royalties"),
            ("SCVE", "Purchase Sale Of Services"),
            ("SUBS", "Subscription"),
            ("SUPP", "Supplier Payment"),
            ("TRAD", "Trade Services"),
            ("CHAR", "Charity Payment"),
            ("COMT", "Consumer Third Party Consolidated Payment"),
            ("CLPR", "Car Loan Principal Repayment"),
            ("GOVI", "Government Insurance"),
            ("HLRP", "Housing Loan Repayment"),
            ("INSU", "Insurance Premium"),
            ("INTE", "Interest"),
            ("LBRI", "Labor Insurance"),
            ("LIFI", "Life Insurance"),
            ("LOAN", "Loan"),
            ("LOAR", "Loan Repayment"),
            ("PPTI", "Property Insurance"),
            ("RINP", "Recurring Installment Payment"),
            ("TRFD", "Trust Fund"),
            ("ADVA", "Advance Payment"),
            ("CCRD", "Credit Card Payment "),
            ("CFEE", "Cancellation Fee"),
            ("COST", "Costs"),
            ("DCRD", "Debit  Card  Payment"),
            ("GOVT", "Government Payment"),
            ("IHRP", "Instalment Hire Purchase Agreement"),
            ("INSM", "Installment"),
            ("MSVC", "Multiple Service Types"),
            ("NOWS", "Not Otherwise Specified"),
            ("OFEE", "Opening Fee"),
            ("OTHR", "Other"),
            ("PADD", "Preauthorized debit"),
            ("PTSP", "Payment Terms"),
            ("RCPT", "Receipt Payment"),
            ("RENT", "Rent"),
            ("STDY", "Study"),
            ("ANNI", "Annuity"),
            ("CMDT", "Commodity Transfer"),
            ("DERI", "Derivatives"),
            ("DIVD", "Dividend"),
            ("FREX", "Foreign Exchange"),
            ("HEDG", "Hedging"),
            ("PRME", "Precious Metal"),
            ("SAVG", "Savings"),
            ("SECU", "Securities"),
            ("TREA", "Treasury Payment"),
            ("ANTS", "Anesthesia Services"),
            ("CVCF", "Convalescent Care Facility"),
            ("DMEQ", "Durable Medicale Equipment"),
            ("DNTS", "Dental Services"),
            ("HLTC", "Home Health Care"),
            ("HLTI", "Health Insurance"),
            ("HSPC", "Hospital Care"),
            ("ICRF", "Intermediate Care Facility"),
            ("LTCF", "Long Term Care Facility"),
            ("MDCS", "Medical Services"),
            ("VIEW", "Vision Care"),
            ("ALMY", "Alimony Payment"),
            ("BECH", "Child Benefit"),
            ("BENE", "Unemployment Disability Benefit"),
            ("BONU", "Bonus Payment."),
            ("COMM", "Commission"),
            ("PENS", "Pension Payment"),
            ("PRCP", "Price Payment"),
            ("SALA", "Salary Payment"),
            ("SSBE", "Social Security Benefit"),
            ("ESTX", "Estate Tax"),
            ("HSTX", "Housing Tax"),
            ("INTX", "Income Tax"),
            ("TAXS", "Tax Payment"),
            ("VATX", "Value Added Tax Payment"),
            ("AIRB", "Air"),
            ("BUSB", "Bus"),
            ("FERB", "Ferry"),
            ("RLWY", "Railway"),
            ("CBTV", "Cable TV Bill"),
            ("ELEC", "Electricity Bill"),
            ("ENRG", "Energies"),
            ("GASB", "Gas Bill"),
            ("NWCH", "Network Charge"),
            ("NWCM", "Network Communication"),
            ("OTLC", "Other Telecom Related Bill"),
            ("PHON", "Telephone Bill"),
            ("WTER", "Water Bill"),
        ],
        help="If neither your bank nor your local regulations oblige you to "
        "set the category purpose, leave the field empty.",
    )
    # PAIN allows 140 characters
    communication = fields.Char(size=140)
    # The field struct_communication_type has been dropped in v9
    # We now use communication_type ; you should add an option
    # in communication_type with selection_add=[]
    communication_type = fields.Selection(
        selection_add=[("ISO", "ISO")], ondelete={"ISO": "cascade"}
    )

    @api.model
    def _get_payment_line_grouping_fields(self):
        """Add specific PAIN fields to the grouping criteria."""
        res = super()._get_payment_line_grouping_fields()
        res += ["priority", "local_instrument", "category_purpose", "purpose"]
        return res


from scipy import signal
import numpy as np

with open('input.txt') as f:
  input = [list(line.strip()) for line in f]
  array = np.array([x for x in input]).astype(int)

rows_len = np.shape(array)[1]
cols_len = np.shape(array)[0]

def LowPoint(array,r,c):
  dirs = [(1,0),(0,1),(0,-1),(-1,0)]
  # for r, c in np.ndindex(array.shape):
  for dr, dc in dirs:
    new_r = r + dr
    new_c = c + dc
    if new_r >=0 and new_c >=0 and new_r < rows_len and new_c < cols_len:
      if array[r][c] >= array[new_r][new_c]:
        return False
  return True

def CalcRisk():
  risk = 0
  for r in range(rows_len):
    for c in range(cols_len):
      if LowPoint(array, r, c):
        risk += array[r][c] + 1
  return risk

print(CalcRisk())


from fastapi import APIRouter

from crud.users import CRUDUser
from schemas import UserSchema, UserInDBSchema

router = APIRouter()

#limit: int = 10, skip: int = 100
@router.get("/")
async def read_users():
    return await CRUDUser.get_all()

@router.post("/", response_model=UserSchema)
async def add(user: UserSchema):
    return await CRUDUser.add(user=user)

@router.put("/", response_model=UserSchema)
async def update(user: UserInDBSchema):
    return await CRUDUser.update(users=user)


'''
Faça um Programa que leia um vetor de 5 números inteiros, mostre a soma, a
multiplicação e os números.

'''

arrayNumbers = []
soma = 0
multiplicacao = 1

for x in range(5):
    num = int(input("Digite o primeiro número: "))
    arrayNumbers.append(num)
    soma += num
    multiplicacao *= num

print("Soma: ", soma)
print("Multiplicação: ", multiplicacao)
print("Números digitados: ", arrayNumbers)


from collections import namedtuple
import random
from typing import List

from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, \
    ReplyKeyboardRemove
from aiogram.utils.callback_data import CallbackData

from async_bot.dialog_branches.clients.question import Question, QuestionType

Button = namedtuple("Button", ["name", "data"])

callback_data_leave_order = CallbackData("leave_order", "answer")
callback_data_station = CallbackData("station", "id")
callback_data_answer = CallbackData("answer", "answer_id")
callback_data_apply = CallbackData("apply", "answer")

def create_keyboard_reply(buttons: List[str], rows: List[int] = None) -> ReplyKeyboardMarkup:
    if rows is None:
        rows = [1] * len(buttons)

    if len(buttons) != sum(rows):
        raise Exception(
            f"Bad amount of button. Button: {len(buttons)}, rows: {sum(rows)}"
        )

    keyboard = ReplyKeyboardMarkup(resize_keyboard=True)
    new_buttons = [KeyboardButton(x) for x in buttons]

    index = 0
    for amount in rows:
        keyboard.row(*new_buttons[index: index + amount])
        index += amount

    return keyboard

def create_keyboard_inline(buttons: List[Button], rows: List[int] = None) -> InlineKeyboardMarkup:
    if rows is None:
        rows = [1] * len(buttons)

    if len(buttons) != sum(rows):
        raise Exception(
            f"Bad amount of button. Button: {len(buttons)}, rows: {sum(rows)}"
        )

    keyboard = InlineKeyboardMarkup(resize_keyboard=True)
    new_buttons = [InlineKeyboardButton(x.name, callback_data=x.data) for x in buttons]

    index = 0
    for amount in rows:
        keyboard.row(*new_buttons[index: index + amount])
        index += amount

    return keyboard

async def process_question(message: types.Message, question: Question | List[Question], additional_message=None):
    keyboard = ReplyKeyboardRemove()
    if type(question) is list:
        question = random.choice(question)
    answers = question.answers
    text_message = question.body

    if question.type == QuestionType.some:
        buttons = [Button(f"âšª {a.answer}", callback_data_answer.new(answer_id=i)) for i, a in enumerate(answers)]
        rows = [2 if (i + 1) * 2 <= len(buttons) else 1 for i in range((len(buttons) + 1) // 2)]
        buttons.append(Button('ÐžÑ‚Ð²ÐµÑ‚Ð¸Ñ‚ÑŒ', 'ÐžÑ‚Ð²ÐµÑ‚'))
        rows.append(1)

        keyboard = create_keyboard_inline(buttons, rows)
    elif question.type == QuestionType.one or question.type == QuestionType.any:
        keyboard = create_keyboard_reply(answers, [len(answers)])
        if additional_message is not None:
            text_message += additional_message

    if question.picture is not None:
        await message.answer_photo(question.picture, caption=text_message,
                                   reply_markup=keyboard)
    else:
        await message.answer(text_message, reply_markup=keyboard)
    if question.state is not None:
        await question.state.set()
    return question

async def process_remain_question(message: types.Message, remain: list, state: FSMContext, session):
    if len(remain) == 0:
        await state.finish()
        await message.answer('ÐŸÐ¾Ð·Ð´Ñ€Ð°Ð²Ð»Ñ�ÑŽ, Ñ‚Ñ‹ Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ð» Ñ�Ñ‚Ñƒ Ñ�Ñ‚Ð°Ð½Ñ†Ð¸ÑŽ!')
    else:
        question = remain.pop()
        await process_question(message, question, session)
        await state.update_data(remain_questions=remain)

def format_text_with_entities(text, entities, as_html=True):
    if text is None:
        return None

    # Create a message object to access the parse_entities method
    message = types.Message(text=text, entities=entities)

    if as_html:
        return message.html_text
    else:
        return message.md_text

menu_keyboard = create_keyboard_reply(["ðŸšŒ ÐŸÐ¾ÐµÑ…Ð°Ð»Ð¸"], rows=[1])


from django.shortcuts import render, HttpResponse

'''
Docs:
EClient: https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClient.html
Ewrapper: https://interactivebrokers.github.io/tws-api/interfaceIBApi_1_1EWrapper.html
Market Data: https://interactivebrokers.github.io/tws-api/top_data.html
Cancel MKT data: https://interactivebrokers.github.io/tws-api/md_cancel.html

Flow:
0) Get/update the list of stocks to display
1) start reqMktData for the list of stocks
2) Collect the data from an API to a buffer (DF)
3) Store the last received values into a temporary variable
4) Display the values from the temp var onto the webpage.
5) Send the values to the calculators of the indicators
-) Stop the stream when disconnected

'''
from time import sleep

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum

from threading import Timer
from background_task import background

from ib_insync import *

from rest_framework import viewsets
from .api import *

# stock_price = []
# stock_ticker = []
stock_dick = dict()

def stock_data_api(request):
    # context = {}

    # context = {
    #     'tickers': stock_ticker,
    #     'prices': stock_price
    # }
    # context['stocks'] = stocks
    context = {
        'items': stock_dick.items()
    }
    return render(request, 'ib_api/stock_data_api.html', context)

def stock_data(request):
    context = {}
    add_stock = []
    if request.method == 'POST':
        add_stock.append(request.POST.get("stock_ticker"))
        background_view(request, add_stock)

    return render(request, 'ib_api/stock_data.html', context)

class TestApp(EClient, EWrapper):

    def __init__(self):
        EClient.__init__(self, self)

    def error(self, reqId, errorCode, errorString):
        print("Error: ", reqId, " ", errorCode, " ", errorString)

    def tickPrice(self, reqId, tickType, price, attrib):
        print("Ticker Price Data:  Ticket ID: ", reqId, " ","tickType: ", TickTypeEnum.to_str(tickType), "Price: ", price, end=" ")
        # stock_streaming_data = StockStreamingData()
        # stock_streaming_data.ticker = "AAPL"
        # stock_streaming_data.price = price
        # stock_streaming_data.save()
        # global stock_price
        # stock_price.append(price)

        # global stock_ticker
        # stock_ticker.append(reqId)
        stock_dick[reqId] = price

    def tickSize(self, reqId, tickType, size):
        print("Ticket ID: ", reqId, " ","tickType: ", TickTypeEnum.to_str(tickType), "Size: ", size)

    # def historicalData(self, reqId, bar):
    #     print("Historical Data:  Ticket ID: ", reqId, " Date: ", bar.date, " Open: ", bar.open, " Close: ", bar.close)

    def stop(self):
        self.done = True
        self.disconnect

# Connecting the TWS, retreive data

def ib_stock_api(stocks):
    app = TestApp()
    app.connect("127.0.0.1", 4004, clientId=0)
    # app.connect("127.0.0.1", 7497, clientId=17)
    contract = Contract()

    for i in range(len(stocks)):
        contract.symbol = stocks[i]
        # contract.symbol = stock
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"
        contract.primaryExchange = "NASDAQ"
        # FOREX
        # contract.symbol = 'EUR'
        # contract.secType = "CASH"
        # contract.exchange = "IDEALPRO"
        # contract.currency = "USD"

        app.reqMarketDataType(4)
        app.reqMktData(i, contract, "", False, False, [])

        # Timer(12, app.stop).start()
    app.run()

@background(schedule=5)
def hello():
	print("Hello World!!!!!!")

def background_view(request, stock_list=['AAPL']):
    # ib_stock_api('EUR.USD', 0, True)
    ib_stock_api(stock_list)
    return render(request, 'ib_api/bg.html')

def cancel_data(request):
    # cancel_stock = TestApp()
    wrapper = EWrapper()
    cancel_data  =EClient(wrapper)
    cancel_data.disconnect()
    return render(request, 'ib_api/cancel_data.html')
    # cancel_stock.cancelMktData(0)


import time
from flask import Flask, Response
from degiro_operator import attempt_trade_degiro, get_stocks_info, place_buy_orders, update_trailing_order_data, \
    update_current_PL_degiro
import ftx_operator
from threading import Thread
# from memory_profiler import profile
from interactive_broker_operator import trigger_orders_ib

app = Flask(__name__)
run_auto_trade = False
message = ''

@app.route('/')
def hello():
    return 'Hello to the Auto-Trading Stocks application!'

# Endpoints for De Giro Stocks trading @profile
@app.route('/start')
def start_auto_trade():
    global run_auto_trade
    run_auto_trade = True
    return Response(run_process(), mimetype="text/html")

@app.route('/stop')
def stop_auto_trade():
    global run_auto_trade
    run_auto_trade = False
    return "Application stopped"

@app.route('/stocks_info')
def stocks_info():
    get_stocks_info()
    return 'Product IDs have been updated'

@app.route('/buy_orders')
def buy_orders():
    place_buy_orders()
    return 'Buy orders have been placed'

@app.route('/update_current_PL')
def update_current_PL():
    update_current_PL_degiro()
    return 'Current P/L have been updated'

@app.route('/update_trailing_orders')
def update_trailing_orders():
    update_trailing_order_data()
    return 'Trailing orders have been updated'

def record_loop():
    global run_auto_trade, message
    while run_auto_trade:
        message = attempt_trade_degiro()
        print(message)
        time.sleep(60*5)

def run_process():
    t = Thread(target=record_loop)
    t.start()
    return 'Processing... :'

# Endpoints for FTX Crypto trading
@app.route('/set_orders_ftx')
def set_orders_ftx():
    ftx_operator.buy_sl_orders_ftx()
    return 'Buy and SL orders have been placed'

@app.route('/place_tp_ftx')
def place_tp_ftx():
    ftx_operator.place_tp_orders_ftx()
    return 'TP orders have been placed'

@app.route('/modify_orders_ftx')
def modify_orders_ftx():
    ftx_operator.modify_sl_tp_orders_ftx()
    return 'SL and TP orders have been modified'

@app.route('/update_history_ftx')
def update_history_ftx():
    ftx_operator.update_closed_trades_ftx()
    return 'Positions history have been updated'

@app.route('/test')
def test_main():
    ftx_operator.test_ftx()
    return 'test'

if __name__ == '__main__':
    # app.run(host='127.0.0.1', port=8080, debug=True, use_reloader=False)
    # attempt_trade_degiro()
    # start_auto_trade()
    # update_current_PL()
    # update_trailing_orders()
    # update_trailing_price()
    # test_main()
    trigger_orders_ib()


string = 'azcbobobegghakl'
#string = input ("Please enter string here")

result = ''
substring = ''

for number in range(len(string)):

    numberbefore = number - 1

    if substring is "":
        substring = string[number]
        continue

    if string[number] >= string[numberbefore]:
        substring += string[number]
    else:
        temp = string[number]

    # print(temp, iterator - 1, end=" - ")

    if len(substring) > len(result):
        result = substring

print(result)


import tensorflow as tf
import scipy.io as sio
import numpy as np
from PIL import Image

img_H = 64
img_W = 64
img_C = 3
GAN_type = "SNGAN"  # DCGAN, WGAN, WGAN-GP, SNGAN, LSGAN, RSGAN, RaSGAN
batchsize = 128
epsilon = 1e-14#if epsilon is too big, training of DCGAN is failure.

def deconv(inputs, shape, strides, out_num, is_sn=False):
    filters = tf.get_variable("kernel", shape=shape, initializer=tf.random_normal_initializer(stddev=0.02))
    bias = tf.get_variable("bias", shape=[shape[-2]], initializer=tf.constant_initializer([0]))
    if is_sn:
        return tf.nn.conv2d_transpose(inputs, spectral_norm("sn", filters), out_num, strides) + bias
    else:
        return tf.nn.conv2d_transpose(inputs, filters, out_num, strides) + bias

def conv(inputs, shape, strides, is_sn=False):
    filters = tf.get_variable("kernel", shape=shape, initializer=tf.random_normal_initializer(stddev=0.02))
    bias = tf.get_variable("bias", shape=[shape[-1]], initializer=tf.constant_initializer([0]))
    if is_sn:
        return tf.nn.conv2d(inputs, spectral_norm("sn", filters), strides, "SAME") + bias
    else:
        return tf.nn.conv2d(inputs, filters, strides, "SAME") + bias

def fully_connected(inputs, num_out, is_sn=False):
    W = tf.get_variable("W", [inputs.shape[-1], num_out], initializer=tf.random_normal_initializer(stddev=0.02))
    b = tf.get_variable("b", [num_out], initializer=tf.constant_initializer([0]))
    if is_sn:
        return tf.matmul(inputs, spectral_norm("sn", W)) + b
    else:
        return tf.matmul(inputs, W) + b

def leaky_relu(inputs, slope=0.2):
    return tf.maximum(slope*inputs, inputs)

def spectral_norm(name, w, iteration=1):
    #Spectral normalization which was published on ICLR2018,please refer to "https://www.researchgate.net/publication/318572189_Spectral_Normalization_for_Generative_Adversarial_Networks"
    #This function spectral_norm is forked from "https://github.com/taki0112/Spectral_Normalization-Tensorflow"
    w_shape = w.shape.as_list()
    w = tf.reshape(w, [-1, w_shape[-1]])
    with tf.variable_scope(name, reuse=False):
        u = tf.get_variable("u", [1, w_shape[-1]], initializer=tf.truncated_normal_initializer(), trainable=False)
    u_hat = u
    v_hat = None

    def l2_norm(v, eps=1e-12):
        return v / (tf.reduce_sum(v ** 2) ** 0.5 + eps)

    for i in range(iteration):
        v_ = tf.matmul(u_hat, tf.transpose(w))
        v_hat = l2_norm(v_)
        u_ = tf.matmul(v_hat, w)
        u_hat = l2_norm(u_)
    sigma = tf.matmul(tf.matmul(v_hat, w), tf.transpose(u_hat))
    w_norm = w / sigma
    with tf.control_dependencies([u.assign(u_hat)]):
        w_norm = tf.reshape(w_norm, w_shape)
    return w_norm

def mapping(x):
    max = np.max(x)
    min = np.min(x)
    return (x - min) * 255.0 / (max - min + epsilon)

def instanceNorm(inputs):
    mean, var = tf.nn.moments(inputs, axes=[1, 2], keep_dims=True)
    scale = tf.get_variable("scale", shape=mean.shape[-1], initializer=tf.constant_initializer([1.0]))
    shift = tf.get_variable("shift", shape=mean.shape[-1], initializer=tf.constant_initializer([0.0]))
    return (inputs - mean) * scale / (tf.sqrt(var + epsilon)) + shift

class Generator:
    def __init__(self, name):
        self.name = name

    def __call__(self, Z):
        with tf.variable_scope(name_or_scope=self.name, reuse=False):
            with tf.variable_scope(name_or_scope="linear"):
                inputs = tf.reshape(tf.nn.relu((fully_connected(Z, 4*4*512))), [batchsize, 4, 4, 512])
            with tf.variable_scope(name_or_scope="deconv1"):
                inputs = tf.nn.relu(instanceNorm(deconv(inputs, [5, 5, 256, 512], [1, 2, 2, 1], [batchsize, 8, 8, 256])))
            with tf.variable_scope(name_or_scope="deconv2"):
                inputs = tf.nn.relu(instanceNorm(deconv(inputs, [5, 5, 128, 256], [1, 2, 2, 1], [batchsize, 16, 16, 128])))
            with tf.variable_scope(name_or_scope="deconv3"):
                inputs = tf.nn.relu(instanceNorm(deconv(inputs, [5, 5, 64, 128], [1, 2, 2, 1], [batchsize, 32, 32, 64])))
            if img_H == 32:
                with tf.variable_scope(name_or_scope="deconv4"):
                    inputs = tf.nn.tanh(deconv(inputs, [5, 5, img_C, 64], [1, 1, 1, 1], [batchsize, img_H, img_W, img_C]))
                return inputs
            with tf.variable_scope(name_or_scope="deconv4"):
                 inputs = tf.nn.tanh(deconv(inputs, [5, 5, img_C, 64], [1, 2, 2, 1], [batchsize, img_H, img_W, img_C]))
            if img_H == 64:
                return inputs

    @property
    def var(self):
        return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, self.name)

class Discriminator:
    def __init__(self, name):
        self.name = name

    def __call__(self, inputs, reuse=False, is_sn=False):
        with tf.variable_scope(name_or_scope=self.name, reuse=reuse):
            with tf.variable_scope("conv1"):
                inputs = leaky_relu(conv(inputs, [5, 5, img_C, 64], [1, 2, 2, 1], is_sn))
            with tf.variable_scope("conv2"):
                inputs = leaky_relu(instanceNorm(conv(inputs, [5, 5, 64, 128], [1, 2, 2, 1], is_sn)))
            with tf.variable_scope("conv3"):
                inputs = leaky_relu(instanceNorm(conv(inputs, [5, 5, 128, 256], [1, 2, 2, 1], is_sn)))
            with tf.variable_scope("conv4"):
                inputs = leaky_relu(instanceNorm(conv(inputs, [5, 5, 256, 512], [1, 2, 2, 1], is_sn)))
            inputs = tf.layers.flatten(inputs)
            return fully_connected(inputs, 1, is_sn)

    @property
    def var(self):
        return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name)

class GAN:
    #Architecture of generator and discriminator just like DCGAN.
    def __init__(self):
        self.Z = tf.placeholder("float", [batchsize, 100])
        self.img = tf.placeholder("float", [batchsize, img_H, img_W, img_C])
        D = Discriminator("discriminator")
        G = Generator("generator")
        self.fake_img = G(self.Z)
        if GAN_type == "DCGAN":
            #DCGAN, paper: UNSUPERVISED REPRESENTATION LEARNING WITH DEEP CONVOLUTIONAL GENERATIVE ADVERSARIAL NETWORKS
            self.fake_logit = tf.nn.sigmoid(D(self.fake_img))
            self.real_logit = tf.nn.sigmoid(D(self.img, reuse=True))
            self.d_loss = - (tf.reduce_mean(tf.log(self.real_logit + epsilon)) + tf.reduce_mean(tf.log(1 - self.fake_logit + epsilon)))
            self.g_loss = - tf.reduce_mean(tf.log(self.fake_logit + epsilon))
            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "WGAN":
            #WGAN, paper: Wasserstein GAN
            self.fake_logit = D(self.fake_img)
            self.real_logit = D(self.img, reuse=True)
            self.d_loss = -tf.reduce_mean(self.real_logit) + tf.reduce_mean(self.fake_logit)
            self.g_loss = -tf.reduce_mean(self.fake_logit)
            self.clip = []
            for _, var in enumerate(D.var):
                self.clip.append(var.assign(tf.clip_by_value(var, -0.01, 0.01)))
            self.opt_D = tf.train.RMSPropOptimizer(5e-5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.RMSPropOptimizer(5e-5).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "WGAN-GP":
            #WGAN-GP, paper: Improved Training of Wasserstein GANs
            self.fake_logit = D(self.fake_img)
            self.real_logit = D(self.img, reuse=True)
            e = tf.random_uniform([batchsize, 1, 1, 1], 0, 1)
            x_hat = e * self.img + (1 - e) * self.fake_img
            grad = tf.gradients(D(x_hat, reuse=True), x_hat)[0]
            self.d_loss = tf.reduce_mean(self.fake_logit - self.real_logit) + 10 * tf.reduce_mean(tf.square(tf.sqrt(tf.reduce_sum(tf.square(grad), axis=[1, 2, 3])) - 1))
            self.g_loss = tf.reduce_mean(-self.fake_logit)
            self.opt_D = tf.train.AdamOptimizer(1e-4, beta1=0., beta2=0.9).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(1e-4, beta1=0., beta2=0.9).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "LSGAN":
            #LSGAN, paper: Least Squares Generative Adversarial Networks
            self.fake_logit = D(self.fake_img)
            self.real_logit = D(self.img, reuse=True)
            self.d_loss = tf.reduce_mean(0.5 * tf.square(self.real_logit - 1) + 0.5 * tf.square(self.fake_logit))
            self.g_loss = tf.reduce_mean(0.5 * tf.square(self.fake_logit - 1))
            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "SNGAN":
            #SNGAN, paper: SPECTRAL NORMALIZATION FOR GENERATIVE ADVERSARIAL NETWORKS
            self.fake_logit = tf.nn.sigmoid(D(self.fake_img, is_sn=True))
            self.real_logit = tf.nn.sigmoid(D(self.img, reuse=True, is_sn=True))
            self.d_loss = - (tf.reduce_mean(tf.log(self.real_logit + epsilon) + tf.log(1 - self.fake_logit + epsilon)))
            self.g_loss = - tf.reduce_mean(tf.log(self.fake_logit + epsilon))
            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "RSGAN":
            #RSGAN, paper: The relativistic discriminator: a key element missing from standard GAN
            self.fake_logit = D(self.fake_img)
            self.real_logit = D(self.img, reuse=True)
            self.d_loss = - tf.reduce_mean(tf.log(tf.nn.sigmoid(self.real_logit - self.fake_logit) + epsilon))
            self.g_loss = - tf.reduce_mean(tf.log(tf.nn.sigmoid(self.fake_logit - self.real_logit) + epsilon))
            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)
        elif GAN_type == "RaSGAN":
            #RaSGAN, paper: The relativistic discriminator: a key element missing from standard GAN
            self.fake_logit = D(self.fake_img)
            self.real_logit = D(self.img, reuse=True)
            self.avg_fake_logit = tf.reduce_mean(self.fake_logit)
            self.avg_real_logit = tf.reduce_mean(self.real_logit)
            self.D_r_tilde = tf.nn.sigmoid(self.real_logit - self.avg_fake_logit)
            self.D_f_tilde = tf.nn.sigmoid(self.fake_logit - self.avg_real_logit)
            self.d_loss = - tf.reduce_mean(tf.log(self.D_r_tilde + epsilon)) - tf.reduce_mean(tf.log(1 - self.D_f_tilde + epsilon))
            self.g_loss = - tf.reduce_mean(tf.log(self.D_f_tilde + epsilon)) - tf.reduce_mean(tf.log(1 - self.D_r_tilde + epsilon))
            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)
            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)
        self.sess = tf.Session()
        self.sess.run(tf.global_variables_initializer())

    def __call__(self):
        saver = tf.train.Saver()
        epoch_nums = 200
        facedata = sio.loadmat("./TrainingSet//facedata.mat")["data"]
        #For face data, i random select about 10,000 images from CelebA and resize them to 64x64 by Matlab.
        for epoch in range(epoch_nums):
            for i in range(facedata.__len__()//batchsize-1):
                batch = facedata[i*batchsize:i*batchsize+batchsize, :, :, :] / 255.0
                z = np.random.standard_normal([batchsize, 100])
                d_loss = self.sess.run(self.d_loss, feed_dict={self.img: batch, self.Z: z})
                g_loss = self.sess.run(self.g_loss, feed_dict={self.img: batch, self.Z: z})
                self.sess.run(self.opt_D, feed_dict={self.img: batch, self.Z: z})
                if GAN_type == "WGAN":
                    self.sess.run(self.clip)#WGAN weight clipping
                self.sess.run(self.opt_G, feed_dict={self.img: batch, self.Z: z})
                if i % 10 == 0:
                    print("epoch: %d, step: %d, d_loss: %g, g_loss: %g"%(epoch, i,  d_loss, g_loss))
                    z = np.random.standard_normal([batchsize, 100])
                    imgs = self.sess.run(self.fake_img, feed_dict={self.img: batch, self.Z: z})
                    for j in range(batchsize):
                        if img_C == 1:
                            Image.fromarray(np.reshape(np.uint8(mapping(imgs[j, :, :, :])), [img_H, img_W])).save(
                                "./result//" + str(epoch) + "_" + str(j) + ".jpg")
                        else:
                            Image.fromarray(np.uint8(mapping(imgs[j, :, :, :]))).save(
                                "./result//" + str(epoch) + "_" + str(j) + ".jpg")
            saver.save(self.sess, "./para//model.ckpt")

if __name__ == "__main__":
    gan = GAN()
    gan()


import numpy as np
from edt import edt
from numba import njit, prange
from porespy.filters import trim_disconnected_blobs, pc_to_satn
from porespy import settings
from porespy.tools import get_tqdm, Results
tqdm = get_tqdm()

__all__ = [
    'drainage',
    'elevation_map',
]

def elevation_map(im_or_shape, voxel_size=1, axis=0):
    r"""
    Generate a image of distances from given axis

    Parameters
    ----------
    im_or_shape : ndarray or list
        This dictates the shape of the output image. If an image is supplied, then
        it's shape is used. Otherwise, the shape should be supplied as a N-D long
        list of the shape for each axis (i.e. `[200, 200]` or `[300, 300, 300]`).
    voxel_size : scalar, optional, default is 1
        The size of the voxels in physical units (i.e. `100e-6` would be 100 um per
        voxel side). If not given that 1 is used, so the returned image is in units
        of voxels.
    axis : int, optional, default is 0
        The direction along which the height is calculated.  The default is 0, which
        is the 'x-axis'.

    Returns
    -------
    elevation : ndarray
        A numpy array of the specified shape with the values in each voxel indicating
        the height of that voxel from the beginning of the specified axis.

    """
    if len(im_or_shape) <= 3:
        im = np.zeros(*im_or_shape, dtype=bool)
    else:
        im = im_or_shape
    im = np.swapaxes(im, 0, axis)
    a = np.arange(0, im.shape[0])
    b = np.reshape(a, [im.shape[0], 1, 1])
    c = np.tile(b, (1, *im.shape[1:]))
    c = c*voxel_size
    h = np.swapaxes(c, 0, axis)
    return h

def drainage(im, pc, inlets=None, bins=25):
    r"""
    Simulate drainage using image-based sphere insertion, optionally including
    gravity

    Parameters
    ----------
    im : ndarray
        The image of the porous media with ``True`` values indicating the
        void space.
    pc : ndarray
        An array containing capillary pressure map.
    inlets : ndarray (default = x0)
        A boolean image the same shape as ``im``, with ``True`` values
        indicating the inlet locations. See Notes. If not specified it is
        assumed that the invading phase enters from the bottom (x=0).
    bins : int or array_like (default =  `None`)
        The range of pressures to apply. If an integer is given
        then bins will be created between the lowest and highest pressures
        in the ``pc``.  If a list is given, each value in the list is used
        directly in order.

    Returns
    -------
    results : Results object
        A dataclass-like object with the following attributes:

        ========== =================================================================
        Attribute  Description
        ========== =================================================================
        im_pc      A numpy array with each voxel value indicating the
                   capillary pressure at which it was invaded
        im_snwp    A numpy array with each voxel value indicating the global
                   non-wetting phase saturation value at the point it was invaded
        ========== =================================================================

    """
    im = np.array(im, dtype=bool)
    dt = np.around(edt(im), decimals=0).astype(int)
    pc[~im] = np.inf

    if inlets is None:
        inlets = np.zeros_like(im)
        inlets[0, ...] = True

    if isinstance(bins, int):
        vals = np.unique(pc)
        vals = vals[~np.isinf(vals)]
        bins = np.logspace(np.log10(vals.min()), np.log10(vals.max()), bins)
    # Digitize pc
    pc_dig = np.digitize(pc, bins=bins)
    pc_dig[~im] = 0
    Ps = np.unique(pc_dig[im])

    # Initialize empty arrays to accumulate results of each loop
    seeds = np.zeros_like(im, dtype=bool)
    inv_pc = np.zeros_like(im, dtype=float)

    count = 0
    for p in tqdm(Ps, **settings.tqdm):
        # Find all locations in image invadable at current pressure
        temp = (pc_dig <= p)*im
        # Trim locations not connected to the inlets
        new_seeds = trim_disconnected_blobs(temp, inlets=inlets)
        # Isolate only newly found locations to speed up inserting
        temp = new_seeds*(~seeds)
        # Find i,j,k coordinates of new locations
        coords = np.where(temp)
        # Add new locations to list of invaded locations
        seeds += new_seeds
        # Extract the local size of sphere to insert at each new location
        radii = dt[coords]
        # Insert spheres at new locations of given radii
        inv_pc = _insert_disks_npoints_nradii_1value_parallel(
            im=inv_pc, coords=coords, radii=radii, v=bins[count])
        count += 1

    # Set uninvaded voxels to inf
    inv_pc[(inv_pc == 0)*im] = np.inf

    # Initialize results object and attached arrays
    results = Results()
    satn = pc_to_satn(pc=inv_pc, im=im)
    results.im_snwp = satn
    results.im_pc = inv_pc
    return results

@njit(parallel=True)
def _insert_disks_npoints_nradii_1value_parallel(
    im,
    coords,
    radii,
    v,
    overwrite=False,
    smooth=False,
):  # pragma: no cover
    if im.ndim == 2:
        xlim, ylim = im.shape
        for row in prange(len(coords[0])):
            i, j = coords[0][row], coords[1][row]
            r = radii[row]
            for a, x in enumerate(range(i-r, i+r+1)):
                if (x >= 0) and (x < xlim):
                    for b, y in enumerate(range(j-r, j+r+1)):
                        if (y >= 0) and (y < ylim):
                            R = ((a - r)**2 + (b - r)**2)**0.5
                            if (R <= r)*(~smooth) or (R < r)*(smooth):
                                if overwrite or (im[x, y] == 0):
                                    im[x, y] = v
    else:
        xlim, ylim, zlim = im.shape
        for row in prange(len(coords[0])):
            i, j, k = coords[0][row], coords[1][row], coords[2][row]
            r = radii[row]
            for a, x in enumerate(range(i-r, i+r+1)):
                if (x >= 0) and (x < xlim):
                    for b, y in enumerate(range(j-r, j+r+1)):
                        if (y >= 0) and (y < ylim):
                            for c, z in enumerate(range(k-r, k+r+1)):
                                if (z >= 0) and (z < zlim):
                                    R = ((a - r)**2 + (b - r)**2 + (c - r)**2)**0.5
                                    if (R <= r)*(~smooth) or (R < r)*(smooth):
                                        if overwrite or (im[x, y, z] == 0):
                                            im[x, y, z] = v
    return im

if __name__ == "__main__":
    import numpy as np
    import porespy as ps
    import matplotlib.pyplot as plt
    from copy import copy
    from edt import edt

    # %%
    im = ps.generators.blobs(shape=[200, 200, 200], porosity=0.7, blobiness=1.5, seed=0)
    inlets = np.zeros_like(im)
    inlets[0, ...] = True
    dt = edt(im)
    voxel_size = 1e-4
    sigma = 0.072
    theta = 180
    delta_rho = 1000
    g = 9.81

    pc = -2*sigma*np.cos(np.radians(theta))/(dt*voxel_size)
    drn1 = drainage(im=im, pc=pc, inlets=inlets, bins=50)
    pc_curve1 = ps.metrics.pc_map_to_pc_curve(drn1.im_pc, im=im)

    h = elevation_map(im, voxel_size=voxel_size)
    pc = pc + delta_rho*g*h
    drn2 = drainage(im=im, pc=pc, inlets=inlets, bins=50)
    pc_curve2 = ps.metrics.pc_map_to_pc_curve(drn2.im_pc, im=im)

    fix, ax = plt.subplots()
    ax.step(np.log10(pc_curve1.pc), pc_curve1.snwp, where='post')
    ax.step(np.log10(pc_curve2.pc), pc_curve2.snwp, where='post')
    ax.set_xlabel('log(Capillary Pressure [Pa])')
    ax.set_ylabel('Non-wetting Phase Saturation')


import json
import os

from creature_formatter import format_monster

if __name__ == "__main__":

    dirpath = os.path.dirname(os.path.realpath(__file__))
    output_folder = f'{dirpath}/../output'
    crawler_repo = '../../spanish-srd5.1-crawl/output/monsters.json'
    with open(f'{dirpath}/{crawler_repo}', 'r') as file:
        monsters = json.load(file)

    result = {}
    for monster in monsters:
        result.update(format_monster(monster))

    if not os.path.isdir(output_folder):
        os.mkdir(output_folder)

    with open(f'{output_folder}/spanish_srd_creatures.json',
              'w',
              encoding='utf-8') as f:
        json.dump(result, f, ensure_ascii=False, indent=2)


#!/usr/bin/env python3

# Created by: Jenoe Balote
# Created on: May 2021
# This program shows all RGB values

def main():

    loop1 = 0
    loop2 = 0
    loop3 = 0

    # process & output
    for loop1 in range(255):
        for loop2 in range(255):
            for loop3 in range(255):
                print("RGB ({0},{1},{2})".format(loop1, loop2, loop3))

if __name__ == "__main__":
    main()


import sys

from fuelclient.objects.release import Release
from fuelclient.objects.role import Role

incompatible_roles = ["compute", "ironic", "cinder", "cinder-block-device"]
restrictions = {
    u"condition": u"'network:neutron:core:nsx' in cluster:components",
    u"action": u"hide"}
role_available_state = "available"
nsx_component_name = u"network:neutron:core:nsx"
clean = True if (len(sys.argv) > 1) else False

try:
    for release in Release.get_all_data():
        if release["state"] == role_available_state:
            for role in Role.get_all(release["id"]):
                if role["name"] in incompatible_roles:
                    meta = role["meta"]
                    if "restrictions" in meta.keys():
                        for restriction in meta["restrictions"]:
                            if nsx_component_name in restriction["condition"]:
                                if len(meta["restrictions"]) == 1 and clean:
                                    del meta["restrictions"]
                                else:
                                    meta["restrictions"].remove(restriction)
                        if not clean:
                            meta["restrictions"].append(restrictions)
                    else:
                        if not clean:
                            meta["restrictions"] = [restrictions]
                    Role.update(release["id"], role["name"], role)
except Exception:
    raise


from django.urls import path
from projects import views

# name our app_name the same as our app that we are
app_name = 'projects'

# We create this one so that it know when it gets redirected to '', push forward to projects views.py
# this path adds another path. so now we need website/projects/test for it to work
'''The names allow us to uniquely identify the view URL's we point to '''
urlpatterns = [
    path('', views.all_projects, name="all_projects"),
    # this syntax captures just one part of the path and passes it forward based on the selected variable
    #   in this instance that variable is pk
    #   int = integer path converter. It ensures that the inserted pk is a number, then goes to project_detail view with the submitted integer
    # ### ALSO, the path here is going to be the pk at the end of the last path. so for example, would be /1
    # ### If its not a valid pk then it won't do anything.
    path('<int:pk>', views.project_detail, name="project_details")
]


from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.utils.timezone import make_naive
from easy_thumbnails.templatetags.thumbnail import thumbnail_url

from rest_framework import serializers

from apps.autenticacion.models import Ciudad
from apps.empresa.models import Producto, CategoriaProducto, FotoProducto, Empresa, Sucursal
# from apps.empresa.serializers import ShowSucursal_Serializer

# class atributo(serializer.Serializer):

class Test_Serializer(serializers.ModelSerializer):
    data = serializers.JSONField(source='atributos',required=True)

    class Meta:
        model = Producto
        fields = ['nombre','precio','sucursal','data']

    #  def validate(self, data):
    #     sr = attrs.get('data')
    #     if config_field:
    #         serializer = ConfigFieldsSerializer(data=config_field)
    #         serializer.is_valid(raise_exception=True)
    #     return data

class ShowCategoriaProducto_Serializer(serializers.Serializer):
    def to_representation(self, instance):
        return {
            'id':instance.id,
            'nombre':instance.nombre,
            'codigo':instance.codigo
        }

class ShowCategoriaProductoNivel_Serializer(serializers.Serializer):

    def to_representation(self, instance):
        estado = self.context.get('estado')
        if estado == 'A':
            query = CategoriaProducto.objects.filter(padre__id=instance.id, estado=True)
        elif estado == 'I':
            query = CategoriaProducto.objects.filter(padre__id=instance.id, estado=False)
        else:
            query = CategoriaProducto.objects.filter(padre__id=instance.id)

        return {
            'id':instance.id,
            'nombre':instance.nombre,
            'codigo':instance.codigo,
            'sub_categorias': ShowCategoriaProductoNivel_Serializer( query, many=True, context={'estado':estado} ).data
        }

# SUCURSAL

class ShowSucursal_Serializer(serializers.Serializer):

    def to_representation(self, instance):
        return {
            'id':instance.id,
            'nombre':instance.nombre,
            'disponible':instance.disponible,
            'estado':instance.estado,
            'telefono':instance.telefono,
            'ubicacion':instance.ubicacion,
            'direccion':instance.direccion,
            'foto':instance.foto.url if instance.foto else None,
            'foto_150':thumbnail_url(instance.foto, '150'),
            'foto_300':thumbnail_url(instance.foto, '300'),
            'foto_450':thumbnail_url(instance.foto, '450'),
            # 'foto':self.context.get('request').build_absolute_uri(instance.foto.url) if instance.foto else None,
            'empresa':{
                'id':instance.empresa.id,
                'nombre':instance.empresa.nombre,
                'descripcion':instance.empresa.descripcion,
                'categoria':{
                    'id':instance.empresa.categoria.id,
                    'nombre':instance.empresa.categoria.nombre,
                    'estado':instance.empresa.categoria.estado
                }
            },
            'hora_inicio':instance.hora_inicio,
            'hora_fin':instance.hora_fin,
            'ciudad':{
                'id':instance.ciudad.id,
                'nombre':instance.ciudad.nombre,
                'estado':instance.ciudad.estado,
                'comision_porcentaje':str(instance.ciudad.comision_porcentaje)
            }
        }

# ARTICULOS
def validar_categoria(categoria, tipo):
    c = categoria.padre
    es = False
    while c is not None:
        if c.nombre == tipo:
            es = True
            break
        else:
            c = c.padre
    return es

class CrearArticulo_Serializer(serializers.ModelSerializer):
    fotos = serializers.ListField(child=serializers.ImageField())

    class Meta:
        model = Producto
        fields = ['nombre','descripcion','precio','sucursal','categoria','atributos','fotos']
        extra_kwargs = {
            'categoria': {'required': True}
        }

    def validate_fotos(self, obj):
        for f in obj:
            MiB = settings.MAXIMO_TAM_ARCHIVOS
            limit = MiB * 1024 * 1024
            if f.size > limit:
                raise serializers.ValidationError('La imagen '+str(f)+' no debe exceder los '+str(MiB)+'Mb')
        return obj

    def validate_categoria(self, value):
        if value.padre is None:
            raise serializers.ValidationError('La categoria debe tener un padre')
        if value.estado is False:
            raise serializers.ValidationError('La categoria esta inactiva')
        if not validar_categoria(value, settings._ECOMMERCE_):
            raise serializers.ValidationError('La categoria no pertenece a ecommerce')
        return value

class EditarArticulo_Serializer(serializers.ModelSerializer):

    class Meta:
        model = Producto
        fields = ['nombre','descripcion','precio','atributos','categoria','foto']

    def validate_categoria(self, value):
        if value.padre is None:
            raise serializers.ValidationError('La categoria debe tener un padre')
        if value.estado is False:
            raise serializers.ValidationError('La categoria esta inactiva')
        if not validar_categoria(value, settings._ECOMMERCE_):
            raise serializers.ValidationError('La categoria no pertenece a ecommerce')
        return value

class ShowBasicArticulo_Serializer(serializers.Serializer):
    def to_representation(self, instance):
        return {
            'id':instance.id,
            'nombre':instance.nombre,
            'precio':str(instance.precio),
            'foto':instance.foto.url if instance.foto else None,
            'foto_150':thumbnail_url(instance.foto, '150'),
            'foto_300':thumbnail_url(instance.foto, '300'),
            'foto_450':thumbnail_url(instance.foto, '450'),
            'creado':make_naive(instance.creado)
        }

# VER ARTICULO

class ShowArticuloSucursal_Serializer(serializers.Serializer):

    def to_representation(self, instance):
        return {
            'id':instance.id,
            'nombre':instance.nombre,
            'disponible':instance.disponible,
            'estado':instance.estado,
            'telefono':instance.telefono,
            'ubicacion':instance.ubicacion,
            'direccion':instance.direccion,
            'foto':instance.foto.url if instance.foto else None,
            'empresa':{
                'id':instance.empresa.id,
                'nombre':instance.empresa.nombre,
                'descripcion':instance.empresa.descripcion,
                'empresario':instance.empresa.empresario.id,
            },
            'hora_inicio':instance.hora_inicio,
            'hora_fin':instance.hora_fin,
            'ciudad':{
                'id':instance.ciudad.id,
                'nombre':instance.ciudad.nombre
            }
        }

class ShowBasicFotoProductoArticulo_Serializer(serializers.Serializer):
    def to_representation(self, instance):
        return {
            'id':instance.id,
            'foto':instance.foto.url if instance.foto else None
        }

class ShowAdvancedArticulo_Serializer(serializers.Serializer):
    def to_representation(self, instance):
        return {
            'id':instance.id,
            'nombre':instance.nombre,
            'descripcion':instance.descripcion,
            'precio':str(instance.precio),
            'estado':instance.estado,
            'foto':instance.foto.url if instance.foto else None,
            'foto_150':thumbnail_url(instance.foto, '150'),
            'foto_300':thumbnail_url(instance.foto, '300'),
            'foto_450':thumbnail_url(instance.foto, '450'),
            'creado':make_naive(instance.creado),
            'atributos':instance.atributos,
            'sucursal':ShowArticuloSucursal_Serializer(instance.sucursal).data,
            'categoria':ShowCategoriaProducto_Serializer(instance.categoria).data,
            'fotos':ShowBasicFotoProductoArticulo_Serializer(FotoProducto.objects.filter(producto__id=instance.id), many=True).data,
        }

# RESPONSES FOR SWAGGER

class ResponseCategoriaProductoNivel2(serializers.ModelSerializer):
    sub_categorias = serializers.ListField()

    class Meta:
        model = CategoriaProducto
        fields = ['id','nombre','codigo','sub_categorias']

class ResponseCategoriaProductoNivel(serializers.ModelSerializer):
    sub_categorias = ResponseCategoriaProductoNivel2(source='padre', read_only=True)

    class Meta:
        model = CategoriaProducto
        fields = ['id','nombre','codigo','sub_categorias']

class ResponseCategoriaProducto(serializers.ModelSerializer):

    class Meta:
        model = CategoriaProducto
        fields = ['id','nombre','codigo']

class ResponseBasicProducto(serializers.ModelSerializer):

    class Meta:
        model = Producto
        fields = ['id','nombre','precio','foto','creado']

# response ver producto

class ResponseCiudad_Serializer(serializers.ModelSerializer):
    class Meta:
        model = Ciudad
        fields = ['id','nombre','estado']

class ResponseArtEmpresaSerializer(serializers.ModelSerializer):

    class Meta:
        model = Empresa
        fields = ['id','nombre','descripcion','empresario']

class ResponseSucursalSerializer(serializers.ModelSerializer):
    empresa = ResponseArtEmpresaSerializer()
    ciudad = ResponseCiudad_Serializer()

    class Meta:
        model = Sucursal
        fields = ['id','nombre','disponible','estado','telefono','ubicacion','direccion','foto','empresa','hora_inicio','hora_fin','ciudad']

class ResponseFotoProducto(serializers.ModelSerializer):
    class Meta:
        model = FotoProducto
        fields = ['id','foto']

class ResponseBasicProducto(serializers.ModelSerializer):
    categoria = ResponseCategoriaProducto()
    sucursal = ResponseSucursalSerializer()
    fotos = ResponseFotoProducto(many=True)

    class Meta:
        model = Producto
        fields = ['id','descripcion','nombre','precio','foto','creado','atributos','sucursal','categoria','fotos']


from oslo_log import log
from xcat3.common import exception
from xcat3.plugins.control import ipmi
from xcat3.plugins.control import ssh
from xcat3.plugins.boot import petitboot
from xcat3.plugins.boot import pxe
from xcat3.plugins.osimage import base as os_base
from xcat3.plugins.osimage.ubuntu import ubuntu
from xcat3.plugins.osimage.redhat import redhat

LOG = log.getLogger(__name__)

class PluginMap(object):
    control_map = dict()
    control_map['ipmi'] = ipmi.IPMIPlugin()
    control_map['kvm'] = ssh.SSHControl()
    boot_map = dict()
    boot_map['pxe'] = pxe.PXEBoot()
    boot_map['petitboot'] = petitboot.Petitboot()
    os_map = dict()
    os_map['base'] = os_base.BaseOSImage()
    os_map['ubuntu'] = ubuntu.UbuntuInterface()
    os_map['rhels'] = redhat.RedhatInterface()

    @classmethod
    def get_control_plugin(cls, node):
        control_plugin = cls.control_map.get(node.mgt)
        if control_plugin is None:
            raise exception.PluginNotFound(name=node.mgt)
        return control_plugin

    @classmethod
    def get_boot_plugin(cls, node):
        boot_plugin = cls.boot_map.get(node.netboot)
        if boot_plugin is None:
            raise exception.PluginNotFound(name=node.netboot)
        return boot_plugin

    @classmethod
    def get_osimage_plugin(cls, osimage):
        os_plugin = cls.os_map.get(os_base.get_plugin_name(osimage))
        if os_plugin is None:
            raise exception.PluginNotFound(name=osimage.name)
        return os_plugin


# -*- coding: utf-8 -*-
"""
Created on Wed Jul 24 15:33:27 2019

@author: Administrator
"""

import matplotlib
matplotlib.use("Agg")
#import matplotlib.pyplot as plt

import numpy as np
from keras.models import load_model
#from keras.layers import Conv2D,MaxPooling2D,UpSampling2D,BatchNormalization,Reshape,Permute,Activation,Input,Dropout
#from keras.utils.np_utils import to_categorical
from keras.preprocessing.image import img_to_array
#from keras.callbacks import ModelCheckpoint,EarlyStopping
from sklearn.preprocessing import LabelEncoder
#from PIL import Image
#import matplotlib.pyplot as plt
import cv2
#import random
import os
#from tqdm import tqdm

#from keras import backend as K
#import tensorflow as tf
#from keras.layers.core import Dropout, Lambda
#from keras.layers.merge import concatenate
from libtiff import TIFF

filepath = 'E:\\test\\'
modelpath= 'E:\\data_segmentated\\model\\'                      ############################

img_w=256
img_h=256
image_size=256
# 有一个为背景
n_label=15+1

classes=[0., 179., 146., 164., 156., 92., 140., 148., 117., 73., 83., 161., 60., 23., 192., 180.]
labelencoder = LabelEncoder()  # 标签标准化
labelencoder.fit(classes)

def read_images(add_tif,single_channel=True):
    '''
    读取tiff图像，tiff图像为4维，分别为NIR,R,G,B,尺寸为(6800,7200,4)
    '''
    tif=TIFF.open(add_tif,mode='r')
    image=tif.read_image()
    print(image.shape)
    channel1=image[:,:,0]#NIR
    channel2=image[:,:,1]#R
    channel3=image[:,:,2]#G
    channel4=image[:,:,3]#B
#由于网络的输入是是RGB,NIR,所以得调整次序
    image[:,:,0]=channel2
    image[:,:,1]=channel3
    image[:,:,2]=channel4
    image[:,:,3]=channel1
    if single_channel:
        return channel1,channel2,channel3,channel4
    else:
        return image
def save_to_tiff(image,filepath):
    tif=TIFF.open(filepath,mode='w')
    tif.write_image(image[:,:,0:3],compression=None,write_rgb=True)
    tif.close()
def gray2rgb(lab_gray):         #lab_gray必须为单通道
    '''transform data from gray to rgb'''
    dict={117:[  0,200,  0],        #水田
          164:[150,250,  0],        #水浇地
          179:[150,200,150],        #旱耕地
           83:[200,  0,200],        #园地
           92:[150,  0,250],        #乔木林地
          180:[150,150,250],        #灌木林地
          146:[250,200,  0],        #天然草地
          140:[200,200,  0],        #人工草地
           23:[200,  0,  0],        #工业用地
           73:[250,  0,150],        #城市住宅
          156:[200,150,150],        #城镇住宅
          161:[250,150,150],        #交通运输
           60:[  0,  0,200],        #河流
          148:[  0,150,200],        #湖泊
          192:[  0,200,250],        #坑塘
            0:[  0,  0,  0]}        #其他类别
    lab_h,lab_w=lab_gray.shape
    lab_rgb=np.zeros((lab_h,lab_w,3))
    for i in range(lab_h):
        for j in range(lab_w):
            lab_rgb[i,j,:]=np.array(dict[lab_gray[i,j]])

    return np.uint8(lab_rgb)
def predict():
    # load the trained convolutional neural network
    print("[INFO] loading network...")
    model=load_model(modelpath+'unet_1_3.h5')  # 载入模型                                   ########################################
    stride = 64
    pad_len = np.int8((256 - stride) / 2)
    TEST_SET = os.listdir(filepath + 'test_image\\')  ########################################

    nextpath = 'test_result'  ########################################
    if not os.path.exists(filepath + nextpath):
        os.makedirs(filepath + nextpath)

    # print(TEST_SET)
    for n in range(len(TEST_SET)):
        path = TEST_SET[n]
        image = read_images(filepath + 'test_image\\' + path,
                                      single_channel=False)  #######################################
        h, w, _ = image.shape
        # padding_h = (h // stride + 2) * stride
        # padding_w = (w // stride + 2) * stride
        padding_h = (h // stride + 1) * stride + pad_len * 2
        padding_w = (w // stride + 1) * stride + pad_len * 2

        padding_img = np.zeros((padding_h, padding_w, 4), dtype=np.uint8)
        padding_img[pad_len:h + pad_len, pad_len:w + pad_len, :] = image[:, :, :]  # padding图像原位置有图像的地方用原图像填充，没有的用0填充
        # padding_img = padding_img.astype("float") / 255.0  # 归一化
        padding_img = img_to_array(padding_img)  # 转换成数组（可能会使矩阵发生转置）
        print('src:', padding_img.shape)
        mask_whole = np.zeros((padding_h - pad_len * 2, padding_w - pad_len * 2), dtype=np.uint8)  # 标签
        for i in range(h // stride + 1):
            for j in range(w // stride + 1):
                crop_tif = padding_img[i * stride:i * stride + image_size, j * stride:j * stride + image_size, :]
                # print(crop_tif.shape,i,j)
                crop = np.zeros((image_size, image_size, 4))
                crop[:, :, 0:3] = crop_tif[:, :, 1:4]
                crop[:, :, 3] = crop_tif[:, :, 0]
                # _, ch, cw = crop.shape
                ch, cw, _ = crop.shape
                if ch != 256 or cw != 256:
                    print('invalid size!,crop size:', ch, cw, i, j)
                    continue

                crop = np.expand_dims(crop, axis=0)
                pred = model.predict(crop)
                pred = np.squeeze(pred)
                pred = np.argmax(pred, axis=1)
                pred = labelencoder.inverse_transform(pred)
                pred = pred.reshape((256, 256)).astype(np.uint8)
                mask_whole[i * stride:i * stride + stride, j * stride:j * stride + stride] = pred[pad_len:pad_len + stride,pad_len:pad_len + stride]

        cv2.imwrite(filepath + nextpath + '\\gray_' + str(n + 1) + '.bmp',
                    mask_whole[0:h, 0:w])  ########################
        rgb = gray2rgb(mask_whole[0:h, 0:w])
        cv2.imwrite(filepath + nextpath + '\\rgb_' + str(n + 1) + '.bmp', rgb)  ########################
        save_to_tiff(rgb, filepath + nextpath + '\\tif_' + str(n + 1) + '.tif')  ########################

if __name__ == '__main__':
    predict()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import numpy as np
import pandas as pd
import _pickle as cPickle
import scipy.optimize as opt
from datetime import datetime
from scipy.stats import uniform, randint
from sklearn.preprocessing import OneHotEncoder

from sklearn.model_selection import cross_val_score, GridSearchCV
from sklearn.model_selection import KFold, RandomizedSearchCV, train_test_split
from sklearn.model_selection import cross_val_score, ShuffleSplit, learning_curve

from sklearn.metrics import auc, accuracy_score,roc_auc_score
from sklearn.metrics import confusion_matrix, mean_squared_error, mean_absolute_error
from sklearn.metrics import roc_curve, confusion_matrix, classification_report
from sklearn.metrics import precision_score, recall_score, f1_score

from sklearn import svm
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier

path = '/Users/tung/Python/WorkProject/PHMresearch/WDCNN&LR_FaultDiagnosis/'

feature_train_scaled = cPickle.load( open(path+'feature_train_scaled.pkl','rb') )
feature_valid_scaled = cPickle.load( open(path+'feature_valid_scaled.pkl','rb') )
feature_test_scaled = cPickle.load( open(path+'feature_test_scaled.pkl','rb') )

y_train_decode = cPickle.load( open(path+'y_train_decode.pkl','rb') )
y_valid_decode = cPickle.load( open(path+'y_valid_decode.pkl','rb') )
y_test_decode = cPickle.load( open(path+'y_test_decode.pkl','rb') )

def encode(data):
    data = np.array(data).reshape([-1, 1])
    print('Shape of data (BEFORE encode): %s' % str(data.shape))
    Encoder = OneHotEncoder()
    Encoder.fit(data)
    encoded = Encoder.transform(data).toarray()
    print('Shape of data (AFTER  encode): %s\n' % str(encoded.shape))
    return encoded

y_test = encode(y_test_decode)

def display_scores(scores):
    print("Scores: {0}\nMean: {1:.3f}\nStd: {2:.3f}".format(scores, np.mean(scores), np.std(scores)))

'lasso lr'

#parameters set
lasso_model = LogisticRegression(C=0.7, penalty='l1', tol=1e-6, solver = 'liblinear',
                                 class_weight = 'balanced',multi_class= 'ovr', max_iter=1000) #不可导

print(lasso_model)

epoch = 5
scores = []

# Train model
start = datetime.now()

for i in range(epoch):
    lasso_model.fit(feature_train_scaled, y_train_decode)
    #     y_score = lasso_model.predict_proba(x_test)
    #     scores.append(roc_auc_score(y_test, y_score, average='micro'))
    scores.append(lasso_model.score(feature_test_scaled, y_test_decode)) #准确率

print("This took ", datetime.now() - start)
print(u'The accuracy of the model is: ')
display_scores(scores)  #准确率

coef_ = pd.DataFrame(lasso_model.coef_, columns = ['maximum', 'minimum', 'mean', 'var', 'std', 'absmean', 'rms',
'vi', 'skew', 'kurt', 'ptp', 'par', 'form', 'impulse', 'margin', 'spectral_kurt', 'spectral_skw','spectral_pow',
'wave_L2', 'frechet_form1', 'frechet_form2', 'frechet_form3', 'frechet_form4', 'frechet_form5', 'frechet_form6',
        'frechet_form7', 'frechet_form8' ])
coef_ #特征权重

#evaluation
prediction_train = lasso_model.predict(feature_train_scaled)
cm_train = confusion_matrix(y_train_decode, prediction_train)
prediction_test = lasso_model.predict(feature_test_scaled)
cm_test = confusion_matrix(y_test_decode, prediction_test)

print("Confusion matrix for training dataset is \n%s\n for testing dataset is \n%s.\n"
      % (cm_train, cm_test))

target_names = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5',
                'class 6', 'class 7', 'class 8', 'class 9']
print(classification_report(y_test_decode, prediction_test, target_names=target_names))

'rige lr'
#parameters set
ridge_model = LogisticRegression(
                                 C=0.8,                      #正则化系数λ的倒数
                                 penalty='l2',
                                 dual = True,                #用在求解线性多核(liblinear)的L2惩罚项上。样本数量>样本特征的时False
                                 tol=1e-6,                   #绝对误差限，停止求解的标准
                                 class_weight = 'balanced',
                                 solver = 'liblinear',       #可导 lbfgs sag
                                 max_iter=5000)

print(ridge_model)

epoch = 5
scores = []

# Train model
start = datetime.now()

for i in range(epoch):
    ridge_model.fit(feature_train_scaled, y_train_decode)
    #     y_score = ridge_model.predict_proba(x_test)
    #     scores.append(roc_auc_score(y_test, y_score, average='micro'))
    scores.append(ridge_model.score(feature_test_scaled, y_test_decode)) #准确率

print("This took ", datetime.now() - start)
print(u'The accuracy of the model is: ')
display_scores(scores)  #准确率

param_test1 = {
    'C':[i/10.0 for i in range(1,11)]         # c：正则化系数λ的倒数
}
gsearch1 = GridSearchCV(estimator = ridge_model,
                        param_grid = param_test1, scoring='accuracy',n_jobs=2, cv=5)

gsearch1.fit(feature_valid_scaled, y_valid_decode)

print(gsearch1.cv_results_['mean_test_score'])
print(gsearch1.best_params_)
print("best accuracy:%f" % gsearch1.best_score_)

coef_ = pd.DataFrame(ridge_model.coef_, columns = ['maximum', 'minimum', 'mean', 'var', 'std', 'absmean', 'rms',
'vi', 'skew', 'kurt', 'ptp', 'par', 'form', 'impulse', 'margin', 'spectral_kurt', 'spectral_skw','spectral_pow',
'wave_L2', 'frechet_form1', 'frechet_form2', 'frechet_form3', 'frechet_form4', 'frechet_form5', 'frechet_form6',
                                                   'frechet_form7', 'frechet_form8' ])

coef_

#evaluation
prediction_train = ridge_model.predict(feature_train_scaled)
cm_train = confusion_matrix(y_train_decode, prediction_train)
prediction_test = ridge_model.predict(feature_test_scaled)
cm_test = confusion_matrix(y_test_decode, prediction_test)

print("Confusion matrix for training dataset is \n%s\n for testing dataset is \n%s.\n"
      % (cm_train, cm_test))

target_names = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5',
                'class 6', 'class 7', 'class 8', 'class 9']
print(classification_report(y_test_decode, prediction_test, target_names=target_names))

y_score = ridge_model.predict_proba(feature_test_scaled)

# 计算micro类型的AUC
# print('调用函数auc：', roc_auc_score(y_test, y_score, average='micro'))

fpr, tpr, thresholds = roc_curve(y_test.ravel(),y_score.ravel())
micro_auc = auc(fpr, tpr)
print ('micro_auc：', micro_auc)

'demo lr'
def demoLr(data):
    def sigmoid(z):
        return 1 / (1 + np.exp(-z))

    # add a ones column - this makes the matrix multiplication work out easier
    data.insert(0, 'Ones', 1)

    # set X (training data) and y (target variable)
    cols = data.shape[1]
    X = data.iloc[:,0:cols-1]
    y = data.iloc[:,cols-1:cols]

    # convert to numpy arrays and initalize the parameter array theta
    X = X.values
    y = y.values.reshape(len(y),)

    theta = np.zeros(X.shape[1])

    #regularized cost
    def cost(theta, X, y):
        ''' cost fn is -l(theta) for you to minimize'''
        return np.mean(-y * np.log(sigmoid(X @ theta)) - (1 - y) * np.log(1 - sigmoid(X @ theta)))

    cost(theta, X, y)

    def regularized_cost(theta, X, y, l=1):
        #     '''you don't penalize theta_0'''
        theta_j1_to_n = theta[1:]
        regularized_term = (l / (2 * len(X))) * np.power(theta_j1_to_n, 2).sum()

        return cost(theta, X, y) + regularized_term

    'this is the same as the not regularized cost because we init theta as zeros...'
    regularized_cost(theta, X, y, l=1)

    #regularized gradient
    def gradient(theta, X, y):
        #     '''just 1 batch gradient'''
        return (1 / len(X)) * X.T @ (sigmoid(X @ theta) - y)
    gradient(theta, X, y)

    def regularized_gradient(theta, X, y, l=1):
        #     '''still, leave theta_0 alone'''
        theta_j1_to_n = theta[1:]
        regularized_theta = (l / len(X)) * theta_j1_to_n

        # by doing this, no offset is on theta_0
        regularized_term = np.concatenate([np.array([0]), regularized_theta])

        return gradient(theta, X, y) + regularized_term

    regularized_gradient(theta, X, y)

    print('init cost = {}'.format(regularized_cost(theta, X, y)))

    res = opt.minimize(fun=regularized_cost, x0=theta, args=(X, y), method='Newton-CG', jac=regularized_gradient)
    res

    #prediction
    def predict(x, theta):
        prob = sigmoid(x @ theta)
        return (prob >= 0.5).astype(int)

    final_theta = res.x
    y_pred = predict(X, final_theta)

    print(classification_report(y, y_pred))

'SVM'
def demoSVM(data):
    positive = data[data['y'].isin([1])]
    negative = data[data['y'].isin([0])]

    svc = svm.LinearSVC(C=1, loss='hinge', max_iter=1000)            #liner
    svc

    svc.fit(data[['spectral_pow', 'mean']], data['y'])
    print(svc.score(data[['spectral_pow', 'mean']], data['y']))

    svc2 = svm.LinearSVC(C=100, loss='hinge', max_iter=100000)       #惩罚系数
    svc2.fit(data[['spectral_pow', 'mean']], data['y'])
    print(svc2.score(data[['spectral_pow', 'mean']], data['y']))

    svc3 = svm.SVC(C=3, kernel='rbf', gamma=5000, probability=True)  #GaussianKernel
    svc3

    svc3.fit(data[['spectral_pow', 'mean']], data['y'])
    print(svc3.score(data[['spectral_pow', 'mean']], data['y']))

    ypred = svc3.predict(data[['spectral_pow', 'mean']])
    print(classification_report(data['y'], ypred))

    candidate = [0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30, 100, 1000, 5000]  #c gamma
    combination = [(C, gamma) for C in candidate for gamma in candidate]

    search = []
    for C, gamma in combination:
        svc = svm.SVC(C=C, gamma=gamma)
        svc.fit(data[['spectral_pow', 'mean']], data['y'])
        search.append(svc.score(data[['spectral_pow', 'mean']], data['y']))   #CV数据

    best_score = search[np.argmax(search)]
    best_param = combination[np.argmax(search)]

    print(best_score, best_param)

'RF'
rf = RandomForestClassifier(
                            n_estimators = 21,
                            max_depth=5,
                            max_features='auto',             #构建决策树最优模型时考虑的最大特征数 n的平方根
                            oob_score = True,                #选用袋外样本，其误差是测试数据集误差的无偏估计
                            min_samples_leaf = 1,            #叶子节点含有的最少样本,小于则剪枝
                            min_samples_split= 2,            #叶子节点可分的最小样本数
                            max_leaf_nodes = None,           #最大叶子节点数
                            min_impurity_decrease = 0.0,     #节点划分的最小不纯度
                            criterion = 'gini',              #表示节点的划分标准
                            min_weight_fraction_leaf=0.0     #叶子节点最小的样本权重和,小于则剪枝,较多样本的缺失值或偏差很大时尝试
                            )
print(rf)

epoch = 5
scores = []

# Train model
start = datetime.now()

for i in range(epoch):
    rf.fit(feature_train_scaled, y_train_decode)
    scores.append(rf.score(feature_test_scaled, y_test_decode)) #准确率

print("This took ", datetime.now() - start)
print(u'The accuracy of the model is: ')
display_scores(scores)      #准确率

param_test2 = {             #bagging参数
    "n_estimators":range(1,101,10)
}
gsearch2 = GridSearchCV(estimator = rf,
                        param_grid = param_test2, scoring='accuracy',n_jobs=2, cv=5)

gsearch2.fit(feature_valid_scaled, y_valid_decode)

print(gsearch2.cv_results_['mean_test_score'])
print(gsearch2.best_params_)
print("best accuracy:%f" % gsearch2.best_score_)

#evaluation
prediction_train = rf.predict(feature_train_scaled)
cm_train = confusion_matrix(y_train_decode, prediction_train)
prediction_test = rf.predict(feature_test_scaled)
cm_test = confusion_matrix(y_test_decode, prediction_test)

print("Confusion matrix for training dataset is \n%s\n for testing dataset is \n%s.\n"
      % (cm_train, cm_test))

#Precision_rate预测为正例的样本中的真正正例的比例
#Recall_rate预测为正例的真正正例占所有真正正例的比例

target_names = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5',
                'class 6', 'class 7', 'class 8', 'class 9']
print(classification_report(y_test_decode, prediction_test, target_names=target_names))

y_score = rf.predict_proba(feature_test_scaled)

# 计算micro类型的AUC
# print('调用函数auc：', roc_auc_score(y_test, y_score, average='micro'))

fpr, tpr, thresholds = roc_curve(y_test.ravel(),y_score.ravel())
micro_auc = auc(fpr, tpr)
print ('micro_auc：', micro_auc)

'Adaboost'
Ada = AdaBoostClassifier(DecisionTreeClassifier(max_depth=4, min_samples_split=20, min_samples_leaf=5),
                         algorithm="SAMME",
                         n_estimators=21, learning_rate=0.8)

print (Ada)
epoch = 5
scores = []

# Train model
start = datetime.now()

for i in range(epoch):
    Ada.fit(feature_train_scaled, y_train_decode)
    scores.append(Ada.score(feature_test_scaled, y_test_decode)) #准确率

print("This took ", datetime.now() - start)
print(u'The accuracy of the model is: ')
display_scores(scores)  #准确率

params = {
    "learning_rate": uniform(0.1, 0.9),     # default 0.1
    "n_estimators": randint(10, 120)        # default 5
#     "max_depth": randint(2, 6)            # default 3
}

search = RandomizedSearchCV(Ada, param_distributions=params, random_state=42,
                            n_iter=30, cv=5, verbose=1, n_jobs=2, return_train_score=True)

search.fit(feature_valid_scaled, y_valid_decode)

print(search.best_estimator_)
print(search.best_score_)

#evaluation
prediction_train = Ada.predict(feature_train_scaled)
cm_train = confusion_matrix(y_train_decode, prediction_train)
prediction_test = Ada.predict(feature_test_scaled)
cm_test = confusion_matrix(y_test_decode, prediction_test)

print("Confusion matrix for training dataset is \n%s\n for testing dataset is \n%s.\n"
      % (cm_train, cm_test))

#Precision_rate预测为正例的样本中的真正正例的比例
#Recall_rate预测为正例的真正正例占所有真正正例的比例

target_names = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5',
                'class 6', 'class 7', 'class 8', 'class 9']
print(classification_report(y_test_decode, prediction_test, target_names=target_names))

y_score = Ada.predict_proba(feature_test_scaled)

# 计算micro类型的AUC
# print('调用函数auc：', roc_auc_score(y_test, y_score, average='micro'))

fpr, tpr, thresholds = roc_curve(y_test.ravel(),y_score.ravel())
micro_auc = auc(fpr, tpr)
print ('micro_auc：', micro_auc)

'GBDT'
GBDT = GradientBoostingClassifier(

                                  loss = 'deviance',
                                  learning_rate = 0.04,
                                  n_estimators = 68,
                                  max_depth = 4,
                                  subsample = 0.42,

                                  max_features = None,
                                  max_leaf_nodes=None,
                                  min_samples_leaf=1,
                                  min_samples_split=2,
                                  min_impurity_decrease=0.0,
                                  min_impurity_split=None,
                                  criterion='friedman_mse',
                                  min_weight_fraction_leaf=0.0,
                                  ccp_alpha=0.0
                                  )
print(GBDT)

epoch = 5
scores = []

# Train model
start = datetime.now()

for i in range(epoch):
    GBDT.fit(feature_train_scaled, y_train_decode)
    scores.append(GBDT.score(feature_test_scaled, y_test_decode)) #准确率

print("This took ", datetime.now() - start)
print(u'The accuracy of the model is: ')
display_scores(scores)  #准确率

params = {
    "learning_rate": uniform(0.03, 0.5),   # default 0.1
    "max_depth": randint(2, 6),            # default 3
    "n_estimators": randint(10, 120),      # default 100
    "subsample": uniform(0.1, 0.8)
}

search = RandomizedSearchCV(GBDT, param_distributions=params, random_state=42,
                            n_iter=30, cv=5, verbose=1, n_jobs=2, return_train_score=True)

search.fit(feature_valid_scaled, y_valid_decode)

print(search.best_estimator_)
print(search.best_score_)

#evaluation
prediction_train = GBDT.predict(feature_train_scaled)
cm_train = confusion_matrix(y_train_decode, prediction_train)
prediction_test = GBDT.predict(feature_test_scaled)
cm_test = confusion_matrix(y_test_decode, prediction_test)

print("Confusion matrix for training dataset is \n%s\n for testing dataset is \n%s.\n"
      % (cm_train, cm_test))

target_names = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5',
                'class 6', 'class 7', 'class 8', 'class 9']
print(classification_report(y_test_decode, prediction_test, target_names=target_names))

y_score = GBDT.predict_proba(feature_test_scaled)

# 计算micro类型的AUC
# print('调用函数auc：', roc_auc_score(y_test, y_score, average='micro'))

fpr, tpr, thresholds = roc_curve(y_test.ravel(),y_score.ravel())
micro_auc = auc(fpr, tpr)
print ('micro_auc：', micro_auc)


from matplotlib import pyplot
import numpy

def matplotlib_function(x_ingredients_embedded1_arg, x_ingredients_embedded2_arg, words_arg, colors, sizes, title, labels):
    # Retrieve all of the vectors from a trained model as follows

    fig_matplotlib, (ax1, ax2) = pyplot.subplots(nrows=1, ncols=2, figsize=(24, 12), dpi=500)
    ax1.set_title('PCA')
    ax2.set_title('T-SNE')
    fig_matplotlib.suptitle(title, fontsize=20)

    ax1.scatter(x_ingredients_embedded1_arg[:, 0], x_ingredients_embedded1_arg[:, 1], c=colors, alpha=0.5, s=list(5000 * numpy.array(sizes)/max(sizes)))
    ax2.scatter(x_ingredients_embedded2_arg[:, 0], x_ingredients_embedded2_arg[:, 1], c=colors, alpha=0.5, s=list(5000 * numpy.array(sizes)/max(sizes)))

    words = words_arg

    if labels:

        # ----- PCA

        for i, word in enumerate(words):
            ax1.annotate(word, fontsize=8, xy=(x_ingredients_embedded1_arg[i, 0], x_ingredients_embedded1_arg[i, 1]))

        # ----- T-SNE

        for i, word in enumerate(words):
            ax2.annotate(word, fontsize=8, xy=(x_ingredients_embedded2_arg[i, 0], x_ingredients_embedded2_arg[i, 1]))


from .models import PostCategory
from .models import ItemsList

rating_choices = {
    '': 'Blank',
    '3': '3.00',
    '4': '4.00',
    '5': '5.00',
    '6': '6.00',
    '7': '7.00',
    '8': '8.00',
    '9': '9.00',
    '10': '10.00',
}

postcriteria_choices = {
    '': 'Blank',
}

category_choices = {
    '': 'Blank',
}

categories = PostCategory.objects.all()
for category in categories:
    category_choices[category.category_name] = category.category_name

titles = ItemsList.objects.all()
for title in titles:
    postcriteria_choices[title.ItemsList_name] = title.ItemsList_name


import random

def pi(how_many):
    """
    Evaluates pi using Monte-Carlo method
    :param how_many: how many points shall we draw
    :return: approximation of pi
    """
    inside = 0
    for x in range(how_many):
        x = random.random()  # x in [0, 1)
        y = random.random()  # y in [0, 1)
        r = x * x + y * y  # distance from point (0, 0)
        if r <= 1:  # is the point in a circle of radius 1 with a center at (0, 0)
            inside += 1
    return 4 * inside / how_many  # we considered a quarter of a circle, so its surface is pi/4

if __name__ == '__main__':
    print(pi(100))
    print(pi(1000))
    print(pi(10000))
    print(pi(100000))
    print(pi(1000000))
    print(pi(5000000))


import logging
from pprint import pprint
from sys import stdout as STDOUT

# Example 1
def factorize(number):
    for i in range(1, number + 1):
        if number % i == 0:
            yield i

# Example 2
from time import time
numbers = [2139079, 1214759, 1516637, 1852285]
start = time()
for number in numbers:
    list(factorize(number))
end = time()
print('Took %.3f seconds' % (end - start))

# Example 3
from threading import Thread

class FactorizeThread(Thread):
    def __init__(self, number):
        super().__init__()
        self.number = number

    def run(self):
        self.factors = list(factorize(self.number))

# Example 4
start = time()
threads = []
for number in numbers:
    thread = FactorizeThread(number)
    thread.start()
    threads.append(thread)

# Example 5
for thread in threads:
    thread.join()
end = time()
print('Took %.3f seconds' % (end - start))

# Example 6
import select, socket

# Creating the socket is specifically to support Windows. Windows can't do
# a select call with an empty list.
def slow_systemcall():
    select.select([socket.socket()], [], [], 0.1)

# Example 7
start = time()
for _ in range(5):
    slow_systemcall()
end = time()
print('Took %.3f seconds' % (end - start))

# Example 8
start = time()
threads = []
for _ in range(5):
    thread = Thread(target=slow_systemcall)
    thread.start()
    threads.append(thread)

# Example 9
def compute_helicopter_location(index):
    pass

for i in range(5):
    compute_helicopter_location(i)
for thread in threads:
    thread.join()
end = time()
print('Took %.3f seconds' % (end - start))


import os
from typing import Any, Optional, Literal

from asgiref.sync import sync_to_async
from langchain.tools import Tool
from metaphor_python import Metaphor

from ix.chains.loaders.tools import extract_tool_kwargs

METAPHOR_METHODS = Literal["search", "get_contents", "find_similar"]

def get_metaphor_tool(
    method: METAPHOR_METHODS,
    description: str,
    metaphor_api_key: Optional[str] = None,
    **kwargs: Any,
) -> Tool:
    """Common logic for initializing a Metaphor client and returning a Tool object that can be used to run queries."""
    tool_kwargs = extract_tool_kwargs(kwargs)
    api_key = metaphor_api_key or os.environ.get("METAPHOR_API_KEY", None)
    assert (
        api_key is not None
    ), "Metaphor API key must be provided as metaphor_api_key or METAPHOR_API_KEY env var"

    client = Metaphor(api_key=api_key)
    func = getattr(client, method)
    return Tool(
        name=f"metaphor_{method}",
        description=description,
        func=func,
        coroutine=sync_to_async(func),
        **tool_kwargs,
    )

def get_metaphor_search(**kwargs: Any) -> Tool:
    """Initialize a Tool that wraps `Metaphor.client.search`"""
    description = (
        "Metaphor search engine searches the web for pages that match a given query."
    )
    return get_metaphor_tool("search", description, **kwargs)

def get_metaphor_contents(**kwargs: Any) -> Tool:
    """Initialize a Tool that wraps `Metaphor.client.get_contents`"""
    description = "Get the contents of pages. Pages are identified by ids returned by the search endpoint."
    return get_metaphor_tool("get_contents", description, **kwargs)

def get_metaphor_find_similar(**kwargs: Any) -> Tool:
    """Initialize a Tool that wraps `Metaphor.client.find_similar`"""
    description = "Find pages that are similar to a given URL."
    return get_metaphor_tool("find_similar", description, **kwargs)


from pytest import fixture, mark

from shorter.database import CRUDMixin
from shorter.start.extensions import DB

# pylint: disable=no-member

PAYLOAD = "omg wtf bbq"
LAYPOAD = "napfkuchen!"

class CRUDMixinPhony(CRUDMixin, DB.Model):
    prime = DB.Column(DB.Integer(), primary_key=True)
    value = DB.Column(DB.String())

@fixture(scope="function")
def _crud_c():
    return CRUDMixinPhony.create(value=PAYLOAD, _commit=True)

@fixture(scope="function")
def _crud_nc():
    return CRUDMixinPhony.create(value=PAYLOAD, _commit=False)

@mark.usefixtures("session")
class TestCRUDMixin:
    @staticmethod
    def test_create_no_commit(_crud_nc):
        assert _crud_nc.prime is None
        assert _crud_nc.value == PAYLOAD
        assert _crud_nc in CRUDMixinPhony.query.all()

    @staticmethod
    def test_create_commit(_crud_c):
        assert _crud_c.prime == 1
        assert _crud_c.value == PAYLOAD
        assert _crud_c in CRUDMixinPhony.query.all()

    @staticmethod
    def test_update_no_comit(_crud_nc):
        assert _crud_nc.value == PAYLOAD
        _crud_nc.update(value=LAYPOAD, _commit=False)
        assert _crud_nc.value == LAYPOAD

    @staticmethod
    def test_update_comit(_crud_c):
        assert _crud_c.value == PAYLOAD
        _crud_c.update(value=LAYPOAD, _commit=True)
        assert _crud_c.value == LAYPOAD

    @staticmethod
    def test_save_no_commit(session, _crud_nc):
        assert _crud_nc not in session.dirty
        _crud_nc.value = LAYPOAD
        assert _crud_nc not in session.dirty
        _crud_nc.save(_commit=False)
        assert _crud_nc not in session.dirty

    @staticmethod
    def test_save_commit(session, _crud_c):
        assert _crud_c not in session.dirty
        _crud_c.value = LAYPOAD
        assert _crud_c in session.dirty
        _crud_c.save(_commit=True)
        assert _crud_c not in session.dirty

    @staticmethod
    def test_delete_no_commit(_crud_nc):
        assert _crud_nc in CRUDMixinPhony.query.all()
        _crud_nc.delete(_commit=False)
        assert _crud_nc not in CRUDMixinPhony.query.all()

    @staticmethod
    def test_delete_commit(_crud_c):
        assert _crud_c in CRUDMixinPhony.query.all()
        _crud_c.delete(_commit=True)
        assert _crud_c not in CRUDMixinPhony.query.all()


from tkinter import Canvas, Tk
import time
import shapes

gui = Tk()
gui.title('Animation')
canvas = Canvas(gui, width=500, height=500, background='white')
canvas.pack()
########################## YOUR CODE BELOW THIS LINE ##############################

top_id = shapes.make_rectangle(canvas, (100, 20), 100, 40)
bottom_id = shapes.make_rectangle(canvas, (50, 50), 200, 45)

wheel1_id = shapes.make_circle(canvas, (100, 100), 20, color='black')
wheel2_id = shapes.make_circle(canvas, (200, 100), 20, color='black')

while True:
    shapes.move(canvas, wheel1_id, x=3, y=0)
    shapes.move(canvas, wheel2_id, x=3, y=0)
    shapes.move(canvas, bottom_id, x=3, y=0)
    shapes.move(canvas, top_id, x=3, y=0)
    gui.update()
    time.sleep(.001)

########################## YOUR CODE ABOVE THIS LINE ##############################
# makes sure the canvas keeps running:
canvas.mainloop()


import io
from re import X
import sys

_INPUT = """\
ooo???xxxx
"""
sys.stdin = io.StringIO(_INPUT)

S = list(input())
O = []
X = []

# Sの文字列の中で、条件に合致するのか確認
def judge(s):
    # 値の中に必ず含まれていないといけないもの
    for i in O:
        if i not in s:
            return False

    # 値の中に含まれていたらダメなもの
    for i in X:
        if i in s:
            return False

    return True

ans = 0

for i,char in enumerate(S):
    if char == "o":
        O.append(str(i))

    elif char == "x":
        X.append(str(i))

# print(O,X)

for i in range(10000):
    s = str(i).zfill(4)
    if judge(s):
        ans += 1

print(ans)


import numpy as np

from vivarium.core.process import Step
from vivarium.library.units import units

from ecoli.library.lattice_utils import (
    get_bin_site,
    get_bin_volume,
    count_to_concentration,
)

class LocalField(Step):

    name = 'local_field'
    defaults = {
        'initial_external': {},
        'bin_volume': 1e-6 * units.L,
        'n_bins': [1, 1],
        'bounds': [1, 1] * units.um,
    }

    def __init__(self, parameters=None):
        super().__init__(parameters)
        self.bin_volume = self.parameters['bin_volume']

    def initial_state(self, config=None):
        return {
            'fields': self.parameters['initial_external']
        }

    def ports_schema(self):
        return {
            'exchanges': {
                '*': {
                    '_default': 0,  # counts!
                }
            },
            'location': {
                '_default': [
                    0.5 * bound
                    for bound in self.parameters['bounds']
                ],
            },
            'fields': {
                '*': {
                    '_default': np.ones(1),
                }
            },
            'dimensions': {
                'bounds': {
                    '_default': self.parameters['bounds'],
                },
                'n_bins': {
                    '_default': self.parameters['n_bins'],
                },
                'depth': {
                    '_default': 1 * units.um,
                },
            }
        }

    def next_update(self, timestep, states):
        location = states['location']
        n_bins = states['dimensions']['n_bins']
        bounds = states['dimensions']['bounds']
        depth = states['dimensions']['depth']
        exchanges = states['exchanges']

        # get bin volume
        bin_site = get_bin_site(location, n_bins, bounds)
        bin_volume = get_bin_volume(n_bins, bounds, depth)

        # apply exchanges
        delta_fields = {}
        reset_exchanges = {}
        for mol_id, value in exchanges.items():

            # delta concentration
            exchange = value * units.count
            concentration = count_to_concentration(exchange, bin_volume).to(
                units.mmol / units.L).magnitude

            delta_field = np.zeros((n_bins[0], n_bins[1]), dtype=np.float64)
            delta_field[bin_site[0], bin_site[1]] += concentration
            delta_fields[mol_id] = {
                '_value': delta_field,
                '_updater': 'nonnegative_accumulate'}

            # reset the exchange value
            reset_exchanges[mol_id] = {
                '_value': -value,
                '_updater': 'accumulate'}

        return {
            'exchanges': reset_exchanges,
            'fields': delta_fields}

def test_local_fields():
    parameters = {}
    local_fields_process = LocalField(parameters)

    bounds = [5, 5] * units.um
    n_bins = [3, 3]
    initial_state = {
        'exchanges': {
            'A': 20
        },
        'location': [0.5, 0.5] * units.um,
        'fields': {
            'A': np.ones((n_bins[0], n_bins[1]), dtype=np.float64)
        },
        'dimensions': {
            'bounds': bounds,
            'n_bins': n_bins,
            'depth': 1 * units.um,
        }
    }

    output = local_fields_process.next_update(0, initial_state)

if __name__ == '__main__':
    test_local_fields()


#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
Module is containing all necessary global variables for the package.

Module also has the ability to read user-defined data from two paths:

- ``$HOME/_SETTINGS_PATH``
- ``/etc/_SETTINGS_PATH``

See :attr:`_SETTINGS_PATH` for details.

Note:
    If the first path is found, other is ignored.

There is also possibility to read data from ``JSON_SETTINGS`` env variable.

Example of the configuration file (``$HOME/edeposit/rest.json``)::

    {
        "WEB_ADDR": "0.0.0.0",
        "WEB_PORT": 80
    }

Attributes
----------
"""
# Imports =====================================================================
import os
import json
import os.path

# Module configuration ========================================================
ZEO_CLIENT_CONF_FILE = ""  #: Path to the ZEO configuration.
ZEO_SERVER_CONF_FILE = ""  #: Path to the ZEO configuration.
PROJECT_KEY = "edeposit_rest"  #: Don't change this!

WEB_ADDR = "localhost"  #: Address where the webserver should listen.
WEB_PORT = 8080  #: Port for the webserver.
WEB_SERVER = 'paste'  #: Use `paste` for threading.
WEB_DEBUG = False  #: Turn on web debug messages?
WEB_RELOADER = False  #: Turn on reloader for webserver?
WEB_BE_QUIET = False  #: Be quiet and don't emit debug messages to terminal.

WEB_CACHE = ""  #: Cache for the WEB upload.

# User configuration reader (don't edit this) =================================
_ALLOWED = [str, unicode, int, float, long, bool]  #: Allowed types.
_SETTINGS_PATH = "edeposit/rest.json"  #: Appended to default search paths.

def _get_all_constants():
    """
    Get list of all uppercase, non-private globals (doesn't start with ``_``).

    Returns:
        list: Uppercase names defined in `globals()` (variables from this \
              module).
    """
    return [
        key for key in globals().keys()
        if all([
            not key.startswith("_"),          # publicly accesible
            key.upper() == key,               # uppercase
            type(globals()[key]) in _ALLOWED  # and with type from _ALLOWED
        ])
    ]

def _substitute_globals(config_dict):
    """
    Set global variables to values defined in `config_dict`.

    Args:
        config_dict (dict): dict with data, which are used to set `globals`.

    Note:
        `config_dict` have to be dictionary, or it is ignored. Also all
        variables, that are not already in globals, or are not types defined in
        :attr:`_ALLOWED` (str, int, ..) or starts with ``_`` are silently
        ignored.
    """
    if not isinstance(config_dict, dict):
        raise ValueError("Configuration file must be contained in dictionary!")

    constants = _get_all_constants()
    for key, val in config_dict.iteritems():
        if key in constants and type(val) in _ALLOWED:
            globals()[key] = val

def _assert_constraints():
    def _format_error(var_name, msg):
        msg = repr(msg) if msg else "UNSET!"
        return "You have to set %s (%s) in rest.json config!" % (var_name, msg)

    def _assert_var_is_set(var_name):
        assert globals()[var_name], _format_error(
            var_name,
            globals()[var_name]
        )

    def _assert_exists_and_perm(var, path, perm):
        msg = "Can't access the required `%s` " % path
        msg += "file set in configuration (%s)!" % var

        assert os.path.exists(path) and os.access(path, perm), msg

    _assert_var_is_set("WEB_CACHE")
    _assert_var_is_set("ZEO_CLIENT_CONF_FILE")
    _assert_var_is_set("ZEO_SERVER_CONF_FILE")

    _assert_exists_and_perm("WEB_CACHE", WEB_CACHE, os.W_OK)
    _assert_exists_and_perm(
        "ZEO_CLIENT_CONF_FILE",
        ZEO_CLIENT_CONF_FILE,
        os.R_OK
    )
    _assert_exists_and_perm(
        "ZEO_SERVER_CONF_FILE",
        ZEO_SERVER_CONF_FILE,
        os.R_OK
    )

def _read_from_paths():
    """
    Try to read data from configuration paths ($HOME/_SETTINGS_PATH,
    /etc/_SETTINGS_PATH).
    """
    home = os.environ.get("HOME", "")
    home_path = os.path.join(home, _SETTINGS_PATH)
    etc_path = os.path.join("/etc", _SETTINGS_PATH)
    env_path = os.environ.get("SETTINGS_PATH", "")

    read_path = None
    if env_path and os.path.exists(env_path):
        read_path = env_path
    elif home and os.path.exists(home_path):
        read_path = home_path
    elif os.path.exists(etc_path):
        read_path = etc_path

    if not read_path:
        return "{}"

    with open(read_path) as f:
        return f.read()

def _apply_settings():
    _substitute_globals(
        json.loads(_read_from_paths())
    )

    _assert_constraints()

_apply_settings()


import random

truetotal = 0
putIn = (125)
for j in range(0, 50):
    total = 0
    for i in range(0, 10000):
        i = random.randint(0, 10000);
        if i == 8888:
            total += 1000000
        total -= 125
    print(total)
    truetotal += total
print(truetotal/50)


# Start time: 7:22am
# End time: 7:41am

import aocd

data = """6,10
0,14
9,10
0,3
10,4
4,11
6,0
6,12
4,1
0,13
10,12
3,4
3,0
8,4
1,10
2,14
8,10
9,0

fold along y=7
fold along x=5"""

data = aocd.get_data(year=2021, day=13)

dots, folds = data.split(("\n\n"))
dots = {tuple(map(int, dot.split(","))) for dot in dots.split("\n")}

folds = [(fold[11], int(fold[13:])) for fold in folds.split("\n")]

ff = folds[0]  # First fold

if ff[0] == "x":
    dots = {(x if x < ff[1] else ff[1] - (x - ff[1]), y) for x, y in dots}
else:
    dots = {(x, y if y < ff[1] else ff[1] - (y - ff[1])) for x, y in dots}


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

import tushare as ts
import numpy as np
import pandas as pd
import os
import time
import datetime
import sys
import math
import preprocess
sys.path.append("..")
from common import base_common
from common import np_common

def DecayTest():
    label_days = 6
    show_data_1 = np.zeros((label_days, 2))
    y = 1.0
    cnt = 0
    while 1:
        show_data_1[cnt][0] = cnt
        show_data_1[cnt][1] = y
        y *= 0.6
        cnt += 1
        if cnt == label_days:
            break
    print(show_data_1)

    show_data_2 = np.zeros((label_days, 2))
    y = 1.0
    cnt = 0
    while 1:
        show_data_2[cnt][0] = cnt
        show_data_2[cnt][1] = y
        y -= 0.185
        cnt += 1
        if cnt == label_days:
            break
    print(show_data_2)
    np_common.Show2DData('Decay', [show_data_1, show_data_2], [])

DecayTest()


from _datetime import date
atual = date.today().year
nasc = int(input('Ano de nascimento: '))
idade = atual - nasc
print('Quem nasceu em {} tem {} anos em {}'.format(nasc,idade,atual))
if idade > 18:
    print('Voce deveria ter se alistado antes')
elif idade < 18:
    saldo = 18 - idade
    print('Falta {} anos pra você se alistar'.format(saldo))
elif idade == 18:
    print('Nesse ano voce deve se alistar ou ja se alistou ')


from pydantic import BaseModel

from distances.entities import Address

from .interactor import ComputeDistanceUCI

class AddressM(BaseModel):
    street: str
    house_number: int
    city: str
    country: str

class ComputeDistanceReqM(BaseModel):
    origin: AddressM
    destination: AddressM

def compute_distance_controller(account_id: int, reqm: ComputeDistanceReqM) -> ComputeDistanceUCI:
    ucin = ComputeDistanceUCI(
        account_id=account_id,
        origin=Address(
            street=reqm.origin.street,
            house_number=reqm.origin.house_number,
            city=reqm.origin.city,
            country=reqm.origin.country,
        ),
        destination=Address(
            street=reqm.destination.street,
            house_number=reqm.destination.house_number,
            city=reqm.destination.city,
            country=reqm.destination.country,
        )
    )
    return ucin