import os
import time
import shutil
import argparse

import torch
import torchvision
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
from torchsummary import summary

import pretrainedmodels

from core.dataset import create_dataset
from core.models import create_model
from core.options.train_options import TrainOptions

opt = TrainOptions().parse()   # get training options
test_dataset = create_dataset(opt, opt.test_split_file)    # create train dataset given opt.dataset_mode and other options

test_dataset_size = len(test_dataset)    # get the number of images in the dataset.

print('The number of testing images = %d' % test_dataset)

# training options
batch_size = opt.batch_size
lr = opt.lr
momentum = opt.momentum

input_size = opt.input_size
input_channel = opt.input_nc

# model
model = create_model(opt)   # create a model given opt.model and other options
model.prepare_model()       # regular setup: load and print networks; create schedulers

if torch.cuda.is_available():
    model.cuda()

# printing to widget
print("----------------------------------------------------------------------------------------")
print("TRAINING SESSION:")
print("Model: %s" % model.__class__.__name__)
print("Dataset: %s" % test_dataset.__class__.__name__)

print("=======================================")
print("HYPERPARAMS: ")
print("Batch-size: %d" % batch_size)
print("Initial learning rate: %s" % lr)

print("========================================")
print("SUMMARY")
print("%s" % summary(model, (input_channel, input_size, input_size)))

print("BEGIN: %s" % time.time())

epoch_start_time = time.time()  # timer for entire epoch
iter_data_time = time.time()    # timer for data loading per iteration

running_acc = 0.0
running_loss = 0.0

model.eval()

for i, (data, labels) in enumerate(test_dataset):
    if torch.cuda.is_available():
        data = data.cuda()
        labels = labels.cuda()

    with torch.no_grad():
        outputs = model(data)
        loss = model.criterion(outputs, labels)

        # evaluate model
        _, preds = torch.max(outputs.data, 1)
        acc = torch.mean((preds == labels.data).float())

        running_acc += acc
        running_loss += loss.data

# average acc and loss over 1 epoch
running_acc = running_acc / len(test_dataset) * batch_size
running_loss = running_loss / len(test_dataset) * batch_size

avg_log_tmpl = (
    ".. Test Avg Acc: {:2.4f} Test Avg Loss: {:2.4f} "
)

print(avg_log_tmpl.format(
    running_acc, running_loss,
))

print("----------------------------------------------------------------------------------------")
print("TESTING SESSION:")
print('*' * 100)


#lists
months = ["January", "february", "March", "March"]

months.remove("March")
print(months)

#tuples - immunable
names = ("January", "february", "March")

#sets - no order
sets = {"January", "february", "March"}
friend = {"Steve", "John", "Bob"}
abroad = {"Wayne", "Bob"}

print(abroad.difference(friend))

user_input = input("Would you like to play? Enter, 'y' for Yes: ")

if user_input in ("y", "Y"):
    print("Ok, Let's Play a Game")

numbers1 = [23, 34, 54, 56, 76, 87]
# List comprehension
doubled1 = [n * 2 for n in numbers1]
print(doubled1)

numbers = [23, 34, 54, 56, 76, 87]
doubled = []
for n in numbers:
    doubled.append(n * 2)
print(doubled)

friend = ['Steve', 'Scott', 'Andrea']
friends = [f for f in friend if f.startswith("S")]
print(friends)

#print(len(numbers))
#print(sum(numbers))


