from matplotlib import pyplot as plt
import matplotlib as mpl
import numpy as np
from utils.data import readcsv, normalize, get_stock, get_total_gdp
from correlations import get_corr_gdp_with_stock

def get_quarterly_data(data_all):
    return {
        '1': [data for index, data in enumerate(data_all) if index % 4 == 0],
        '2': [data for index, data in enumerate(data_all) if index % 4 == 1],
        '3': [data for index, data in enumerate(data_all) if index % 4 == 2],
        '4': [data for index, data in enumerate(data_all) if index % 4 == 3],
    }

def plot_quarterly_data(quarterly_data, label):
    years_wo_2020 = [i for i in range(2011, 2020)]
    years_w_2020 = [i for i in range(2011, 2021)]
    fig, ax = plt.subplots()
    ax.plot(years_w_2020, quarterly_data['1'], 'C1o-', label='Quarter 1')
    ax.plot(years_w_2020, quarterly_data['2'], 'C2o-', label='Quarter 2')
    ax.plot(years_wo_2020, quarterly_data['3'], 'C3o-', label='Quarter 3')
    ax.plot(years_wo_2020, quarterly_data['4'], 'C0o-', label='Quarter 4')
    plt.ylabel(label)
    plt.xlabel('Year')
    plt.legend()
    plt.grid(True)
    plt.show()

def plot_all_data(gdp1, gdp2, nifty, sensex):
    fig, ax = plt.subplots()
    years = get_x_axis_years()
    ax.plot(years, nifty, 'C1o-', label='Nifty')
    ax.plot(years, sensex, 'C2o-', label='Sensex')
    ax.plot(years, gdp1, 'C0o-', label='Total GDP at Constant Price')
    ax.plot(years, gdp2, 'C4o-', label='Total GDP at Current Price')
    plt.xlabel('Year')
    plt.legend()
    plt.grid(True)
    plt.show()

def plot_all_sectors_with_stock(gdp_data, stock_data, xlabel, ylabel):
    fig, ax = plt.subplots()
    years = get_x_axis_years()

    # GDP Sectors
    gdp_sectors = list(gdp_data.columns.values[1:9])

    for i, sector in enumerate(gdp_sectors):
        sector_data = gdp_data[sector]
        ax.plot(stock_data, sector_data, 'C' + str(i) + 'o--', label=sector)

    plt.xlabel(xlabel + ' Prices')
    plt.ylabel('GDP at ' + ylabel+' Price')
    plt.grid()
    plt.legend()
    plt.show()

def plot_vs(data1, data2, label1, label2):
    fig, ax = plt.subplots()
    ax.scatter(data1, data2, marker='o')
    plt.xlabel(label1)
    plt.ylabel(label2)
    plt.grid(True)
    plt.show()

def plot_vs_gdp(gdp_constant, gdp_current, data,  label):
    fig, ax = plt.subplots()
    ax.plot(data, gdp_constant, marker='o',
            color='C1', label="GDP at Constant Price")
    ax.plot(data, gdp_current, marker='o',
            color='C2', label="GDP at Current Price")
    plt.xlabel(label)
    plt.ylabel('GDP')
    plt.title('GDP vs ' + label + ' with year quarterly')
    plt.grid(True)
    plt.legend()
    plt.show()

def plot_bar_graph(xdata, ydata1, ydata2, xlabel, ylabel1, ylabel2):
    fig, ax = plt.subplots()
    barWidth = 0.25
    br1 = np.arange(len(xdata))
    br2 = [x + barWidth for x in br1]
    ax.bar(br1, ydata1, color='C1', width=barWidth)
    ax.bar(br2, ydata2, color='C2', width=barWidth)
    ax.legend(labels=[ylabel1, ylabel2])
    plt.title('Correlation between GDP at Current Price and Nifty Prices')
    plt.xlabel(xlabel)
    plt.xticks([r + barWidth for r in range(len(ydata1))], xdata)
    plt.show()

def get_x_axis_years():
    # X-axis Years
    years = []
    for year in range(2011, 2020):
        for quarter in range(1, 5):
            years.append(str(year) + '\nQ' + str(quarter))
    years.append(str(2020) + '\nQ' + str(1))
    years.append(str(2020) + '\nQ' + str(2))
    return years

# Read files
gdp_data_constant = readcsv('data/gdp_constant.csv')
gdp_data_current = readcsv('data/gdp_current.csv')
sensex_data = readcsv('data/sensex.csv')
nifty_data = readcsv('data/nifty.csv')
gdp_annual_data_constant = readcsv('data/gdp_constant_annual.csv')
gdp_annual_data_current = readcsv('data/gdp_current_annual.csv')
sensex_annual_data = readcsv('data/sensex_annual.csv')
nifty_annual_data = readcsv('data/nifty_annual.csv')

gdp_normalized_constant = normalize(gdp_data_constant)
gdp_normalized_current = normalize(gdp_data_current)
sensex_normalized = normalize(sensex_data)
nifty_normalized = normalize(nifty_data)

gdp_constant_plot_data = get_total_gdp(gdp_data_constant)
gdp_current_plot_data = get_total_gdp(gdp_data_current)
sensex_plot_data = get_stock(sensex_data)
nifty_plot_data = get_stock(nifty_data)

gdp_constant_plot_normalized_data = get_total_gdp(gdp_normalized_constant)
gdp_current_plot_normalized_data = get_total_gdp(gdp_normalized_current)
sensex_plot_normalized_data = get_stock(sensex_normalized)
nifty_plot_normalized_data = get_stock(nifty_normalized)

nifty_data_quarterly = get_quarterly_data(nifty_plot_data)
sensex_data_quarterly = get_quarterly_data(sensex_plot_data)
gdp_constant_data_quarterly = get_quarterly_data(gdp_constant_plot_data)
gdp_current_data_quarterly = get_quarterly_data(gdp_current_plot_data)

# GDP Sectors
gdp_sectors = list(gdp_data_constant.columns.values[1:9])
gdp_sectors_wrapped = [label.replace(',', ',\n') for label in gdp_sectors]
gdp_sectors_wrapped = [label.replace('&', ' &\n')
                       for label in gdp_sectors_wrapped]
# Plot Quarterly data
# plot_quarterly_data(gdp_constant_data_quarterly, "GDP at Constant Price")
# plot_quarterly_data(gdp_current_data_quarterly, "GDP at Current Price")

# Plot GDP versus Stocks
# plot_vs(nifty_plot_data, gdp_constant_plot_data,
#         'Nifty Prices', 'GDP at Constant Price')
# plot_vs(nifty_plot_data, gdp_current_plot_data,
#         'Nifty Prices', 'GDP at Current Price')
# plot_vs(sensex_plot_data, gdp_constant_plot_data,
#         'Sensex Prices', 'GDP at Constant Price')
# plot_vs(sensex_plot_data, gdp_current_plot_data,
#         'Sensex Prices', 'GDP at Current Price')

# Plot both GDP versus Stocks
# plot_vs_gdp(gdp_constant_plot_data, gdp_current_plot_data, sensex_plot_data,
#             'Sensex Prices')
# plot_vs_gdp(gdp_constant_plot_data, gdp_current_plot_data, nifty_plot_data,
#             'Nifty Prices')

# Plot GDP and stock for all years
# plot_all_data(gdp_constant_plot_normalized_data, gdp_current_plot_normalized_data,
#               nifty_plot_normalized_data, sensex_plot_normalized_data)

# Plot correlations

sensex_corr_gdp_constant = get_corr_gdp_with_stock(
    gdp_data_constant, sensex_data)

sensex_corr_gdp_current = get_corr_gdp_with_stock(
    gdp_data_current, sensex_data)

nifty_corr_gdp_constant = get_corr_gdp_with_stock(
    gdp_data_constant, nifty_data)

nifty_corr_gdp_current = get_corr_gdp_with_stock(
    gdp_data_current, nifty_data)

# plot_bar_graph(
#     gdp_sectors_wrapped, sensex_corr_gdp_constant['pearson'], sensex_corr_gdp_constant['spearman'], "GDP Sectors", "Pearson Correlation", "Spearman Correlation")

# plot_bar_graph(
#     gdp_sectors_wrapped, sensex_corr_gdp_current['pearson'], sensex_corr_gdp_current['spearman'], "GDP Sectors", "Pearson Correlation", "Spearman Correlation")

# plot_bar_graph(
#     gdp_sectors_wrapped, nifty_corr_gdp_constant['pearson'], nifty_corr_gdp_constant['spearman'], "GDP Sectors", "Pearson Correlation", "Spearman Correlation")

# plot_bar_graph(
#     gdp_sectors_wrapped, nifty_corr_gdp_current['pearson'], nifty_corr_gdp_current['spearman'], "GDP Sectors", "Pearson Correlation", "Spearman Correlation")

# plot_all_sectors_with_stock(
#     gdp_data_constant, sensex_plot_data,  "Sensex", "Constant")
# plot_all_sectors_with_stock(
#     gdp_data_current, sensex_plot_data,  "Sensex", "Current")
# plot_all_sectors_with_stock(
#     gdp_data_constant, nifty_plot_data,  "Nifty", "Constant")
# plot_all_sectors_with_stock(
#     gdp_data_current, nifty_plot_data,  "Nifty", "Current")

def plot_separate(gdp_constant_data, gdp_current_data, gdp_sectors, stock_data, pearson_data_constant, pearson_data_current, label):
    f3, a = plt.subplots(2, 4)

    i = 0
    j = 0

    for sector in gdp_sectors:
        sector_constant_data = gdp_constant_data[sector][:-1]
        sector_current_data = gdp_current_data[sector][:-1]
        regression_func_constant = np.poly1d(
            np.polyfit(stock_data, sector_constant_data, 1))
        regression_func_current = np.poly1d(
            np.polyfit(stock_data, sector_current_data, 1))
        a[i][j].plot(stock_data, sector_constant_data, 'C1o-',
                     label=sector[:20] + '... at Constant Price')
        a[i][j].plot(stock_data, sector_current_data, 'C2o-',
                     label=sector[:20] + '... at Current Price')
        a[i][j].set_xlabel(label+" Data($)")
        a[i][j].set_ylabel("GDP(Cr)")
        a[i][j].set_title(
            "Spearman Coeff. at \nConstant/Current Price\n {:.3f}/{:.3f}".format(pearson_data_constant[i*4+j], pearson_data_current[i*4+j]))
        a[i][j].plot(stock_data, regression_func_constant(stock_data), 'C3-')
        a[i][j].plot(stock_data, regression_func_current(stock_data), 'C4-')
        a[i][j].ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
        a[i][j].ticklabel_format(axis="x", style="sci", scilimits=(0, 0))
        a[i][j].grid()
        a[i][j].legend()

        j += 1
        if j == 4:
            i += 1
            j = 0
    plt.subplots_adjust(left=0.05, bottom=0.1, right=0.95,
                        top=0.9, wspace=0.4, hspace=0.4)
    plt.show()

# plot_separate(gdp_annual_data_constant, gdp_annual_data_current, gdp_sectors,
#               sensex_annual_data[sensex_annual_data.columns[1]][:-1], sensex_corr_gdp_constant['pearson'])

# plot_separate(gdp_annual_data_constant, gdp_annual_data_current, gdp_sectors,
#               sensex_annual_data[sensex_annual_data.columns[1]][:-1],
#               sensex_corr_gdp_constant['pearson'], sensex_corr_gdp_current['pearson'],
#               label='Sensex')

# plot_separate(gdp_annual_data_constant, gdp_annual_data_current, gdp_sectors,
#               nifty_annual_data[nifty_annual_data.columns[1]][:-1],
#               nifty_corr_gdp_constant['pearson'], nifty_corr_gdp_current['pearson'],
#               label='Nifty')

plot_separate(gdp_annual_data_constant, gdp_annual_data_current, gdp_sectors,
              sensex_annual_data[sensex_annual_data.columns[1]][:-1],
              sensex_corr_gdp_constant['spearman'], sensex_corr_gdp_current['spearman'],
              label='Sensex')

plot_separate(gdp_annual_data_constant, gdp_annual_data_current, gdp_sectors,
              nifty_annual_data[nifty_annual_data.columns[1]][:-1],
              nifty_corr_gdp_constant['spearman'], nifty_corr_gdp_current['spearman'],
              label='Nifty')


import numpy as np

BAG_CAPACITY = 50
DEFAULT_ITERATIONS = 50

