import numpy as np
import h5py
from keras import layers
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from keras.models import Model
from keras.preprocessing import image
from keras.utils import layer_utils
from keras.utils.data_utils import get_file
from keras.applications.imagenet_utils import preprocess_input
from keras.utils.vis_utils import model_to_dot
from keras.utils import plot_model
from matplotlib.pyplot import imshow

import keras.backend as K
K.set_image_data_format('channels_last')
import matplotlib.pyplot as plt

# ----------------------------------------------------------------
class HappyCNN:
    def __init__(self, train=True, has_weights=False):
        # hyper parameter
        max_epoch = 40
        batch_size = 40

        X_train, y_train, X_test, y_test, classes = self.load_dataset()
        print(X_train.shape, y_train.shape)

        # Normalize image vectors
        self.X_train = X_train / 255.
        self.X_test = X_test / 255.

        # Reshape
        self.Y_train = y_train.T
        self.Y_test = y_test.T

        print("number of training examples = " + str(self.X_train.shape[0]))
        print("number of test examples = " + str(self.X_test.shape[0]))
        print("X_train shape: " + str(self.X_train.shape))
        print("Y_train shape: " + str(self.Y_train.shape))
        print("X_test shape: " + str(self.X_test.shape))
        print("Y_test shape: " + str(self.Y_test.shape))

        # create the model.
        self.model = self.BuildModel(X_train.shape[1:])
        # compile the model.
        self.model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])

        if train:
            self.train(max_epoch, batch_size, has_weights)

    def load_dataset(self):
        train_dataset = h5py.File('datasets/train_happy.h5', "r")
        train_set_x_orig = np.array(train_dataset["train_set_x"][:])  # your train set features
        train_set_y_orig = np.array(train_dataset["train_set_y"][:])  # your train set labels

        test_dataset = h5py.File('datasets/test_happy.h5', "r")
        test_set_x_orig = np.array(test_dataset["test_set_x"][:])  # your test set features
        test_set_y_orig = np.array(test_dataset["test_set_y"][:])  # your test set labels

        classes = np.array(test_dataset["list_classes"][:])  # the list of classes

        train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
        test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))

        return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes

    def mean_pred(self, y_true, y_pred):
        return K.mean(y_pred)

    def BuildModel(self, input_shape):
        """
        Implementation of the Cifar10Model.

        Arguments:
        input_shape -- shape of the images of the dataset

        Returns:
        model -- a Model() instance in Keras
        """
        x_input = Input(input_shape)

        x = ZeroPadding2D((3, 3))(x_input)
        x = Conv2D(32, (7, 7), strides=(1, 1), name='conv0')(x)
        x = BatchNormalization(axis=3, name='btn0')(x)
        x = Activation('relu')(x)

        x = MaxPooling2D((2, 2), name='max_pool')(x)

        x = Flatten()(x)
        x = Dense(1, activation='sigmoid', name='fc')(x)

        model = Model(inputs=x_input, outputs=x, name='cifar10Model')

        return model

    def train(self, max_epoch, batch_size, has_weights):
        if has_weights:
            self.model.load_weights('happycnn.h5')

        self.model.fit(x=self.X_train, y=self.Y_train, epochs=max_epoch, batch_size=batch_size)
        self.model.save_weights('happycnn.h5')

    def test(self):
        self.model.load_weights('happycnn.h5')
        preds = self.model.evaluate(x=self.X_test, y=self.Y_test)
        print()
        print("Loss = " + str(preds[0]))
        print("Test Accuracy = " + str(preds[1]))

    def predict(self, path):
        # 'images/test.jpg'
        img_path = path
        img = image.load_img(img_path, target_size=(64, 64))
        imshow(img)

        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)

        self.model.load_weights('happycnn.h5')
        print(self.model.predict(x))

# ----------------------------------------------------------------
if __name__ == "__main__":
    model = HappyCNN(train=False, has_weights=True)
    model.test()
    model.predict('datasets/test.jpg')


import struct
import numpy

# -----------------------------------------
# DM DATファイル読み込みクラス
# 2020.05.23 K.Takamoto(takamoto.biz)
# -----------------------------------------
class DM:
    #============================================================
    # コンストラクタ
    # out: self._DATFile
    #============================================================
    def __init__(self ,inDMFile ):
        # 入力ファイルをクラス変数に保存
        self._DMFile = inDMFile
        # 図形情報出力用ディクショナリ配列の宣言（0始まり）
        self._elementDict = {}

    #============================================================
    # Function : イテレータ開始処理：指定ファイルの形状情報をすべて読みだす。
    # in       : None（コンストラクタの引数 inATRFile）
    # out      : 図形情報の配列(self.elementDict)
    #============================================================
    def __iter__(self):
        # DATファイルの読み込み
        with open(self._DMFile ,mode='rb') as dmfd:
            # 全レコードの読み込み（バイナリでも行として取得できる模様）
            # DMファイルの1レコードは87バイト（CR+LFの2バイトを含む）
            # DMファイルの最後のEOF（0x1A）の明示的な取得は不要
            self._reclist = dmfd.readlines()
            # レコードカウンタ初期化
            dictSeqno = recno = 0
            while recno < len(self._reclist)-1:
                # レコードの取得
                record = self._reclist[recno]
                # レコードタイプの取得
                rectype = str(record[0:2].decode('cp932'))
                # レコード判定
                if rectype[0]=='M':
                    # 図郭レコード(a) 図郭ごとに1レコード群のみ
                    # 図郭識別番号
                    self.unitcode = str(record[2:10].decode('cp932')).rstrip()
                    # 修正回数取得
                    editcnt = int(record[65:67].decode('cp932'))
                    recno+=1
                    # 図郭レコード(b)の取得（単位はメートル）
                    record = self._reclist[recno]
                    self.ldx = float(record[0:7].decode('cp932'))
                    self.ldy = float(record[7:14].decode('cp932'))
                    # 図郭レコード(d)までシーク
                    recno += 2
                    cnt = 0
                    while cnt < editcnt+1:
                        # 図郭レコード(d)の取得（捨て）
                        record = self._reclist[recno]
                        reccnt = int(record[9:10].decode('cp932'))
                        recno += reccnt+2
                        cnt += 1
                elif rectype[0]=='E':
                    # 要素レコード（"E1"～"E8"）
                    # 分類コード
                    layercode = str(record[2:6].decode('cp932'))
                    # 要素識別番号
                    elementno = int(record[12:16].decode('cp932'))
                    # レコード数
                    recordcnt = int(record[31:35].decode('cp932'))
                    # 実データ区分（0,1：データなし、2：二次元、4：注記）
                    datakind = str(record[20:21].decode('cp932'))
                    # データ数（座標点数、文字数）
                    datacnt = int(record[27:31].decode('cp932'))
                    if rectype=='E1' or rectype=='E2':
                        # 線（E2）と面（E1）
                        # 実データレコード取得Loop
                        pointcnt = cnt = 0
                        xy = []
                        # 座標情報の取得
                        while pointcnt < datacnt:
                            if ( pointcnt % 6 )==0:
                                # 二次元座標レコード(8)の取得
                                recno += 1
                                record = self._reclist[recno]
                            start = ( pointcnt * 14 ) % 84
                            # 座標をミリメートルからメートルに変換
                            xy.append( [ self.ldy + float(record[start+7:start+14].decode('cp932'))/1000, \
                                         self.ldx + float(record[start:start+7].decode('cp932'))/1000 ] )
                            #print(float(record[start:start+7].decode('cp932')) ,float(record[start+7:start+14].decode('cp932')))
                            pointcnt += 1
                        # 始終点が一致していれば面化する
                        if xy[0]==xy[len(xy)-1]:
                            rectype = 'E1'
                        # ディクショナリへのデータ設定
                        self._elementDict[dictSeqno] = {"FIGTYPE":rectype,"LAYER":layercode, \
                                                        "ELNO":self.unitcode + '-' + layercode + '-' + str(elementno).zfill(4),\
                                                        "XYList":xy}
                        #print(self._elementDict[dictSeqno])
                        # ディクショナリカウンタの加算
                        dictSeqno += 1
                        # レコードカウンタの加算
                        recno += 1
                    elif rectype=='E7':
                        # 注記（E7）
                        # 代表点座標（ミリメートルからメートルに変換）
                        pointxy = [ self.ldy + float(record[42:49].decode('cp932'))/1000 , \
                                    self.ldx + float(record[35:42].decode('cp932'))/1000 ]
                        # 二次元座標レコード(8)の取得
                        record = self._reclist[recno+1]
                        # 縦横フラグ（0:横書き、1:縦書き）
                        vnflag = str(record[0:1].decode('cp932'))
                        # 角度（横書き:-45～45、縦書き:-135～-45）
                        angle = int(record[1:8].decode('cp932'))
                        # 注記文字：今回は1レコード目まで。2レコード目以降は捨てる
                        text = str(record[20:84].decode('cp932')).rstrip()
                        #print(str(elementno) +':' + text)
                        # ディクショナリへのデータ設定
                        self._elementDict[dictSeqno] = {"FIGTYPE":rectype,"LAYER":layercode, \
                                                        "ELNO":self.unitcode + '-' + layercode + '-' + str(elementno).zfill(4),\
                                                        "XYList":pointxy ,"ANGLE":angle ,"VNFLAG":vnflag ,"TEXT":text}
                        #print(self._elementDict[dictSeqno])
                        # ディクショナリカウンタの加算
                        dictSeqno += 1
                        # レコード数分シーク
                        recno += recordcnt+1
                    else:
                        # レコード数分シーク
                        recno += recordcnt+1
                elif rectype[0]=='H':
                    # グループヘッダレコード
                    recno += 1
                elif rectype[0]=='G' or rectype[0]=='T':
                    # グリッドヘッダ、TINレコード
                    # レコード数
                    recordcnt = int(record[31:35].decode('cp932'))
                    recno += recordcnt+1

        # イテレータ用カウンタ初期化
        self._i=0
        return self

    #============================================================
    # Function : イテレータ取得処理：指定ファイルの形状情報を順次読みだす。
    # in       : 図形情報の配列(self.elementDict)
    # out      : 図形情報(self.elementDictのメンバ)
    #============================================================
    def __next__(self):
        if self._i >= len(self._elementDict):
            raise StopIteration()
        value = self._elementDict[self._i]
        self._i+=1
        return value

    # デストラクタ
    def __del__(self):
        pass


from django.urls import path
from . import views

urlpatterns = [
    # path('', views.userlist, name='userlist'),
    path ('', views.UserList.as_view(), name='userlist'),
    path('deluser/', views.deluser, name='deluser'),
    path('register/', views.register, name='register'),
    path('edit/', views.edit, name='edit'),
]