class Solution:
    def matrixReshape(self, nums, r, c):
        return [[nums[(c * j + i) // len(nums[0])][(c * j + i) % len(nums[0])] for i in range(c)] for j in range(r)] \
                if len(nums) * len(nums[0]) == r * c else nums

nums1 = [[1, 2], [3, 4]]
r = 1
c = 4
sol = Solution()
print(sol.matrixReshape(nums1, 1, 4))
print(sol.matrixReshape([[1, 2, 3, 4]], 2, 2))

competitiveprogramming-python/src/com/mounacheikhna/leetcode/easy/566. Reshape the Matrix.py


'''Loads every item on the GW2 trading post (i.e. every item on api.guildwars2.com/v2/commerce/prices).
Takes the items and maps them to a csv that associates each item name to its id.'''

import sys
import time
import urllib3
import certifi
import json

pricesUrl = "https://api.guildwars2.com/v2/commerce/prices"
itemsUrl = "https://api.guildwars2.com/v2/items"

Items = {}

def bytesToJson(bytes):
    '''Given bytes string, parse bytes as a json object and return the object.
    Replaces any instance of ' in the string with ".'''
    return json.loads(str(bytes).strip("'b").replace("'", '"'))

def percentStr(percent=1):
    '''Given a number percent, returns a formatted string percentage. Accepts the decimal value of the percentage.'''
    return '{0:8.4%}'.format(percent)

def formatSeconds(secs):
    '''Transforms secs into a string in HHH:MM:SS format. Supports up to 3,599,999 seconds.'''
    if secs > 3599999:
        secs = 3599999
    m, s = divmod(secs,60)
    h, m = divmod(m,60)
    return '{:3}:{:02}:{:02}'.format(int(h), int(m), int(s))

def timeRemaining(progress, time):
    '''Calculates the time remaining given current progress and time taken so far.'''
    if progress == 1:
        return 0
    return time / progress - time

http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
def request(url):
    '''Returns json object representing the data given by the specified url.'''
    return bytesToJson(http.request('GET', url).data)

itemsOnMarket = request(pricesUrl)
count = 0
total = len(itemsOnMarket)
startTime = time.time()
for item in itemsOnMarket:
    try:
        itemData = request(itemsUrl + '/' + str(item))
        key = itemData['name'].replace('"', "'")
        Items[key] = item
        count += 1
        progress = count / total
        totalTime = time.time() - startTime
        print('\r' + percentStr(progress) + '\tTime remaining: ' + formatSeconds(timeRemaining(progress, totalTime)), end='', flush=True)
    except KeyboardInterrupt:
        print('Aborting')
        break
    except:
        print('\r', sys.exc_info()[0], ' occurred while processing item ' + str(item) + '. Skipping...')
        continue

if Items:
    print('Writing name/id pairs to names.csv')
    with open('names.csv', 'w') as file:
        file.write('name, id\n')
        for name in Items:
            file.write('"' + name + '",' + str(Items[name]) + '\n')
    print('Done')


import os
import numpy as np
from matplotlib import pyplot as plt
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

f = open(os.path.join('..', 'inClassExample_LDA.txt'))
original_data = f.readlines()
f.close()

f = open('inClassExample_rebuilt_lda_1.csv')
data_lda = f.readlines()
f.close()

f = open('inClassExample_rebuilt_comp_1.csv')
data_pca = f.readlines()
f.close()

for i in range(len(data_lda)):
    original_data[i] = np.array(original_data[i].split())

    data_lda[i] = ''.join(data_lda[i].split())
    data_lda[i] = np.array(data_lda[i].split(','))

    data_pca[i] = ''.join(data_pca[i].split())
    data_pca[i] = np.array(data_pca[i].split(','))
data_lda = np.array(data_lda)
original_data = np.array(original_data)
data_pca = np.array(data_pca)

# f = open(os.path.join('inClassExample_lda_vectors.csv'))
# components = f.readlines()
# f.close()

# for i in range(len(components)):
#     components[i] = np.array(components[i].split(','), dtype=np.float)
# components = np.array(components)

# print components

X_lda = {}
X_orig = {}
X_pca = {}
X2 = data_lda[:, :2].astype(dtype=np.float)
y = data_lda[:, -1].astype(dtype=str)\

for i in range(len(data_lda)):
    obs_class = y[i]
    if obs_class not in X_lda.keys():
        X_lda[obs_class] = []
        X_orig[obs_class] = []
        X_pca[obs_class] = []
    X_lda[obs_class].append(data_lda[i, :2])
    X_orig[obs_class].append(original_data[i, :2])
    X_pca[obs_class].append(data_pca[i, :2])

# components = np.matrix(components)

# lda = LinearDiscriminantAnalysis(solver='eigen')
# lda.fit(X2, y)
#
# lda_coef = np.array(lda.coef_[0])
# print lda_coef

for key in X_lda.keys():
    X_lda[key] = np.matrix(X_lda[key], dtype=np.float)
    X_orig[key] = np.matrix(X_orig[key], dtype=np.float)
    X_pca[key] = np.matrix(X_pca[key], dtype=np.float)

    # X[key] = components[:, 0].transpose() * X[key].transpose()
    # X[key] = (np.linalg.inv(components.transpose())[:, 0] * X[key]).transpose()
    # print '{}:\n'.format(key), X[key]

    # X[key] = lda_coef * X[key].transpose()
    # X[key] = (np.linalg.inv(lda_coef) * X[key]).transpose()
    # print '{}:\n'.format(key), X[key]

# cp_order = [x for x in range(len(X2[0]))]
cp_order = [x for x in range(len(X2[0])-1, -1, -1)]

data_mean = np.array([3.18182, 2.72727])

# comp_X = np.array([-3, 0, 4])
# comp_Y = [x*components[cp_order[0], 0]/components[cp_order[1], 0] for x in comp_X]
# comp_Y = [x*components[cp_order[0], 0] for x in comp_X]
# comp_Y = [x*components[cp_order[0], 1]/components[cp_order[1], 1] for x in comp_X]
# comp_Y2 = [x*components[cp_order[0], 1] for x in comp_X]

# comp_Y2 = [x*lda_coef[cp_order[0]]/lda_coef[cp_order[1]] for x in comp_X]

plt.grid(linestyle=':')
# plt.plot(comp_X + data_mean[0], comp_Y + data_mean[1], 'b')
# plt.plot(comp_X + data_mean[0], comp_Y2 + data_mean[1], 'g')
x = X_orig['2']
plt.plot(x[:, 0], x[:, 1], 'bo', label='classe 2')
x = X_orig['1']
plt.plot(x[:, 0], x[:, 1], 'rx', label='classe 1')
plt.legend()
# plt.plot(data_mean[0], data_mean[1], 'kX')
plt.savefig(os.path.join('plots', 'inClassExample.png'))

plt.show()

plt.grid(linestyle=':')
# plt.plot(comp_X + data_mean[0], comp_Y + data_mean[1], 'b')
# plt.plot(comp_X + data_mean[0], comp_Y2 + data_mean[1], 'g')
x = X_pca['2']
plt.plot(x[:, 0], x[:, 1], 'bo', label='classe 2')
x = X_pca['1']
plt.plot(x[:, 0], x[:, 1], 'rx', label='classe 1')
plt.legend()
# plt.plot(data_mean[0], data_mean[1], 'kX')
plt.savefig(os.path.join('plots', 'inClassExample_pca.png'))

plt.show()

plt.grid(linestyle=':')
# plt.plot(comp_X + data_mean[0], comp_Y + data_mean[1], 'b')
# plt.plot(comp_X + data_mean[0], comp_Y2 + data_mean[1], 'g')
x = X_lda['2']
plt.plot(x[:, 0], x[:, 1], 'bo', label='classe 2')
x = X_lda['1']
plt.plot(x[:, 0], x[:, 1], 'rx', label='classe 1')
plt.legend()
# plt.plot(data_mean[0], data_mean[1], 'kX')
plt.savefig(os.path.join('plots', 'inClassExample_lda.png'))

plt.show()


import numpy as np
import math
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import LabelEncoder
data_path = "D:/unique studio/熬测/联创有限公司裁员表/联创有限公司裁员表.csv"

learning_rate = 0.0001
def preprocess(data_path):
    f = open(data_path)
    data = pd.read_csv(f)
    str_cols = data.select_dtypes(
        exclude=[np.number]).columns  # str_cols为为字符串的列
    flt_cols = data.select_dtypes(include=[np.number]).columns
    s = []  # s为存在缺失值的列数
    z = data.columns
    transform = LabelEncoder()

    for i in z:
        if data[i].isnull().sum() != 0:
            s.append(i)

    for i in range(len(s)):
        data[s[i]].fillna(data[s[i]].mode().values[0],
                          inplace=True)  # 对缺失值均使用众数进行填充

    for i in str_cols:
        data_new = transform.fit_transform(data[i])
        data[i] = pd.DataFrame(data_new)

    return data

class sigmoid(object):
    def __init__(self, input=None):
        self.input = input

    def forward(self):
        return 1 / (1 + math.e ** self.input)

    def backward(self, grad):
        return self.forward() * (1 - self.forward())

class relu(object):
    def __init__(self, input=None):
        self.input = input

    def forward(self):
        return np.maximum(0, self.input)

    def backward(self, grad):
        return grad*(self.input > 0).astype(int)

class tanh(object):
    def __init__(self, input=None):
        self.input = input

    def forward(self):
        return (math.e ** self.input - math.e ** (-self.input))/(math.e**self.input+math.e**(-self.input))

    def backward(self, grad):
        return 1 - self.forward() ** 2

class dense(object):
    def __init__(self, input=None, shape=None):
        self.input = input
        self.weight = np.random.randn(shape[0], shape[1])
        self.bias = np.random.randn(shape[-1])

    def forward(self):
        return np.dot(self.input, self.weight) + self.bias.T

    def backward(self, grad):
        grad_weight = np.dot(self.input.T, grad) / \
            self.input.shape[0]  # 总认为input的第一维为每个batch的
        grad_bias = grad.mean(axis=0)  # axis=0 压缩行，对各列求均值
        grad_input = np.dot(grad, self.weight.T)
        self.weight = self.weight - learning_rate * grad_weight
        self.bias = self.bias - learning_rate * grad_bias
        return grad_input

class mseloss(object):
    def __init__(self, input):
        self.input = input

    def forward(self, label):
        return np.square(self.input - label).sum()

    def backward(self, label):
        return 2 * (self.input - label)

class batchnorm(object):
    def __init___(self, input):
        self.input = input
        self.w = 1
        self.b = 0
    def forward(self):
        mean = self.input.mean()
        sq = ((self.input - mean)** 2).sum() / self.input.shape[0]
        x_norm = (self.input - mean) / math.sqrt(sq + 0.01)
        return self.w * x_norm + self.b
    def backward(self, grad):
        grad_w = (grad * x_norm).mean()
        grad_b = grad.mean()
        grad_input = self.w * grad
        self.w = self.w - learning_rate * grad_w
        self.b = self.b - learning_rate * grad_b
        return grad_input

def forward(network, input):
    data = input
    for i in network:
        i.input = data
        data = i.forward()
    return data

def backward(network, grad, label):
    grad = mseloss(grad).backward(label.reshape([-1, 1]))
    for i in list(reversed(network)):
        grad = i.backward(grad)
    return

def evaluate_net(network, x, y):
    data = forward(network, x)
    loss = mseloss(data).forward(y.reshape(data.shape))/data.shape[0]
    t = data
    t = (t > 0.5).astype(int)
    accuracy = (t == y.reshape([-1, 1])).astype(
        int).sum() / y.shape[0]
    return [loss, accuracy]

if __name__ == '__main__':
    network = [dense(shape=[32,200]),relu(),dense(shape=[200,1])]
    data = preprocess(data_path)
    x = data.drop(['Attrition'], axis=1).values
    y = data['Attrition'].values
    mean = x.mean()
    sq = ((x - mean)** 2).mean()
    x = (x - mean) / math.sqrt(sq + 0.01)
    # network = [dense(shape=[32, 20]), relu(), dense(shape=[20, 1])]
    for i in range(50000):
        batch_size = 200
        X = x[(i * batch_size) %
                    200:min((i * batch_size) % 1000 + batch_size, 1470)]
        Y = y[(i * batch_size) %
                    200:min((i * batch_size) % 1000 + batch_size, 1470)]
        data = forward(network, x)
        backward(network, data, y)
        if i % 50 == 0:
            result = evaluate_net(network, x, y)
            print("after %d iteration,MSE is %s,accuaracy is %s" %
                (i, result[0], result[1]))


#https://codeforces.com/contest/1473/problem/B

import math
tests = int(input())

def lcm(a, b):
    return abs(a*b) // math.gcd(a, b)

for i in range(tests):
    word1= input()
    word2= input()
    lword1=len(word1)
    lword2=len(word2)

    k= lcm(lword1,lword2)

    word1=(k//lword1)*word1
    word2 = (k // lword2) * word2

    if(word1==word2):
        print(word1)
    else:
        print(-1)

CodeForces/Educational Codeforces Round 102 (Rated for Div. 2)/B. String LCM.py


import logging
import pandas as pd
from load_model.generics import task as t
from load_model.generics.file_type_enum import SupportedFileReadType

logger = logging.getLogger('LCTK_APPLICATION_LOGGER')

class HeatcoolIndexer(t.Task):
    def __init__(self, name, pipeline_artifact_dir):
        super().__init__(self)
        self.name = name
        self.pipeline_artifact_dir = pipeline_artifact_dir
        self.data_files = [
            { 'name': f'{pipeline_artifact_dir}/area_loads.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/594.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/596.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/597.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/598.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/833.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/835.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/836.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/837.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/838.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/970.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/971.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/972.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/973.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/974.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/980.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/981.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/982.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/983.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/984.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/985.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/988.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/989.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/990.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/991.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/992.csv', 'read_type': SupportedFileReadType.DATA },
            { 'name': f'{pipeline_artifact_dir}/noaa/993.csv', 'read_type': SupportedFileReadType.DATA },
        ]
        self.task_function = self._task
        self.output_artifact_enduse_loads = f'{pipeline_artifact_dir}/enduse_loads.csv'

        self.data_map = None
        self.df = None

        # these should be read from config, they are different for RBSA and CEUS
        self.theat = 15
        self.tcool = 25

    def _save_data(self):
        self.save_data(self.df)

    def _get_data(self):
        self.data_map = self.load_data(self.data_files)
        self.df = self.data_map[f'{self.pipeline_artifact_dir}/area_loads.csv']

    def _task(self):
        self._get_data()

        zipcodes = self.df.zipcode.unique()
        enduse_loads = pd.DataFrame()

        for zipcode in zipcodes:
            zipcode_df = self.df.loc[self.df.zipcode == zipcode]
            zipcode_df = zipcode_df.reset_index()

            filename = f'{self.pipeline_artifact_dir}/noaa/{str(zipcode)}.csv'
            zipcode_weather = self.data_map[filename]

            # validation for date ranges of zip codes load data date range to noaa data for that zipcode
            if (zipcode_df.time.max() > zipcode_weather.DATE.max()) | (zipcode_df.time.min() < zipcode_weather.DATE.min()):
                logger.exception(f'Task {self.name} did not pass validation. Error found in matching noaa weather file date range to {zipcode} zip code.')
                self.did_task_pass_validation = False
                self.on_failure()

            # make start and end dates of weather data match load
            start = zipcode_df.time.min()
            end = zipcode_df.time.max()

            zipcode_weather = zipcode_weather.loc[(zipcode_weather.DATE >= start) & (zipcode_weather.DATE <= end)]

            load_df = pd.DataFrame(columns=['HeatCool', 'Temperature', 'Indexer','Heating', 'Cooling', 'Ventilation', 'HeatCoolVent'])

            # apply indexing
            load_df['HeatCool'] = zipcode_df['HeatCool']
            load_df['Temperature'] = zipcode_weather['Temperature']
            load_df['Indexer'] = zipcode_weather.apply(self.temp_dir, axis=1)
            load_df['Heating'] = load_df.apply(self.heat_method, axis=1)
            load_df['Cooling'] = load_df.apply(self.cool_method, axis=1)
            load_df['HeatCoolVent'] = load_df.apply(self.vent_method, axis=1)

            load_df['Heating'] = load_df['Heating'] + (load_df['HeatCoolVent'] / 3)
            load_df['Cooling'] = load_df['Cooling'] + (load_df['HeatCoolVent'] / 3)
            load_df['Ventilation'] = load_df['HeatCoolVent'] / 3

            load_df = load_df.fillna(0)

            enduses_updated = ['Heating', 'Cooling', 'Ventilation']

            # zipcode_df['Ventilation'] = 0 # no ventilation coming in

            # apply changes
            for enduse in enduses_updated:
                zipcode_df[enduse] = zipcode_df[enduse] + load_df[enduse]

            enduse_loads = enduse_loads.append(zipcode_df)

        enduse_loads = enduse_loads.drop('HeatCool', axis=1)
        enduse_loads = enduse_loads.set_index('time')
        enduse_loads = enduse_loads.drop('index', axis=1)

        self.validate(enduse_loads)
        self.on_complete({self.output_artifact_enduse_loads: enduse_loads})

    def temp_dir(self, row):
        """
        Function used for seperating heatcool
        """
        if row['Temperature'] < self.theat:
            return "Heating"
        if row['Temperature'] > self.tcool:
            return "Cooling"
        return "Ventilation"

    def heat_method(self, row):
        """
        Function used for seperating heat from heatcool
        """
        if row['Indexer'] == "Heating":
            return row['HeatCool']
        return 0

    def cool_method(self, row):
        """
        Function used for seperating cool from heatcool
        """
        if row['Indexer'] == "Cooling":
            return row['HeatCool']
        return 0

    def vent_method(self, row):
        """
        Function used for seperating vent from heatcool
        """
        if row['Indexer'] == "Ventilation":
            return row['HeatCool']
        return 0

    def validate(self, df):
        """
        Validation
        """
        logger.info(f'Validating task {self.name}')
        if df.isnull().values.any():
            logger.exception(f'Task {self.name} did not pass validation. DataFrame contains null values when it should not.')
            self.did_task_pass_validation = False
            self.on_failure()

    def on_failure(self):
        logger.info('Perform task cleanup because we failed')
        super().on_failure()


import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
data=pd.read_csv("A.csv",sep=";")
s=data[["G3","traveltime"]]
q=data[["G3","traveltime"]]
plt.scatter(s["traveltime"],s["G3"])
plt.title("The traveltime vs gradepoint graph")
plt.show()
kmeans=KMeans(n_clusters=3)
kmeans.fit(q)
s["healthw"]=None#healthw is equivalent to traveltime in words
for i in range(0,len(s)):
    if s["traveltime"][i]==1:
        s["healthw"][i]="<15 min"
    elif s["traveltime"][i] == 2:
        s["healthw"][i] = "15 to 30 min"
    elif s["traveltime"][i] == 3:
        s["healthw"][i] = "30 min to 1 hour"
    elif s["traveltime"][i] == 4:
        s["healthw"][i] = "> 1 hour "
colors=np.array(["Red","Blue","Green"])
plt.scatter(s["healthw"],s["G3"],color=colors[kmeans.labels_])
plt.title("The traveltime vs Gradepoint cluster")
plt.xlabel("Travel time")
plt.ylabel("Grade point")
plt.show()
s=s.groupby(["traveltime","healthw"])["G3"].mean()
s=s.reset_index()
print(s)
q=s[["traveltime","G3"]]
kmeans=KMeans(n_clusters=3)
kmeans.fit(q)
colors=np.array(["Red","Blue","Green"])
plt.scatter(s["healthw"],s["G3"],color=colors[kmeans.labels_])
plt.title("The traveltime vs Gradepoint cluster")
plt.xlabel("Travel time")
plt.ylabel("Grade point")
plt.show()


'''
Created on May 16, 2013

@author: Toshiba
'''
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import ui_snorttab

class view(QDialog, ui_snorttab.Ui_Form):

    def __init__(self,  parent=None):
        super(view, self).__init__(parent)
        self.setupUi(self)
        #header = self.tableWidget.horizontalHeader()
        #header.setStretchLastSection(True)
        self.tableWidget.setRowCount(1)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    form = view()
    form.show()
    app.exec_()


#!/usr/bin/env python3
import urllib.request
import xml.dom.minidom as dom

class rssReader:

    def __init__(self, url):
        self.url = url

        resp = urllib.request.urlopen(self.url)
        data = resp.read()
        text = data.decode('UTF-8')
        self.xmlDocument = dom.parseString(text)

    def searchTag(self, tag):
        self.tag = tag

        for node in self.xmlDocument.getElementsByTagName(self.tag):
            print(node.toxml())

    def createList(self, tag):
        self.tag = tag
        self.elementList = []

        for node in self.xmlDocument.getElementsByTagName(self.tag):
            self.elementList.append(node.toxml())
        return self.elementList

    def compare(self, updatedList, oldList):
        self.updatedList = updatedList
        self.oldList = oldList
        self.newUpdateList = []

        for uElement in self.updatedList:
            if not uElement in self.oldList:
                self.newUpdateList.append(uElement)
        return self.newUpdateList

    def saveList(self, fileName, saveList):
        self.saveList = saveList

        outFile = open(fileName, "wt")
        for element in self.saveList:
            outFile.write(element + " \n")
        outFile.close()

    def readList(self, fileName):
        self.list = []
        self.aList = []
        self.fileName = fileName

        inFile = open(self.fileName, "rt")
        while True:
            line = inFile.readline()
            if(len(line) == 0):
                break
            else:
                self.list.append(line)
        inFile.close()
        for element in self.list:
            self.aList.append(element.strip())
        return self.aList


from __future__ import print_function
from keras.callbacks import LambdaCallback
from keras.models import Sequential, load_model
from keras.layers import Dense, Activation
from keras.layers import LSTM
from keras.optimizers import RMSprop
from keras.utils.data_utils import get_file
import numpy as np
import random
import sys
import io
import argparse

DEFAULT_TEXT_FILE='corpus.txt'
DEFAULT_MODEL_FILE='model.h5'
DEFAULT_EPOCHS=60

DESCRIPTION = """
Example script to build a model from example texts, and
generate synthetic texts from that model, using LSTMs.
At least 20 epochs are required before the generated text
starts sounding coherent.

It is recommended to run this script on GPU, as recurrent
networks are quite computationally intensive.
Make sure your corpus has at least ~100k characters.
~1M is better.

Based on a script from the Keras Team at
https://github.com/keras-team/keras/tree/master/examples
"""

parser = argparse.ArgumentParser(
    description=DESCRIPTION,
    epilog="",
    formatter_class=argparse.ArgumentDefaultsHelpFormatter
)

parser.add_argument('-t', '--text', type=str, nargs='?', const=DEFAULT_TEXT_FILE,
                    required=True, help='text file from which to build the model')
parser.add_argument('-f', '--fit', action='store_true',
                    help='fit the model to the text file')
parser.add_argument('-e', '--epochs', type=int, nargs='?', const=DEFAULT_EPOCHS,
                    help='number of training epochs')
parser.add_argument('-s', '--save', type=str, nargs='?', const=DEFAULT_MODEL_FILE,
                    help='save the model to the given file')
parser.add_argument('-l', '--load', type=str, nargs='?',
                    help='load the model from the given file')
parser.add_argument('-g', '--generate', action='store_true',
                    help='generate examples from the model (either one built via -f, or one loaded via -l), taking seeds from the file given by -t')

args = parser.parse_args()

epochs=args.epochs
path=args.text

with io.open(path, encoding='utf-8') as f:
    text = f.read().lower()
print('corpus length:', len(text))

chars = sorted(list(set(text)))
print('total chars:', len(chars))
char_indices = dict((c, i) for i, c in enumerate(chars))
indices_char = dict((i, c) for i, c in enumerate(chars))

# cut the text in semi-redundant sequences of maxlen characters
maxlen = 40
step = 3
sentences = []
next_chars = []
for i in range(0, len(text) - maxlen, step):
    sentences.append(text[i: i + maxlen])
    next_chars.append(text[i + maxlen])
print('nb sequences:', len(sentences))

# Vectorize text and build the model
if args.fit:

  print('Vectorization...')
  x = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool)
  y = np.zeros((len(sentences), len(chars)), dtype=np.bool)
  for i, sentence in enumerate(sentences):
      for t, char in enumerate(sentence):
          x[i, t, char_indices[char]] = 1
      y[i, char_indices[next_chars[i]]] = 1

  # build the model: a single LSTM
  print('Build model...')
  model = Sequential()
  model.add(LSTM(128, input_shape=(maxlen, len(chars))))
  model.add(Dense(len(chars)))
  model.add(Activation('softmax'))

  optimizer = RMSprop(lr=0.01)
  model.compile(loss='categorical_crossentropy', optimizer=optimizer)

def sample(preds, temperature=1.0):
    # helper function to sample an index from a probability array
    preds = np.asarray(preds).astype('float64')
    preds = np.log(preds) / temperature
    exp_preds = np.exp(preds)
    preds = exp_preds / np.sum(exp_preds)
    probas = np.random.multinomial(1, preds, 1)
    return np.argmax(probas)

def on_epoch_end(epoch, logs):
    # Function invoked at end of each epoch. Prints generated text.
    print()
    print('----- Generating text after Epoch: %d' % epoch)
    generate_text()

def generate_text():
    # Create a seed and generate some examples
    start_index = random.randint(0, len(text) - maxlen - 1)
    for diversity in [0.2, 0.5, 1.0, 1.2]:
        print('----- diversity:', diversity)

        generated = ''
        sentence = text[start_index: start_index + maxlen]
        generated += sentence
        print('----- Generating with seed: "' + sentence + '"')
        sys.stdout.write(generated)

        for i in range(400):
            x_pred = np.zeros((1, maxlen, len(chars)))
            for t, char in enumerate(sentence):
                x_pred[0, t, char_indices[char]] = 1.

            preds = model.predict(x_pred, verbose=0)[0]
            next_index = sample(preds, diversity)
            next_char = indices_char[next_index]

            generated += next_char
            sentence = sentence[1:] + next_char

            sys.stdout.write(next_char)
            sys.stdout.flush()
        print()

print_callback = LambdaCallback(on_epoch_end=on_epoch_end)

# Fit the model
if args.fit:
  model.fit(x, y,
            batch_size=128,
            epochs=epochs,
            callbacks=[print_callback])

# Save the model
if args.save:
  print("saving to ", args.save)
  model.save(args.save)

# Load the model
if args.load:
  model = load_model(args.load)

# Generate examples
if args.generate:
  generate_text()


from aironDev import General_Register
import numpy as np
import openpyxl
import pandas as pd
from pandas import ExcelWriter
from openpyxl import Workbook
from openpyxl.worksheet.table import Table, TableStyleInfo

def Calculo_RCL(data,carga1,nombre,fecha):
    t88=Tabla88_Disp('aironDev/Tabla88.xlsx')
    t87=Tabla87_Disp('aironDev/Tabla87.xlsx')
    list_carga1=[]

    LCR=[]
    for i in t87:
        if(not(i in LCR)):
            LCR.append(t87[i]['LCR'])

    piv1=[]
    piv2=[]

    for i in LCR:
        piv1.append(i)
        info={
            'PesoI':0,
            'USDI':0,
            'Otras_1I':0,
            'Otras_2I':0,
            'Individual':0,
            'PesoC':0,
            'USDC':0,
            'Otras_1C':0,
            'Otras_2C':0,
            'Consolidado':0,
        }
        piv2.append(info)
    hash1 = {k:v for k, v in zip(piv1,piv2)}

    for i in data:
        cod=t87[i['Categoria']]['LCR']

        if(i['Nivel_Consolidacion']==1):
            if(i['Vencimiento_Contractual']==1):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['1_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoI']=hash1[cod]['PesoI']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDI']=hash1[cod]['USDI']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1I']=hash1[cod]['Otras_1I']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2I']=hash1[cod]['Otras_2I']+resultado
                hash1[cod]['Individual'] = hash1[cod]['Individual'] + resultado

            elif(i['Vencimiento_Contractual']==2):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['2_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoI']=hash1[cod]['PesoI']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDI']=hash1[cod]['USDI']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1I']=hash1[cod]['Otras_1I']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2I']=hash1[cod]['Otras_2I']+resultado
                hash1[cod]['Individual'] = hash1[cod]['Individual'] + resultado

            elif(i['Vencimiento_Contractual']==3):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['3a7_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoI']=hash1[cod]['PesoI']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDI']=hash1[cod]['USDI']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1I']=hash1[cod]['Otras_1I']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2I']=hash1[cod]['Otras_2I']+resultado
                hash1[cod]['Individual'] = hash1[cod]['Individual'] + resultado

            elif(i['Vencimiento_Contractual']==4):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['3a7_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoI']=hash1[cod]['PesoI']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDI']=hash1[cod]['USDI']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1I']=hash1[cod]['Otras_1I']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2I']=hash1[cod]['Otras_2I']+resultado
                hash1[cod]['Individual'] = hash1[cod]['Individual'] + resultado

            elif(i['Vencimiento_Contractual']==5):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['3a7_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoI']=hash1[cod]['PesoI']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDI']=hash1[cod]['USDI']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1I']=hash1[cod]['Otras_1I']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2I']=hash1[cod]['Otras_2I']+resultado
                hash1[cod]['Individual'] = hash1[cod]['Individual'] + resultado

            elif(i['Vencimiento_Contractual']==6):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['3a7_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoI']=hash1[cod]['PesoI']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDI']=hash1[cod]['USDI']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1I']=hash1[cod]['Otras_1I']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2I']=hash1[cod]['Otras_2I']+resultado
                hash1[cod]['Individual'] = hash1[cod]['Individual'] + resultado

            elif(i['Vencimiento_Contractual']==7):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['3a7_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoI']=hash1[cod]['PesoI']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDI']=hash1[cod]['USDI']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1I']=hash1[cod]['Otras_1I']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2I']=hash1[cod]['Otras_2I']+resultado
                hash1[cod]['Individual'] = hash1[cod]['Individual'] + resultado

        if(i['Nivel_Consolidacion']==2):

            if(i['Vencimiento_Contractual']==1):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['1_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoC']=hash1[cod]['PesoC']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDC']=hash1[cod]['USDC']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1C']=hash1[cod]['Otras_1C']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2C']=hash1[cod]['Otras_2C']+resultado
                hash1[cod]['Consolidado'] = hash1[cod]['Consolidado'] + resultado

            elif(i['Vencimiento_Contractual']==2):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['2_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoC']=hash1[cod]['PesoC']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDC']=hash1[cod]['USDC']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1C']=hash1[cod]['Otras_1C']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2C']=hash1[cod]['Otras_2C']+resultado
                hash1[cod]['Consolidado'] = hash1[cod]['Consolidado'] + resultado

            elif(i['Vencimiento_Contractual']==3):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['3a7_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoC']=hash1[cod]['PesoC']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDC']=hash1[cod]['USDC']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1C']=hash1[cod]['Otras_1C']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2C']=hash1[cod]['Otras_2C']+resultado
                hash1[cod]['Consolidado'] = hash1[cod]['Consolidado'] + resultado

            elif(i['Vencimiento_Contractual']==4):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['3a7_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoC']=hash1[cod]['PesoC']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDC']=hash1[cod]['USDC']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1C']=hash1[cod]['Otras_1C']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2C']=hash1[cod]['Otras_2C']+resultado
                hash1[cod]['Consolidado'] = hash1[cod]['Consolidado'] + resultado

            elif(i['Vencimiento_Contractual']==5):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['3a7_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoC']=hash1[cod]['PesoC']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDC']=hash1[cod]['USDC']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1C']=hash1[cod]['Otras_1C']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2C']=hash1[cod]['Otras_2C']+resultado
                hash1[cod]['Consolidado'] = hash1[cod]['Consolidado'] + resultado

            elif(i['Vencimiento_Contractual']==6):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['3a7_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoC']=hash1[cod]['PesoC']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDC']=hash1[cod]['USDC']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1C']=hash1[cod]['Otras_1C']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2C']=hash1[cod]['Otras_2C']+resultado
                hash1[cod]['Consolidado'] = hash1[cod]['Consolidado'] + resultado

            elif(i['Vencimiento_Contractual']==7):
                resultado=i['Flujo_Efectivo'] * t88[i['Categoria']]['3a7_RCL']
                if(i['Moneda']=='000'):
                    hash1[cod]['PesoC']=hash1[cod]['PesoC']+resultado
                elif(i['Moneda']=='013'):
                    hash1[cod]['USDC']=hash1[cod]['USDC']+resultado
                elif(i['Moneda']=='777'):
                    hash1[cod]['Otras_1C']=hash1[cod]['Otras_1C']+resultado
                elif(i['Moneda']=='888'):
                    hash1[cod]['Otras_2C']=hash1[cod]['Otras_2C']+resultado
                hash1[cod]['Consolidado'] = hash1[cod]['Consolidado'] + resultado

    for i in hash1:
        info={
            'Recalculo Auditorio':i,
            'CLP_Individual':hash1[i]['PesoI'],
            'USD_Individual':hash1[i]['USDI'],
            'Otras 1_Individual':hash1[i]['Otras_1I'],
            'Otras 2_Individual':hash1[i]['Otras_2I'],
            'Total Moneda 1':hash1[i]['Individual'],
            'CLP_Consolidado':hash1[i]['PesoC'],
            'USD_Consolidado':hash1[i]['USDC'],
            'Otras 1_Consolidado':hash1[i]['Otras_1C'],
            'Otras 2_Consolidado':hash1[i]['Otras_2C'],
            'Total Moneda 2':hash1[i]['Consolidado'],
        }
        list_carga1.append(info)

    cabecera=Cabecera_Cuadratura(carga1)
    limite=Ingresos_Lim(hash1['Ingresos'],hash1['Ingresos individual de riesgo < A3 o equivalente. (2)'],hash1['Egreso'],cabecera)
    list_carga1.append(limite)
    egresos=Egresos_Netos(limite,hash1['Egreso'])
    list_carga1.append(egresos)
    dif_caratula=Diferencia_Caratula(cabecera[1:],egresos)
    list_carga1.append(dif_caratula)
    General_Register.reporte_Vista(cabecera,list_carga1,nombre+'_'+fecha+'_RATIO')