class ScoreEvaluator:
    def __init__(self, bag_capacity=BAG_CAPACITY):
        self.bag_capacity = bag_capacity
        self.gift_weights = None

    def calculate_score(self, bags, iterations=DEFAULT_ITERATIONS):
        score = 0
        for _ in range(iterations):
            self.gift_weights = self._generate_random_weights()
            score += self._calculate_single_score(bags)
        return score / iterations

    def _calculate_single_score(self, bags):
        score = 0
        for bag in bags:
            score += self._calculate_score_for_bag(bag)
        return score

    def _calculate_score_for_bag(self, bag):
        score = 0
        for gift in bag:
            score += self.gift_weights[gift]
        return score if score <= self.bag_capacity else 0

    def _generate_random_weights(self):
        weights = {
            'horse': max(0, np.random.normal(5, 2, 1)[0]),
            'ball': max(0, 1 + np.random.normal(1, 0.3, 1)[0]),
            'bike': max(0, np.random.normal(20, 10, 1)[0]),
            'train': max(0, np.random.normal(10, 5, 1)[0]),
            'coal': 47 * np.random.beta(0.5, 0.5, 1)[0],
            'book': np.random.chisquare(2, 1)[0],
            'doll': np.random.gamma(5, 1, 1)[0],
            'blocks': np.random.triangular(5, 10, 20, 1)[0],
            'gloves': 3.0 + np.random.rand(1)[0] if np.random.rand(1) < 0.3 else np.random.rand(1)[0],
        }
        return weights


from geopy.geocoders import Nominatim
from geopy import distance
import threading
import time

closecities = []
is_done = False
start_time = False
# find the cities within 20 miles of the location entered

def currentlyClose(location):
    global is_done,start_time
    try:
        # Prompt user for zip code or city name
        print("finding cities close to: {}".format(location))
        with open('cities.txt', 'r') as file:
            cities = file.read().splitlines()
        # Prompt user for zip code or city name
        start_time = True
        # Geocode location using Nominatim
        geolocator = Nominatim(user_agent="my_app")
        location_coords = geolocator.geocode(location, exactly_one=True).point

        # Find cities within 20 miles of location
        nearby_cities = []
        for city in cities:
            city_coords = geolocator.geocode(city, exactly_one=True).point
            if distance.distance(location_coords, city_coords).miles <= 20:
                nearby_cities.append(city)

        # Print out nearby cities
        print("Cities within 20 miles of {}:".format(location))
        for city in nearby_cities:
            closecities.append(city)
        is_done = True
    except Exception as e:
        print(e)

def print_time():
    seconds = 0
    while not is_done:
        if start_time:
            print("Running timer : {}  seconds - ".format(seconds), end="\r")
            seconds += 1
            time.sleep(1)

def currentlyCloseWithTimer(location):
    timer_thread = threading.Thread(target=print_time)
    timer_thread.start()
    currentlyClose(location)
    timer_thread.join()

def checkCache(location):
    with open('closecities.txt', 'r') as file:
        lines = file.read().splitlines()
        try:
            zip_index = lines.index(location)
            cities = []
            for i in range(zip_index + 1, len(lines)):
                if lines[i].startswith("--"):
                    break
                cities.append(lines[i])
            return cities
        except ValueError:
            return False

def saveCache(location, cities):
    with open('closecities.txt', 'a') as file:
        file.write(location + "\n")
        for city in cities:
            file.write(city + "\n")

def searching():
    location = input("Enter zip code or city name: ")
    if location == "":
        location = "New York"

    _request_ = checkCache(f"-- {location}")
    if _request_ == False:
        currentlyCloseWithTimer(location)
        saveCache(f"-- {location}", closecities)
    else:
        print(_request_)
        exit()


import sys
si = sys.stdin.readline

n = int(si())
array = []

for _ in range(n):
    a, b = map(str, si().rstrip().split())
    array.append((int(a), b))

array.sort(key=lambda x:x[0])

for i in range(n):
    print(array[i][0], array[i][1])

03_구현/나이순 정렬.py


class Solution(object):
    def __init__(self):
        self.nums = None
        self.smallest_value_index = None

    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        self.nums = nums
        self.search_smallest_value_index()

        left = 0
        right = len(nums)
        while left < right:
            mid = (left + right) // 2
            mid_value = self.get_value_by_unrotated_index(mid)
            if mid_value == target:
                return self.get_rotated_index(mid)

            if mid_value > target:
                right = mid
            else:
                left = mid + 1

        return -1

    def search_smallest_value_index(self):
        # [left, right]
        left = 0
        right = len(self.nums) - 1

        while left <= right:
            if self.nums[left] <= self.nums[right]:
                self.smallest_value_index = left
                return

            if left + 1 == right:
                self.smallest_value_index = right
                return

            mid = (left + right) // 2
            if self.nums[mid] > self.nums[left]:
                left = mid + 1  # middle is not a candidate of smallest value.
            elif self.nums[mid] < self.nums[right]:
                right = mid  # middle value is a candidate of smallest value.

    def get_rotated_index(self, index):
        return (index + self.smallest_value_index) % len(self.nums)

    def get_value_by_unrotated_index(self, index):
        return self.nums[self.get_rotated_index(index)]

def test_0033():
    s = Solution()
    nums = [4, 5, 6, 7, 0, 1, 2]

    assert s.search(nums, 0) == 4
    assert s.search(nums, 3) == -1
    assert s.search([1], 0) == -1

    nums = [0, 1, 2, 4, 5, 6, 7]
    assert s.search(nums, 0) == 0

    nums = [1, 2, 4, 5, 6, 7, 0]
    assert s.search(nums, 0) == 6

    nums = [7, 0, 1, 2, 4, 5, 6]
    assert s.search(nums, 0) == 1

    nums = [3, 1]
    assert s.search(nums, 0) == -1

    nums = [5, 1, 3]
    assert s.search(nums, 5) == 0


import time
WORDLIST_FILENAME = "words.txt"
delimiter="\n" #REPLACE "\N" WITH YOUR DELIMITER OR SEPARATOR
def Convert(string):
    ls=list(string.split(delimiter)) #delimiter
    return ls
with open("wordlist.py", "w+") as external_file:
    rawfile = open(WORDLIST_FILENAME, "r")
    z=rawfile.read()
    print("Loading words...")
    time.sleep(1)
    print("words = ",Convert(z),file=external_file)
    print(len(Convert(z)),"words successfully loaded into converted.txt!\nYou may close this window.")
    input()


#
# @lc app=leetcode id=46 lang=python
#
# [46] Permutations
#
# https://leetcode.com/problems/permutations/description/
#
# algorithms
# Medium (58.27%)
# Likes:    2609
# Dislikes: 84
# Total Accepted:    458.9K
# Total Submissions: 787.5K
# Testcase Example:  '[1,2,3]'
#
# Given a collection of distinct integers, return all possible permutations.
#
# Example:
#
#
# Input: [1,2,3]
# Output:
# [
#  [1,2,3],
#  [1,3,2],
#  [2,1,3],
#  [2,3,1],
#  [3,1,2],
#  [3,2,1]
# ]
#
#
#

# @lc code=start
class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

    #     # === 回溯 ===
    #     res = []
    #     self.dfs(nums, res, [])
    #     return res

    # def dfs(self, nums, res, path):
    #     if len(path) == len(nums):
    #         res.append(path)
    #         return

    #     for i in range(len(nums)):
    #         if nums[i] not in path:
    #             self.dfs(nums, res, path+[nums[i]])

        res = [[]]
        for i in range(len(nums)):
            temp = []
            for item in res:
                for j in range(len(item)+1):
                    # 插入
                    temp.append(item[:j] + [nums[i]] + item[j:])
            res = temp
        return res
# @lc code=end

sol = Solution()
nums = [1,2,3]
sol.permute(nums)


__author__ = 'Independence'

def combinations(n, k):
    if n < 0 or k < 0:
        print('Error in combinations, you will die')
    elif k > n:
        return 0
    elif k == n or k == 0:
        return 1
    else:
        return combinations(n-1, k-1) + combinations(n-1, k)
inp = str(input())
inp = inp.split(' ')
print(combinations(int(inp[0]), int(inp[1])))


'''
  This program gets a stocks opening and closing price given the
  stock abreviation and date as input.
'''

import yfinance as yf
import sys

if len(sys.argv) != 3:
  sys.exit('usage: python3 get_stonks.py [name-of-stock] [date: yyyy-mm-dd]')

name = sys.argv[1]
date_start = sys.argv[2]

# adds 1 day to the date passed in
date_end = date_start[:(len(date_start)-2)] + str(int(date_start[len(date_start)-2:])+1)

data = yf.download(name, start=date_start, end=date_end)
price_open = (data.tail(1)['Open'].iloc[0])
price_close = (data.tail(1)['Close'].iloc[0])
diff = price_open-price_close

print(f'name: {name}')
print(f'  date: {date_start}')
print(f'    open price:  ${price_open}')
print(f'    close price: ${price_close}')
if diff < 0:
  print(f'    total gain/loss: -${diff * -1}')
else:
  print(f'    total gain/loss: ${diff}')


from config import *
from modelo import Montadora, Carro, Cliente

@app.route("/")
def inicio():
    return 'Sistema de cadastro de carros. '+\
        'Listar Carros'
#ROTA PARA LISTAR CARROS
@app.route("/listar/<string:classe>")
def listar(classe):
    dados = None
    if classe == "Montadora":
        dados = db.session.query(Montadora).all()
    elif classe == "Carro":
        dados = db.session.query(Carro).all()
    elif classe == "Cliente":
        dados = db.session.query(Cliente).all()
    lista_jsons = [x.json() for x in dados]
    resposta = jsonify(lista_jsons)
    resposta.headers.add("Access-Control-Allow-Origin", "*")
    return resposta

#ROTA PARA INCLUIR CARROS
@app.route("/incluir_carro", methods=['post'])
def incluir_carro():
    resposta = jsonify({"resultado": "ok", "detalhes": "ok"})
    dados = request.get_json()
    try:
        novo = Carro(**dados)
        db.session.add(novo)
        db.session.commit()
    except Exception as e:
        resposta = jsonify({"resultado":"erro", "detalhes":str(e)})
    resposta.headers.add("Access-Control-Allow-Origin", "*")
    return resposta

#ROTA PARA EXCLUIR CARROS (AV4)
@app.route("/excluir_carro/<int:carro_id>", methods=["delete"])
def excluir_carro(carro_id):
    resposta = jsonify({"resultado": "ok", "detalhes": "ok"})
    try:
        Carro.query.filter(Carro.id == carro_id).delete()
        db.session.commit()
    except Exception as e:
        resposta = jsonify({"resultado": "erro", "detalhes": str(e)})
    resposta.headers.add("Access-Control-Allow-Origin", "*")
    return resposta

app.run(debug=True)


## 2001 파리퇴치
import sys
sys.stdin = open('input.txt', 'r')

def kill_flys(n, m, flylist):
    hit = n - m + 1
    result = 0

    for a in range(hit):
        for b in range(hit):  # 파리채이동
            kills = 0
            for i in range(a, a + m):
                for j in range(b, b + m):
                    kills += flylist[i][j]  # 파리잡기
            if kills > result:
                result = kills  # 최대값 비교

    return result

testcase = int(input())

for i in range(testcase):
    N , M = map(int, input().split())
    flys = []
    for _ in range(N):
        flys.append(list(map(int, input().split())))
    print('#{}'.format(i+1), kill_flys(N, M, flys))


"""
  Unit tests for LTI Platform Auth endpoints
"""
import os
import pytest
# disabling pylint rules that conflict with pytest fixtures
# pylint: disable=unused-argument,redefined-outer-name,unused-import, line-too-long

from fastapi import FastAPI
from fastapi.testclient import TestClient
from common.testing.firestore_emulator import (firestore_emulator,
                                               clean_firestore)
from common.utils.http_exceptions import add_exception_handlers
from testing.test_config import API_URL
import mock
with mock.patch(
    "google.cloud.secretmanager.SecretManagerServiceClient",
    side_effect=mock.MagicMock()) as mok:
  from routes.platform_auth import router
  from schemas.schema_examples import BASIC_TOOL_EXAMPLE

app = FastAPI()
add_exception_handlers(app)
app.include_router(router, prefix="/lti/api/v1")

client_with_emulator = TestClient(app)

os.environ["FIRESTORE_EMULATOR_HOST"] = "localhost:8080"
os.environ["GOOGLE_CLOUD_PROJECT"] = "fake-project"