from django.test import TestCase
from workflow.models import WorkflowLevel1, Country, AdminLevelOne, WorkflowLevel2, Sector, SiteProfile, Office
from formlibrary.models import TrainingAttendance, Distribution, Beneficiary
from datetime import datetime

class TrainingAttendanceTestCase(TestCase):

    def setUp(self):
        new_program = WorkflowLevel1.objects.create(name="testprogram")
        new_program.save()
        get_program = WorkflowLevel1.objects.get(name="testprogram")
        new_training = TrainingAttendance.objects.create(training_name="testtraining", workflowlevel1=get_program,
                                                           implementer = "34",
                                                           reporting_period = "34",
                                                           total_participants = "34",
                                                           location = "34",
                                                           community = "34",
                                                           training_duration = "34",
                                                           start_date = "34",
                                                           end_date = "34",
                                                           trainer_name = "34",
                                                         )
        new_training.save()

    def test_training_exists(self):
        """Check for Training object"""
        get_training = TrainingAttendance.objects.get(training_name="testtraining")
        self.assertEqual(TrainingAttendance.objects.filter(id=get_training.id).count(), 1)

class DistributionTestCase(TestCase):

    fixtures = ['fixtures/001_organization.json','fixtures/007_projecttype.json','fixtures/003_sectors.json']

    def setUp(self):
        new_program = WorkflowLevel1.objects.create(name="testprogram")
        new_program.save()
        get_program = WorkflowLevel1.objects.get(name="testprogram")
        new_country = Country.objects.create(country="testcountry")
        new_country.save()
        get_country = Country.objects.get(country="testcountry")
        new_province = AdminLevelOne.objects.create(name="testprovince", country=get_country)
        new_province.save()
        get_province = AdminLevelOne.objects.get(name="testprovince")
        new_office = Office.objects.create(name="testoffice", country=new_country)
        new_office.save()
        get_office = Office.objects.get(name="testoffice")
        #create project agreement -- and load from fixtures
        new_community = SiteProfile.objects.create(name="testcommunity", country=get_country, office=get_office,province=get_province)
        new_community.save()
        get_community = SiteProfile.objects.get(name="testcommunity")
        get_sector = Sector.objects.get(id='2')
        new_agreement = WorkflowLevel2.objects.create(workflowlevel1=get_program, name="testproject",
                                                      office=get_office,
                                                      sector=get_sector, on_time=True, community_handover=False)
        new_agreement.save()
        new_agreement.site.add(get_community)
        get_agreement = WorkflowLevel2.objects.get(name="testproject")
        new_distribution = Distribution.objects.create(distribution_name="testdistribution", workflowlevel1=get_program,
                                                            workflowlevel2=get_agreement,
                                                            office_code=get_office,
                                                            distribution_implementer = "34",
                                                            reporting_period = "34",
                                                            province=get_province,
                                                            total_beneficiaries_received_input = "34",
                                                            distribution_location = "testlocation",
                                                            input_type_distributed = "testinputtype",
                                                            distributor_name_and_affiliation = "testdistributorperson",
                                                            distributor_contact_number = "1-dis-tri-bute",
                                                         )
        new_distribution.save()

    def test_distribution_exists(self):
        """Check for Distribution object"""
        get_distribution = Distribution.objects.get(distribution_name="testdistribution")
        self.assertEqual(Distribution.objects.filter(id=get_distribution.id).count(), 1)

class BeneficiaryTestCase(TestCase):

    def setUp(self):
        new_program = WorkflowLevel1.objects.create(name="testprogram")
        new_program.save()
        get_program = WorkflowLevel1.objects.get(name="testprogram")
        new_training = TrainingAttendance.objects.create(training_name="testtraining", workflowlevel1=get_program)
        new_training.save()
        get_training = TrainingAttendance.objects.get(training_name="testtraining")
        new_benny = Beneficiary.objects.create(beneficiary_name="Joe Test", father_name="Mr Test", age="42", gender="male", signature=False,remarks="life")
        new_benny.training.add(new_training)
        new_benny.save()

    def test_beneficiary_exists(self):
        """Check for Benny object"""
        get_benny = Beneficiary.objects.get(beneficiary_name="Joe Test")
        self.assertEqual(Beneficiary.objects.filter(id=get_benny.id).count(), 1)


import torch
import torch.nn as nn
class Network_reconstruction(nn.Module):

    def __init__(self, input_size, hidden_size, activation=None, dropout=0):
        super().__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.activation = activation
        self.dropout = nn.Dropout(dropout)

    def forward(self, x):
        out = self.dropout(x)
        out = self.fc1(out)
        if not self.activation == None:
            out = self.activation(out)
        out_sigma = out
        out_mean = out
        return out_mean, out_sigma


"""
Author: Tran Chau Khanh
Date: 02/09/2021
Program: project_08_page_63.py
Problem:
    Light travels at 3 * 10^8 meters per second. A light-year is the distance a light beam
    travels in one year. Write a program that calculates and displays the value of a light-year.

Solution:
    Display:
        The value of a light-year = 9467280000000000 m
"""
year = 365.25
vLight = 3 * pow(10, 8)
swapMinutes = year * 24 * 60 * 60
SLight = vLight * swapMinutes

# print
print("\nThe value of a light-year = " + str(round(SLight)) + " m")


#! python3

#Advent of Code Day 2 Part 1

#TODO: Get input from file

import os

file = open('aoc2.txt','r')

input = file.read()
initialList = input.split(',') #Splits the text file into respective int elements, using the , as the divided. However ints are saved as string so remember to convert them
inputList = []
opCount = 0
operationComplete = False

for i in initialList:
    inputList.append(int(i))

print('Input List is: %s' % (inputList))

#Converts all the strings in initialList to an int and stores them in a new list, inputList.

operationList = []
##outputList = inputList[:]

#TODO: Execute opcodes via functions/classes

def opcode(list):
    #opcode operation for a single list of length 4.

    global inputList
    global operationComplete

##    print('Current operation on list: %s' % (list))

    id = list[0]

    if id == 1:
        #Opcode 1 - Addition

        returnValue = inputList[list[1]] + inputList[list[2]]
        position = list[3]

##        list.remove(position)
##        list.insert(position,sum)

    elif id == 2:
        #Opcode 2 - Multiplication

        returnValue = inputList[list[1]] * inputList[list[2]]
        position = list[3]

    elif id == 99:
        #Opcode 99 - Halt program
        print('Halting program...')
        operationComplete = True
        return inputList

    else:
##        print('Invalid ID detected')
        pass

    inputList.pop(position)
    inputList.insert(position,returnValue)

##    print('New input list is now: %s' % (inputList))
    return inputList

#TODO: Opcode operation for continuous input

def operation(inputList):

    global operationList
##    global outputList
    global opCount

    while operationComplete == False:

        if opCount == 0:
            for i in range(4):
                operationList.append(inputList[i])
                opCount += 1

        else:
            for i in range(opCount,opCount+4):
                operationList.append(inputList[i])
                opCount += 1

        opcode(operationList)
        operationList.clear()

    print('Operation complete.')
    return inputList

#TODO: Return final output back

print(operation(inputList))


"""

Schorfheide--Song--Yaron code

"""

import numpy as np
from numpy.random import randn
from numpy import exp, log
from numba import jit, njit, prange
from utils import quantile, lininterp_3d