def Egresos_Netos(limite,dato):
    info={
        'Recalculo Auditorio':'Egresos Netos',
        'CLP_Individual':dato['PesoI']-limite['CLP_Individual'],
        'USD_Individual':dato['USDI']-limite['USD_Individual'],
        'Otras 1_Individual':dato['Otras_1I']-limite['Otras 1_Individual'],
        'Otras 2_Individual':dato['Otras_2I']-limite['Otras 2_Individual'],
        'Total Moneda 1':dato['Individual']-limite['Total Moneda 1'],
        'CLP_Consolidado':dato['PesoC']-limite['CLP_Consolidado'],
        'USD_Consolidado':dato['USDC']-limite['USD_Consolidado'],
        'Otras 1_Consolidado':dato['Otras_1C']-limite['Otras 1_Consolidado'],
        'Otras 2_Consolidado':dato['Otras_2C']-limite['Otras 2_Consolidado'],
        'Total Moneda 2':dato['Consolidado']-limite['Total Moneda 2'],
    }
    return info

def Diferencia_Caratula(cabecera,egresos):
    data={
        'Recalculo Auditorio':'Diferencia contra carátula ',
    }
    for i in egresos:
        if(egresos[i]!='Egresos Netos'):
            data[i]=cabecera[0][i]-egresos[i]
    return data