test_key_set = {
    "key": "test_rsa_key",
    "key_id": "key_hash_value",
    "public_keyset": {
        "keys": [{
            "kty": "RSA",
            "alg": "RS256",
            "kid": "key_hash_value",
            "use": "sig",
            "e": "v92b7ey9o",
            "n": "obvr189yr398bPNv"
        }]
    },
    "web_key": {
        "kty": "RSA",
        "alg": "RS256",
        "kid": "key_hash_value",
        "use": "sig",
        "e": "v92b7ey9o",
        "n": "obvr189yr398bPNv"
    }
}

@mock.patch("routes.platform_auth.get_platform_public_keyset")
def test_jwks(mock_key_set, clean_firestore):
  mock_key_set.return_value = test_key_set
  url = f"{API_URL}/jwks"
  resp = client_with_emulator.get(url)

  assert resp.status_code == 200
  assert resp.json() == test_key_set.get("public_keyset")

@mock.patch("routes.platform_auth.generate_token_claims")
@mock.patch("routes.platform_auth.encode_token")
@mock.patch("routes.platform_auth.get_unverified_token_claims")
def test_post_authorize(mock_claims, mock_token, mock_key_set, clean_firestore):
  test_token = "ey7abos8f.8astvd9q.87cb"
  mock_token.return_value = test_token
  mock_claims.return_value = {"lti_request_type": "deep_link"}

  form_data = {
      "client_id": "test_client_id",
      "login_hint": "test_user_id",
      "lti_message_hint": "test_resource_id",
      "redirect_uri": "test_redirect_uri",
      "nonce": "1tr8b174b7134813v",
      "state": "b54b725vt9y9",
      "scope": "openid",
      "response_type": "id_token",
      "response_mode": "form_post",
      "prompt": "none"
  }
  mock_key_set.return_value = test_key_set
  url = f"{API_URL}/authorize"
  headers = {"Content-Type": "application/x-www-form-urlencoded"}
  resp = client_with_emulator.post(url, data=form_data, headers=headers)

  assert resp.status_code == 200
  assert resp.context.get("id_token") == test_token

@mock.patch("routes.platform_auth.generate_token_claims")
@mock.patch("routes.platform_auth.encode_token")
@mock.patch("routes.platform_auth.get_unverified_token_claims")
def test_get_authorize(mock_claims, mock_token, mock_key_set, clean_firestore):
  test_token = "ey7abos8f.8astvd9q.87cb"
  mock_token.return_value = test_token
  mock_claims.return_value = {"lti_request_type": "deep_link"}

  req_params = {
      "client_id": "test_client_id",
      "login_hint": "test_user_id",
      "lti_message_hint": "test_resource_id",
      "redirect_uri": "test_redirect_uri",
      "nonce": "1tr8b174b7134813v",
      "state": "b54b725vt9y9",
      "scope": "openid",
      "response_type": "id_token",
      "response_mode": "form_post",
      "prompt": "none"
  }

  mock_key_set.return_value = test_key_set
  url = f"{API_URL}/authorize"
  resp = client_with_emulator.get(url, params=req_params)

  assert resp.status_code == 200
  assert resp.context.get("id_token") == test_token

@pytest.mark.parametrize("create_tool", [BASIC_TOOL_EXAMPLE], indirect=True)
@mock.patch("routes.platform_auth.get_remote_keyset")
@mock.patch("routes.platform_auth.get_unverified_token_claims")
@mock.patch("routes.platform_auth.decode_token")
@mock.patch("routes.platform_auth.encode_token")
def test_token(mock_encoded_token, mock_decoded_token, mock_claims,
               mock_key_set, clean_firestore, create_tool):

  test_tool = create_tool
  test_claims = {
      "iss": test_tool.tool_url,
      "iat": "token_issued_time",
      "exp": "token_expired_time",
      "aud": "audience_token_url",
      "sub": test_tool.client_id
  }

  test_encoded_token = {
      "access_token": "test_token_value",
      "token_type": "bearer",
      "expires_in": 3600
  }

  mock_decoded_token.return_value = test_claims
  mock_encoded_token.return_value = "test_token_value"
  mock_claims.return_value = test_claims

  req_data = {
      "grant_type":
          "client_credentials",
      "client_assertion_type":
          "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      "client_assertion":
          "ey7ot812b.t3s4vb7kra3.tb7i3vsatb92va2tovn",
      "scope":
          "https://purl.imsglobal.org/spec/lti-ags/scope/lineitem"
  }
  mock_key_set.return_value = test_key_set
  url = f"{API_URL}/token"
  headers = {"Content-Type": "application/x-www-form-urlencoded"}
  resp = client_with_emulator.post(url, data=req_data, headers=headers)

  assert resp.status_code == 200
  json_res = resp.json()
  assert json_res.get("access_token") == test_encoded_token.get("access_token")


# Name: trinomialsplit.py
# Description: class that stores an ST and its split-up version
# Attributes:
#   Variables:
#       trinomial - string containing an instance of an ST.
#       statenumber - contains the state code. 1 - 50, alphabetical except for Alaska and Hawaii
#       countycode - contains alphabetical county code string.
#       sitenumber - contains actual site number.#

class TrinomialSplit:

    trinomial = ""
    statenumber = ""
    countycode = ""
    sitenumber = ""
    count = 0
    countycount = 0

    def __init__(self, trinomialinstance):
        self.trinomial = trinomialinstance
        self.split_trinomial()

    def has_dashes(self):
        if self.trinomial.find("-") != -1:
            return True
        else:
            return False

    def has_spaces(self):
        if self.trinomial.find(" ") != -1:
            return True
        else:
            return False

    def has_state_no(self):
        if self.statenumber == "00":
            return False
        else:
            return True

    # strip dashes
    def strip_dashes(self):
        self.trinomial = self.trinomial.replace("-", "")

    #strip spaces
    def strip_spaces(self):
        self.trinomial = self.trinomial.replace(" ", "")

    def has_parens(self):
        if ((self.trinomial.find("(") != -1) or (self.trinomial.find(")") != -1)):
            return True
        else:
            return False

    def has_brackets(self):
        if ((self.trinomial.find("[") != -1) or (self.trinomial.find("]") != -1)):
            return True
        else:
            return False

    # Strip trinomial of brackets or parens
    def strip_parens(self):
        self.trinomial = self.trinomial.replace("(", "")
        self.trinomial = self.trinomial.replace(")", "")

    def strip_brackets(self):
        self.trinomial = self.trinomial.replace("]", "")
        self.trinomial = self.trinomial.replace("[", "")

    #Grabs the state code.

    def get_state_code(self):
        self.statenumber = self.trinomial[self.count:2]
        self.count += 2

    #Grabs the county code
    def get_county_code(self):
        # If there is a state number, the starting off point for the loop should be its length.
        # else, it should be 0.

        #keep track of what the length of the county code is.
        countylen = 0

        for char in self.trinomial:
            if char.isalpha():
                countylen += 1

        #county code spans from the current count to the end of the code
        self.countycode = self.trinomial[self.count:self.count + countylen]
        self.count += countylen

    #grabs the site number
    def get_site_number(self):
        self.sitenumber = self.trinomial[self.count:]

    # see if the site number has leading zeros
    def has_leading(self):
        if self.sitenumber[0] == "0":
            return True
        else:
            return False

    #count and return the number of leading zeros
    def leadingzeros(self):
        leading = 0
        for n in self.sitenumber:
            if n == "0":
                leading += 1
            else:
                return leading

    # remove the leading zeroes
    def remove_leading(self):
        self.sitenumber = self.sitenumber[self.leadingzeros():]

    def split_trinomial(self):

        if self.has_parens():
            self.strip_parens()
        if self.has_brackets():
            self.strip_brackets()

        if self.has_dashes():
            self.strip_dashes()
        if self.has_spaces():
            self.strip_spaces()

        if self.is_lowercase():
            self.change_toupper()

        if self.has_state_no():
             self.get_state_code()
        else:
            self.statenumber = "00"
        self.get_county_code()
        self.get_site_number()

        if self.has_leading():
            self.remove_leading()

    # Test function to print out the trinomial elements.
    def print_elements(self):
        print(self.statenumber + " " + self.countycode + " " + self.sitenumber)
     # test function
    def print_trinomial(self):
        print(self.trinomial)

    # checks if any of the letters are lower case, and, if so, returns true.
    def is_lowercase(self):
        for char in self.trinomial:
            if char.islower():
                return True
        return False

    #changes any lowercase letters to uppercase.
    def change_toupper(self):
        temp = ""
        for char in self.trinomial:
            if char.islower():
                temp += char.upper()
            else:
                temp += char

        self.trinomial = temp


import numpy as np
from tqdm import tqdm
from data import make_bow_vector, make_target

def train(
    model,
    texts,
    targets,
    review_dict,
    vocab_size,
    optimizer,
    loss_function,
    epochs,
    device,
    log_file
):
    ffnn_loss_file_name = log_file
    f = open(ffnn_loss_file_name, "w")
    f.write("iter, loss")
    f.write("\n")
    losses = []
    iter = 0
    min_valid_loss = np.inf
    bad_epochs = 0
    # Start training
    for epoch in tqdm(range(epochs), total=epochs, desc='Training FFNN model..'):
        train_loss = 0
        model.train()
        for index, row in texts.iterrows():
            # Clearing the accumulated gradients
            optimizer.zero_grad()

            # Make the bag of words vector for stemmed tokens
            # bow_vec = make_bow_vector(review_dict, row['tokenized_text'])

            bow_vec = make_bow_vector(
                review_dict, row["tokenized_text"], vocab_size, device
            )

            # Forward pass to get output
            probs = model(bow_vec)

            # Get the target label
            target = make_target(targets["label"][index], device)

            # Calculate Loss: softmax --> cross entropy loss
            loss = loss_function(probs, target)
            # Accumulating the loss over time
            train_loss += loss.item()

            # Getting gradients w.r.t. parameters
            loss.backward()

            # Updating parameters
            optimizer.step()

        f.write(str((epoch + 1)) + "," + str(train_loss / len(texts)))
        f.write("\n")
        train_loss = 0


import pandas as pd
import numpy as np
import datetime
from pandas import DataFrame

#rawdata=pd.read_csv('10_fe_1.txt',dtype=str,sep='\t',nrows=1000)

passenger_label=pd.read_csv('value_pas_0710.txt',sep='\t',names=['passenger_id','label'],header=None)
jzyh=jiazid.loc[passenger_label['label'] == '3']

raw_pid=list(np.loadtxt('rawdata_pid.txt'))   #761603
pospid=list(passenger_label[passenger_label['label'] == '3'].passenger_id)  # positive pid   18879
negpid=list(passenger_label[passenger_label['label'] == '2'].passenger_id)  # negative  pid 749209

pos_pid=list(set(pospid).intersection(set(raw_pid)))   #18478
neg_pid=list(set(negpid).intersection(set(raw_pid)))    #743124

#--------------------------- begin  提取快车&专车原始数据：正样本&负样本 --------------------
import random
sample_size=int(1.5*len(pos_pid))
sam_neg_pid=random.sample(neg_pid,sample_size)  #负样本抽取
for i in range(len(pos_pid)):
    pos_pid[i]=str(pos_pid[i])
for i in range(len(sam_neg_pid)):
    sam_neg_pid[i]=str(sam_neg_pid[i])

#找出pid对应正负数据
#专车 neg
given_pid = {p:None for p in sam_neg_pid}
order_file = open("{}/10_fe_1.txt".format('/data1/dengyuying//COMPETING_DATA'), "r")
lines = order_file.readlines()  #readlines读取所有行(直到结束符 EOF)并返回列表
order_file.close()
row_num=[]
num_lines = len(lines)
for i in range(num_lines):
    row = lines[i].strip().split('\t')  #strip()去掉每行头尾空白
    pid = row[60]#int(row[60])
    if pid in given_pid:  # given_pid:  pos_pid, sam_neg_pid
        row_num.append(i)  #找出pid对应rawdata行号
path_prefix = "{}/neg_data_zc_15.txt".format('/data1/dengyuying//COMPETING_DATA')
data_file = open(path_prefix, "w")
for i in range(len(row_num)):
    data_file.write(lines[row_num[i]])
data_file.close()
print('Done zhuanche')