class SSY:
    """
    Class for the SSY model, with state process

            g_c = μ_c + z + σ_c η'

            g_d = μ_d + α z + δ σ_c η' + σ_d υ'

            z' = ρ z + sqrt(1 - ρ^2) σ_z e'

            h_z' = ρ_hz h_z + σ_hz u'

            h_c' = ρ_hc h_c + σ_hc w'

            h_d' = ρ_hd h_d + σ_hd w'

            σ_z = ϕ_z σ_bar exp(h_z)

            σ_c = ϕ_c σ_bar exp(h_c)

            σ_d = ϕ_d σ_bar exp(h_d)

        Innovations are IID and N(0, 1).

        Default values from May 2017 version of Schorfheide, Song and Yaron.
        See p. 28.

    """

    def __init__(self,
                 β=0.999,
                 γ=8.89,
                 ψ=1.97,
                 μ_c=0.0016,
                 ρ=0.987,
                 ϕ_z=0.215,
                 σ_bar=0.0032,
                 ϕ_c=1.0,
                 ρ_hz=0.992,
                 σ_hz=np.sqrt(0.0039),
                 ρ_hc=0.991,
                 σ_hc=np.sqrt(0.0096),
                 μ_d=0.001,
                 α=3.65,                     # = ϕ in SSY's notation
                 δ=1.47,                     # = π in SSY's notation
                 ϕ_d=4.54,
                 ρ_hd=0.969,
                 σ_hd=np.sqrt(0.0447),
                 z_grid_size=14,
                 h_z_grid_size=10,
                 h_c_grid_size=10,
                 h_d_grid_size=10,
                 mc_draw_size=6000,
                 build_grids=True):

        # Preferences
        self.β, self.γ, self.ψ = β, γ, ψ
        # Consumption
        self.μ_c, self.ρ, self.ϕ_z = μ_c, ρ, ϕ_z
        self.σ_bar, self.ϕ_c, self.ρ_hz = σ_bar, ϕ_c, ρ_hz
        self.σ_hz, self.ρ_hc, self.σ_hc  = σ_hz, ρ_hc, σ_hc
        # Dividends
        self.μ_d, self.α, self.δ = μ_d, α, δ
        self.ϕ_d, self.ρ_hd, self.σ_hd = ϕ_d, ρ_hd, σ_hd

        self.z_grid_size = z_grid_size
        self.h_z_grid_size = h_z_grid_size
        self.h_c_grid_size = h_c_grid_size
        self.h_d_grid_size = h_d_grid_size
        self.mc_draw_size = mc_draw_size

        # Build grid and draw shocks for Monte Carlo
        if build_grids:
            self.build_grid_and_shocks()

        # An array to store the current guess of w_star
        self.w_star_guess = np.ones((z_grid_size, h_z_grid_size, h_c_grid_size))

    def params(self):
        return self.β, self.γ, self.ψ, \
               self.μ_c, self.ρ, self.ϕ_z, \
               self.σ_bar, self.ϕ_c, self.ρ_hz, \
               self.σ_hz, self.ρ_hc, self.σ_hc,  \
               self.μ_d, self.α, self.δ, \
               self.ϕ_d, self.ρ_hd, self.σ_hd

    def utility_params_differ(self, other):
        p1 = self.β, self.γ, self.ψ, \
                 self.μ_c, self.ρ, self.ϕ_z, \
                 self.σ_bar, self.ϕ_c, self.ρ_hz, \
                 self.σ_hz, self.ρ_hc, self.σ_hc
        p2 = other.β, other.γ, other.ψ, \
                 other.μ_c, other.ρ, other.ϕ_z, \
                 other.σ_bar, other.ϕ_c, other.ρ_hz, \
                 other.σ_hz, other.ρ_hc, other.σ_hc
        return not np.allclose(p1, p2)

    def simulate_paths(self, n=1_000_000, seed=1234):
        """
        Creates a jitted function to generate and return the state process,
        along with consumption and dividends.  Dates for returned processes
        are

            x[0], ..., x[n-1]
            g_c[0], ..., g_c[n-2]
            g_d[0], ..., g_d[n-2]

        """
        β, γ, ψ, μ_c, ρ, ϕ_z, σ_bar, ϕ_c, ρ_hz, σ_hz, ρ_hc, σ_hc, μ_d, α, δ, \
           ϕ_d, ρ_hd, σ_hd = self.params()

        # Some useful constants
        τ_z = ϕ_z * σ_bar
        τ_c = ϕ_c * σ_bar
        τ_d = ϕ_d * σ_bar
        κ = np.sqrt(1 - ρ**2)

        @njit
        def jitted_sim_paths():

            np.random.seed(seed)

            # Allocate memory for states with initial conditions at the stationary
            # mean, which is zero
            z_vec = np.zeros(n)
            h_z_vec = np.zeros(n)
            h_c_vec = np.zeros(n)
            h_d_vec = np.zeros(n)

            # Allocate memory for consumption and dividend growth
            g_c_vec = np.empty(n-1)
            g_d_vec = np.empty(n-1)

            # Simulate
            for t in range(n-1):

                # Simplify names of state variables
                z, h_z, h_c, h_d = z_vec[t], h_z_vec[t], h_c_vec[t], h_d_vec[t]
                # Map h to σ
                σ_z = τ_z * exp(h_z)
                σ_c = τ_c * exp(h_c)
                σ_d = τ_d * exp(h_d)
                # Simulate consumption and dividends given state
                g_c_vec[t] = μ_c + z + σ_c * randn()
                g_d_vec[t] = μ_d + α * z + δ * σ_c * randn() + σ_d * randn()
                # Update states
                z_vec[t+1] = ρ * z + κ * σ_z * randn()
                h_z_vec[t+1] = ρ_hz * h_z + σ_hz * randn()
                h_c_vec[t+1] = ρ_hc * h_c + σ_hc * randn()
                h_d_vec[t+1] = ρ_hd * h_d + σ_hd * randn()

            return z_vec, h_z_vec, h_c_vec, h_d_vec, g_c_vec, g_d_vec

        return jitted_sim_paths()

    def build_grid_and_shocks(self,
                                ts_length=10_000_000,
                                seed=1234,
                                q1=0.025,  # lower quantile
                                q2=0.925): # upper quantile

        paths = self.simulate_paths()
        z_vec, h_z_vec, h_c_vec, h_d_vec, g_c, g_d = paths

        # Obtain quantiles of state process time series
        z_min, z_max = quantile(z_vec, q1), quantile(z_vec, q2)
        h_z_min, h_z_max = quantile(h_z_vec, q1), quantile(h_z_vec, q2)
        h_c_min, h_c_max = quantile(h_c_vec, q1), quantile(h_c_vec, q2)
        h_d_min, h_d_max = quantile(h_d_vec, q1), quantile(h_d_vec, q2)

        # Build grid along each state axis using these quantiles as bounds
        self.z_grid = np.linspace(z_min, z_max, self.z_grid_size)
        self.h_z_grid = np.linspace(h_z_min, h_z_max, self.h_z_grid_size)
        self.h_c_grid = np.linspace(h_c_min, h_c_max, self.h_c_grid_size)
        self.h_d_grid = np.linspace(h_d_min, h_d_max, self.h_d_grid_size)

        # Shocks for Monte Carlo integration
        np.random.seed(1234)
        self.shocks = randn(3, self.mc_draw_size)

    def koopmans_operator_factory(self):
        """
        Build and return a jitted version of the operator

            Tw(x) = 1 + (Kw^θ(x))^(1/θ)

        where

            Kg(z, h_z, h_c)
               =  exp((1-γ)(μ_c + z) + (1-γ)^2 σ_c^2 / 2) E g(z', h_z', h_c')

        Here σ_c = ϕ_c σ_bar exp(h_c) and (z', h_z', h_c') update via the
        dynamics for the SSY model.

        When we write x as the state, the meaning is

            x = (z, h_z, h_c)

        """

        # Unpack parameters and related objects
        β, γ, ψ, μ_c, ρ, ϕ_z, σ_bar, ϕ_c, ρ_hz, σ_hz, ρ_hc, σ_hc, μ_d, α, δ, \
           ϕ_d, ρ_hd, σ_hd = self.params()
        θ = (1 - γ) / (1 - 1/ψ)
        z_grid = self.z_grid
        h_z_grid = self.h_z_grid
        h_c_grid = self.h_c_grid
        shocks = self.shocks

        # Some useful constants
        τ_z = ϕ_z * σ_bar
        τ_c = ϕ_c * σ_bar
        κ = np.sqrt(1 - ρ**2)
        nz = self.z_grid_size
        nh_z = self.h_z_grid_size
        nh_c = self.h_c_grid_size
        ns = self.mc_draw_size

        @njit(parallel=True)
        def T(w):
            g = w**θ
            Kg = np.empty_like(g)

            # Apply the operator K to g, computing Kg
            for i in prange(nz):
                z = z_grid[i]
                for k in range(nh_c):
                    h_c = h_c_grid[k]
                    σ_c = τ_c * exp(h_c)
                    mf = exp((1 - γ) * (μ_c + z) + (1 - γ)**2 * σ_c**2 / 2)
                    for j in range(nh_z):
                        h_z = h_z_grid[j]
                        σ_z = τ_z * exp(h_z)
                        g_exp = 0.0
                        for l in range(ns):
                            η, ω, ϵ = shocks[:, l]
                            zp = ρ * z + κ * σ_z * η
                            h_cp = ρ_hc * h_c + σ_hc * ω
                            h_zp = ρ_hz * h_z + σ_hz * ϵ
                            r = zp, h_zp, h_cp
                            g_exp += lininterp_3d(z_grid, h_z_grid, h_c_grid, g, r)
                        Kg[i, j, k] = mf * (g_exp / ns)

            return 1.0 + β * Kg**(1/θ)  # Tw

        return T

    def stability_exponent_factory(self, parallel_flag=True):

        # Unpack params and related objects
        β, γ, ψ, μ_c, ρ, ϕ_z, σ_bar, ϕ_c, ρ_hz, σ_hz, ρ_hc, σ_hc, μ_d, α, δ, \
           ϕ_d, ρ_hd, σ_hd = self.params()
        θ = (1 - γ) / (1 - 1/ψ)

        z_grid = self.z_grid
        h_z_grid = self.h_z_grid
        h_c_grid = self.h_c_grid
        h_d_grid = self.h_d_grid

        # Initial conditions
        z_0 = 0.0
        h_z_0 = 0.0
        h_c_0 = 0.0
        h_d_0 = 0.0

        # Useful constants
        τ_z = ϕ_z * σ_bar
        τ_c = ϕ_c * σ_bar
        τ_d = ϕ_d * σ_bar
        κ = np.sqrt(1 - ρ**2)

        w_star = self.w_star_guess

        @njit(parallel=parallel_flag)
        def compute_stability_exponent(n=1000, num_reps=10000, seed=1234):
            """
            Uses fact that

                M_j = β**θ * exp(g_d_j - γ * g_c_j) * (w(x_j) / (w(x_{j-1}) - 1)**(θ - 1)

            where w is the value function.
            """
            phi_obs = np.empty(num_reps)

            np.random.seed(seed)

            for m in prange(num_reps):

                # Reset accumulator and state to initial conditions
                phi_sum = 1.0
                z, h_z, h_c, h_d = z_0, h_z_0, h_c_0, h_d_0

                # Calculate W_0
                r = z, h_z, h_c
                W = lininterp_3d(z_grid, h_z_grid, h_c_grid, w_star, r)

                # We'll accumulate using 4 terms
                a1 = 0.0
                a2 = 0.0
                a3 = 0.0
                a4 = 0.0

                for t in range(n):
                    # Update state
                    σ_z = τ_z * exp(h_z)
                    z = ρ * z + κ * σ_z * randn()
                    h_z = ρ_hz * h_z + σ_hz * randn()
                    h_c = ρ_hc * h_c + σ_hc * randn()
                    h_d = ρ_hd * h_d + σ_hd * randn()
                    # Map h to σ for the updated states
                    σ_c = τ_c * exp(h_c)
                    σ_d = τ_d * exp(h_d)
                    # Calculate w_hat
                    r = z, h_z, h_c
                    W_next = lininterp_3d(z_grid, h_z_grid, h_c_grid, w_star, r)
                    # Accumulate
                    a1 += z
                    a2 += σ_c * randn()
                    a3 += σ_d * randn()
                    a4 += log(W_next / (W - 1.0))
                    # Update W
                    W = W_next

                total = (α - γ) * a1 + (δ - γ) * a2 + a3 + (θ - 1.0) * a4
                phi_obs[m] = exp(total)

            return θ * log(β) + μ_d - γ * μ_c + (1/n) * log(np.mean(phi_obs))

        return compute_stability_exponent


#!/usr/bin/env python3.1

# first character in match counts as a "match," remaining are "similar"
# everything else is a mismatch
rnaMatch = { 'A' : 'U', 'C': 'G', 'G': 'CU', 'U': 'AG' }

# these parameters determine how to score match
# if seeding is used, the scores can be multiplied in the seed region
rnaValues = { "match": 5.0,
              "targetGap":-0.5, "queryGap":-0.5,
              "openGap":-8.0, "extendGap":-2.0,
              "mismatch":-3.0,
              "similar": 2.0,
              "seedLength" : 11.0,
              "seedWeight" : 2.0 }