def Ingresos_Lim(data1,data2,data3,cabecera):
    info={
        'Recalculo Auditorio':'Ingresos con Lim 75%',
    }

    info2={
        'Recalculo Auditorio':'Ingresos con Lim 75%',
    }

    info['CLP_Individual']=data1['PesoI']+data2['PesoI']
    info['USD_Individual']=data1['USDI']+data2['USDI']
    info['Otras 1_Individual']=data1['Otras_1I']+data2['Otras_1I']
    info['Otras 2_Individual']=data1['Otras_2I']+data2['Otras_2I']
    info['Total Moneda 1']=data1['Individual']+data2['Individual']
    info['CLP_Consolidado']=data1['PesoC']+data2['PesoC']
    info['USD_Consolidado']=data1['USDC']+data2['USDC']
    info['Otras 1_Consolidado']=data1['Otras_1C']+data2['Otras_1C']
    info['Otras 2_Consolidado']=data1['Otras_2C']+data2['Otras_2C']
    info['Total Moneda 2']=data1['Consolidado']+data2['Consolidado']

    info2['CLP_Individual']=(data3['PesoI'] * 0.75)
    info2['USD_Individual']=(data3['USDI'] * 0.75)
    info2['Otras 1_Individual']=(data3['Otras_1I'] * 0.75)
    info2['Otras 2_Individual']=(data3['Otras_2I'] * 0.75)
    info2['Total Moneda 1']=(data3['Individual'] * 0.75)
    info2['CLP_Consolidado']=(data3['PesoC'] * 0.75)
    info2['USD_Consolidado']=(data3['USDC'] * 0.75)
    info2['Otras 1_Consolidado']=(data3['Otras_1C'] * 0.75)
    info2['Otras 2_Consolidado']=(data3['Otras_2C'] * 0.75)
    info2['Total Moneda 2']=(data3['Consolidado'] * 0.75)

    for i in info:
        if(info[i] > info2[i]):
            info[i]=info2[i]

    return info

def Cabecera_Cuadratura(carga1):
    list_cabecera=[]
    info={
        'Recalculo Auditorio':'Activos_Liquidos',
        'CLP_Individual':carga1[0]['Activos_Liquidos'],
        'USD_Individual':carga1[1]['Activos_Liquidos'],
        'Otras 1_Individual':carga1[2]['Activos_Liquidos'],
        'Otras 2_Individual':carga1[3]['Activos_Liquidos'],
        'Total Moneda 1':carga1[4]['Activos_Liquidos'],
        'CLP_Consolidado':carga1[5]['Activos_Liquidos'],
        'USD_Consolidado':carga1[6]['Activos_Liquidos'],
        'Otras 1_Consolidado':carga1[7]['Activos_Liquidos'],
        'Otras 2_Consolidado':carga1[8]['Activos_Liquidos'],
        'Total Moneda 2':carga1[9]['Activos_Liquidos'],
    }
    list_cabecera.append(info)
    info={
        'Recalculo Auditorio':'Egresos_Netos',
        'CLP_Individual':carga1[0]['Egresos_Netos'],
        'USD_Individual':carga1[1]['Egresos_Netos'],
        'Otras 1_Individual':carga1[2]['Egresos_Netos'],
        'Otras 2_Individual':carga1[3]['Egresos_Netos'],
        'Total Moneda 1':carga1[4]['Egresos_Netos'],
        'CLP_Consolidado':carga1[5]['Egresos_Netos'],
        'USD_Consolidado':carga1[6]['Egresos_Netos'],
        'Otras 1_Consolidado':carga1[7]['Egresos_Netos'],
        'Otras 2_Consolidado':carga1[8]['Egresos_Netos'],
        'Total Moneda 2':carga1[9]['Egresos_Netos'],
    }
    list_cabecera.append(info)
    return list_cabecera

def Tabla88_Disp(excel):
    doc = openpyxl.load_workbook(excel)
    doc.get_sheet_names()
    hoja = doc.get_sheet_by_name('Hoja1')
    hoja.rows
    list_Cu=[]
    list_CM=[]
    for filas in hoja.rows:
        data2={
            '1_RCL':filas[1].value,
            '2_RCL':filas[2].value,
            '3a7_RCL':filas[3].value,
            '1_RFEN':filas[4].value,
            '2_RFEN':filas[5].value,
            '3_RFEN':filas[6].value,
            '4_RFEN':filas[7].value,
            '5_RFEN':filas[8].value,
            '6_RFEN':filas[9].value,
            '7_RFEN':filas[10].value,
        }
        list_Cu.append(str(filas[0].value))
        list_CM.append(data2)
    hash = {k:v for k, v in zip(list_Cu,list_CM)}
    return hash

def Tabla87_Disp(excel):
    doc = openpyxl.load_workbook(excel)
    doc.get_sheet_names()
    hoja = doc.get_sheet_by_name('Hoja1')
    hoja.rows
    list_Cu=[]
    list_CM=[]
    for filas in hoja.rows:
        data={
            'LCR':filas[1].value,
            'NSFR':filas[2].value,
            'Pais Domicilio':filas[3].value,
            'Tipo Flujo':filas[4].value,
            'Categoria':filas[5].value,
        }
        list_Cu.append(str(filas[0].value))
        list_CM.append(data)
    hash = {k:v for k, v in zip(list_Cu,list_CM)}
    return hash


play_again = True

while play_again:
    p1 = input('P1: Enter command: ')
    p2 = input('P2: Enter command: ')

    if (p1 == 'Paper' and p2 == 'Rock') or (p1 == 'Rock' and p2 == 'Scissors') or (p1 == 'Scissors' and p2 == 'Paper'):
        print('P1 wins')
    elif (p2 == 'Paper' and p1 == 'Rock') or (p2 == 'Rock' and p1 == 'Scissors') or (p2 == 'Scissors' and p1 == 'Paper'):
        print('P2 wins')
    else:
        print('Draw')

    game_command = input('Play again? Yes / No: ')

    if game_command == 'No':
        play_again = False


'''
Created on 21 Apr 2013

@author: Nikhil
'''

def get_page(url):
    try:
        import urllib
        return urllib.urlopen(url).read()
    except:
        return ""

def crawl_web(seed):
    tocrawl = [seed]
    crawled = []
    index = []
    while tocrawl:
        page = tocrawl.pop()
        if page not in crawled:
            content = get_page(page)
            index.add_page_to_index(index, page, content)
            union(tocrawl,get_all_links(content))
            crawled.append(page)
    return index

def union(l1, l2):
    for b in l2:
        if (b not in l1):
            l1.append(b)
        return l1,l2;