#快车  neg
order_file = open("{}/fe_kuaiche.tsv".format('/data1/dengyuying//COMPETING_DATA'), "r")
lines = order_file.readlines()
order_file.close()
row_num=[]
num_lines = len(lines)
for i in range(num_lines):
    row = lines[i].strip().split('\t')
    pid = row[118]#int(row[60])
    if pid in given_pid:  # given_pid:  pos_pid, sam_neg_pid
        row_num.append(i)
path_prefix = "{}/neg_data_kc_15.txt".format('/data1/dengyuying//COMPETING_DATA')
data_file = open(path_prefix, "w")
for i in range(len(row_num)):
    data_file.write(lines[row_num[i]])
data_file.close()

#--------------------------- end 提取快车&专车原始数据：正样本&负样本--------------------

#  clean data

from clean_data_kc_zc import *
path1 = '/nfs/project/dengyuying/zhuanche/neg_data_zc_1102.txt'
path2 = '/nfs/project/dengyuying/zhuanche/neg_data_kc_1102.txt'
file_name1 = 'clean_neg_data_zc_1102.txt'
file_name2 = 'clean_neg_data_kc_1102.txt'
clean_data_kc_zc(path1,path2,file_name1, file_name2)

clean_neg_data_kc = pd.DataFrame(np.loadtxt('/data1/dengyuying/COMPETING_DATA/clean_neg_data_kc_1102.txt'))
clean_neg_data_zc = pd.DataFrame(np.loadtxt('/data1/dengyuying/COMPETING_DATA/clean_neg_data_zc_1102.txt'))
clean_pos_data_kc = pd.DataFrame(np.loadtxt('/data1/dengyuying/COMPETING_DATA/clean_pos_data_kc.txt'))
clean_pos_data_zc = pd.DataFrame(np.loadtxt('/data1/dengyuying/COMPETING_DATA/clean_pos_data_zc.txt'))

# 按pid合并快车与专车数据
clean_pos_merge_kz=clean_pos_data_kc.merge(clean_pos_data_zc,left_on=clean_pos_data_kc.iloc[:,0],right_on=clean_pos_data_zc.iloc[:,0],how="inner")
clean_neg_merge_kz=clean_neg_data_kc.merge(clean_neg_data_zc,left_on=clean_neg_data_kc.iloc[:,0],right_on=clean_neg_data_zc.iloc[:,0],how="inner")

clean_pos_merge_kz=clean_pos_merge_kz.drop(clean_pos_merge_kz.columns[[0,3601]],axis=1) #删除pid
clean_neg_merge_kz=clean_neg_merge_kz.drop(clean_neg_merge_kz.columns[[0,3601]],axis=1)

clean_pos_merge_kz.to_csv('clean_pos_merge_kz_1102.csv')
clean_neg_merge_kz.to_csv('clean_neg_merge_kz_1102.csv')

import xgboost as xgb
from xgboost import XGBClassifier
from xgboost import XGBRegressor   # this is for regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score,accuracy_score
from scipy.stats import ranksums
from sklearn.metrics import precision_recall_fscore_support
import pickle

clean_pos_merge_kz = pd.read_csv('/data1/dengyuying/COMPETING_DATA/clean_pos_merge_kz_1102.csv')
clean_neg_merge_kz = pd.read_csv('/data1/dengyuying/COMPETING_DATA/clean_neg_merge_kz_1102.csv')
if clean_pos_merge_kz.shape[1] == 5431:
    clean_pos_merge_kz = clean_pos_merge_kz.iloc[:,1:]
if clean_neg_merge_kz.shape[1] == 5431:
    clean_neg_merge_kz = clean_neg_merge_kz.iloc[:,1:]

response = [ 1 for _ in range(clean_pos_merge_kz.shape[0])]
response += [0 for _ in range(clean_neg_merge_kz.shape[0])]
y = np.array(response)
x = np.concatenate((clean_pos_merge_kz, clean_neg_merge_kz), axis=0)
from model import *
importances, select_marker, index, train_data = model(y, x)

#半个月专车特征数据
#clean_pos_merge_kz_half = clean_pos_merge_kz.iloc[:,0:4515]
#clean_neg_merge_kz_half = clean_neg_merge_kz.iloc[:,0:4515]

#一周专车特征数据
#clean_pos_merge_kz_week = clean_pos_merge_kz.iloc[:,0:4027]
#clean_neg_merge_kz_week = clean_neg_merge_kz.iloc[:,0:4027]

DAYSINC = 30
sorted_argument = np.argsort(-importances)
inds = index[select_marker[sorted_argument]]
sorted_impo = np.sort(importances)[::-1]

selected_name_kc = np.load("selected_name_kc.npy")
selected_name_zc = np.load("selected_name_zc.npy")
selected_name=np.append(selected_name_kc,selected_name_zc)
all_col_name = []
for i in range(DAYSINC):
    for j in range(len(selected_name)):
        all_col_name.append(str(i+1)+'_'+selected_name[j])
fe_importance = list(zip(sorted_impo, [all_col_name[i] for i in inds]))
fe_importance=DataFrame(fe_importance)
fe_importance[0:20]


"""This is the food object for our snake game"""

from turtle import *
import random

class Food(Turtle):
    def __init__(self):
        super().__init__()
        self.shape("circle")
        self.penup()
        self.shapesize(stretch_wid=0.5, stretch_len=0.5)
        self.speed("fastest")
        self.color("blue")
        self.refresh_food()

    def refresh_food(self):
        position_x = random.randint(-260, 260)
        position_y = random.randint(-260, 260)
        self.goto(x=position_x, y=position_y)


from odoorpc_toolbox import base_helper
import os

print ("Einstellungen der Reports nun gesetzt...")

# Connect to the odoo system
base_path = os.path.dirname(os.path.abspath(__file__))
helper = base_helper.EqOdooConnection(base_path + '/config.yaml')
odoo = helper.odoo

IR_ACTION_REPORT_XML = odoo.env['ir.actions.report']
REPORT_PAPERFORMAT = odoo.env['report.paperformat']

_report_format_id = REPORT_PAPERFORMAT.search([('name', '=', "European A4")])
_format = REPORT_PAPERFORMAT.browse(_report_format_id)

# Rechnungen
_report_id = IR_ACTION_REPORT_XML.search([('name', '=', "Rechnungen"), ('model', '=', "account.invoice")])
eq_format_found = len(_report_id) != 0
if eq_format_found and len(_report_id) != 0:
    _report_data = {}
    _report_data['attachment'] = "(object.state in ('open','paid')) and ('Rechnung-'+(object.number or '').replace('/','')+'.pdf')"
    _report_data['print_report_name'] = "(object.state in ('open','paid')) and ('Rechnung-'+(object.number or '').replace('/','')+'.pdf')"
    _report_data['attachment_use'] = True
    _report_data['paperformat_id'] = _report_format_id[0]
    _report = IR_ACTION_REPORT_XML.browse(_report_id)
    _report.write(_report_data)
    print("Rechnungen aktualisiert!")
else:
    print("Rechnungen NICHT gefunden!")

# Angebot / Bestellung (Verkauf)
_report_id = IR_ACTION_REPORT_XML.search([('name', '=', "Angebot / Bestellung"), ('model', '=', "sale.order")])
if eq_format_found and len(_report_id) != 0:
    _report_data = {}
    _report_data['attachment'] = "(object.state in ('draft','sent')) and ('Angebot-' + (object.name or '').replace('/','')+'.pdf') or (object.state in ('sale','done')) and ('Auftrag-' + (object.name or '').replace('/','')+'.pdf')"
    _report_data['print_report_name'] = "(object.state in ('draft','sent')) and ('Angebot-' + (object.name or '').replace('/','')+'.pdf') or (object.state in ('sale','done')) and ('Auftrag-' + (object.name or '').replace('/','')+'.pdf')"
    _report_data['attachment_use'] = True
    _report_data['paperformat_id'] = _report_format_id[0]
    _report = IR_ACTION_REPORT_XML.browse(_report_id)
    _report.write(_report_data)
    print("Angebot / Bestellung aktualisiert!")
else:
    print("Angebot / Bestellung NICHT gefunden!")

# Angebotsanfrage (Einkauf)
_report_id = IR_ACTION_REPORT_XML.search([('name', '=', "Angebotsanfrage"), ('model', '=', "purchase.order")])
if eq_format_found and len(_report_id) != 0:
    _report_data = {}
    _report_data['attachment'] = "('Einkaufanfrage-' + (object.name or '').replace('/','')+'.pdf')"
    _report_data['print_report_name'] = "('Einkaufanfrage-' + (object.name or '').replace('/','')+'.pdf')"
    _report_data['attachment_use'] = True
    _report_data['paperformat_id'] = _report_format_id[0]
    _report = IR_ACTION_REPORT_XML.browse(_report_id)
    _report.write(_report_data)
    print("Angebotsanfrage aktualisiert!")
else:
    print("Angebotsanfrage NICHT gefunden!")

# Beschaffungsauftrag (Einkauf)
_report_id = IR_ACTION_REPORT_XML.search([('name', '=', "Beschaffungsauftrag"), ('model', '=', "purchase.order")])
if eq_format_found and len(_report_id) != 0:
    _report_data = {}
    _report_data['attachment'] = "('Einkauf-' + (object.name or '').replace('/','')+'.pdf')"
    _report_data['print_report_name'] = "('Einkauf-' + (object.name or '').replace('/','')+'.pdf')"
    _report_data['attachment_use'] = True
    _report_data['paperformat_id'] = _report_format_id[0]
    _report = IR_ACTION_REPORT_XML.browse(_report_id)
    _report.write(_report_data)
    print("Beschaffungsauftrag aktualisiert!")
else:
    print("Beschaffungsauftrag NICHT gefunden!")

# Packvorgänge (Lager)
_report_id = IR_ACTION_REPORT_XML.search([('name', '=', "Packvorgänge"), ('model', '=', "stock.picking")])
if eq_format_found and len(_report_id) != 0:
    _report_data = {}
    _report_data['attachment'] = "('Packschein-' + (object.name or '').replace('/','')+'.pdf')"
    _report_data['print_report_name'] = "('Packschein-' + (object.name or '').replace('/','')+'.pdf')"
    _report_data['attachment_use'] = True
    _report_data['paperformat_id'] = _report_format_id[0]
    _report = IR_ACTION_REPORT_XML.browse(_report_id)
    _report.write(_report_data)
    print("Packvorgänge aktualisiert!")
else:
    print("Packvorgänge NICHT gefunden!")

# Lieferschein (Lager)
_report_id = IR_ACTION_REPORT_XML.search([('name', '=', "Lieferschein"), ('model', '=', "stock.picking")])
if eq_format_found and len(_report_id) != 0:
    _report_data = {}
    _report_data['attachment'] = "('Lieferschein-' + (object.name or '').replace('/','')+'.pdf')"
    _report_data['print_report_name'] = "('Lieferschein-' + (object.name or '').replace('/','')+'.pdf')"
    _report_data['attachment_use'] = True
    _report_data['paperformat_id'] = _report_format_id[0]
    _report = IR_ACTION_REPORT_XML.browse(_report_id)
    _report.write(_report_data)
    print("Lieferschein aktualisiert!")
else:
    print("Lieferschein NICHT gefunden!")

    #('Packschein-' + (object.name or '').replace('/', '') + '.pdf')


from json.tool import main
import os
import SimpleITK as sitk
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['image.cmap'] = 'gray'
plt.rcParams['image.interpolation'] = 'nearest'
import nibabel as nib
from dipy.viz import regtools
from dipy.align.imaffine import (AffineMap,
                                 MutualInformationMetric,
                                 AffineRegistration)
from dipy.align.transforms import (TranslationTransform3D,
                                   RigidTransform3D,
                                   AffineTransform3D)

# $ git clone https://github.com/SuperElastix/SimpleElastix
# $ mkdir build
# $ cd build
# $ cmake ../SimpleElastix/SuperBuild
# $ make -j4

# set default parameter
new_spacing = [1, 1, 1]
registrated_type = 'affine'
# See the Dipy registration tutorial for the details of what these parameters mean:
nbins = 32
sampling_prop = None
level_iters = [10, 10, 5]
sigmas = [3.0, 1.0, 0.0]
factors = [4, 2, 1]

dirname = r'F:\BaiduNetdiskDownload\shuju\shuju\226630'