def sw(query, target, scoreCount=50,
       match=rnaMatch, scoreValue=rnaValues):

    # table has an extra row and column
    height = len(query) + 1
    width = len(target) + 1

    # initialize the edges of the table.
    # each table entry has a score, a match type, and a
    table = {}
    for row in range(0,height):
        table[row,0] = { "score":0.0, "start":(row,0), "type": "begin", "gapScore":0.0 }
    for col in range(1,width):
        table[0,col] = { "score":0.0, "start":(0,col), "type": "begin", "gapScore":0.0 }

    # grab parameters for later use
    seedLength = scoreValue["seedLength"]
    seedWeight = scoreValue["seedWeight"]
    openGap = scoreValue["openGap"]
    extendGap = scoreValue["extendGap"]

    # fill out the Smith Waterman matrix with values
    for row in range(1,height):
        for col in range(1,width):

            # grab the query and target characters
            # strings start at 0, but bases count from 1
            qc = query[row-1]
            tc = target[col-1]

            # assume a match or similar extension
            newScore = { "score" : table[row-1,col-1]["score"],
                         "start" : table[row-1,col-1]["start"],
                         "gapScore":0.0}

            # "row" is the position of the base currently being matched
            # get rid of one of these two terms if you want
            # seed region at one end
            in_seed = (row <= seedLength) or ((height - row) <= seedLength)

            # types of matching: strong/match, weak/similar, bad/mismatch
            if match[qc][0] == tc:
                newScore["type"] = "match"
            elif (tc in match[qc]):
                newScore["type"] = "similar"
            else:
                newScore["type"] = "mismatch"

            # matching (only) may be counted more heavily at ends
            if in_seed:
                newScore["score"] += seedWeight * scoreValue[newScore["type"]]
            else:
                newScore["score"] += scoreValue[newScore["type"]]

            # two other ways these strings may be aligned:
            # current query character is dropped (a targetGap)
            # or the current target character is dropped (a queryGap)
            tgap = table[row-1,col]["gapScore"]
            qgap = table[row,col-1]["gapScore"]
            tgap_score = table[row-1,col]["score"] + openGap + tgap * extendGap
            qgap_score = table[row,col-1]["score"] + openGap + qgap * extendGap

            # check if dropping target is a better approach
            if tgap_score > newScore["score"]:
                newScore  = {"score":tgap_score,
                             "type":"targetGap",
                             "start": table[row-1,col]["start"],
                             "gapScore": table[row-1,col]["gapScore"]+1.0}

            # perhaps dropping a query character is better
            if qgap_score > newScore["score"]:
                newScore = {"score":qgap_score,
                            "type":"queryGap",
                            "start": table[row,col-1]["start"],
                            "gapScore": table[row,col-1]["gapScore"]+1.0}

            # if the best score is not positive,
            # we terminate any matching here
            if newScore["score"] <= 0:
                newScore = {"score":0,
                            "type":"begin",
                            "start": (row,col),
                            "gapScore": 0.0}

            # write the entry in the table
            table[row,col] = newScore

    # compute the top scoreCount highest scores from the table
    # if there are ties, we may get a few more
    scores = [(table[row,col]["score"],(row,col))
                   for row in range(1,height) for col in range(1,width)]
    # sorts based on (1) score, (2) position in target
    scores = sorted(scores,key=lambda s: (s[0],width-s[1][1]),reverse=True)
    if len(scores) > scoreCount:
        l = scoreCount
        while l < len(scores) and scores[l][0] == scores[scoreCount][0]:
            l = l+1
        scoreCount = l

    return scores[:scoreCount]


from decimal import Decimal

COMMISSION_VALUE = Decimal(0.0005)

TICKERS = [
    "SPCE",
    "TSLA",
    "ACAD",
    "COIN",
    "FGEN",
    "JD",
    "BABA",
    "TCS",
    "SBER",
    "AFLT",
    "MSFT",
    "NFLX",
    "GAZP",
    "GOOG",
    "FB",
    "ORCL",
    "HYDR",
    "NXPI",
    "XLNX",
    "NEE",
    "AMD",
    "DELL",
    "HHR",
    "KO",
    "TDOC",
    "PLZL",
    "IRAO",
    "AGRO",
    "OZON",
    "PFE",
    "ACH",
    "ENPH",
    "EDIT",
    "GMKN",
    "BIDU",
    "BIIB",
    "NVDA",
    "ATRA",
    "SPOT",
    "RDY",
    "TTM",
    "MOMO",
    "CNC",
    "TXN",
    "ADI",
    "POLY",
    "IBN",
    "SCCO",
    "FCX",
]


import pycparser
def _traverse_tree(root):
    num_nodes = 1
    queue = [root]
    root_json = {
        "node": _name(root),

        "children": []
    }
    queue_json = [root_json]
    while queue:
        current_node = queue.pop(0)
        num_nodes += 1
        current_node_json = queue_json.pop(0)
        global alltokenlist
        alltokenlist = []
        vistast(current_node)
        if alltokenlist != []:
            ss = alltokenlist[0]
            sss = ss.replace(' ', '')
            if sss.startswith('"') or sss.startswith("'"):
                k=1
            else:
                child_json = {
                "node": sss,
                "children": []
                }

                current_node_json['children'].append(child_json)
        for item in current_node.children():
            if _name(item[1]).startswith('"') or _name(item[1]).startswith("'"):
                pass
            else:
                queue.append(item[1])
                child_json = {
                "node": _name(item[1]),
                "children": []
                }
                current_node_json['children'].append(child_json)
                queue_json.append(child_json)
    return root_json, num_nodes

def _name(node):
    return type(node).__name__
def vistast(node):
    nvlist=[(n,getattr(node,n)) for n in node.attr_names]
    # print("nvlists:")
    # print(nvlist)
    # print("nvliste:")
    if nvlist!=[]:
        if hasattr(node,'op'):
            word=node.op
            #print("word_op:" + word)
        elif hasattr(node,'declname'):
            word=node.declname
            #print("word_declname:" + word)
            if word is None:
                word=node.__class__.__name__
        elif isinstance(node,pycparser.c_ast.IdentifierType):
            word=node.names[0]
            #print("word_IdentifierType:" + word)
        elif isinstance(node,pycparser.c_ast.Constant):
            word=node.value
            #print("word_Constant:" + word)
        elif isinstance(node,pycparser.c_ast.ID):
            word=node.name
            #print("word_ID:" + word)
        else:
            word=nvlist[0][1]
            word=str(word)
            #print("word_word:" + word)
        alltokenlist.append(word)
numnodes=0
def dfsDict(root):
    global listtfinal
    listtfinal.append(str(root['node']))
    global numnodes
    numnodes+=1
    if len(root['children']):
        pass
    else:
        return
    for dictt in root['children']:
        dfsDict(dictt)
f=open("flistPOJ.txt",'r')
ff=open("sentencePOJwithid.txt",'w')
line=f.readline().rstrip("\t")
li=line.split("\t")
for l in li:
    tree = pycparser.parse_file(l)
    listtfinal = []
    numnodes = 0
    sample,num_nodes=_traverse_tree(tree)
    dfsDict(sample)
    for lis in listtfinal:
        ff.write(lis)
        ff.write(" ")
    ff.write("\n")
    #print(listtfinal)
ff.close()


import math

def pythagorus_check(dimensions):
    hyp = dimensions[2]
    leg1 = dimensions[0]
    leg2 = dimensions[1]
    check = math.sqrt(pow(leg1, 2) + pow(leg2, 2))
    if check == hyp:
        return 'R'
    elif hyp > check:
        return 'O'
    else:
        return 'A'

if __name__ == '__main__':
    num_cases = int(input())
    cases = [[int(dim) for dim in input().split()] for num in range(num_cases)]
    for case in cases:
        print(pythagorus_check(case), end=' ')


class Solution:
    """
    @param: nums: A list of integers.
    @return: A list of permutations.
    """
    def permute(self, nums):
        # write your code here
        answer = []

        self.dfs(nums, [], answer)

        return answer
    def dfs(self, nums, currentSet, answer):

        if len(nums) == len(currentSet):
            answer.append(list(currentSet))
            return
        for num in nums:
            if num not in currentSet:
                currentSet.append(num)
                self.dfs(nums, currentSet, answer)
                currentSet.pop()


m = int(input())
target = [list(map(int, input().split())) for i in range(m)]
n = int(input())
stars = []
dic = {}
for i in range(n):
    x, y = map(int, input().split())
    stars.append([x, y])
    dic[(x, y)] = True
x, y = target[0]
for i in range(n):
    x2, y2 = stars[i]
    xmove = x2-x
    ymove = y2-y
    movedtarget = []
    for j in range(m):
        movedtarget.append([target[j][0] + xmove, target[j][1] + ymove])
    # すべて含んでいるか判定
    boollist = []
    for j in range(m):
        boollist.append(dic.get((movedtarget[j][0], movedtarget[j][1]), False))
    if all(boollist):
        break
print('{0} {1}'.format(xmove, ymove))


import os
import sys
import nfqueue
import socket
import signal
import time
import whitelist
from collections import defaultdict
import logging

class GZA(object):
    def __init__(self, vmnum, opts):
        self.gamestate = defaultdict(int)
        self.vmnum = vmnum
        #self.iface = 'tap%d' % vmnum
        self.iface = 'virbr1'
        self.opts = opts
        self.mac = '52:54:00:1D:3A:4F'
        self.log = logging.getLogger(__name__)

        if self.opts.whitelist:
            whitelist.makewhitelist(self.opts.whitelistpath)
            self.whitelisted = whitelist.whitelisted
            whitelist.makeipwhitelist(self.opts.ipwhitelistpath)
            self.whitelistedip = whitelist.whitelistedip

        # Set the game (only used in subclass games)
        if self.opts.taken > 0:
            self.game = 'taken'
        elif self.opts.dropn > 0:
            self.game = 'dropn'
        elif self.opts.dropall:
            self.game = 'dropall'

    def reset(self, signum, frame):
        self.log.debug('Cleared game state!')
        self.gamestate.clear()
        try:
            self.q.try_run()
        except KeyboardInterrupt:
            self.log.debug('Clean shutdown')
            self.q.unbind(socket.AF_INET)
            sys.exit(0)

    def playgame(self, payload):
        payload.set_verdict(nfqueue.NF_ACCEPT)

    def startgame(self):
        good = False
        while not good:
            try:
                self.q = nfqueue.queue()
                self.q.open()
                self.q.set_callback(self.playgame)
                self.q.fast_open(self.vmnum, socket.AF_INET)
                good = True
            except RuntimeError as e:
                self.log.error(str(e))
                self.log.error('Retrying to connect to nfqueue #%d...', self.vmnum)
                time.sleep(3)
        try:
            self.log.debug('Successfully bound to nfqueue #%d', self.vmnum)
            self.q.try_run()
        except KeyboardInterrupt:
            self.log.debug('Clean shutdown')
            self.q.unbind(socket.AF_INET)
            os._exit(0)


import time, json
import smtplib
from email.message import EmailMessage
import props

import drive_upload
global_flags = {"appname": "", "mail": "", "download_link": "", "begin_upload": "FALSE"}

with open("globals.json", "w") as fp:
    json.dump(global_flags, fp)