def get_next_target(page):
    start_link = page.find('<a href=')
    if start_link == -1:
        return None,0
    start_quote = page.find('"', start_link)
    end_quote = page.find('"', start_quote+1)
    url = page[start_quote+1:end_quote]  #end quote is the index but we end the url at index-1
    return url, end_quote

def get_all_links(page):
    i = 0
    while True:
        url, endpos = get_next_target(page)
        if url:
            if i ==0:
                links = [url]
                i = i+1
                page = page[endpos:]
            else:
                links.append(url)
                page = page[endpos:]
        else:
            break
    return links


# -*- encoding: utf-8 -*-
#
# Copyright © 2017 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.

# NOTE(sileht): usefull for gunicon, not really for uwsgi
# import gevent
# import gevent.monkey
# gevent.monkey.patch_all()

import hmac
import json
import logging

import flask
import github
import raven.contrib.flask
import rq
import rq_dashboard
import uhashring

from mergify_engine import config
from mergify_engine import utils
from mergify_engine import worker

LOG = logging.getLogger(__name__)

app = flask.Flask(__name__)

app.config.from_object(rq_dashboard.default_settings)
app.register_blueprint(rq_dashboard.blueprint, url_prefix="/rq")
app.config["REDIS_URL"] = utils.get_redis_url()
app.config["RQ_POLL_INTERVAL"] = 10000  # ms
sentry = raven.contrib.flask.Sentry(app, dsn=config.SENTRY_URL)

# TODO(sileht): Make the ring dynamic
global RING
nodes = []
for fqdn, w in sorted(config.TOPOLOGY.items()):
    nodes.extend(map(lambda x: "%s-%003d" % (fqdn, x), range(w)))

RING = uhashring.HashRing(nodes=nodes)

def get_queue(slug, subscription):
    global RING
    name = "%s-%s" % (RING.get_node(slug),
                      "high" if subscription["subscribed"] else "low")
    return rq.Queue(name, connection=utils.get_redis_for_rq())

def authentification():  # pragma: no cover
    # Only SHA1 is supported
    header_signature = flask.request.headers.get('X-Hub-Signature')
    if header_signature is None:
        LOG.warning("Webhook without signature")
        flask.abort(403)

    try:
        sha_name, signature = header_signature.split('=')
    except ValueError:
        sha_name = None

    if sha_name != 'sha1':
        LOG.warning("Webhook signature malformed")
        flask.abort(403)

    mac = utils.compute_hmac(flask.request.data)
    if not hmac.compare_digest(mac, str(signature)):
        LOG.warning("Webhook signature invalid")
        flask.abort(403)

@app.route("/check_status_msg/<path:key>")
def check_status_msg(key):
    msg = utils.get_redis_for_cache().hget("status", key)
    if msg:
        return flask.render_template("msg.html", msg=msg)
    else:
        flask.abort(404)

@app.route("/refresh/<owner>/<repo>/<path:refresh_ref>",
           methods=["POST"])
def refresh(owner, repo, refresh_ref):
    authentification()

    integration = github.GithubIntegration(config.INTEGRATION_ID,
                                           config.PRIVATE_KEY)
    installation_id = utils.get_installation_id(integration, owner)
    if not installation_id:  # pragma: no cover
        flask.abort(400, "%s have not installed mergify_engine" % owner)

    token = integration.get_access_token(installation_id).token
    g = github.Github(token)
    r = g.get_repo("%s/%s" % (owner, repo))
    try:
        r.get_contents(".mergify.yml")
    except github.GithubException as e:  # pragma: no cover
        if e.status == 404:
            return "No .mergify.yml", 202
        else:
            raise

    if refresh_ref == "full" or refresh_ref.startswith("branch/"):
        if refresh_ref.startswith("branch/"):
            branch = refresh_ref[7:]
            pulls = r.get_pulls(base=branch)
        else:
            branch = '*'
            pulls = r.get_pulls()
        key = "queues~%s~%s~%s~%s~%s" % (installation_id, owner.lower(),
                                         repo.lower(), r.private, branch)
        utils.get_redis_for_cache().delete(key)
    else:
        try:
            pull_number = int(refresh_ref[5:])
        except ValueError:  # pragma: no cover
            return "Invalid PR ref", 400
        pulls = [r.get_pull(pull_number)]

    subscription = utils.get_subscription(utils.get_redis_for_cache(),
                                          installation_id)

    if not subscription["token"]:  # pragma: no cover
        return "", 202

    if r.private and not subscription["subscribed"]:  # pragma: no cover
        return "", 202

    for p in pulls:
        # Mimic the github event format
        data = {
            'repository': r.raw_data,
            'installation': {'id': installation_id},
            'pull_request': p.raw_data,
        }
        get_queue(r.full_name, subscription).enqueue(
            worker.event_handler, "refresh", subscription, data)

    return "", 202

@app.route("/refresh", methods=["POST"])
def refresh_all():
    authentification()

    integration = github.GithubIntegration(config.INTEGRATION_ID,
                                           config.PRIVATE_KEY)

    counts = [0, 0, 0]
    for install in utils.get_installations(integration):
        counts[0] += 1
        token = integration.get_access_token(install["id"]).token
        g = github.Github(token)
        i = g.get_installation(install["id"])

        subscription = utils.get_subscription(utils.get_redis_for_cache(),
                                              install["id"])
        if not subscription["token"]:  # pragma: no cover
            continue

        for r in i.get_repos():
            if r.private and not subscription["subscribed"]:
                continue
            try:
                r.get_contents(".mergify.yml")
            except github.GithubException as e:  # pragma: no cover
                if e.status == 404:
                    continue
                else:
                    raise

            counts[1] += 1
            for p in list(r.get_pulls()):
                # Mimic the github event format
                data = {
                    'repository': r.raw_data,
                    'installation': {'id': install["id"]},
                    'pull_request': p.raw_data,
                }
                get_queue(r.full_name, subscription).enqueue(
                    worker.event_handler, "refresh", subscription, data)

    return ("Updated %s installations, %s repositories, "
            "%s branches" % tuple(counts)), 202

# FIXME(sileht): rename this to new subscription something
@app.route("/subscription-cache/<installation_id>", methods=["DELETE"])
def subscription_cache(installation_id):  # pragma: no cover
    authentification()
    r = utils.get_redis_for_cache()
    r.delete("subscription-cache-%s" % installation_id)

    subscription = utils.get_subscription(
        utils.get_redis_for_cache(), installation_id)

    # New subscription, create initial configuration for private repo
    # public repository have already been done during the installation
    # event.
    if subscription["token"] and subscription["subscribed"]:
        # FIXME(sileht): We should pass the slugs
        get_queue(installation_id, subscription).enqueue(
            worker.installation_handler, installation_id, "private")
    return "Cache cleaned", 200

@app.route("/event", methods=["POST"])
def event_handler():
    authentification()

    event_type = flask.request.headers.get("X-GitHub-Event")
    event_id = flask.request.headers.get("X-GitHub-Delivery")
    data = flask.request.get_json()

    subscription = utils.get_subscription(
        utils.get_redis_for_cache(), data["installation"]["id"])

    if not subscription["token"]:
        msg_action = "ignored (no token)"

    elif event_type == "installation" and data["action"] == "created":
        for repository in data["repositories"]:
            if repository["private"] and not subscription["subscribed"]:  # noqa pragma: no cover
                continue

            get_queue(repository["full_name"], subscription).enqueue(
                worker.installation_handler, data["installation"]["id"],
                [repository])
        msg_action = "pushed to backend"

    elif event_type == "installation" and data["action"] == "deleted":
        key = "queues~%s~*~*~*~*" % data["installation"]["id"]
        utils.get_redis_for_cache().delete(key)
        msg_action = "handled, cache cleaned"

    elif (event_type == "installation_repositories" and
          data["action"] == "added"):
        for repository in data["repositories_added"]:
            if repository["private"] and not subscription["subscribed"]:  # noqa pragma: no cover
                continue

            get_queue(repository["full_name"], subscription).enqueue(
                worker.installation_handler, data["installation"]["id"],
                [repository])

        msg_action = "pushed to backend"

    elif (event_type == "installation_repositories" and
          data["action"] == "removed"):
        for repository in data["repositories_removed"]:
            if repository["private"] and not subscription["subscribed"]:  # noqa pragma: no cover
                continue
            key = "queues~%s~%s~%s~*~*" % (
                data["installation"]["id"],
                data["installation"]["account"]["login"].lower(),
                repository["name"].lower()
            )
            utils.get_redis_for_cache().delete(key)
        msg_action = "handled, cache cleaned"

    elif event_type in ["installation", "installation_repositories"]:
        msg_action = "ignored (action %s)" % data["action"]

    elif event_type in ["pull_request", "pull_request_review", "status",
                        "refresh"]:

        if data["repository"]["private"] and not subscription["subscribed"]:
            msg_action = "ignored (not public or subscribe)"

        elif event_type == "status" and data["state"] == "pending":
            msg_action = "ignored (state pending)"

        elif (event_type == "pull_request" and data["action"] not in [
                "opened", "reopened", "closed", "synchronize",
                "labeled", "unlabeled"]):
            msg_action = "ignored (action %s)" % data["action"]

        else:
            get_queue(data["repository"]["full_name"], subscription).enqueue(
                worker.event_handler, event_type, subscription, data)
            msg_action = "pushed to backend"

    else:
        msg_action = "ignored (unexpected event_type)"

    if "repository" in data:
        repo_name = data["repository"]["full_name"]
    else:
        repo_name = data["installation"]["account"]["login"]

    LOG.info('[%s/%s] received "%s" event "%s", %s',
             data["installation"]["id"], repo_name,
             event_type, event_id, msg_action)

    return "", 202

# NOTE(sileht): These endpoints are used for recording cassetes, we receive
# Github event on POST, we store them is redis, GET to retreive and delete
@app.route("/events-testing", methods=["POST", "GET", "DELETE"])
def event_testing_handler():  # pragma: no cover
    authentification()
    r = utils.get_redis_for_cache()
    if flask.request.method == "DELETE":
        r.delete("events-testing")
        return "", 202
    elif flask.request.method == "POST":
        event_type = flask.request.headers.get("X-GitHub-Event")
        event_id = flask.request.headers.get("X-GitHub-Delivery")
        data = flask.request.get_json()
        r.rpush("events-testing", json.dumps(
            {"id": event_id, "type": event_type, "payload": data}
        ))
        return "", 202
    else:
        p = r.pipeline()
        p.lrange("events-testing", 0, -1)
        p.delete("events-testing")
        values = p.execute()[0]
        data = [json.loads(i) for i in values]
        return flask.jsonify(data)

@app.route("/")
def index():  # pragma: no cover
    return flask.redirect("https://mergify.io/")


# This is an example of QView customization for a specific application
# (DPP in this case). This example animates the Phil images on the
# QView canvas. Additionally, there is a button in the middle of the screen,
# which, when clicked once pauses the DPP ("forks" are not being served).
# A second click on the button, "un-pauses" the DPP ("forks" are served
# to all hungry Philosophers).
#
# This version of the DPP customization uses the application-specific
# packet QS_USER_00 (PHILO_STAT) produced when the status of a Philo changes.
#