filename = r'F:\BaiduNetdiskDownload\shuju\shuju\226630\ep2d_diff_tra_b800_b1000_p2_160 - as a 3 frames MultiVolume by Siemens.B-value.raw.gz'
filename2 = r'F:\BaiduNetdiskDownload\shuju\ep2d_diff_tra_b800_b1000_p2_160 - as a 3 frames MultiVolume by Siemens.B-value.raw.gz'
def registrate_valid():
    moving = nib.load(r'F:\BaiduNetdiskDownload\shuju\shuju\226630\8 ep2d_diff_tra_b800_b1000_p2_160_ADC_1_resampled.nii')
    fixed = nib.load(r'F:\BaiduNetdiskDownload\shuju\shuju\226630\4 t2_tse_tra_p2_4_resampled.nii')
    moving_data = moving.get_data()
    fixed_data = fixed.get_data()
    moving_affine = moving.affine
    fixed_affine = fixed.affine
    identity = np.eye(4)
    affine_map = AffineMap(identity, fixed_data.shape, fixed_affine, moving_data.shape, moving_affine)
    resampled = affine_map.transform(moving_data)  # 3-4 minutes
    # regtools.overlay_slices(fixed_data, resampled, None, 0, 'fixed', 'moving')
    # regtools.overlay_slices(fixed_data, resampled, None, 1, 'fixed', 'moving')
    # regtools.overlay_slices(fixed_data, resampled, None, 2, 'fixed', 'moving')
    metric = MutualInformationMetric(nbins, sampling_prop)
    affreg = AffineRegistration(metric=metric, level_iters=level_iters, sigmas=sigmas, factors=factors)

    # optimize the translations
    transform = TranslationTransform3D()
    params0 = None
    translation = affreg.optimize(fixed_data, moving_data, transform, params0, fixed_affine, moving_affine)
    # translation.affine
    transformed = translation.transform(moving_data)
    # regtools.overlay_slices(fixed_data, transformed, None, 0, 'fixed', 'transformed')
    # regtools.overlay_slices(fixed_data, transformed, None, 1, 'fixed', 'transformed')
    # regtools.overlay_slices(fixed_data, transformed, None, 2, 'fixed', 'transformed')

    # optimize a rigid-body transform
    transform = RigidTransform3D()
    rigid = affreg.optimize(fixed_data, moving_data, transform, params0, fixed_affine, moving_affine, starting_affine=translation.affine)
    transformed = rigid.transform(moving_data)

    # full affine registration
    transform = AffineTransform3D()
    affreg.level_iters = [1000, 1000, 100]
    affine = affreg.optimize(fixed_data, moving_data, transform, params0, fixed_affine, moving_affine, starting_affine=rigid.affine)
    transformed = affine.transform(moving_data)
    regtools.overlay_slices(fixed_data, transformed, None, 0, 'fixed', 'transformed')
    regtools.overlay_slices(fixed_data, transformed, None, 1, 'fixed', 'transformed')
    regtools.overlay_slices(fixed_data, transformed, None, 2, 'fixed', 'transformed')
    transformed_image = sitk.GetImageFromArray(transformed.transpose(2,1,0))
    resampled_fix = sitk.ReadImage(r'F:\BaiduNetdiskDownload\shuju\shuju\226630\4 t2_tse_tra_p2_4_resampled.nii')
    transformed_image.SetOrigin(resampled_fix.GetOrigin())
    transformed_image.SetSpacing(resampled_fix.GetSpacing())
    transformed_image.SetDirection(resampled_fix.GetDirection())
    sitk.WriteImage(transformed_image, r'F:\BaiduNetdiskDownload\shuju\shuju\226630\8 ep2d_diff_tra_b800_b1000_p2_160_ADC_1_registrated.nii')

# write a function for z-score
def z_score_process_image(sitk_image):
    sitk_arr = sitk.GetArrayFromImage(sitk_image)  # ndarray
    volume = sitk_arr != 0  # type bool
    sitk_arr[volume] = (sitk_arr[volume] - np.mean(sitk_arr[volume])) / np.std(sitk_arr[volume])
    return sitk.GetImageFromArray(sitk_arr)

def resample_process_image(sitk_image, new_spacing=[1,1,1]):
    ori_size = np.array(sitk_image.GetSize(), dtype=np.int)
    ori_origin = sitk_image.GetOrigin()
    ori_spacing = np.array(sitk_image.GetSpacing(), dtype=np.float)
    ori_direction = sitk_image.GetDirection()

    new_spacing = np.array(new_spacing, dtype=np.float)
    new_size = ori_size * (ori_spacing / new_spacing)
    new_size = np.ceil(new_size).astype(np.int)  # Image dimensions are in integers
    new_size = [int(s) for s in new_size]  # SimpleITK expects lists, not ndarrays

    resampler_filter = sitk.ResampleImageFilter()
    resampler_filter.SetReferenceImage(sitk_image)
    resampler_filter.SetSize(new_size)
    resampler_filter.SetInterpolator(sitk.sitkBSpline)
    resampler_filter.SetOutputSpacing(new_spacing)
    resampler_filter.SetOutputOrigin(ori_origin)
    resampler_filter.SetOutputDirection(ori_direction)
    resampled_sitk_image = resampler_filter.Execute(sitk_image)

    return resampled_sitk_image

def registration_process_image(fixed_image, moving_image, type='affine'):
    elastixImageFilter = sitk.ElastixImageFilter()
    elastixImageFilter.SetFixedImage(fixed_image)
    elastixImageFilter.SetMovingImage(moving_image)
    elastixImageFilter.SetParameterMap(sitk.GetDefaultParameterMap("affine"))
    elastixImageFilter.Execute()
    registed_image = elastixImageFilter.GetResultImage()
    return registed_image

def z_score_resample():
    under_preprocess = {}
    for file in os.listdir(dirname):
        if 'zscore' in file:
            continue
        if 'resampled' in file:
            continue
        if 't2' in file:
            under_preprocess['T2WI'] = os.path.join(dirname, file)
        if 'ADC' in file:
            under_preprocess['ADC'] = os.path.join(dirname, file)
        if 'DWI' in file:
            under_preprocess['DWI'] = os.path.join(dirname, file)
    # Step1: z-score each image
    for key, value in under_preprocess.items():
        z_score_name = value.split('.nii')[0] + '_zscore.nii'
        if not os.path.exists(z_score_name):
            image = sitk.ReadImage(value)
            image = sitk.Cast(image, sitk.sitkFloat64)
            original_origin = image.GetOrigin()
            original_spacing = image.GetSpacing()
            original_direction = image.GetDirection()
            z_score_image = z_score_process_image(image)
            z_score_image.SetOrigin(original_origin)
            z_score_image.SetSpacing(original_spacing)
            z_score_image.SetDirection(original_direction)
            sitk.WriteImage(z_score_image, z_score_name)
    # Step2: Resample each image
    for key, value in under_preprocess.items():
        z_score_name = value.split('.nii')[0] + '_zscore.nii'
        resampled_name = value.split('.nii')[0] + '_resampled.nii'
        if os.path.exists(z_score_name) and not os.path.exists(resampled_name):
            z_score_image = sitk.ReadImage(z_score_name)
            resampled_image = resample_process_image(z_score_image)
            sitk.WriteImage(resampled_image, resampled_name)
    # Step3: Registration (Affine)
    fixed_name = under_preprocess['T2WI'].split('.nii')[0] + '_resampled.nii'
    fixed_image = sitk.ReadImage(fixed_name)
    # fixed = under_preprocess.pop(under_preprocess['T2WI'])
    for key, value in under_preprocess.items():
        resampled_name = value.split('.nii')[0] + '_resampled.nii'
        regis_name = value.split('.nii')[0] + '_registed.nii'
        if os.path.exists(resampled_name) and not os.path.exists(regis_name):
            if key == 'T2WI':
                continue
            moving_image = sitk.ReadImage(resampled_name)
            registed_image = registration_process_image(fixed_image, moving_image)
            sitk.WriteImage(registed_image, regis_name)

if __name__ == '__main__':
    # z_score_resample()
    registrate_valid()

    # readdata, header = nrrd.read(filename2)
    # b = 1


from pymongo import MongoClient
from app.config import settings
# by default connect to the local host
conn = MongoClient(
    settings.DATABASE_URL)

db = conn.prosperity_profile

collection_users = db["users"]
collection_feedback = db["feedback"]
collection_aadhar = db["aadhar"]
collection_pan = db["pan"]
collection_cards = db["cards"]
collection_coverage = db["coverage"]


import subprocess

def execute(command):
    if isinstance(command, str):
        process = subprocess.Popen(command.split(),stdout=subprocess.PIPE,stderr=subprocess.STDOUT,bufsize=1, universal_newlines=True)
    elif isinstance(command, list):
        process = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,bufsize=1, universal_newlines=True)
    else:
        return
    for line in process.stdout:
      yield line