def upload_results():
    with open('globals.json', 'r') as fp:
        active_flags = json.load(fp)
    if active_flags["begin_upload"] == "TRUE":
        print("received app " + active_flags["appname"] + " for upload")
        drive = drive_upload.authenticate()
        download_link = drive_upload.upload_results(active_flags["appname"], drive)
        global_flags["download_link"] = download_link
        global_flags["send_mail"] = "TRUE"
        with open("globals.json", "w") as fp:
            json.dump(global_flags, fp)

        msg = EmailMessage()
        msg.set_content("Analysis request submitted by    " + active_flags["mail"] + " complete. Please visit " + download_link + " for results")
        msg['Subject'] = "Analysis Complete"
        msg['From'] = props.MAIL_USERNAME
        msg['To'] = active_flags["mail"]
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(props.MAIL_USERNAME, props.MAIL_PASSWORD)
        server.send_message(msg)
        server.quit()

        active_flags["begin_upload"] = "FALSE"
        active_flags["mail"] = ""
        active_flags["appname"] = ""
        with open("globals.json", "w") as fp:
            json.dump(global_flags, fp)
        return "Email Trigger set"

    return "Waiting for trigger"

i = 0
while True:
    i = i + 1
    print("wait cycle " + str(i))
    time.sleep(120)
    print(upload_results())


# -*- coding: utf-8 -*-
"""Various utilities."""

from . import utils as tasks, rq
from datetime import datetime

def setup():
    """Set up the application schedule. Remove any already scheduled jobs."""
    scheduler = rq.get_scheduler()
    for job in scheduler.get_jobs():
        job.delete()

    tasks.process_tasks.schedule(datetime.utcnow(), interval=3600)


##################################################
#-Pi Quick Tools
#-Coded on 18/08/21
#-Made by Splocko
#-Contributed by @R2Boyo25
#-https://github.com/Splocko
#################################################
tempWin= 'sudo bash /home/pi/Pi-Quick-Tools/Temp.sh'
import os
import gi
import time
gi.require_version('Gtk','3.0')
from gi.repository import Gtk
class window(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self,title='Pi Quick Tools')
        Gtk.Window.set_default_size(self, 640, 480)

        self.box = Gtk.Box(spacing=6)
        self.add(self.box)

        self.addButton('Free up space', 'sudo apt -y autoremove\nsudo apt purge\nsudo apt clean', 'Cleaning APT...')
        self.addButton('Update All Packages', 'sudo apt update\nsudo apt -y upgrade', 'Updating all packages... This may take a long time.')
        self.addButton('Reboot', 'sudo reboot')
        self.addButton('Shutdown', 'sudo shutdown now')
        self.addButton('Raspberry Pi Config', f'bash {script_dir}/rpicnfgscrpt.sh')
        self.addButton('Temperature', 'sudo bash /home/pi/Pi-Quick-Tools/Temp.sh', 'Temperature opened')
        self.addButton('Cpu Stats','sudo bash /home/pi/Pi-Quick-Tools/Htopstats.sh', 'Stats opened')

    def runCommands(self, button, commands, successText, failText, startMessage = None) -> None:
        if startMessage:
            print(startMessage)
        failed = False
        for command in commands:
            if os.system(command.strip()) != 0:
                failed = True
        if failed:
            print(failText)
        else:
            print(successText)

    def addButton(self, buttonName, action, startMessage = None, successText = None, failText = None) -> None:

        if not failText:
            failText = f'{buttonName} failed...'
        if not successText:
            successText = f'{buttonName} successful...'

        if str(type(action)) == "<class 'function'>":
            button = Gtk.Button(label = buttonName)
            button.connect('clicked', action)
            self.box.pack_start(button, True, True, 0)
        else:
            button = Gtk.Button(label = buttonName)
            if not type(action) == list:
                if '\n' in action:
                    converted = action.split('\n')
                else:
                    converted = [action]
            else:
                converted = action
            button.connect('clicked', self.runCommands, converted, successText, failText, startMessage)
            self.box.pack_start(button, True, True, 0)

    def on_tempButton_clicked(self, widget):
        def measure_temp() -> str:
            temp = os.popen("vcgencmd measure_temp").readline()
            return (temp.replace("temp=",""))

        while True:
            self.temperature = measure_temp()
            self.tempButton = Gtk.Button(label= f'Temperature: {self.temperature}')
            time.sleep(1)

script_dir = os.path.abspath(os.getcwd())

win = window()
win.connect('destroy', Gtk.main_quit)
win.show_all()
Gtk.main()


def get_url(api_name):
	fp = open('D:\\python\\work\\HDapi\\config\\api_house.txt')
	api_infos = fp.readlines()
	fp.close()
	api_urls = []
	for api in api_infos:
		api_f = api.strip(' \t\r\n')
		api_c = api_f.split('=')
		if api_name == api_c[0]:
			return api_c[1]
		else:
			print('错误的接口名')


"""
Metadata management for the files and blocks stored in playcloud
"""
import datetime
import logging
import json
import random
import socket
import time

import enum
import IPy
import numpy
import redis

LOGGER = logging.getLogger("metadata")

def compute_block_key(path, index, length=2):
    """
    Computes a block key from a file path and an index.
    Args:
        path(str): Path to the file related to the blocloggerk
        index(int): index of the block
        length(int, optional): Length of the index part of the key for zero filling (Defaults to 2)
    Returns:
        str: Block key
    """
    return path + "-" + str(index).zfill(length)

def uniform_random_selection(t, n):
    """
    Args:
        t(int): Number of pointers
        n(int): Number of blocks avaialable
    Returns:
        list(int): A list of indices that can be used for random selection of t
                   elements in a list of n elements
    """
    if t >= n:
        return [index for index in xrange(n)]
    difference = n - t
    if difference < t:
        selected = [index for index in xrange(n)]
        while len(selected) > t:
            selected.pop(random.randint(0, len(selected) - 1))
        return selected
    selected = []
    while len(selected) < t:
        index = random.randint(0, n - 1)
        if index not in selected:
            selected.append(index)
    return selected

def normal_selection(t, n, std=1000):
    """
    Select pointer indices using normal distribution
    Args:
        t(int): Number of pointers
        n(int): Number of blocks
        std(int, optional): Standard deviation (defaults to 1000)
    Returns:
        list(int): A list of unique indices ranging from 0 to (n - 1) selected
                   using normal distribution
    """
    selected = []
    if t >= n:
        return [element for element in xrange(n)]
    std = min(n, std)
    difference = n - t
    if difference < t:
        selected = [index for index in xrange(n)]
        while len(selected) > t:
            index = int(round(numpy.random.normal(len(selected), min(std, len(selected)))))
            if index < 0 or index >= len(selected): # Checking that we are withtin bounds
                continue
            selected.pop(index)
        return selected
    while len(selected) < t:
        index = int(round(numpy.random.normal(n, std)))
        if index < 0 or index >= n: # Checking that we are withtin bounds
            continue
        if index in selected:
            continue
        selected.append(index)
    return selected

class BlockType(enum.Enum):
    """
    Informs on the type of block and its use where DATA blocks are needed for
    decoding while PARITY blocks are needed for reconstruction
    """
    DATA = 0
    PARITY = 1

class MetaBlock(object):
    """
    A class that represents a data block
    """
    def __init__(self, key, providers=None, creation_date=None,
                 block_type=BlockType.DATA, checksum=None, entangled_with=None,
                 size=0):
        """
        MetaBlock constructor
        Args:
            key (str): Key under which the block is stored
            providers (list(str), optional): Ids of the providers
            creation_date (datetime.datetime, optional): Time of creation of the
                                                         block, defaults to
                                                         current time
            block_type (BlockType, optional): Type of the block
            checksum (bytes, optional): SHA256 digest of the data
            entangled_with(list(str), optional): List of documents the block is
                                                 entangled with
        """
        self.key = key
        if providers:
            self.providers = providers
        else:
            self.providers = []
        if creation_date is None:
            self.creation_date = datetime.datetime.now()
        else:
            self.creation_date = creation_date
        self.block_type = block_type
        self.checksum = checksum
        if entangled_with:
            self.entangled_with = entangled_with
        else:
            self.entangled_with = []
        self.size = size

    def __json__(self):
        """
        Returns a representation of a MetaBlock as a serializable dictionary
        Returns:
            dict: Returns a representation of a MetaBlock as a serializable dictionary
        """
        return {
            "key": self.key,
            "providers": [provider for provider in self.providers],
            "creation_date": self.creation_date.isoformat(),
            "block_type": self.block_type.name,
            "checksum": convert_binary_to_hex_digest(self.checksum),
            "entangled_with": self.entangled_with
        }

    def __str__(self):
        """
        Returns a string representation of a Metadata object
        Return:
            str: a string representation of a Metadata object
        """
        return json.dumps(self.__json__())

def convert_binary_to_hex_digest(binary_digest):
    """
    Converts a binary digest from hashlib.sha256.digest
    Args:
        binary_digest(str): Binary digest from hashlib.sha256.digest()
    Returns:
        str: Equivalent of the hexdigest for the same input
    """
    return "".join(["{:02x}".format(ord(c)) for c in binary_digest])

class MetaDocument(object):
    """
    A class describing how a file has been stored in the system
    """

    def __init__(self, path, original_size=0):
        """
        Constructor for Metadata objects
        Args:
            path(string): Path to the file in the system
            original_size(int): Original size of the file in bytes
        """
        self.path = path
        self.creation_date = datetime.datetime.now()
        self.blocks = []
        self.entangling_blocks = []
        self.original_size = original_size

    def __json__(self):
        """
        Returns a representation of a MetaBlock as a serializable dictionary
        Returns:
            dict: Returns a representation of a MetaBlock as a serializable dictionary
        """
        return {
            "path": self.path,
            "creation_date": self.creation_date.isoformat(),
            "blocks": [block.__json__() for block in self.blocks],
            "entangling_blocks": self.entangling_blocks,
            "original_size": self.original_size
        }

    def __str__(self):
        """
        """
        return json.dumps(self.__json__())

def extract_entanglement_data(block_data):
    """
    Extract and list the entangling information from the blocks header
    Args:
        block_data(str): A data block with an entanglement header
    Returns:
        list((str, int)): A list of the blocks used for entanglement
    """
    header_delimiter = chr(29)
    pos = block_data.find(header_delimiter)
    if pos <= 0:
        return ""
    raw_header = block_data[:pos]
    formatted_header = json.loads(raw_header)
    return formatted_header

def extract_document_size(block_data):
    """
    Args:
        block_data(str): A data block with an entanglement header
    Returns:
        int: The size of the original document
    """
    if not block_data or not isinstance(block_data, str):
        raise ValueError("argument block_data must be a non-empty sequence of bytes")
    header_delimiter = chr(29)
    start = block_data.find(header_delimiter) + 1
    end = block_data.find(header_delimiter, start)
    return int(block_data[start:end])