class DPP:
    def __init__(self):

        # add commands to the Custom menu...
        QView.custom_menu.add_command(label="Custom command",
                                      command=self.cust_command)

        # configure the custom QView.canvas...
        QView.show_canvas() # make the canvas visible
        QView.canvas.configure(width=400, height=260)

        # tuple of activity images (correspond to self._philo_state)
        self._act_img = (
            PhotoImage(file=HOME_DIR + "/img/thinking.gif"),
            PhotoImage(file=HOME_DIR + "/img/hungry.gif"),
            PhotoImage(file=HOME_DIR + "/img/eating.gif"),
        )
        # tuple of philo canvas images (correspond to self._philo_obj)
        self._philo_img = (\
            QView.canvas.create_image(190,  57, image=self._act_img[0]),
            QView.canvas.create_image(273, 100, image=self._act_img[0]),
            QView.canvas.create_image(237, 185, image=self._act_img[0]),
            QView.canvas.create_image(146, 185, image=self._act_img[0]),
            QView.canvas.create_image(107, 100, image=self._act_img[0])
        )

        # button images for UP and DOWN
        self.img_UP  = PhotoImage(file=HOME_DIR + "/img/BTN_UP.gif")
        self.img_DWN = PhotoImage(file=HOME_DIR + "/img/BTN_DWN.gif")

        # images of a button for pause/serve
        self.btn = QView.canvas.create_image(200, 120, image=self.img_UP)
        QView.canvas.tag_bind(self.btn, "<ButtonPress-1>", self.cust_pause)

        # request target reset on startup...
        # NOTE: Normally, for an embedded application you would like
        # to start with resetting the Target, to start clean with
        # Qs dictionaries, etc.
        reset_target()

    # on_reset() callback
    def on_reset(self):
        # clear the lists
        self._philo_obj   = [0, 0, 0, 0, 0]
        self._philo_state = [0, 0, 0]

    # on_run() callback
    def on_run(self):
        glb_filter("QS_USER_00")

        # NOTE: the names of objects for current_obj() must match
        # the QS Object Dictionaries produced by the application.
        current_obj(OBJ_AO, "Table_inst")

        # turn lists into tuples for better performance
        self._philo_obj = tuple(self._philo_obj)
        self._philo_state = tuple(self._philo_state)

    # example of a custom command
    def cust_command(self):
        command(1, 12345)

    # example of a custom interaction with a canvas object (pause/serve)
    def cust_pause(self, event):
        if QView.canvas.itemcget(self.btn, "image") != str(self.img_UP):
            QView.canvas.itemconfig(self.btn, image=self.img_UP)
            post("SERVE_SIG")
            QView.print_text("Table SERVING")
        else:
            QView.canvas.itemconfig(self.btn, image=self.img_DWN)
            post("PAUSE_SIG")
            QView.print_text("Table PAUSED")

    # intercept the QS_USER_00 application-specific packet
    # this packet has the following structure (see bsp.c:displayPhilStat()):
    # record-ID, seq-num, Timestamp, format-byte, Philo-num,
    #    format-bye, Zero-terminated string (status)
    def QS_USER_00(self, packet):
        # unpack: Timestamp->data[0], Philo-num->data[1], status->data[3]
        data = qunpack("xxTxBxZ", packet)
        i = data[1]
        j = ("t", "h", "e").index(data[2][0]) # the first letter

        # animate the given philo image according to its activity
        QView.canvas.itemconfig(self._philo_img[i], image=self._act_img[j])

        # print a message to the text view
        QView.print_text("%010d Philo %1d is %s"%(data[0], i, data[2]))

#=============================================================================
QView.customize(DPP()) # set the QView customization


import os
import csv
import neural_funcs
import cPickle as pickle
import numpy as np
import pandas as pd

TEST = "./raw_data/test.csv"
TRAIN = "./raw_data/train.csv"
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))

class NeuralNetwork:
    """
    :param layers: A list containing the number of units in each layer.
    The last integer element is considered the output layer
    :param activation_: The activation function to be used. Can be
    "logistic" or "tanh"
    :param cost: the cost function to be used. Can be "mse" or "cross_entropy"
    :param weight_init: Function used to generate initial weights of model. Can be "epsilon" or "gaussian"
    """
    def __init__(self,
                 activation_="logistic",
                 cost="mse",
                 alpha=0.05,
                 lamda=0.5,
                 epochs=30,
                 layers=None,
                 batch_size=10,
                 evaluate=True,
                 weight_init="epsilon"):

        layers = layers or [25, 10]  # Default to one hidden layer with 25 units and one 10 unit output layer

        if len(layers) < 2:
            raise TypeError("The layers arg should be a list containing at least two integers")

        self.curr_cost = 0
        self.weights = [neural_funcs.Weight().get(weight_init)(x, y) for x, y in zip(layers[:-1], layers[1:])]
        self._params = {
            "evaluate": evaluate,
            "activation": activation_,
            "cost": cost,
            "alpha": alpha,
            "lamda": lamda,
            "epochs": epochs,
            "num_layers": len(layers) + 1,
            "layers": layers,
            "hidden_layers": layers[:-1],
            "output_layer": layers[-1],
            "batch_size": batch_size,
            "weight_init": weight_init
        }

    def rst_weights(self):
        layers = self.params["layers"]
        self.weights = [neural_funcs.Weight().get(self.params["weight_init"])(x, y) for x, y in zip(layers[:-1], layers[1:])]

    def fit(self, X=None, y=None, tuning=None):
        if not X:
            print("Fitting with default (MNIST) training data and labels...")
            X = pd.read_csv(TRAIN)
            y = np.array([X["label"].as_matrix()])
            X = X.drop("label", axis=1).as_matrix()

        self.params["layers"] = [X.shape[1]] + self.params["layers"]
        self._sgd(X, y, tuning=None)

    def predict(self, x):
        _, output = self._feedforward(x)
        return np.argmax(output[-1])

    def evaluate(self, test):
        test_results = [(self.predict(row[1:]), row[0]) for row in test]
        accuracy = neural_funcs.Evaluation.accuracy(test_results)
        f1 = neural_funcs.Evaluation.f1(test_results)
        return accuracy, f1

    @property
    def params(self):
        return self._params

    @params.setter
    def params(self, key_value):
        key, value = key_value
        self._params[key] = value
        return self._params

    def _feedforward(self, x):
        weighted_sums = []
        activations = [x]
        a = x  # init the first activation layer to the input X
        for theta in self.weights:
            a = np.insert(a, 0, 1)  # add bias term
            z = np.dot(theta, a)
            weighted_sums.append(z)
            a = neural_funcs.Activation().get(self.params["activation"])(z)

            activations.append(a)

        return weighted_sums, activations

    def _backprop(self, x, y):
        weighted_sums, activations = self._feedforward(x)
        nabla = [np.zeros(w.shape) for w in self.weights]

        # Use the output layer activations and weights to initialize error delta
        activ_deriv = neural_funcs.Activation().get(self.params["activation"])(weighted_sums[-1], derivative=True)
        delta = neural_funcs.Cost().get(self.params["cost"])(self._label(y), activations[-1], derivative=True, activation_deriv=activ_deriv)

        delta = np.array([delta]).T
        a = np.array([np.insert(activations[-2], 0, 1)]).T
        nabla[-1] = np.dot(delta, a.T)

        delta = np.insert(delta, 0, 1)
        delta = np.array([delta]).T

        # Backpropagate error
        for l in xrange(2, self.params["num_layers"]):
            delta = np.dot(self.weights[-l + 1].T, delta[1:]) \
                    * np.array([np.insert(neural_funcs.Activation().get(self.params["activation"])(weighted_sums[-l], derivative=True), 0, 1)]).T

            a = np.array([np.insert(activations[-l - 1], 0, 1)]).T
            nabla[-l] = np.dot(delta[1:], a.T)

        return nabla

    def _label(self, y):
        label = np.zeros(self.params["output_layer"])
        label[y] = 1
        return label

    def _sgd(self, X, y, tuning=None):
        tuning = tuning or ('lamda', lambda x: x / 10)
        data = np.concatenate((y.T, X), axis=1)
        np.random.shuffle(data)
        training_length = int(len(data) * .9)
        train_val = data[:training_length]
        test = data[training_length:]

        cross_val_size = int(len(train_val) * .10)

        fold_num = 0
        fold_score = {}
        for cross_start in xrange(0, len(train_val), cross_val_size):
            self.rst_weights()
            if cross_start > 0:
                self.params[tuning[0]] = tuning[1](self.params[tuning[0]])

            print("\nStarting kfold #{0} with hyperparameter \"{1}\" at value {2}".format(fold_num, tuning[0], self.params[tuning[0]]))

            fold_num += 1
            filename = ROOT_DIR + "/models/score_{0}.csv".format(fold_num)

            try:
                os.remove(filename)
            except OSError:
                pass

            fold_score[fold_num] = {"accu": 0, "f1": 0, "weights": self.weights, "params": self.params}
            cross_end = cross_start + cross_val_size
            cross_val = train_val[cross_start:cross_end]
            train = np.concatenate((train_val[:cross_start], train_val[cross_end:]))

            n = len(train)
            alpha = self.params["alpha"]
            for i in xrange(self.params["epochs"]):
                train = np.random.permutation(train)
                batches = [train[m:m + self.params["batch_size"]]
                           for m in xrange(0, n, self.params["batch_size"])]

                print("Updating model with alpha {0}".format(round(alpha, 3)))
                for batch in batches:
                    y = batch[:, 0]
                    X = batch[:, 1:]
                    self._update_model(X, y)

                alpha *= 0.90 if alpha > 0.01 else .95

                self.curr_cost = self._compute_cost(train)

                if not i % 5:
                    print("\nCurrent cost: {0}\n".format(round(self.curr_cost, 3)))

                if self.params["evaluate"]:
                    train_accu = self.evaluate(train)[0] * 100
                    train_f1 = self.evaluate(train)[1]
                    cross_accu = self.evaluate(cross_val)[0] * 100
                    cross_f1 = self.evaluate(cross_val)[1]

                    with open(filename, "a+") as f:
                        writer = csv.writer(f)

                        if i == 0:
                            writer.writerow(("epoch", "cross_accu", "cross_f1", "cost"))

                        writer.writerow((i, cross_accu, cross_f1, self.curr_cost))

                    print("Epoch #{0} results:".format(i + 1))
                    print("\tTrain set:")
                    print("\t    accuracy: {0}%".format(train_accu))
                    print("\t    F1: {0}".format(train_f1))
                    print("\tCross validation set:")
                    print("\t    accuracy: {0}%".format(cross_accu))
                    print("\t    F1: {0}".format(cross_f1))

            fold_score[fold_num]["accu"] = cross_accu
            fold_score[fold_num]["f1"] = cross_f1
            fold_score[fold_num]["weights"] = list(self.weights)
            fold_score[fold_num]["params"] = dict(self.params)

        # Select the best fold and load params/weights back into model before testing
        best = 0
        for fold, scores in fold_score.iteritems():
            if best < scores["f1"]:
                best = scores["f1"]
                self._params = scores["params"]
                self.weights = scores["weights"]

        test_accu = self.evaluate(test)[0] * 100
        test_f1 = self.evaluate(test)[1]
        print("\nFinal results:")
        print("Best value for \"{0}\" param: {1}".format(tuning[0], self.params[tuning[0]]))
        print("\tTest set:")
        print("\t    accuracy: {0}%".format(test_accu))
        print("\t    F1: {0}\n".format(test_f1))

        with open(ROOT_DIR + "/models/weights.pkl".format(fold_num), 'w') as f:
            pickle.dump(self.weights, f)

        with open(ROOT_DIR + "/models/params.pkl".format(fold_num), 'w') as f:
            pickle.dump(self.params, f)

    def _update_model(self, X, y):
        nabla = [np.zeros(w.shape) for w in self.weights]
        m = len(X)
        for i in xrange(m):
            delta_nabla = self._backprop(X[i], y[i])
            nabla = [n + dn for n, dn in zip(nabla, delta_nabla)]

        # Update model weights
        alpha = self.params["alpha"]
        lamda = self.params["lamda"]
        self.weights = [w - (alpha / m) * n for w, n in zip(self.weights, nabla)]

        for theta in self.weights:
            theta[:, 1:] = [w - ((alpha * lamda) / m) * w for w in theta[:, 1:]]

    def _compute_cost(self, data):
        cost = 0
        m = len(data)
        for row in data:
            _, activations = self._feedforward(row[1:])
            cost += neural_funcs.Cost().get(self.params["cost"])(self._label(row[0]), activations[-1]) / m

        cost += np.sum([(self.params["lamda"] / (2 * m)) * np.sum(np.square(theta[:, 1:])) for theta in self.weights])
        return cost