def execute_with_output(command):
    if isinstance(command, str):
        process = subprocess.Popen(command.split(),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    elif isinstance(command, list):
        process = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    else:
        return
    out,err = process.communicate()
    return out,err

def check_execution(command):
    try:
        if isinstance(command, str):
            subprocess.run(command.split(), check=True, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
        elif isinstance(command, list):
            subprocess.run(command, check=True, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
        else:
            return False
        return True
    except:
        return False


# -*- coding: utf-8 -*-
"""
Created on Fri Apr 15 16:08:01 2016

@author: EBianco
"""

import requests
from bs4 import BeautifulSoup
import re
import dateutil.parser
from pprint import pprint
import re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.common.exceptions import NoSuchElementException

url1 = 'http://www.boxofficemojo.com/movies/?id=atlasshruggedpart2.htm'
url2 = 'http://www.boxofficemojo.com/movies/?id=starwars4.htm'
url = url1
response = requests.get(url)
page = response.text
soup = BeautifulSoup(page, 'lxml')
driver = webdriver.PhantomJS()

#Tried and True Functions
def get_movie_value(soup, field_name):
    obj = soup.find(text=re.compile(field_name))
    if not obj:
        return None
    next_sibling = obj.findNextSibling()
    if next_sibling:
        return next_sibling.text
    else:
        return None

def get_dlg (string):
    try:
        obj = str(soup.find(text=re.compile('Domestic Lifetime Gross:')))
        obj = obj.split(':')
        obj = int(obj[1].replace('$','').replace(',',''))
        return obj
    except IndexError:
        return None

def get_the_players(soup, field_name):
    obj = soup.find(text = field_name)
    if not obj:
        return None
    elif field_name == 'Actors:':
        return obj.parent.parent.findNext('td')
    else:
        return obj.parent.parent.findNext('td').text

def get_adjusted(field_name):
    driver.get(url)
    inf_adjust_2016_selector = '//select[@name="ticketyr"]/option[@value="2016"]'
    driver.find_element_by_xpath(inf_adjust_2016_selector).click()
    go_button = driver.find_element_by_name("Go")
    go_button.click()
    if field_name == "DTotalAG":
        gross_selector = '//font[contains(text(), "Domestic Total")]/b'
        return driver.find_element_by_xpath(gross_selector).text
    elif field_name == "DLifetimeAG":
        try:
            gross_selector = '//b[contains(text(), "Domestic Lifetime Adj. Gross")]'
            item = driver.find_element_by_xpath(gross_selector).text
            items = item.split(':')
            return(items[1])
        except NoSuchElementException:
            return None

#Formatting Functions
def to_date(datestring):
    date = dateutil.parser.parse(datestring)
    return date

def money_to_int(moneystring):
    moneystring = moneystring.replace('$','').replace(',','')
    return int(moneystring)

def runtime_to_minutes(runtimestring):
    runtime = runtimestring.split()
    try:
        minutes = int(runtime[0])*60 + int(runtime[2])
        return minutes
    except:
        return None

def budget_to_int(budgetstring):
    if budgetstring == 'N/A':
        return None
    else:
        budgetstring = budgetstring.replace('$','').replace(' million','')
        budget = int(budgetstring)*1000000
        return budget

def create_list(actors):
    if not actors:
        return None
    else:
        actor_list = []
        actors = str(actors)
        actors = actors.split('
')
        for i in actors:
            i = re.sub('<.+?>', '', i)
            actor_list.append(i)
        return actor_list

    #function to create dict
def createdict():
    title_string = soup.find('title').text
    title = title_string.split('(')[0].strip()

    raw_release_date = get_movie_value(soup, 'Release Date')
    release_date = to_date(raw_release_date)

    raw_dtg = get_movie_value(soup, 'Domestic Total')
    domestic_total_gross = money_to_int(raw_dtg)

    dlg = get_dlg(dlg)

    raw_total_adj_gross = get_adjusted('DTotalAG')
    total_adj_gross = money_to_int(raw_total_adj_gross)

    raw_lifetime_adj_gross = get_adjusted('DLifetimeAG')
    if raw_lifetime_adj_gross is None:
        lifetime_adj_gross = None
    else:
        lifetime_adj_gross = money_to_int(raw_lifetime_adj_gross)

    raw_runtime = get_movie_value(soup, 'Runtime')
    runtime =runtime_to_minutes(raw_runtime)

    genre_string = soup.find(text=re.compile('Genre:'))
    genre=str(genre_string.findNextSibling())
    genre=genre.replace('','').replace('','')

    rating = get_movie_value(soup, 'MPAA Rating')

    budgetstring = get_movie_value(soup, 'Production Budget')
    budget = budget_to_int(budgetstring)

    series_raw = str(soup.find(text=re.compile('Series:')))
    series_raw = series_raw.split(': ')
    series = str(series_raw[1])

    director = get_the_players(soup, 'Director:')

    writer = get_the_players(soup, 'Writer:')

    producer = get_the_players(soup,'Producer:')

    composer = get_the_players(soup, 'Composer:')

    actors = get_the_players(soup, 'Actors:')
    actor_list = create_list(actors)

    headers = ['domestic total adj gross(2016)', 'domestic lifetime adj gross(2016)', 'budget', 'actors', 'director', 'writer', 'producer', 'composer', 'series', 'movie title', 'domestic total gross', 'domestic lifetime', 'release date', 'runtime (mins)', 'rating', 'genre']

    movie_data = []
    movie_dict = dict(zip(headers, [total_adj_gross, lifetime_adj_gross, budget, actor_list, director, writer, producer, composer, series, title, domestic_total_gross, dlg, release_date, runtime, rating, str(genre)]))
    movie_data.append(movie_dict)

    pprint (movie_data)

    driverjs.close()


class TreeNode:
    def __init__(self, val) -> None:
        self.val = val
        self.left = None
        self.right = None

root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)

root1 = TreeNode(1)
root1.left = TreeNode(2)
root1.right = TreeNode(3)
root1.left.left = TreeNode(4)
root1.left.right = TreeNode(5)

class solution:
    def isSame(self, s, t):
        if not s and not t:
            return True
        if s and t and s.val == t.val:
            return self.isSame(s.left, t.left) and self.isSame(s.right, t.right)

        return False

    def isSubTree(self, root: TreeNode, subRoot:  TreeNode):
        if not subRoot:
            return True

        if not root:
            return False

        if self.isSame(root, subRoot):
            return True

        return self.isSubTree(root.left, subRoot) or self.isSubTree(root.right, subRoot)

x = solution()
print(x.isSubTree(root, root1))


# =============================================================================
# Libs
# =============================================================================
from dudu_tests.bert.custom_strategy_bert import train_and_test
import unittest
import random
import torch
import os
import torch.distributed as dist
from fairscale.nn.model_parallel import initialize_model_parallel, destroy_model_parallel
from dudu_tests import strategy_handler
from fairscale.utils.testing import set_random_seed
from dudu_tests.strategy_handler import LayerStrategy

# Turns a dictionary into a class
class Dict2Class(object):
    def __init__(self, my_dict):
        for key in my_dict:
            setattr(self, key, my_dict[key])

class StrategyTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        set_random_seed(12345)
        cls.train_args = Dict2Class({'seq_length': 128, 'embed_size': 512, 'hidden_layer_size': 512, 'atten_heads': 8,
                                     'encoder_layers': 2, 'batch_size': 32, 'print_params': False, 'epochs': 1,
                                     'budget': 50, 'import_strategy': "strategies/strategy.json",
                                     'export_strategy': "strategies/exported_strat.json", 'name': 'no_name.pt'})
        cls.vanilla_strategy = strategy_handler.import_strategy('strategies/bert_vanilla.json')
        cls.local_rank = int(os.environ['LOCAL_RANK'])
        dist.init_process_group(backend='nccl')
        backends = {"model_parallel_backend": "nccl", "pipeline_backend": "nccl", "ddp_backend": "nccl"}
        initialize_model_parallel(dist.get_world_size(), 1, **backends)

    @classmethod
    def tearDownClass(cls) -> None:
        destroy_model_parallel()
        dist.destroy_process_group()

    def setUp(self) -> None:
        global_rank = dist.get_rank()
        print(f"[{os.getpid()}] rank = {global_rank}, " + f"world_size = {dist.get_world_size()}")
        torch.cuda.set_device(self.local_rank)
        self.train_args.strategy = self.vanilla_strategy.copy()

    # def test_best_vs_vanilla_strategies(self):
    #     if self.local_rank == 0 and self.train_args.print_params:
    #         print(self.train_args.strategy)
    #     # warmup run to make sure comparison between runs doesnt include set up times and memory pinning
    #     self.train_args.n_iteration = 30
    #     self.train_args.epochs = 1
    #     train_and_test(self.local_rank, self.train_args)
    #     # run both vanilla and custom strategies to make sure the custom strategy is an improvement
    #     self.train_args.n_iteration = 200
    #     self.train_args.epochs = 1
    #     vanilla_ips = train_and_test(self.local_rank, self.train_args)
    #     self.train_args.strategy = strategy_handler.import_strategy('strategies/strategy.json')
    #     best_ips = train_and_test(self.local_rank, self.train_args)
    #     print(f'vanilla ips: {vanilla_ips}, best ips: {best_ips}')
    #     self.assertGreater(best_ips, vanilla_ips)

    def test_a_illegal_strategies_test(self):
        n_iteration = 10
        avg_ips, latency = train_and_test(self.local_rank, self.train_args)

    def test_a_vanilla_strategy(self):
        if self.local_rank == 0 and self.train_args.print_params:
            print(self.train_args.strategy)
        self.train_args.n_iteration = 30
        self.assertIs(type(train_and_test(self.local_rank, self.train_args)), float)

    def test_b_column_without_gather_then_row_with_input_is_parallel(self):
        self.train_args.strategy["encoders.0.ff.linear1"] = LayerStrategy(column_linear=True, gather_output=False)
        self.train_args.strategy["encoders.0.ff.linear2"] = LayerStrategy(row_linear=True, input_is_parallel=True)
        if self.local_rank == 0 and self.train_args.print_params:
            print(self.train_args.strategy)
        self.train_args.n_iteration = 30
        self.assertIs(type(train_and_test(self.local_rank, self.train_args)), float)

    def test_c_row_parallel_with_input_is_parallel(self):
        self.train_args.strategy["encoders.0.ff.linear1"] = LayerStrategy(row_linear=True, input_is_parallel=True)
        if self.local_rank == 0 and self.train_args.print_params:
            print(self.train_args.strategy)
        self.train_args.n_iteration = 30
        with self.assertRaises(RuntimeError):
            train_and_test(self.local_rank, self.train_args)

    def test_d_consecutive_column_parallel_without_gather_in_between(self):
        self.train_args.strategy["encoders.0.ff.linear1"] = LayerStrategy(column_linear=True, gather_output=False)
        self.train_args.strategy["encoders.0.ff.linear2"] = LayerStrategy(column_linear=True, gather_output=False)
        if self.local_rank == 0 and self.train_args.print_params:
            print(self.train_args.strategy)
        self.train_args.n_iteration = 30
        with self.assertRaises(RuntimeError):
            train_and_test(self.local_rank, self.train_args)

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


import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import messagebox

print (" Librerias Leidas")

ventana= tk.Tk()
ventana.title("Interfaz Gráfica")
ventana.geometry("400x500")

#Crear los comandos
def imagen ():
    img=Image.open("C:/Users\claud\OneDrive - Universidad Tecnologica de Jalisco\OneDrive\Documentos\MAESTRIA INTELIGENCIA ARTIFICIAL\MIA PYTHON VSC\GUI\imagenes\Paisajes\descarga.gif")
    new_img=img.resize((300,256))
    render=ImageTk.PhotoImage(new_img)
    #Llamar imagen
    img1=Label(ventana, image=render)
    img1.image=render
    img1.place(x=10,y=30)
def mensaje():
    salir= messagebox.askquestion("Salir", "¿Desea salir de la interfaz?")
    if salir == 'yes':
        ventana.quit()
        ventana.detroy()

#Crear botones
boton=tk.Button(ventana, command=imagen, text="Abrir Imagen", height=2,width=20 )
boton.place(x=100, y=350)

boton1=tk.Button(ventana, command=mensaje, text="Salir", height=2,width=20 )
boton1.place(x=100, y=450)

ventana.mainloop()


import theano
import theano.tensor as T
import sklearn
import sklearn.datasets
import numpy as np
import matplotlib.pyplot as plt
import timeit

theano.config.floatX = 'float32'

# Helper function to plot a decision boundary.
def plot_decision_boundary(pred_func):
    # Set min and max values and give it some padding
    x_min, x_max = train_X[:, 0].min() - .5, train_X[:, 0].max() + .5
    y_min, y_max = train_X[:, 1].min() - .5, train_X[:, 1].max() + .5
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    # Predict the function value for the whole gid
    Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.scatter(train_X[:, 0], train_X[:, 1], c=train_y, cmap=plt.cm.Spectral)

# Generate datasets
train_X, train_y = sklearn.datasets.make_moons(200, noise='0.2')
train_y_onehot = np.eye(2)[train_y]

# Size definitions
num_examples = len(train_X)  # training set size
nn_input_dim = 2  # input layer dimensionality
nn_output_dim = 2  # output layer dimensionality
nn_hdim = 100

epsilon = np.float32(0.01) # learning rate for gradient descent
reg_lambda = np.float32(0.01) # regularization strength

# These float32 values will be initialized on the GPU
X = theano.shared(train_X.astype('float32'), name='X')
y = theano.shared(train_y_onehot.astype('float32'), name='y')
W1 = theano.shared(np.random.randn(nn_input_dim, nn_hdim).astype('float32'), name='W1')
b1 = theano.shared(np.zeros(nn_hdim).astype('float32'), name='b1')
W2 = theano.shared(np.random.randn(nn_hdim, nn_output_dim).astype('float32'), name='W2')
b2 = theano.shared(np.zeros(nn_output_dim).astype('float32'), name='b2')

# Forward propagation
# Note: We are just defining the expressions, nothing is evaluated here!
z1 = X.dot(W1) + b1
a1 = T.tanh(z1)
z2 = a1.dot(W2) + b2
y_hat = T.nnet.softmax(z2)  # output probabilties

# The regularization term (optional)
loss_reg = 1./num_examples * reg_lambda/2 * (T.sum(T.sqr(W1)) + T.sum(T.sqr(W2)))
# the loss function we want to optimize
loss = T.nnet.categorical_crossentropy(y_hat, y).mean() + loss_reg

# Returns a class prediction
prediction = T.argmax(y_hat, axis=1)

# Theano functions that can be called from our Python code
forward_prop = theano.function([], y_hat)
calculate_loss = theano.function([], loss)
predict = theano.function([], prediction)

# Easy: Let Theano calculate the derivatives for us!
dW2 = T.grad(loss, W2)
db2 = T.grad(loss, b2)
dW1 = T.grad(loss, W1)
db1 = T.grad(loss, b1)

gradient_step = theano.function(
    [],
    updates=((W2, W2 - epsilon * dW2),
             (W1, W1 - epsilon * dW1),
             (b2, b2 - epsilon * db2),
             (b1, b1 - epsilon * db1)))

def build_model(num_passes=20000, print_loss=False):
    # Re-Initialize the parameters to random values. We need to learn these.
    np.random.seed(0)
    # GPU NOTE: Conversion to float32 to store them on the GPU!
    W1.set_value((np.random.randn(nn_input_dim, nn_hdim) / np.sqrt(nn_input_dim)).astype('float32'))
    b1.set_value(np.zeros(nn_hdim).astype('float32'))
    W2.set_value((np.random.randn(nn_hdim, nn_output_dim) / np.sqrt(nn_hdim)).astype('float32'))
    b2.set_value(np.zeros(nn_output_dim).astype('float32'))

    # Gradient descent. For each batch...
    for i in range(0, num_passes):
        # This will update our parameters W2, b2, W1 and b1!
        gradient_step()

        # Optionally print the loss.
        # This is expensive because it uses the whole dataset, so we don't want to do it too often.
        if print_loss and i % 1000 == 0:
            print("Loss after iteration %i: %f" %(i, calculate_loss()))

# Profiling
# theano.config.profile = True
# theano.config.profile_memory = True
# gradient_step()\
# theano.printing.debugprint(gradient_step)
# print gradient_step.profile.summary()

def plot_decision_boundary_gpu(pred_func):
    # Set min and max values and give it some padding
    x_min, x_max = train_X[:, 0].min() - .5, train_X[:, 0].max() + .5
    y_min, y_max = train_X[:, 1].min() - .5, train_X[:, 1].max() + .5
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    X.set_value((np.c_[xx.ravel(), yy.ravel()]).astype('float32'))
    # Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
    Z = pred_func()
    Z = Z.reshape(xx.shape)

    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.scatter(train_X[:, 0], train_X[:, 1], c=train_y, cmap=plt.cm.Spectral)

build_model()
# print(timeit.timeit("build_model()", "from __main__ import build_model"))
# Plot the decision boundary

plot_decision_boundary(lambda x: predict(x))
plt.title("Decision Boundary for hidden layer size 3")
plt.show()


from openerp import fields, models, api, exceptions, _
from openerp import tools
from openerp.tools.safe_eval import safe_eval as eval

LISTA_ESTADOS = [
    ('paid', 'Pagado'),
    ('confirm', 'Cerrado')
]

class grp_agrupar_fondo_rotarios(models.Model):
    _name = 'grp.agrupar.fondo.rotarios'
    _auto = False
    _order = 'id_documento desc, tipo_documento, id'

    tipo_documento = fields.Selection([('account_invoice_fr', 'Facturas de fondo rotatorio'),
                                       ('account_invoice_refund_fr', u'Nota de Crédito fondo rotatorio'),
                                       ('hr_expense_anticipo', u'Rendición de anticipo'),
                                       ('hr_expense', u'Rendición de viático'),
                                       ('hr_expense_v', 'Vales'),
                                       ('bank_statement', u'Líneas de Registros de caja'),
                                       ('caja_chica', u'Líneas de Caja efectivo'),
                                       ('hr_expense_a', u'Abonos')], 'Tipo de Documento', size=86,
                                      default='account_invoice_fr')
    proveedor = fields.Char(string='Proveedor')
    fecha_factura = fields.Date(string='Fecha factura')
    n_documento = fields.Char(string='N° documento')
    n_documento2 = fields.Char(string='N° documento 2')
    total = fields.Float(string='Total')
    estado = fields.Selection(LISTA_ESTADOS, 'Estado', size=86, readonly=True, default='paid')
    ue = fields.Char(string='UE')
    inciso = fields.Char(string='Inciso')
    id_documento = fields.Integer(string='Documento')
    journal_id = fields.Many2one('account.journal', 'Diario')
    operating_unit_id = fields.Many2one('operating.unit', 'Unidad ejecutora')
    fecha_pago = fields.Date('Fecha de pago', compute='_compute_fecha_pago', search='_search_fecha_pago')

    currency_id = fields.Many2one('res.currency', string=u'Moneda')
    company_id = fields.Many2one('res.company', string=u'Compañía')

    @api.multi
    def _get_fecha_pago(self):
        self = self.sudo()
        self.ensure_one()
        if self.tipo_documento == 'account_invoice_fr':
            payment_ids = self.env['account.invoice'].browse(self.id_documento).payment_ids
            if payment_ids:
                _fecha_pago = payment_ids[0].date
            else:
                _fecha_pago = False
        elif self.tipo_documento == 'bank_statement':
            _fecha_pago = self.env['account.bank.statement.line'].browse(self.id_documento).date or False
        elif self.tipo_documento in ['hr_expense', 'hr_expense_anticipo']:
            _fecha_pago = self.env['hr.expense.expense'].browse(self.id_documento).account_move_id.date or False
        elif self.tipo_documento == 'caja_chica':
            _fecha_pago = self.env['grp.caja.chica.tesoreria.line'].browse(self.id_documento).account_move_id.date or False
        else:
            _fecha_pago = False
        return _fecha_pago

    @api.one
    def _compute_fecha_pago(self):
        self.fecha_pago = self._get_fecha_pago()

    def _search_fecha_pago(self, operator, value):
        ids = []
        if operator == '=':
            operator = '=='
        for line in self.search([]):
            _fecha_pago = line._get_fecha_pago()
            if eval("'%s' %s '%s'" % (_fecha_pago,operator,value)):
                ids.append(line.id)
        return [('id', 'in', ids)]

    def _subquery(self):
        return """(select
                        'account_invoice_fr' as tipo_documento,
                        l.id as id_documento,
                        p.name as proveedor,
                        l.date_invoice as fecha_factura,
                        l.nro_factura_grp as n_documento,
                        l.amount_total as total,
                        l.state as estado,
                        ue.ue as ue,
                        i.inciso as inciso,
                        l.journal_id as journal_id,
                        l.operating_unit_id as operating_unit_id,
                        l.currency_id,
                        l.company_id,
                        '' as n_documento2
                    from
                        account_invoice l
                        left join res_partner p on (l.partner_id = p.id)
                        left join grp_estruc_pres_ue ue on (ue.id=l.ue_siif_id)
                        left join grp_estruc_pres_inciso i on (l.inciso_siif_id=i.id)
                        left join tipo_ejecucion_siif ej on (l.siif_tipo_ejecucion=ej.id)
                        where l.state = 'paid' and l.type = 'in_invoice' and l.doc_type in ('invoice','3en1_invoice') and ej.codigo = 'P' and fondo_rotarios <> True)
                    UNION
                    (select
                        'account_invoice_refund_fr' as tipo_documento,
                        l.id as id_documento,
                        p.name as proveedor,
                        l.date_invoice as fecha_factura,
                        l.nro_factura_grp as n_documento,
                        - l.amount_total as total,
                        l.state as estado,
                        ue.ue as ue,
                        i.inciso as inciso,
                        l.journal_id as journal_id,
                        l.operating_unit_id as operating_unit_id,
                        l.currency_id,
                        l.company_id,
                        '' as n_documento2
                    from
                        account_invoice l
                        left join res_partner p on (l.partner_id = p.id)
                        left join grp_estruc_pres_ue ue on (ue.id=l.ue_siif_id)
                        left join grp_estruc_pres_inciso i on (l.inciso_siif_id=i.id)
                        left join tipo_ejecucion_siif ej on (l.siif_tipo_ejecucion=ej.id)
                        where l.state = 'paid' and l.type = 'in_refund' and l.doc_type in ('invoice','3en1_invoice') and ej.codigo = 'P' and fondo_rotarios <> True)"""

    def init(self, cr):
        tools.drop_view_if_exists(cr, 'grp_agrupar_fondo_rotarios')
        cr.execute("""
            create or replace view grp_agrupar_fondo_rotarios as (
                select
                    ROW_NUMBER() OVER(ORDER BY tipo_documento) as id,
                    tipo_documento,
                    id_documento,
                    proveedor,
                    fecha_factura,
                    n_documento,
                    total,
                    estado,
                    ue,
                    inciso,
                    journal_id,
                    operating_unit_id,
                    COALESCE(currency_id,(SELECT currency_id FROM res_company WHERE id = company_id LIMIT 1)) currency_id,
                    company_id,
                    n_documento2
                from(
                    %s
                    UNION
                    (select rv.tipo_documento,rv.id_documento,rv.proveedor,rv.fecha_factura,rv.n_documento,rv.total,rv.estado,rv.ue,rv.inciso,rv.journal_id,rv.operating_unit_id,rv.currency_id,rv.company_id,sv.name n_documento2 FROM
(select
                        'hr_expense' as tipo_documento,
                        hee.id as id_documento,
                        hr.name_related as proveedor,
                        hee.date as fecha_factura,
                        hee.x_sequence as n_documento,
                        hee.amount as total,
                        hee.state as estado,
                        '' as ue,
                        '' as inciso,
                        hee.journal_id AS journal_id,
                        hee.operating_unit_id as operating_unit_id,
                        hee.currency_id,
                        hee.company_id,
                        '' as n_documento2,
                        hee.solicitud_viatico_id
                    from
                        hr_expense_expense hee
                        left join hr_employee hr on (hee.employee_id = hr.id)
                        where hee.state = 'paid' and hee.doc_type = 'rendicion_viatico' and fondo_rotarios <> True) AS rv

                        left join grp_solicitud_viaticos sv ON rv.solicitud_viatico_id = sv.id)
                    UNION
                    (select ra.tipo_documento,ra.id_documento,ra.proveedor,ra.fecha_factura,ra.n_documento,ra.total,ra.estado,ra.ue,ra.inciso,ra.journal_id,ra.operating_unit_id,ra.currency_id,ra.company_id,sa.name n_documento2 FROM
(select
                        'hr_expense_anticipo' as tipo_documento,
                        hee.id as id_documento,
                        hr.name_related as proveedor,
                        hee.date as fecha_factura,
                        hee.x_sequence as n_documento,
                        hee.amount as total,
                        hee.state as estado,
                        '' as ue,
                        '' as inciso,
                        hee.journal_id AS journal_id,
                        hee.operating_unit_id as operating_unit_id,
                        hee.currency_id,
                        hee.company_id,
                        hee.solicitud_anticipos_id
                    from
                        hr_expense_expense hee
                        left join hr_employee hr on (hee.employee_id = hr.id)
                        where hee.state = 'paid' and hee.doc_type = 'rendicion_anticipo' and fondo_rotarios <> True) AS ra
                        left join grp_solicitud_anticipos_fondos sa ON ra.solicitud_anticipos_id = sa.id)
                    UNION
                    (select
                        'bank_statement' as tipo_documento,
                        abs.id as id_documento,
                        r.name as proveedor,
                        abs.date as fecha_factura,
                        abs.name as n_documento,
                        - abs.amount as total,
                        ab.state as estado,
                        ou.unidad_ejecutora as ue,
                        rc.inciso as inciso,
                        abs.journal_id as journal_id,
                        j.operating_unit_id as operating_unit_id,
                        j.currency,
                        j.company_id,
                        ab.name as n_documento2
                    from
                        account_bank_statement_line abs
                        left join res_partner r on (abs.partner_id = r.id)
                        left join account_bank_statement ab on (ab.id = abs.statement_id)
                        left join account_journal j on (abs.journal_id = j.id)
                        left join grp_concepto_gasto_cc_viaticos g on (abs.concepto_id = g.id)
                        left join operating_unit ou on (j.operating_unit_id=ou.id)
                        left join res_company rc on (ab.company_id=rc.id)
                        where ab.state = 'confirm' and j.type= 'cash' and fondo_rotarios <> True and g.a_rendir = true
                    )
                    UNION
                    (select
                        'caja_chica' as tipo_documento,
                        cctl.id as id_documento,
                        p.name as proveedor,
                        cctl.date as fecha_factura,
                        cctl.ref as n_documento,  -- TODO: take ref here?
                        - cctl.amount as total,
                        'confirm' as estado,
                        COALESCE(ou.unidad_ejecutora, ou2.unidad_ejecutora) as ue,
                        rc.inciso as inciso,
                        cct.journal_id as journal_id,
                        COALESCE(ccme.operating_unit_id, j.operating_unit_id) as operating_unit_id,
                        j.currency,
                        j.company_id,
                        '' as n_documento2
                    from
                        grp_caja_chica_tesoreria_line cctl
                        inner join grp_caja_chica_tesoreria cct ON (cctl.caja_chica_id=cct.id)
                        inner join grp_concepto_gasto_cc_viaticos g on (cctl.concept_cc_id = g.id)
                        left join grp_caja_chica_movimiento_efectivo ccme on (cctl.catch_mov_id = ccme.id)
                        left join res_partner p on (cctl.partner_id = p.id)
                        left join res_company rc on (cct.company_id=rc.id)
                        left join account_journal j on (cct.journal_id = j.id)
                        left join operating_unit ou on (ccme.operating_unit_id=ou.id)
                        left join operating_unit ou2 on (j.operating_unit_id=ou2.id)
                    where cct.state = 'check' and j.type= 'cash' and g.a_rendir = true and cctl.fondo_rotario <> true
                    )
                ) as fr
            )
        """ % self._subquery())

    def open_document(self, cr, uid, ids, context=None):
        for rec in self.browse(cr, uid, ids):
            mod_obj = self.pool.get('ir.model.data')
            if rec.tipo_documento == 'account_invoice':
                res = mod_obj.get_object_reference(cr, uid, 'grp_factura_siif',
                                                   'invoice_siif_retention_supplier_form_inherit')
                models = 'account.invoice'
                res_id = res and res[1] or False
                ctx = dict(context)
                invoice_id = rec.id_documento
                return {
                    'name': "Facturas de proveedor",
                    'view_mode': 'form',
                    'view_id': res_id,
                    'view_type': 'form',
                    'res_model': models,
                    'type': 'ir.actions.act_window',
                    'target': 'current',
                    'res_id': invoice_id,
                    'context': ctx,
                }
            elif rec.tipo_documento == 'account_invoice_fr':
                res = mod_obj.get_object_reference(cr, uid, 'grp_factura_siif',
                                                   'invoice_siif_retention_supplier_form_inherit')
                models = 'account.invoice'
                res_id = res and res[1] or False
                ctx = dict(context)
                invoice_id = rec.id_documento
                return {
                    'name': "Facturas de fondo rotatorio",
                    'view_mode': 'form',
                    'view_id': res_id,
                    'view_type': 'form',
                    'res_model': models,
                    'type': 'ir.actions.act_window',
                    'target': 'current',
                    'res_id': invoice_id,
                    'context': ctx,
                }
            elif rec.tipo_documento == 'account_invoice_refund_fr':
                res = mod_obj.get_object_reference(cr, uid, 'grp_factura_siif',
                                                   'view_account_form_credit_note')
                models = 'account.invoice'
                res_id = res and res[1] or False
                ctx = dict(context)
                invoice_id = rec.id_documento
                return {
                    'name': u"Nota de Crédito fondo rotatorio",
                    'view_mode': 'form',
                    'view_id': res_id,
                    'view_type': 'form',
                    'res_model': models,
                    'type': 'ir.actions.act_window',
                    'target': 'current',
                    'res_id': invoice_id,
                    'context': ctx,
                }
            elif rec.tipo_documento in ['hr_expense','hr_expense_anticipo']:
                models = 'hr.expense.expense'
                ctx = dict(context)
                hr_expense_id = rec.id_documento
                expense_id = self.pool.get('hr.expense.expense').browse(cr,uid,hr_expense_id)
                if expense_id.doc_type == u'rendicion_anticipo':
                    res = mod_obj.get_object_reference(cr, uid, 'grp_tesoreria', 'view_grp_rendicion_anticipo_form1')
                else:
                    res = mod_obj.get_object_reference(cr, uid, 'hr_expense', 'view_expenses_form')
                res_id = res and res[1] or False
                return {
                    'name': "Gastos",
                    'view_mode': 'form',
                    'view_id': res_id,
                    'view_type': 'form',
                    'res_model': models,
                    'type': 'ir.actions.act_window',
                    'target': 'current',
                    'res_id': hr_expense_id,
                    'context': ctx,
                }
            elif rec.tipo_documento == 'bank_statement':
                res = mod_obj.get_object_reference(cr, uid, 'facturas_uy', 'grp_view_bank_statement_form2')
                models = 'account.bank.statement'
                res_id = res and res[1] or False
                ctx = dict(context)
                bank_statement_line = self.pool.get('account.bank.statement.line').browse(cr, uid, rec.id_documento,
                                                                                context)
                bank_statement_id = bank_statement_line.statement_id.id
                return {
                    'name': "Registros de caja",
                    'view_mode': 'form',
                    'view_id': res_id,
                    'view_type': 'form',
                    'res_model': models,
                    'type': 'ir.actions.act_window',
                    'target': 'current',
                    'res_id': bank_statement_id,
                    'context': ctx,
                }
            elif rec.tipo_documento == 'caja_chica':
                res = mod_obj.get_object_reference(cr, uid, 'grp_tesoreria', 'view_grp_caja_chica_line_form2')
                res_id = res and res[1] or False
                ctx = dict(context)
                return {
                    'name': "Registros de caja",
                    'view_mode': 'form',
                    'view_id': res_id,
                    'view_type': 'form',
                    'res_model': 'grp.caja.chica.tesoreria.line',
                    'type': 'ir.actions.act_window',
                    'target': 'current',
                    'res_id': rec.id_documento,
                    'context': ctx,
                }
            return True

    # TODO: R RETENCIONES EN FR
    def _get_retentions_dict(self,cr,uid, invoice_ids, context=None):
        invoice_retention_obj = self.pool.get('account.invoice.summary.group.ret')
        retentions = []
        for line in invoice_retention_obj.browse(cr,uid,invoice_retention_obj.search(cr,uid,[('invoice_id','in',invoice_ids)],context=context),context=context):
            new_retention_group = True
            for retention in retentions:
                if retention[2]['creditor_id'] and retention[2]['iva'] and retention[2]['group_id'] and retention[2]['tipo_retencion']:
                    retention[2]['base_linea'] += line.base_linea
                    retention[2]['base_linea_pesos'] += line.base_linea_pesos
                    retention[2]['base_impuesto'] += line.base_impuesto
                    retention[2]['base_impuesto_pesos'] += line.base_impuesto_pesos
                    retention[2]['monto_retencion'] += line.monto_retencion
                    retention[2]['monto_retencion_unround'] += line.monto_retencion_unround
                    retention[2]['monto_retencion_pesos'] += line.monto_retencion_pesos
                    retention[2]['ret_amount_round'] += line.ret_amount_round
                    retention[2]['ret_amount_pesos_round'] += line.ret_amount_pesos_round
                    new_retention_group = False
                    break
            if new_retention_group:
                retentions.append((0,0,{'creditor_id':line.creditor_id.id,
                                        'iva':line.iva,
                                        'group_id':line.group_id.id,
                                        'tipo_retencion':line.tipo_retencion,
                                        'base_linea': line.base_linea,
                                        'base_linea_pesos': line.base_linea_pesos,
                                        'base_impuesto': line.base_impuesto,
                                        'base_impuesto_pesos': line.base_impuesto_pesos,
                                        'monto_retencion': line.monto_retencion,
                                        'monto_retencion_unround': line.monto_retencion_unround,
                                        'monto_retencion_pesos': line.monto_retencion_pesos,
                                        'ret_amount_round': line.ret_amount_round,
                                        'ret_amount_pesos_round': line.ret_amount_pesos_round
                                        }))
        return retentions

    def agrupar_comprobantes(self, cr, uid, ids, context=None):
        ue = ''
        line_invoice_ids = []
        invoice_ids = []
        line_invoice_fr_ids = []
        invoice_fr_ids = []
        line_expense_ids = []
        line_expense_vales_ids = []
        line_statement_ids = []
        statement_ids = []
        # TODO R SPRING 9 GAP 111 adicionando validacion de que sean las lineas a agrupar de la misma UE
        operating_unit = self.read_group(cr, uid, [('id', 'in', ids)], ['operating_unit_id'], 'operating_unit_id')
        if len(operating_unit) > 1:
            raise exceptions.ValidationError(_(u'No puede seleccionar documentos de distinta Unidad Ejecutora u Operativa!'))
        currency = self.read_group(cr, uid, [('id', 'in', ids)], ['currency_id'], 'currency_id')
        if len(currency) > 1:
            raise exceptions.ValidationError(
                _(u'No puede seleccionar documentos con diferentes monedas!'))
        operating_unit_id = operating_unit[0]['operating_unit_id'][0]
        currency_id = currency[0]['currency_id'][0]
        operating_unit = self.pool.get('operating.unit').browse(cr, uid, operating_unit_id)
        unidad_ejecutora_ids = self.pool.get('unidad.ejecutora').search(cr, uid, [('codigo', '=', int(operating_unit.unidad_ejecutora))])

        for rec in self.browse(cr, uid, ids):
            if rec.tipo_documento == 'account_invoice':
                vals_line = (0, 0, {
                    'supplier_invoice_id': rec.id_documento,
                    'tipo_documento': 'account_invoice',
                })
                line_invoice_ids.append(vals_line)
                invoice_ids.append(rec.id_documento)
            elif rec.tipo_documento == 'account_invoice_fr':
                vals_line = (0, 0, {
                    'supplier_invoice_id': rec.id_documento,
                    'tipo_documento': 'account_invoice_fr'
                })
                line_invoice_fr_ids.append(vals_line)
                invoice_fr_ids.append(rec.id_documento)
            elif rec.tipo_documento == 'account_invoice_refund_fr':
                vals_line = (0, 0, {
                    'supplier_invoice_id': rec.id_documento,
                    'tipo_documento': 'account_invoice_fr'
                })
                line_invoice_fr_ids.append(vals_line)
                invoice_fr_ids.append(rec.id_documento)
            elif rec.tipo_documento in ['hr_expense']:
                vals_line = (0, 0, {
                    'hr_expense_id': rec.id_documento,
                    'tipo_documento': 'hr_expense'
                })
                line_expense_ids.append(vals_line)
            elif rec.tipo_documento in ['hr_expense_anticipo']:
                vals_line = (0, 0, {
                    'hr_expense_id': rec.id_documento,
                    'tipo_documento': 'hr_expense_v'
                })
                line_expense_vales_ids.append(vals_line)
            elif rec.tipo_documento == 'bank_statement':
                vals_line = (0, 0, {
                    'bank_statement_id': rec.id_documento,
                    'tipo_documento': 'bank_statement'
                })
                line_statement_ids.append(vals_line)
                statement_ids.append(rec.id_documento)
            elif rec.tipo_documento == 'caja_chica':
                vals_line = (0, 0, {
                    'caja_chica_line_id': rec.id_documento,
                    'tipo_documento': 'bank_statement'
                })
                line_statement_ids.append(vals_line)
            if not ue:
                ue = rec.ue

        fiscal_year_id = self.pool['account.fiscalyear'].find(cr, uid, dt=fields.Date.today())
        inciso_company = self.pool['res.users'].browse(cr, uid, uid).company_id.inciso
        inciso_siif_llp_id = self.pool['grp.estruc_pres.inciso'].search(cr, uid, [('fiscal_year_id', '=', fiscal_year_id),
                                                             ('inciso', '=', inciso_company)])
        ue_siif_llp_id = False
        if len(inciso_siif_llp_id) > 0:
            inciso_siif_llp_id = inciso_siif_llp_id[0]

            ue_ids = self.pool.get('grp.estruc_pres.ue').search(cr, uid, [('inciso_id', '=', inciso_siif_llp_id),('ue', '=', operating_unit.unidad_ejecutora)], order='id desc', limit=1)
            ue_siif_llp_id = ue_ids and ue_ids[0] or False

        beneficiario_ids = self.pool.get('res.partner').search(cr, uid, [('es_inciso_default', '=', True)], limit=1)
        if not beneficiario_ids:
            raise exceptions.ValidationError(_(u'No esta definido el beneficiario SIIF.'))
        beneficiario_id = beneficiario_ids[0]

        vals = {
            'beneficiario_siif_id': beneficiario_id,
            'fiscal_year_id': fiscal_year_id,
            'ue_siif_llp_id': ue_siif_llp_id,
            'inciso_siif_llp_id': inciso_siif_llp_id,
            'state': 'draft',
            'currency_id': currency_id,
            'line_invoice_ids': line_invoice_ids,
            'line_invoice_fr_ids': line_invoice_fr_ids,
            'line_expense_ids': line_expense_ids,
            'line_expense_vales_ids': line_expense_vales_ids,
            'line_statement_ids': line_statement_ids,
            'operating_unit_id': operating_unit_id,
            'unidad_ejecutora_id': unidad_ejecutora_ids and unidad_ejecutora_ids[0] or False,
        }
        fondo_id = self.pool.get('grp.fondo.rotatorio').create(cr, uid, vals, context)
        mod_obj = self.pool.get('ir.model.data')
        res = mod_obj.get_object_reference(cr, uid, 'grp_reposicion_fr', 'view_grp_fondo_rotatorio_form')
        res_id = res and res[1] or False
        value = {
            'name': "3 en 1-Fondo rotatorio",
            'view_mode': 'form',
            'view_id': res_id,
            'view_type': 'form',
            'res_model': 'grp.fondo.rotatorio',
            'type': 'ir.actions.act_window',
            'target': 'current',
            'res_id': fondo_id,
        }
        return value

    def update_liquido_pagable_ajustado_currency(self, cr, uid, ids, context=None):
        _env = api.Environment(cr,uid,context)
        _env['grp.fondo.rotatorio'].search([('currency_id','=',False)]).write({'currency_id': _env.user.company_id.currency_id.id})
        _env['grp.fondo.rotatorio.line'].search([]).update_liquido_pagable_ajustado_currency()
        return True