def split_blocks_field(path, joined_keys):
    pos = 0
    extracted_keys = []
    while pos != -1 and pos < len(joined_keys):
        start = joined_keys.find(path, pos)
        if start == -1:
            break
        end = joined_keys.find(",", start + len(path))
        if end == -1:
            extracted_keys.append(joined_keys[start:])
        else:
            extracted_keys.append(joined_keys[start:end])
        pos = end
    return extracted_keys

class Files(object):
    """
    Represents metadata stored in the cluster
    """
    FILE_PREFIX = "files:"
    BLOCK_PREFIX = "blocks:"
    READ_BUFFER_SIZE = 100
    CONNECTION_POOLS = {}

    @staticmethod
    def get_pool(host, port):
        """
        Gets an existing connection pool to a given server or creates a new one
        Args:
            host(str): Host of the redis server
            port(int): Port number the resdis server is listening on
        Returns:
            BlockingConnectionPool: A blocking redis connection pool
        """
        if not isinstance(host, (str, unicode)) or not host:
            raise ValueError("host argument must be a non empty string")
        if not isinstance(port, int) or port <= 0 or port > 65535:
            raise ValueError("port argument must be an integer between 0 and 65535")
        if not host in Files.CONNECTION_POOLS:
            Files.CONNECTION_POOLS[host] = {}
        if not port in Files.CONNECTION_POOLS[host]:
            pool = redis.ConnectionPool(host=host,
                                        port=port,
                                        db=0,
                                        max_connections=128,
                                        socket_keepalive=True)
            Files.CONNECTION_POOLS[host][port] = pool
        return Files.CONNECTION_POOLS[host][port]

    def __init__(self, host="metadata", port=6379, pointer_selector=normal_selection):
        try:
            ip_address = str(IPy.IP(host))
        except ValueError:
            ip_address = socket.gethostbyname(host)
        pool = Files.get_pool(ip_address, port)
        self.redis = redis.StrictRedis(connection_pool=pool,
                                       encoding=None,
                                       socket_keepalive=True)
        self.select_pointers = pointer_selector

    def exists(self, path):
        """
        Checks if a file is in the metadata
        Args:
            path(str): Path to the file
        Returns:
            bool: True if the file exists in the documents
        """
        if not path or not isinstance(path, (str, unicode)):
            raise ValueError("path argument must be a non empty string")
        return self.redis.exists("{:s}{:s}".format(Files.FILE_PREFIX, path))

    def get(self, path):
        """
        Returns a Metadata object stored under a given path.
        Args:
            path(str): The key the Metadata object was stored under
        Returns:
            MetaDocument: The Metadata object stored under the key
        Raises:
            ValueError: If path is an empty string
        """
        if not path or not isinstance(path, (str, unicode)):
            raise ValueError("path argument must be a valid non-empty string")
        return self.get_files([path])[0]

    def get_files(self, paths):
        """
        Returns a Metadata object stored under a given path.
        Args:
            paths(list(str)): The key the Metadata object was stored under
        Returns:
            MetaDocument: The Metadata object stored under the key
        Raises:
            ValueError: If the paths argument is an empty list or if one of the
                        paths is an empty string
            KeyError: If one of the paths requested does not exist
        """
        if not paths:
            raise ValueError("path argument must be a valid list of string")

        pipeline = self.redis.pipeline()
        translated_paths = []
        # Pipeline command to check that all paths exist
        for path in paths:
            if not path:
                raise ValueError("path in paths list must be a valid non-empty string")
            file_key = "{:s}{:s}".format(Files.FILE_PREFIX, path)
            translated_paths.append(file_key)
            pipeline.exists(file_key)
        # Check result from pipelined exists requests to make sure that all the
        # paths exist and pipeline command to get file hashes
        for index, in_database in enumerate(pipeline.execute()):
            if not in_database:
                raise KeyError("path {:s} not found".format(paths[index]))
            pipeline.hgetall(translated_paths[index])
        hashes = pipeline.execute()
        metadata = []
        keys = []
        for hsh in hashes:
            mtdt = Files.parse_metadata(hsh)
            path = hsh.get("path")
            keys += split_blocks_field(path, hsh.get("blocks"))
            metadata.append(mtdt)
        blocks = self.get_blocks(keys)
        step = len(blocks) / len(metadata)
        for index in xrange(0, len(metadata)):
            metadata[index].blocks = blocks[index * step:(index * step) + step]
        return sorted(metadata, key=lambda mtdt: mtdt.path)

    def get_block(self, key):
        """
        Returns a block from the database
        Returns:
            key(str): The key under which a block is stored
        Returns:
            MetaBlock: The MetaBlock that was retrieved
        """
        return self.get_blocks([key])[0]

    def get_blocks(self, keys):
        """
        Returns multiple blocks from the database
        Args:
            keys(list(str)): A list of keys under witch the blocks to fetch are stored
        Returns:
            list(MetaBlock): The MetaBlocks that were retrieved
        Raises:
            KeyError: If one of the keys does not exist
        """
        pipeline = self.redis.pipeline()
        translated_keys = ["{:s}{:s}".format(Files.BLOCK_PREFIX, key) for key in keys]
        for key in translated_keys:
            pipeline.exists(key)
        for index, is_in_database in enumerate(pipeline.execute()):
            if not is_in_database:
                raise KeyError("key {:s} not found ({:d} = {:s})".format(keys[index], index, translated_keys[index]))
            pipeline.hgetall(translated_keys[index])
        blocks = [Files.parse_metablock(hsh) for hsh in pipeline.execute()]
        return sorted(blocks, key=lambda block: block.key)

    def put(self, path, metadata):
        """
        Stores a Metadata object using the given path as the key
        Args:
            metadata(MetaDocument): The object to store
        Returns:
            str: The key under which the object was stored
        """
        start = time.clock()
        if not path:
            raise ValueError("path argument must be a valid non-empty string")
        if not metadata:
            raise ValueError("metadata argument must be a valid Metadata object")
        entangling_block_keys = [compute_block_key(eb[0], eb[1]) for eb in metadata.entangling_blocks]
        entangling_blocks = self.get_blocks(entangling_block_keys)

        pipeline = self.redis.pipeline(transaction=True)
        for block in entangling_blocks:
            block.entangled_with.append(path)
            pipeline.hset("{:s}{:s}".format(Files.BLOCK_PREFIX, block.key),
                          "entangled_with",
                          ",".join(sorted(block.entangled_with)))
        meta_hash = {
            "path": metadata.path,
            "creation_date": str(metadata.creation_date),
            "original_size": metadata.original_size,
            "blocks": ",".join([block.key for block in metadata.blocks]),
            "entangling_blocks": json.dumps(metadata.entangling_blocks)
        }
        block_keys = []
        for block in metadata.blocks:
            block_hash = {
                "key": block.key,
                "creation_date": str(block.creation_date),
                "providers": ",".join(sorted(block.providers)),
                "block_type": block.block_type.name,
                "checksum": block.checksum,
                "entangled_with": ",".join(sorted(block.entangled_with)),
                "size": block.size
            }
            metablock_key = "{:s}{:s}".format(Files.BLOCK_PREFIX, block.key)
            timestamp = (block.creation_date - datetime.datetime(1970, 1, 1)).total_seconds()
            block_keys.append(timestamp)
            block_keys.append(block.key)
            pipeline.hmset(metablock_key, block_hash)
        pipeline.zadd("block_index", *block_keys)
        pipeline.hmset("files:{:s}".format(path), meta_hash)
        timestamp = (metadata.creation_date - datetime.datetime(1970, 1, 1)).total_seconds()
        pipeline.zadd("file_index", timestamp, path)
        pipeline.execute()
        end = time.clock()
        elapsed = end - start
        LOGGER.debug("Storing metadata for {:s} took {:f} seconds".format(path, elapsed))
        return path

    @staticmethod
    def parse_metablock(record):
        """
        Parses a metablock from an object
        Args:
            record(dict): A dictionary describing the metablock
        Returns:
            MetaBlock: The parsed MetaBlock
        """
        key = record.get("key")
        try:
            creation_date = datetime.datetime.strptime(record.get("creation_date"),"%Y-%m-%d %H:%M:%S.%f")
        except:
            creation_date = datetime.datetime.strptime(record.get("creation_date"),"%Y-%m-%d %H:%M:%S")
        providers = record.get("providers").strip()
        if providers:
            providers = providers.split(",")
        else:
            providers = []

        entangled_with = record.get("entangled_with", "").strip()
        if entangled_with:
            entangled_with = entangled_with.split(",")
        else:
            entangled_with = []

        block_type = BlockType[record.get("block_type")]
        checksum = record.get("checksum")
        size = int(record.get("size", "0"))
        metablock = MetaBlock(key,
                              creation_date=creation_date,
                              providers=providers,
                              block_type=block_type,
                              checksum=checksum,
                              entangled_with=entangled_with,
                              size=size)
        return metablock

    @staticmethod
    def parse_metadata(record):
        """
        Parses metadata information from a record.
        Args:
            record(dict): A dictionary describing the metadata
        Returns:
            MetaDocument: The parsed Metadata
        """
        path = record.get("path")
        original_size = int(record.get("original_size"))
        creation_date = datetime.datetime.strptime(record.get("creation_date"),
                                                   "%Y-%m-%d %H:%M:%S.%f")
        metadata = MetaDocument(path, original_size=original_size)
        metadata.creation_date = creation_date
        metadata.entangling_blocks = json.loads(record.get("entangling_blocks"))
        return metadata

    def keys(self):
        """
        Returns a list of all the files stored in the system
        Returns:
            list(str): The list of files in the system
        """
        return self.redis.zrange("file_index", 0, -1)

    def list_blocks(self):
        """
        Returns a list of the blocks in the system
        Returns:
            list(str): A list of all the blocks in the system
        """
        return self.redis.zrange("block_index", 0, -1)

    def values(self):
        """
        Returns all files metadata objects
        Returns:
            list(MetaDocument): All the metadata object stored in the system
        """
        filenames = self.keys()
        if not filenames:
            return []
        return self.get_files(filenames)

    def select_random_blocks(self, requested):
        """
        Returns up to blocks_desired randomly selected metablocks from the index
        Args:
            requested(int): The number of random blocks to select
        Returns:
            list(MetaBlock): randomly selected blocks
        """
        start = time.clock()
        blocks_desired = requested
        blocks_available = self.redis.zcard("block_index")

        if blocks_available <= blocks_desired:
            block_keys = self.redis.zrange("block_index", 0, blocks_available)
            return [self.get_block(key) for key in block_keys]

        selected_indexes = self.select_pointers(blocks_desired, blocks_available)

        selected_keys = []
        for index in selected_indexes:
            selected_key = self.redis.zrange("block_index", index, index + 1)[0]
            selected_keys.append(selected_key)
        random_blocks = self.get_blocks(selected_keys)
        end = time.clock()
        elapsed = end - start
        LOGGER.debug("Took {:f} seconds to select random blocks".format(elapsed))
        return random_blocks

    def get_entanglement_graph(self):
        """
        Scan the database to return the entanglement graph
        Returns:
            dict(str, list): The entanglement graph
        """
        graph = {}
        filenames = self.keys()
        for filename in filenames:
            metadata = self.get(filename)
            creation_date = str(metadata.creation_date)
            entangling_blocks = json.dumps(metadata.entangling_blocks)
            blocks = str([[block.key, block.providers[0]] for block in metadata.blocks])
            graph[filename] = [
                creation_date,
                entangling_blocks,
                blocks
            ]
        return graph

    def has_been_entangled_enough(self, block_key, pointers):
        """
        Tests whether a block can have its replicas deleted due to a high enough
        number of pointers directed at it.
        Returns True if it is entangled with enough documents to have its replicas
        deleted, False otherwise.
        Args:
            block_key(str): Path of the block
            pointers(int): The number of documents that use the block as part of
                           their entanglement
        Returns:
            bool: Whether the replicas of the block can be erased
        Raises:
            ValueError:
                * if path is not of type `str` or empty
                * if pointers is not of type `int` or is lower than 0
        """
        if not block_key or not isinstance(block_key, str):
            raise ValueError("path argument must be a valid non-empty string")
        if not isinstance(pointers, int) or pointers < 0:
            raise ValueError("pointers argument must be a valid integer greater or equal to 0")
        metablock = self.get_block(block_key)
        return len(metablock.entangled_with) >= pointers

    def get_blocks_from_provider(self, provider):
        """
        Returns the list of blocks located on a given provider
        Args:
            provider(str): Name of the provider
        Returns:
            list(MetaBlock): The list of blocks located on the provider
        """
        if not isinstance(provider, str) or not provider:
            raise ValueError("provider argument must be a non empty string")
        block_names = self.list_blocks()
        if not block_names:
            return []
        number_of_blocks = len(block_names)
        step = min(number_of_blocks, Files.READ_BUFFER_SIZE)
        blocks_from_provider = []
        for index in xrange(0, number_of_blocks, step):
            current_range = block_names[index:index + step]
            blocks = self.get_blocks(current_range)
            for block in blocks:
                if provider in block.providers:
                    blocks_from_provider.append(block)
        return blocks_from_provider

    def get_number_of_blocks_available(self):
        """
        Return the number of blocks in the system
        Returns:
             int: number of blocks in the system
        """
        return self.redis.zcard("block_index")