from socket_usage import *
from io import BytesIO
import sys

def main():
    client_socket = Client_Socket('127.0.0.1', 1729)
    client_socket.connect()
    command = ""
    while command != "exit":
        command = input("Enter a command: ")
        client_socket.send(command)
        if not command.startswith("send"):
            print(client_socket.receive())
            if command == "close_server":
                sys.exit()
        else:
            byte = client_socket.receive('b')
            if byte == b'done':
                print("File doesn't exist")
            else:
                with open(command[command.rfind('\\') + 1:], 'wb') as result:
                    while byte != b'done':
                        result.write(byte)
                        byte = client_socket.receive('b')

if __name__ == "__main__":
    main()


from os import listdir
from os.path import isfile, join
from tests.ViewHelper import getTestDir
from tests.CorepHelper import setGuiEnvironment

def getSolvencyFiles():
    testDir = getTestDir()
    svcDir = testDir + "/solvency/2.0/random"
    files = [ f for f in listdir(svcDir) if isfile(join(svcDir, f)) ]
    result = []
    for f in sorted(files):
        result.append(join(svcDir, f))
    return result

def setSolvencyGuiEnvironment(cntlrWinMain):
    # make sure we use the proper disclosure system for validation
    cntlrWinMain.config["disclosureSystem"] = "EIOPA Filing Rules"

    setGuiEnvironment(cntlrWinMain)


def g(m):
  i=1
  for i in range(m):
    print(" "*(m),"*"*i)
    i+=1
    m-=1
  j=0
  for j in range(i):
    print(" "*(j),"*"*i)
    j+=1
    i-=1
a = int(input("How many size do you want?:"))
#Please considering about matching size program window
g(a)


# coding=utf-8
__author__ = 'FAKIR.Marouane'

from Medius.utils import to_date, dt
from Medius.dal.db_utils import query_to_dict
from Medius.dal.Models import DataModel, FondMd, EtatFondMd, OperationMd
import Medius.dal.procedures as procedures
import sqlalchemy

class Fond(object):

    def __init__(self, fond='CMROBLIG', date_valeur=dt.date.today()):
        self._session = DataModel().get_session()
        # self.fond -> FondMd
        self.fond = fond
        self.date_valeur = to_date(date_valeur)
        self.inventaire = Inventaire(fond, date_valeur)

    def etat(self, date_valeur=None):
        if date_valeur:
            _date = date_valeur
        else:
            _date = self.date_valeur
        state = self.fond.etat.filter(EtatFondMd.date_etat == _date).one()
        result = state.data
        return result

    def etat_historique(self, date_debut, date_fin):
        deb, fin = to_date(date_debut), to_date(date_fin)
        historique = self.fond.etat.filter(
                EtatFondMd.date_etat >= deb,
                EtatFondMd.date_etat <= fin).order_by(EtatFondMd.date_etat)
        result = query_to_dict(historique)
        return result

    def operations(self, date_operation=None, type_operation='repo'):
        if date_operation:
            _date = to_date(date_operation)
        else:
            _date = self.date_valeur
        query = self._session.query(OperationMd).filter_by(
                fond=self.fond.p_isin, date_operation=_date, type_operation=type_operation)
        result = query_to_dict(query)
        return result

    def operations_historique(self, date_debut, date_fin, type_operation='repo'):
        debut = to_date(date_debut)
        fin = to_date(date_fin)
        query = self._session.query(OperationMd).filter(
            OperationMd.fond == self.fond.p_isin,
            OperationMd.date_operation >= debut,
            OperationMd.date_operation <= fin,
            OperationMd.type_operation == type_operation).order_by(OperationMd.date_operation)
        result = query_to_dict(query)
        return result

    def operations_encours(self, date_valeur=None, type_operation='repo', depth=90):
        """
        Retourne les operations en cours.
        la table ne contient que les dates d'initiation des opérations.
        depth permet de chercher des operations initiées avant N jours.
        """
        if date_valeur:
            fin = to_date(date_valeur)
        else:
            fin = self.date_valeur
        debut = fin - dt.timedelta(depth)
        query = self._session.query(OperationMd).filter(
            OperationMd.fond == self.fond.p_isin,
            OperationMd.date_operation >= debut,
            OperationMd.date_operation <= fin,
            OperationMd.type_operation == type_operation).order_by(OperationMd.date_operation)
        encours = [x.data for x in query if x.date_retour > fin]
        return encours

    def tam(self, date_valeur=None, taxe_repo=0.1):
        inventaire = self.inventaire.items('obligation')['obligation']
        actif_net = self.etat(date_valeur)['actif_net']
        tam_inventaire = sum([x['prix'] * x['quantite'] * x['taux_valorisation'] for x in inventaire])
        repo_encours = self.operations_encours(date_valeur, type_operation='repo')
        rrepo_encours = self.operations_encours(date_valeur, type_operation='rrepo')
        tam_repo = sum(x['valeur_nominale'] * x['taux_placement'] * (1 + taxe_repo) for x in repo_encours) * -1
        tam_rrepo = sum(x['valeur_nominale'] * x['taux_placement'] for x in rrepo_encours)
        letam = sum((tam_repo, tam_rrepo, tam_inventaire)) / actif_net
        return letam

    def sensibilite(self, date_valeur=None):
        titres = self.inventaire.items('obligation')['obligation']
        actif_net = self.etat(date_valeur)['actif_net']
        sensi_titres = sum([x['prix'] * x['quantite'] * x['sensibilite'] for x in titres])
        sensi = sensi_titres / actif_net
        return sensi

    def sensibilite_cdvm(self, date_valeur=None):
        actif_net = self.etat(date_valeur)['actif_net']
        opcvm = self.opcvm(date_valeur)
        sensi_opcvm = sum([x['valeur_nominale'] * x['sensi'] for x in opcvm]) / actif_net
        sensi_cdvm = self.sensibilite(date_valeur) + sensi_opcvm
        return sensi_cdvm

    def opcvm(self, date_valeur=None):
        if date_valeur:
            _date = date_valeur
        else:
            _date = self.date_valeur
        opcvm = self.inventaire.items('opcvm')['opcvm']
        # liste_fonds = [f['p_isin'] for f in query_to_dict(self._session.query(FondMd))]
        for opc in opcvm:
            valo_nominale = opc['cours'] * opc['quantite']
            f = Fond(fond=opc['code'], date_valeur=_date)
            if f.fond:
                sensi = f.sensibilite()
            else:
                sensi = 0
            dico = {'valeur_nominale': valo_nominale, 'sensi': sensi}
            opc.update(dico)
        return opcvm

    # To-Do : Sensibilite opcvm.
    def duration(self, date_valeur=None):
        titres = self.inventaire.items('obligation')['obligation']
        actif_net = self.etat(date_valeur)['actif_net']
        duration_titres = sum([x['prix'] * x['quantite'] * x['duration'] for x in titres])
        duration = duration_titres / actif_net
        return duration

    def liquidite(self, date_valeur=None):
        total_repo = self.repo_total(date_valeur)
        cash = self.etat(date_valeur)['cash']
        return total_repo + cash

    def repo_total(self, date_valeur=None):
        type_operation = 'repo'
        encours = self.operations_encours(date_valeur, type_operation=type_operation)
        if encours:
            total = sum([x['valeur_nominale'] for x in encours])
        else:
            total = 0
        sens = -1
        return total * sens

    def levier(self, date_valeur=None):
        type_operation = 'rrepo'
        encours = self.operations_encours(date_valeur, type_operation=type_operation)
        if encours:
            total = sum([x['valeur_nominale'] for x in encours])
        else:
            total = 0
        return total

    @property
    def date_valeur(self):
        return self._date_valeur

    @date_valeur.setter
    def date_valeur(self, value):
        self._date_valeur = to_date(value)
        if hasattr(self, 'inventaire'):
            self.inventaire.date_valeur = to_date(value)

    @property
    def infos(self):
        return self.fond.data

    @property
    def fond(self):
        return self._fond

    @fond.setter
    def fond(self, value):
        if isinstance(value, FondMd):
            self._fond = value
        else:
            self._fond = self._session.query(FondMd).get(value)

class Inventaire(object):

    def __init__(self, code_fond, date_valeur):
        self._func = procedures.inventaire
        self.date_valeur = date_valeur
        self.code_fond = code_fond

    def items(self, type_actif='obligation'):
        inventaire = self._func(self.code_fond, self.date_valeur, type_actif)
        l = query_to_dict(inventaire)
        return {type_actif: l}

    def all_items(self):
        types = ('action', 'obligation', 'opcvm')
        inventaire = {}
        for t in types:
            inventaire = self._func(self.code_fond, self.date_valeur, t)
            l = query_to_dict(inventaire)
            dic = {t: l}
            inventaire.update(dic)
        return inventaire

if __name__ == '__main__':
    f = Fond('ALIJTIMAI', date_valeur='04/09/2015')
    info = f.infos
    etat = f.etat()
    oblig = f.inventaire.items('oblig')
    action = f.inventaire.items('action')
    opcvm = f.inventaire.items('opcvm')
    position_cash = f.etat()['cash']
    op_encours = f.operations_encours()
    tam = f.sensibilite_cdvm()
    # print(liquidite, ...)
    print(tam, ...)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 28 16:23:32 2018

plot lever and food cup approach under and after flupenthixol injection