from rest_framework import viewsets, generics, views, response
from serializers import *
from django.db.models import Count

class PlayerViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows players to be viewed or edited.
    """
    queryset = Player.objects.all()
    serializer_class = PlayerSerializer

class DartViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows darts to be viewed or edited.
    """
    queryset = Dart.objects.all()
    serializer_class = DartSerializer

class ContestViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows darts to be viewed or edited.
    """
    queryset = Contest.objects.all()
    serializer_class = ContestSerializer

class ShotViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows darts to be viewed or edited.
    """
    queryset = Shot.objects.all()
    serializer_class = ShotSerializer

class PlayerListRandom(generics.ListAPIView):
    """
    API endpoint that lists players in a random order.
    """
    queryset = Player.objects.order_by('?')
    serializer_class = PlayerSerializer

class PlayerAccuracyList(views.APIView):
    """
    API endpoint that lists players by accuracy.
    """
    queryset = Player.objects.all()

    def get(self, request, format=None):
        players = list(self.queryset)
        players = sorted(players, key=lambda p: p.get_accuracy(), reverse=True)
        accuracies = [{"id": player.id, "name": player.name, "accuracy": player.get_accuracy()} for player in players]
        return response.Response(accuracies)

class PlayerHitsList(views.APIView):
    """
    API endpoint that lists players by hits.
    """
    queryset = Player.objects.all()

    def get(self, request, format=None):
        players = list(self.queryset)
        players = sorted(players, key=lambda p: p.get_hits(), reverse=True)
        hits = [{"id": player.id, "name": player.name, "hits": player.get_hits()} for player in players]
        return response.Response(hits)

class PlayerWinningsList(views.APIView):
    """
    API endpoint that lists players by total winnings.
    """
    queryset = Player.objects.all()

    def get(self, request, format=None):
        players = list(self.queryset)
        players = sorted(players, key=lambda p: p.get_total_winnings(), reverse=True)
        winnings = [{
            "id": player.id,
            "name": player.name,
            "winnings": player.get_total_winnings()
        } for player in players]
        return response.Response(winnings)

class WinningShotsList(views.APIView):
    """
    API endpoint that lists winning shots by amount won.
    """
    queryset = Shot.objects.all()

    def get(self, request, format=None):
        shots = list(self.queryset.filter(hit=True))
        shots = sorted(shots, key=lambda s: s.get_winnings(), reverse=True)
        winners = [{
            "id": shot.id,
            "player": shot.player.name,
            "date": shot.contest.date,
            "winnings": shot.get_winnings()
        } for shot in shots]
        return response.Response(winners)

class DartAccuracyList(views.APIView):
    """
    API endpoint that lists darts by accuracy.
    """
    queryset = Dart.objects.all()

    def get(self, request, format=None):
        darts = list(self.queryset)
        darts = sorted(darts, key=lambda d: d.get_accuracy(), reverse=True)
        accuracies = [{"id": dart.id, "name": dart.name, "accuracy": dart.get_accuracy()} for dart in darts]
        return response.Response(accuracies)

class FavoriteDartList(views.APIView):
    """
    API endpoint that lists each player's favorite dart.
    """
    queryset = Player.objects.all()

    def get(self, request, format=None):
        favorites = []
        for player in self.queryset:
            try:
                shots = player.shot_set.values("dart").annotate(num_shots=Count("dart")).order_by('-num_shots')[0]
                dart = Dart.objects.get(pk=shots.get('dart'))
                favorites.append({
                    "player_id": player.id,
                    "player_name": player.name,
                    "dart_id": dart.id,
                    "dart_name": dart.name,
                    "num_shots": shots.get('num_shots')
                })
            except IndexError:
                pass

        return response.Response(favorites)

class PotCarryoverView(views.APIView):
    """
    API endpoint that shows the amount of money carried over from the last contest.
    """
    queryset = Contest.objects.order_by('-date')

    def get(self, request, format=None):
        try:
            last_contest = self.queryset[0]
            if len(last_contest.get_winners()) > 0:
                pot = 0
            else:
                pot = last_contest.get_pot_end()
        except IndexError:
            pot = 0

        return response.Response({"pot_carryover": Decimal(pot)})


import json
import pika

subject = input("Ingrese asunto: >")
from_email = input("Ingrese email remitente: >")
to = input("Ingrese email destino: >")
body = input("Ingrese mensaje: >")

info = {
    'subject': subject,
    'from_email': from_email,
    'to': to,
    'body': body
}
data = json.dumps(info)

connection = pika.BlockingConnection(
    pika.ConnectionParameters('localhost')
)

channel = connection.channel()

channel.queue_declare(queue="send_email")

channel.basic_publish(
    exchange="",
    routing_key="send_email",
    body=data
)

print("Finalizado")

connection.close()


import urllib.request as req
import re
import os

def saveImage(url):
	global count
	global filmName
	print(url)
	file_name = filmName + "_%03d" %count
	img = req.urlopen(url).read()
	open(filmName + "/" + file_name + '.jpg','wb').write(img)
	count = count + 1

def spider(url):
	Page = req.urlopen(url).read()
	data = Page.decode('utf-8')
	file = open("urls.txt", "a")
	image_urls = re.findall("\"img_1000\":\"(\S+1000.jpg)\"", data)
	for url in image_urls:
		saveImage(url)

def main():
	global count
	global filmName
	filmName = input('Please input the name of the Moive:')
	Code = input('Please input the Code of the Moive:')
	os.mkdir(filmName)
	count = 0
	startUrl = 'http://movie.mtime.com/%s/posters_and_images/stills/hot.html'%Code
	spider(startUrl)

if __name__ == '__main__':
	main()


'''
Binary Search:
Time Complexity: O(nlog(high-low)) m is rows
Space Complexity: O(1)
Did this code successfully run on Leetcode : Yes
Explanation: Create a count of all elements of which are less than mid. low initially is first element and high is the
last element in the matrix, count all elements less than mid, if number of elements <k then move to the right by setting
mid to mid +1 else set mid to high. return low

MinHeap
Time Complexity: O(mlog k) m is rows
Space Complexity: O(m)
Did this code successfully run on Leetcode : Yes
Explanation: Push the first column of every row into a heap. Pop the smallest element and then use that row to find the
next smallest. keep doing this till u reach the kth element. The min element in the heap is the kth element.
'''

import heapq

class obj:
    def __init__(self, val, i, j):
        self.val = val
        self.i = i
        self.j = j

    def __lt__(self, other):
        return self.val < other.val

class Solution:
    def getCount(self, matrix, mid):
        length = len(matrix) - 1
        j = length
        count = 0
        for i in range(0, len(matrix)):
            while j >= 0 and matrix[i][j] > mid:
                j -= 1
            count += j + 1

        return count

    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        if k == None or matrix == None:
            return 0
        n = len(matrix)
        low = matrix[0][0]
        high = matrix[n - 1][n - 1]

        while low < high:
            mid = int(low + (high - low) / 2)
            countOfElements = self.getCount(matrix, mid)
            if countOfElements < k:
                low = mid + 1
            else:
                high = mid

        return low
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        if k == None or matrix == None:
            return 0

        heapmin = []

        for i in range(0, len(matrix)):
            temp = obj(matrix[i][0], i, 0)
            heapq.heappush(heapmin, (temp))

        while k > 1:

            mini = heapq.heappop(heapmin)

            if mini.j < len(matrix[0]) - 1:
                temp = obj(matrix[mini.i][(mini.j) + 1], mini.i, (mini.j) + 1)
                heapq.heappush(heapmin, (temp))
            k -= 1

        return heapmin[0].val


# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from rdomhelper.server import Server

class Undercloud(Server):
    def __init__(self, undercloud_ip, user, via_ip=None, key_filename=None):
        Server.__init__(self,
                        hostname=undercloud_ip,
                        user=user,
                        via_ip=via_ip,
                        key_filename=key_filename)

    def start_undercloud(self, guest_image_path, guest_image_checksum, files):
        for name, file in files.items():
            self.fetch_image(
                path=file['path'],
                checksum=file['checksum'],
                dest='/home/stack/%s.tar' % name,
                user='stack')
            self.run('tar xf /home/stack/%s.tar' % name,
                     user='stack')
        self.fetch_image(
            path=guest_image_path,
            checksum=guest_image_checksum,
            dest='/home/stack/guest_image.qcow2',
            user='stack')
        hostname_s = self.run('hostname -s')[0].rstrip('\n')
        hostname_f = self.run('cat /etc/hostname')[0].rstrip('\n')
        self.run("sed 's,127.0.0.1,127.0.0.1 %s %s,' /etc/hosts" % (hostname_s, hostname_f))
        self.set_selinux('permissive')
        self.run('openstack undercloud install', user='stack')
        self.add_environment_file(user='stack', filename='stackrc')
        self.run('heat stack-list', user='stack')
        self.run('openstack overcloud image upload', user='stack')
        self.run('openstack baremetal import --json instackenv.json', user='stack')
        self.run('openstack baremetal configure boot', user='stack')
        self.run('openstack flavor create --id auto --ram 4096 --disk 40 --vcpus 1 baremetal', user='stack', success_status=(0, 1))

    def start_overcloud(self):
        self.run('openstack flavor set --property "cpu_arch"="x86_64" --property "capabilities:boot_option"="local" baremetal', user='stack')
        self.run('for uuid in $(ironic node-list|awk \'/available/ {print$2}\'); do ironic node-update $uuid add properties/capabilities=profile:baremetal,boot_option:local; done', user='stack')
        self.run(('openstack overcloud deploy --debug '
                  '--templates '
                  '--log-file overcloud_deployment.log '
                  '--libvirt-type=qemu '
                  '--neutron-network-type vxlan '
                  '--neutron-tunnel-types vxlan '
                  '--ntp-server north-america.pool.ntp.org '
                  '--control-scale 1 '
                  '--compute-scale 1 '
                  '--ceph-storage-scale 0 '
                  '--block-storage-scale 0 '
                  '--swift-storage-scale 0 '
                  '--control-flavor baremetal '
                  '--compute-flavor baremetal '
                  '--ceph-storage-flavor baremetal '
                  '--block-storage-flavor baremetal '
                  '--swift-storage-flavor baremetal'), user='stack')


# coding=utf-8
"""这个模块用来返回搜索结果"""
from whoosh.index import create_in,open_dir
from whoosh import query,qparser
from whoosh.fields import *
from jieba.analyse import ChineseAnalyzer
import json
from generateIndex import pageRank
from resultsProcess import resultProcess

def searchName(name):
    # 存储schema信息至'indexdir'目录下
    indexdir = 'indexdir/'
    ix=open_dir(indexdir)
    # 创建一个检索器
    searcher = ix.searcher()

    # 检索标题中出现'文档'的文档
    results = searcher.find("name",name)

    results=resultProcess(results)

    return results

def searchIntro(query_string):
    # 存储schema信息至'indexdir'目录下
    indexdir = 'indexdir/'
    ix=open_dir(indexdir)
    # 创建一个检索器
    searcher = ix.searcher()

    #对intro和basic共同进行搜索，得到的结构合并
    qp1 = qparser.QueryParser("intro", ix.schema)
    qp2 = qparser.QueryParser('basic', ix.schema)
    user_q1 = qp1.parse(query_string)
    user_q2 = qp2.parse(query_string)

    results1 = searcher.search(user_q1,limit=None)
    results = searcher.search(user_q2,limit=None)
    results.extend(results1)

    results = resultProcess(results)
    # 检索标题中出现'文档'的文档
    return results


import re

file = str(input("File name: "))
f = open(file, 'r')
lines = f.readlines()

title_re = re.compile('>(\S+)')
notitle_re = re.compile('^(\S+)')

total_count = 0
nucleotide_count = {'A': 0, 'T': 0, 'G': 0, 'C': 0}
gc_content = 0

DNAseq_str = []

for line in lines:
	outh = title_re.search(line)
	if outh:
		continue
	else:
		outl = notitle_re.search(line)
		outm = outl.group(1)
		DNAseq = list(outm)
		DNAseq_str += DNAseq

for i in range(1, len(DNAseq_str)+1):
	total_count += 1

for i in DNAseq_str:
	nucleotide_count[i] += 1

gc_content = ((nucleotide_count['G'] + nucleotide_count['C'])/total_count)*100

print(nucleotide_count)
print('GC content: ',gc_content)
print('Total: ',total_count)


import numpy as np
import torch
from torchvision.utils import save_image
from tqdm import tqdm

from model import Generator
from sampling import sample, get_cycling_grid_same, n_classes

device = 'cuda'

model = Generator(n_feat=36, codes_dim=24, n_classes=n_classes).to(device)
model.load_state_dict(torch.load('generator.pth'))

height = 8
width = 15
cycles = 8
frames_per_half_cycle = 24*4
all_zs = get_cycling_grid_same(height, width, cycles, frames_per_half_cycle)

for f_idx in tqdm(range(all_zs.size(2))):
    z_batch = all_zs[:, :, f_idx]
    z_batch = z_batch.view(-1, 120)

    aux_labels = np.arange(120)

    images = sample(model, z_batch, aux_labels=aux_labels)

    frame = torch.empty((3, height * 64, width * 64), device=device)
    for h in range(height):
        for w in range(width):
            frame[:, h * 64:(h + 1) * 64, w * 64:(w + 1) * 64] = images[h * width + w]
    save_image(frame, 'breed_frames/{}.png'.format(f_idx))


class Solution:
    # @param matrix, a list of lists of integers
    # @return a list of lists of integers
    def rotate(self, matrix):
        '''hint: reverse the matrix first,
        then interchange elements along the diagonal'''
        matrix = matrix[::-1]
        for row in range(0, len(matrix)):
            for col in range(row, len(matrix)):
                t = matrix[col][row]
                matrix[col][row] = matrix[row][col]
                matrix[row][col] = t
        return matrix


#!/usr/bin/env python3
# Converts the Bazaar CSV copied from https://ffxii.us/bazaar into a JSON file
import csv
import json

def convert():
    data = []
    with open('bazaar.csv') as f:
        reader = csv.reader(f)
        id = 1
        for row in reader:
            package, price, loot, reward = row
            loot = split_items(loot)
            reward = split_items(reward)
            data.append({
                'id': id,
                'package': package,
                'price': price,
                'loot': loot,
                'reward': reward
            })
            id += 1
    with open('bazaar.json', 'w') as f:
        json.dump(data, f, indent=2)

def split_items(raw):
    rows = raw.split('\n')
    pairs = [row.split(' x') for row in rows]
    items = [{
        'name': p[0],
        'quantity': int(p[1]) if len(p) > 1 else 1
    } for p in pairs]
    return items

if __name__ == "__main__":
    convert()


lista = enumerate('zero um dois três quatro cinco seis sete oito nove'.split())
num_str=dict(lista)
string_numero={valor:chave for chave,valor in num_str.items()}
print (num_str)
print(string_numero)

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

def to_num(n):
    num=[]
    for digit in str(n):
        num.append(num_str[int(digit)])
    return ", ".join(num)

assert "um" == to_num(1)
assert "dois, dois" == to_num(22)

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

def to_int(string_n):
    string=""
    lista=string_n.split(", ")
    for digit in lista:
        string+=str(string_numero[digit])
    return int(string)

assert 1== to_int('um')
assert 22== to_int('dois, dois')


from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
import uuid

class Game(models.Model):
	name = models.CharField(max_length=200, default='None', blank=False, null=True)
	description = models.TextField(default='Describe the Game Here!', blank=False, null=True)
	number_of_participants = models.PositiveIntegerField(verbose_name='Number Of Participants', blank=False, null=True)
	estimated_length = models.PositiveIntegerField(verbose_name='Estimated Length', default=10, blank=False, help_text='Minutes')
	communities = models.ManyToManyField(CommunityInstance )

	def __str__(self):
		return '{}'.format(self.name)

class Talent(models.Model):
	name = models.CharField(primary_key=True, max_length=200, help_text='Use what was done, Piano, Story, Violion, Etc', blank=False)
	description = models.TextField(default='Describe the talent here!', blank=True, null=True)
	author = models.CharField(max_length=200, help_text='Name the Preformer (optional)', blank=True, null=True)

	def __str__(self):
		return '{}'.format(self.name)

class CommunityInstance(models.Model):
	id = models.SlugField(primary_key=True, default=uuid.uuid4, unique=True)
	date = models.DateField(blank=False)

	number_of_games = models.PositiveIntegerField(blank=False, default=1)
	games = models.ManyToManyField(Game, help_text='Select the games that appeard this community!', blank=True)

	number_of_announcements = models.PositiveIntegerField(default=3, blank=False)
	length_of_announcements = models.PositiveIntegerField(default=10, help_text='minutes')
	announcements_made = models.TextField()

	host = models.CharField(max_length=20)

	number_of_talent = models.PositiveIntegerField(blank=False, verbose_name="Number of Student Preformances")
	talent = models.ManyToManyField(Talent, blank=True, help_text='Enter all the talent that was preformed, if there was no talent preformed, don\'t select anything. If the talent that was preformed is not listed, use the + button to add it to the list.')

	number_of_it_awards = models.PositiveIntegerField(blank=False, default=0, verbose_name='Independent Thinker Awards')
	number_of_pc_awards = models.PositiveIntegerField(blank=False, default=0, verbose_name='Profiles in Courage Awards')
	number_of_ds_awards = models.PositiveIntegerField(blank=False, default=0, verbose_name='Durkheim Scholar Awards')
	number_of_gp_awards = models.PositiveIntegerField(blank=False, default=0, verbose_name='Gary Phillips Awards')

	minutes_end_early = models.PositiveIntegerField(default=15, help_text='in minutes', verbose_name="Minutes Left When Community Ended")

	class Meta:
		verbose_name = 'Community Instance'
		verbose_name_plural = 'Community Instances'

	def __str__(self):
		return '{}'.format(self.date)

class CommunityInstanceReview(models.Model):
	user = models.ForeignKey(User, blank=False)
	community = models.ForeignKey(CommunityInstance, blank=False)


from PIL import Image
import cv2
import imutils

image = cv2.imread(r".jpg")
resized = imutils.resize(image, width=300)
ratio = image.shape[0] / float(resized.shape[0])

# convert the resized image to grayscale, blur it slightly,
# and threshold it
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]

# find contours in the thresholded image and initialize the
# shape detector
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[0]
cnts = imutils.grab_contours(cnts)

image2=Image.open('cloth.jpg')
peri = cv2.arcLength(cnts, True)
approx = cv2.approxPolyDP(c, 0.04 * peri, True)
(x, y, w, h) = cv2.boundingRect(approx)

croppedIm = image2.crop((x,y,x+w,y+h))

croppedIm.save('cropped.jpg')