@author: francois
"""

import numpy as np
import matplotlib.pyplot as plt
from SEM import sem

n_blocks = 8
n_trials = 50
flupenthixol = 0.9
x = range(1, n_blocks)

iti_scale = 1

if iti_scale == 1:
    duration = 'standard'
elif iti_scale == 0.5:
    duration = 'short'
elif iti_scale == 5:
    duration = 'long'

magazine_present = True
lever_present = False

if magazine_present == False:
    ITIcondition = 'magazine absent'
elif lever_present:
    ITIcondition = 'lever present'
else:
    ITIcondition = 'lever absent'
print(ITIcondition)

#filename = 'flupenthixol inhibition/ST flupenthixol inhibition = ' + str(flupenthixol) + '.npz'
filename = 'replication Lesaint 2014/ST flupenthixol inhibition = ' + str(flupenthixol) + '.npz'
data_flu = np.load(filename)

filename = 'replication Lesaint 2014/STSimulations with intertrial ' + str(iti_scale) + '.npz'
data_control = np.load(filename)

plt.figure()
y1 = np.mean(data_flu['goL_counter'] / n_trials, axis = 0)
y1err = sem(data_flu['goL_counter'] / n_trials)
plt.errorbar(x, y1[0:7], y1err[0:7], color='r', label='flu')
y2 = np.mean(data_control['goL_counter'] / n_trials, axis = 0)
y2err = sem(data_control['goL_counter'] / n_trials)
plt.errorbar(x, y2[0:7], y2err[0:7], color='k', label='veh')
plt.axis([0, 9, 0, 1])
plt.legend(loc='best')

plt.savefig('replication Lesaint 2014/ST Approach to lever under flupenthixol treatment.png')

plt.figure()
plt.bar([7.75, 8.25], [y2[7], y1[7]], align='center', width = 0.4, yerr = [y2err[7], y1err[7]], color=['k', 'r'])
plt.savefig('replication Lesaint 2014/ST Approach to lever after flupenthixol treatment.png')

filename = 'replication Lesaint 2014/GT flupenthixol inhibition = ' + str(flupenthixol) + '.npz'
data_flu = np.load(filename)

filename = 'replication Lesaint 2014/GTSimulations with intertrial ' + str(iti_scale) + '.npz'
data_control = np.load(filename)

plt.figure()
y1 = np.mean(data_flu['goM_counter'] / n_trials, axis = 0)
y1err = sem(data_flu['goM_counter'] / n_trials)
plt.errorbar(x, y1[0:7], y1err[0:7], color='b', label='flu')
y2 = np.mean(data_control['goM_counter'] / n_trials, axis = 0)
y2err = sem(data_control['goM_counter'] / n_trials)
plt.errorbar(x, y2[0:7], y2err[0:7], color='k', label='veh')
plt.axis([0, 9, 0, 1])
plt.legend(loc='best')

plt.savefig('replication Lesaint 2014/GT Approach to food cup under flupenthixol treatment.png')

plt.figure()
plt.bar([7.75, 8.25], [y2[7], y1[7]], align='center', width = 0.4, yerr = [y2err[7], y1err[7]], color=['k', 'b'])
plt.savefig('replication Lesaint 2014/GT Approach to lever after flupenthixol treatment.png')


import pygame
from pygame.locals import *
from constant import *

def set_layout(keyboard=None):
    """ Switch Keyboard layout with KEYBOARD constant or with specified argument

        :param str keyboard: Keyboard layout (azerty or qwerty)
    """
    if not keyboard:
        keyboard = KEYBOARD
    if keyboard == 'azerty':
        pygame.K_q = 97
        pygame.K_a = 113
        pygame.K_w = 122
        pygame.K_z = 119
    elif keyboard == 'qwerty':
        pygame.K_q = 113
        pygame.K_a = 97
        pygame.K_w = 119
        pygame.K_z = 122


# -*- coding: utf-8 -*-
"""
Created on Sun May 27 10:34:21 2018

@author: 帅老板
"""

import ply.lex as lex

#定义保留关键字
reversed = (
    'CREATE','SELECT','FROM','WHERE','DROP','INSERT',
    'SET','VALUES','DELETE','INTO','SHOW','UPDATE',
    'TABLE','USE','DATABASE','DATABASES','TABLES',
    'AND','OR','NOT','INT','CHAR','NULL','EXIT'
    )
#定义标记
tokens = reversed + (
    'ID','NUMBER','STRING',
    'EQ','NE','LT','GT','LE','GE'
    )

#定义特殊符号
literals = ['(',')',',',';','.','+','-','*','/']
#定义可忽略字符
t_ignore = r' '#忽略空格
t_ignore_note = r'\/\/.*?$'#忽略单行注释
t_ignore_notes =  r'\/\*.*?\*\/'#忽略多行注释
#定义标记对应的描述符
t_LT = r'<'
t_GT = r'>'
t_LE = r'<='
t_GE = r'>='
t_EQ = r'='
t_NE = r'!='
#定义模式
"""
定义正则表达式以及根据正则表达式识别出记号后的操作
正则表达式作为函数的doc，参数t是LexToken类型，表示识别出的词法单元，具有属性：
                value：默认就是识别出的字符串序列。
                type：词法单元的类型，就是在tokens元组中的定义的。
                line：词法单元在源代码中的行号。
                lexpos：词法单元在该行的列号。
"""
def t_ID(t):
  r'[a-zA-Z_][a-zA-Z_0-9]*'
  if t.value.upper() in reversed:
    t.type = t.value.upper()
  else:
    t.type = 'ID'
  return t

def t_STRING(t):
  r'(\'|").*?(\'|")'
  t.value = t.value[1:-1]#去除括号
  return t

def t_NUMBER(t):
  r'\d+'
  t.value = int(t.value)
  return t

def t_newline(t):
  r'\n+'
  t.lexer.lineno += len(t.value)

def t_error(t):
  print("Lex Error [%s,%s]:Illegal word '%s'."%(t.lexer.lineno,t.lexer.lexpos,t.value[0]))

lexer = lex.lex()


from input_generation.pde_generation_data import OdeFn
from input_generation.input_generation import DataGeneration
import numpy as np
import tensorflow as tf
from typing import Union

class OdePendulum(OdeFn):
    """
    Partial equation differential to generate data with

    d2Theta/dt2 - omega^2.Theta - alpha.dTheta/dt = u(t)

    """

    def __init__(self, u: np.array, time_duration: int, dt: float, t_init: float, omega: float, alpha: float):
        super(OdePendulum, self).__init__(u, time_duration, dt, t_init)
        self._omega = omega
        self._alpha = alpha

    def ode_fn(self, t, x, u):
        t_idx = int(np.abs((self._t - t.numpy())).argmin())
        return tf.Variable([x[1], u[t_idx] - (self._omega ** 2) * np.sin(x[0]) - self._alpha * x[1]])

class DampedPendulumDataGeneration(DataGeneration):

    def __init__(self, solver: OdeFn, initial_state_number: int, time_duration: int, dt: float, t_init: float,
                 rng: Union[np.random.RandomState, int] = None, add_white_gaussian: tuple = None):
        """

        :param initial_state_number: number of initial states to generate
        :param time_duration: number of time step
        :param rng: random framework
        :param add_white_gaussian: tuple(mean, standard deviation), if None, no white gaussian noise
        """
        super(DampedPendulumDataGeneration, self).__init__(solver, initial_state_number, time_duration, dt, t_init, rng,
                                                           add_white_gaussian)

    def generate_initial_states(self, angle_bounds: Union[tuple, list], speed_bounds: Union[tuple, list]):
        """
        generate a set of initial angle ande initial angle speed
        :param angle_bounds:
        :param speed_bounds:
        :return:
        """
        angle_lb, angle_up = angle_bounds
        speed_lb, speed_up = speed_bounds
        angle_inits = np.linspace(angle_lb, angle_up, self._init_states_nb)
        speed_inits = np.linspace(speed_lb, speed_up, self._init_states_nb)
        init_states_idx = [(self._rng.randint(self._init_states_nb), self._rng.randint(self._init_states_nb))
                           for _ in range(self._ts_nb)]
        init_states = np.array([(angle_inits[i], speed_inits[j]) for i, j in init_states_idx])
        return init_states

    def generate_sample(self, angle_bounds: Union[tuple, list],
                        speed_bounds: Union[tuple, list]):
        """
        generate a set of initial angle ande initial angle speed
        :param angle_bounds:
        :param speed_bounds:
        :return:
        """
        init_states = self.generate_initial_states(angle_bounds, speed_bounds)
        res = np.zeros((self.t.shape[0], init_states.shape[0], init_states.shape[1]))
        white_gaussian_noise = np.zeros(self.t.shape[0])
        if self._white_gaussian:
            white_gaussian_noise = self.add_white_gaussian_noise(mean=self._wg_noise_mean, std=self._wg_noise_std)
        for i, (theta0, v0) in enumerate(init_states):
            x_init = tf.constant([theta0, v0], dtype=tf.float64)
            results = self._solver.solve(self.t_init, x_init, solution_times=self.t)
            res[:, i, 0] = results.states.numpy()[:, 0] + white_gaussian_noise
            res[:, i, 1] = results.states.numpy()[:, 1] + white_gaussian_noise
        self._res = res
        return res

    def get_one_sample(self, idx=None):
        if idx is None:
            idx = self.get_one_case_idx()
        return self._res[:, idx, :]


def delayed_print(string):
      import time
      sleep=0.05 ## Isso faz com que o printe seja atrasado por segundo
      for x in string:
            print (x, end="") #É necessario o end="" pois sem ele o programa crash ??
            time.sleep(sleep)
print('.:.:.:.:')

##Game de desenvolvimento por texto

nome = input('Informe seu nome: ')
print('')

delayed_print('Prazer em te conhecer {}. \n Aqui começa uma aventura por linhas de comando e \n'
      ' mesmo que seja apenas uma demonstração \n bem simples, não se engane '
      'esse \n é apenas o começo de uma grande historia, certo...Humm'.format(nome))

print('')
print('')

delayed_print('Opá antes de começar gostaria de avisar os \n '
      'principais comandos, pois como se trata de uma demo \n '
      'os comandos são muito delimitados "sorry". \n '
      'LISTA DE COMANDOS\n'
      ' * olhar em volta\n'
      ' * ir ate porta\n'
      ' * entrar\n'
              '\n')

enter = input('Tecle enter para começar...')

r1 = 'olhar em volta'
r2 = 'ir ate a porta'
r3 = 'entrar'

print('')
print('')

texto = ('Hora atual: 18:00 PM\n'
         '\n'
         'Você se vê em frente a uma casa\n'
         'aparentemente abandonada...')

print("{0:^60}".format(texto))

print('')
print('')

resposta = input('O que vc gostaria de fazer? ')

print('')
print('')

if resposta == r1:
      print('Olhando para a casa em si vc observa que \n'
            'ela tem uma coloração acinzentada, \n'
            'com a tinta toda quebradiça, nela á uma janela \n'
            'fechada por tabuas e suja pela poeira além \n'
            'de uma varanda vazia que se observa uma \n'
            'porta azul e isso lhe chama a atenção')
else:
      resposta = input('Comando invalido \n'
                       'O que vc gostaria de fazer? ')
print('')
print('')

resposta2 = input('O que vc gostaria de fazer? ')

print('')
print('')

if resposta2 == r2:
      print('vc passa pela varanda e chega ate a porta \n'
            'assim parando na frente da mesma...')
else:
      resposta2 = input('Comando invalido \n'
                       'O que vc gostaria de fazer? ')

print('')
print('')

resposta3 = input('O que vc gostaria de fazer? ')

print('')
print('')

if resposta3 == r1:
      print('Meticulosamente você observa a porta \n'
            'e escuta o vento passar por entre sua fresta, \n'
            'você roda a maçaneta e descobre \n'
            'que a mesma se encontra destrancada...')

else:
      resposta3 = input('Comando invalido \n'
                       'O que vc gostaria de fazer? ')

print('')
print('')

resposta3 = input('O que vc gostaria de fazer? ')

print('')
print('')

if resposta3 == r3:
      print('passando pela porta vc se encontra em um cômodo \n'
      'que dá vai a uma que vai a cozinha \n'
      'e uma outra que vai a sala alem, de \n'
      'uma escada que sobe a o segundo andar.')

else:
      resposta3 = input('Comando invalido \n'
                       'O que vc gostaria de fazer? ')

print('')
print('')

print('De repente um estrondo é ouvido \n'
      'e da escada algo vem correndo em sua direção ...')

print('')
print('')

delayed_print('ESSE É O FIM POR ENQUANTO\n'
              'MUITO OBRIGADO POR JOGAR')