from numpy import genfromtxt
import numpy as np
import matplotlib.pyplot as plt
import glob, os, shutil

#

os.chdir("C:\\RugJelmertModelingOutput\\test\\")

cities = ["1x10_ingroup.half","1x10_ingroup"]
#cities = ["heerde","diemen","schiedam","emmen","breda","groningen","almere","rotterdam"]
#cities = ["01_Heerde","02_Diemen","03_Schiedam","04_Emmen","05_Breda","06_Groningen","07_Almere","08_Rotterdam"]

for city in cities:

    os.chdir("C:\\RugJelmertModelingOutput\\test\\")
    os.chdir(city)
    os.chdir("_aggregated");

    print(os.getcwd())

    if(os.path.isdir("png")):
        shutil.rmtree("png")

    if(os.path.isdir("pdf")):
        shutil.rmtree("pdf")

    if(os.path.isdir("csv")):
        shutil.rmtree("csv")

    os.mkdir("png")
    os.mkdir("png/mean")
    os.mkdir("pdf")
    os.mkdir("csv")
    os.mkdir("csv/mean")

    for file in glob.glob("*.aggregated.csv"):
        my_data = genfromtxt(file, delimiter=';')

        avg = my_data[0];

        for i in range(0,len(my_data)):

            if i > 0:
                avg += my_data[i]
            plt.plot(my_data[i])

        avg /= len(my_data)

        split = file.split('.')

        plt.grid(True)
        plt.xlim(0,100)

        ylim = plt.ylim()

        if ylim[0] < 0:
            plt.ylim(-1.1,1.1)
        elif ylim[1] > 1.1:
            plt.ylim(0,2.1)
        else:
            plt.ylim(-0.1,1.1)

        #plt.title(split[0])
        plt.savefig("pdf/{0}{1}".format(split[0],'.pdf'), bbox_inches='tight')
        plt.savefig("png/{0}{1}".format(split[0],'.png'), bbox_inches='tight')
        plt.clf()

        plt.plot(avg)
        #plt.title("".join([split[0]," AVG"]))

        plt.grid(True)
        plt.xlim(0,100)

        ylim = plt.ylim()

        if ylim[0] < 0:
            plt.ylim(-1.1,1.1)
        elif ylim[1] > 1.1:
            plt.ylim(0,2.1)
        else:
            plt.ylim(-0.1,1.1)

        np.savetxt("csv/mean/{0}{1}".format(split[0],'.avg.csv'), avg, delimiter=";")
        plt.savefig("png/mean/{0}{1}".format(split[0],'.avg.png'), bbox_inches='tight')
        plt.clf()

        shutil.copy(file, "".join(["csv/",file]))

    print("Done..")


'''Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de tinta a serem compradas e o preço total.'''

largura_parede = float(input(f'Informe a largura da parede: '))
altura_parede = float(input(f'Informe a altura da parede: '))
area = largura_parede * altura_parede

tinta_necessaria = area / 3
baldes_tinta = tinta_necessaria / 18
dinheiro_balde = baldes_tinta * 80

print('=' * 35)
print(f'Para uma parede com área de {area}m² é necessário {tinta_necessaria:.1f} litros de tinta')
print(f'Serão gastos {baldes_tinta:.1f} baldes')
print(f'R$80,00/balde x {baldes_tinta:.1f} = R${dinheiro_balde:.2f}')


# Adds support for obtaining property types from docstring signatures, and
# improves formatting by PyProperty of type annotations.

import re
from typing import Tuple, Optional, List

import docutils.nodes
import docutils.parsers.rst.directives
import sphinx.addnodes
import sphinx.domains
import sphinx.domains.python
import sphinx.ext.autodoc

property_sig_re = re.compile('^(\\(.*)\\)\\s*->\\s*(.*)$')

def _get_property_return_type(obj: property) -> Optional[str]:
    if obj.fget is None: return None
    doc = obj.fget.__doc__
    if doc is None: return None
    line = doc.splitlines()[0]
    line = line.rstrip('\\').strip()
    match = property_sig_re.match(line)
    if not match: return None
    _, retann = match.groups()
    return retann

def _apply_property_documenter_type_annotation_fix():

    # Modify PropertyDocumenter to support obtaining signature from docstring.
    PropertyDocumenter = sphinx.ext.autodoc.PropertyDocumenter

    orig_import_object = PropertyDocumenter.import_object

    def import_object(self: PropertyDocumenter, raiseerror: bool = False) -> bool:
        result = orig_import_object(self, raiseerror)
        if not result:
            return False
        if not self.retann:
            self.retann = _get_property_return_type(self.object)
        return True

    PropertyDocumenter.import_object = import_object

    old_add_directive_header = PropertyDocumenter.add_directive_header

    def add_directive_header(self, sig: str) -> None:
        old_add_directive_header(self, sig)

        # Check for return annotation
        retann = self.retann or _get_property_return_type(self.object)
        if retann is not None:
            self.add_line('   :type: ' + retann, self.get_sourcename())

    PropertyDocumenter.add_directive_header = add_directive_header

    # Modify PyProperty to improve formatting of :type: option
    PyProperty = sphinx.domains.python.PyProperty

    def handle_signature(
            self, sig: str,
            signode: sphinx.addnodes.desc_signature) -> Tuple[str, str]:
        fullname, prefix = super(PyProperty,
                                 self).handle_signature(sig, signode)

        typ = self.options.get('type')
        if typ:
            signode += sphinx.addnodes.desc_sig_punctuation('', ' : ')
            signode += sphinx.domains.python._parse_annotation(typ, self.env)

        return fullname, prefix

    PyProperty.handle_signature = handle_signature

_apply_property_documenter_type_annotation_fix()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('vegetation', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='vegetationstate',
            name='revision',
            field=models.PositiveIntegerField(default=1, editable=False, blank=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='areavegetation',
            name='territory',
            field=models.ForeignKey(blank=True, to='coremodels.Territory', null=True),
        ),
        migrations.AlterField(
            model_name='pointvegetation',
            name='territory',
            field=models.ForeignKey(blank=True, to='coremodels.Territory', null=True),
        ),
    ]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import subprocess
from sys import platform
import sys
import requests
import gzip
import shutil
import os.path

# Credit goes to Sumit Ghosh: https://sumit-ghosh.com/articles/python-download-progress-bar/
def download(url, filename):
    with open(filename, 'wb') as f:
        response = requests.get(url, stream=True)
        total = response.headers.get('content-length')

        if total is None:
            f.write(response.content)
        else:
            downloaded = 0
            total = int(total)
            for data in response.iter_content(chunk_size=max(int(total/1000), 1024*1024)):
                downloaded += len(data)
                f.write(data)
                done = int(50*downloaded/total)
                sys.stdout.write('\r[{}{}]'.format('█' * done, '.' * (50-done)))
                sys.stdout.flush()
    sys.stdout.write('\n')

if platform == "linux" or platform == "linux2":
    known_versions = {
        b"0.35.1" : "https://github.com/elbywan/crystalline/releases/download/v0.1.9/crystalline_linux.gz",
        b"0.36"   : "https://github.com/elbywan/crystalline/releases/download/v0.2.1/crystalline_x86_64-unknown-linux-gnu.gz",
        b"1.0.0"  : "https://github.com/elbywan/crystalline/releases/download/v0.3.0/crystalline_x86_64-unknown-linux-gnu.gz"
        }
elif platform == "darwin":
    known_versions = {
        b"0.35.1" : "https://github.com/elbywan/crystalline/releases/download/v0.1.9/crystalline_darwin.gz",
        b"0.36"   : "https://github.com/elbywan/crystalline/releases/download/v0.2.1/crystalline_x86_64-apple-darwin.gz",
        b"1.0.0"  : "https://github.com/elbywan/crystalline/releases/download/v0.3.0/crystalline_x86_64-apple-darwin.gz"
        }
else:
    print("Unable to probe OS version, or your OS is not supported")
    exit(1)

# result = subprocess.Popen('/opt/crystal-0.36/bin/crystal --version', shell=True, stdout=subprocess.PIPE)
result = subprocess.Popen('crystal --version', shell=True, stdout=subprocess.PIPE)
result.wait()
if result.returncode:
    print("There is an error looking for Crystal version. Possibly, Crystal is not installed")
    exit(2)

versionline = result.stdout.readlines()
if not (versionline and versionline[0][:7] == b"Crystal"):
    print("Unable to find Crystal version in crystal output")
    exit(3)

versionline = versionline[0]
sspace = versionline.index(b' ', 8)
version = versionline.split()[1]
print(f"Found Crystal version {version.decode('utf-8')}")

url = ""
for v in known_versions:
    if version >= v:
        url = known_versions[v]

if not url:
    print("Unable to find crystalline URL for your Crystal version")
    exit(4)

print(f"Using URL {url}")
if os.path.isfile("/tmp/crystalline.gz"):
    print("Re-using downloaded file")
else:
    download(url, "/tmp/crystalline.gz")

with gzip.open("/tmp/crystalline.gz", "rb") as z:
    with open("/tmp/crystalline", "wb") as f:
        f.write(z.read())
subprocess.check_call( ("chmod", "+x", "/tmp/crystalline") )

try:
    try:
        os.mkdir("bin")
    except FileExistsError:
        pass
    shutil.move("/tmp/crystalline", "bin/crystalline")
except OSError:
    print("Error writing bin/crystalline. Possibly, you don't have permissions")


import random
import functions

def main():
    while True:

        choice = input("Do you want to register, login or see leaderboard?")
        if choice == "register":
            functions.register()
        elif choice == 'login':
            print("Player 1 please login")
            player1 = functions.login()
            choice1 = input("Do you want to register another player(You will need to login once again)")
            if choice1 == "yes":
                functions.register()
            elif choice1== "no" :
                    print("Player 2 please login")
                    player2 = functions.login()

                    Player1Roll = functions.roll(player1)
                    Player2Roll = functions.roll(player2)

                    functions.decisive(Player1Roll, Player2Roll, player1, player2)
            elif choice == "see leaderboard":
                    functions.printLeaderboard()
            else:
                print('Wrong keyword, please try again.')

main()


# Databricks notebook source
# MAGIC %pip install pydantic

# COMMAND ----------

from pydantic import BaseSettings
class Settings(BaseSettings):
    SPARK_MASTER: str = "local[*]"
    AZURE_ACC_1: str = ""
    AZURE_CLIENT_ID_1: str = ""
    AZURE_CLIENT_SECRET_1: str = ""
    AZURE_TENANT_ID_1: str = ""
    AZURE_ACC_2: str = ""
    AZURE_ACC_KEY_2 = ""

    class Config:
        env_file = ".env"
        case_sensitive = True

settings = Settings()

# COMMAND ----------

spark.conf.set(f"fs.azure.account.auth.type.{settings.AZURE_ACC_1}.dfs.core.windows.net",
               "OAuth")
spark.conf.set( f"fs.azure.account.oauth.provider.type.{settings.AZURE_ACC_1}.dfs.core.windows.net",
               "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider", )
spark.conf.set( f"fs.azure.account.oauth2.client.id.{settings.AZURE_ACC_1}.dfs.core.windows.net",
               settings.AZURE_CLIENT_ID_1, )
spark.conf.set( f"fs.azure.account.oauth2.client.secret.{settings.AZURE_ACC_1}.dfs.core.windows.net",
               settings.AZURE_CLIENT_SECRET_1, )
spark.conf.set( f"fs.azure.account.oauth2.client.endpoint.{settings.AZURE_ACC_1}.dfs.core.windows.net",
               settings.AZURE_TENANT_ID_1, )
spark.conf.set(f"fs.azure.account.key.{settings.AZURE_ACC_2}.dfs.core.windows.net", settings.AZURE_ACC_KEY_2)

# COMMAND ----------

df = spark.read.parquet(f"abfss://m07sparksql@{settings.AZURE_ACC_1}.dfs.core.windows.net/hotel-weather")
av_df = spark.read.format("avro").load(f"abfss://m07sparksql@{settings.AZURE_ACC_1}.dfs.core.windows.net/expedia")
df.write.mode("overwrite").format("delta").saveAsTable("hotel_weather")
av_df.write.format("delta").saveAsTable("expedia_delta")

# COMMAND ----------

# MAGIC %md
# MAGIC # First part

# COMMAND ----------

# MAGIC %sql
# MAGIC create or replace temp view max_dif_tmpr_hotels as
# MAGIC select *
# MAGIC from (select rank() over (partition by y_m order by avg_tmpr_c desc, id) as temp_rank,
# MAGIC   id, y_m, avg_tmpr_c
# MAGIC   from (
# MAGIC       select year || "_" || month as y_m, max(avg_tmpr_c) as avg_tmpr_c, id
# MAGIC       from hotel_weather
# MAGIC       group by y_m, id
# MAGIC   )
# MAGIC )
# MAGIC   where temp_rank <= 10

# COMMAND ----------

# MAGIC %md
# MAGIC # Second part

# COMMAND ----------

# MAGIC %sql
# MAGIC create or replace temp view year_month_day
# MAGIC as select min(srch_ci) as min_d, max(srch_co) as max_d from expedia_delta

# COMMAND ----------

months_dif = int(spark.sql("select round(months_between(max_d, min_d)) as month_diff from year_month_day").first()["month_diff"])
spark.range(0, months_dif + 1).createOrReplaceTempView("months_dif")

# COMMAND ----------

# MAGIC %sql
# MAGIC create or replace temp view year_months
# MAGIC as select extract('year', (add_months(ymd.min_d, md.id))) || "-" || extract('month', (add_months(ymd.min_d, md.id))) as m
# MAGIC   from months_dif md, year_month_day ymd

# COMMAND ----------

# MAGIC %sql
# MAGIC create or replace temp view mnth_cnt
# MAGIC as select e.hotel_id, ym.m, 1 as cnt
# MAGIC     from expedia_delta e
# MAGIC     join year_months ym
# MAGIC     on ym.m >= e.srch_ci and ym.m <= e.srch_co

# COMMAND ----------

# MAGIC %sql
# MAGIC create or replace temp view busy_hotels as
# MAGIC select *  from (
# MAGIC   select row_number() over (partition by m order by cnt desc) as busy_rank,
# MAGIC     m, hotel_id, cnt
# MAGIC     from (
# MAGIC   select m, hotel_id, sum(cnt) as cnt
# MAGIC   from mnth_cnt
# MAGIC   group by m, hotel_id
# MAGIC )
# MAGIC )
# MAGIC where busy_rank <= 10
# MAGIC

# COMMAND ----------

# MAGIC %md
# MAGIC # Third part

# COMMAND ----------

# MAGIC %sql
# MAGIC create or replace temp view lng_stay as
# MAGIC select id, hotel_id, srch_ci, srch_co, datediff(srch_co, srch_ci) as st_d  from expedia_delta
# MAGIC where datediff(srch_co, srch_ci) >= 7

# COMMAND ----------

# MAGIC %sql
# MAGIC create or replace temp view ech_day_tmpr as
# MAGIC select ls.id, hw.wthr_date, hw.avg_tmpr_c
# MAGIC from lng_stay ls
# MAGIC join hotel_weather hw
# MAGIC on ls.hotel_id = hw.id
# MAGIC where ls.srch_ci <= hw.wthr_date and ls.srch_co >= hw.wthr_date
# MAGIC

# COMMAND ----------

# MAGIC %sql
# MAGIC create or replace temp view avg_min_max_data as
# MAGIC select t1.*, t2.avg_tmpr_c as max_day_tmpr
# MAGIC from (select t1.*, t2.avg_tmpr_c as min_day_tmpr
# MAGIC from (
# MAGIC select id,
# MAGIC avg(avg_tmpr_c) as avg_tmpr,
# MAGIC min(wthr_date) as min_date,
# MAGIC max(wthr_date) as max_date
# MAGIC from ech_day_tmpr
# MAGIC group by id
# MAGIC ) t1
# MAGIC join ech_day_tmpr t2
# MAGIC on t1.id = t2.id
# MAGIC where t1.min_date = t2.wthr_date) t1
# MAGIC join ech_day_tmpr t2
# MAGIC on t1.id = t2.id
# MAGIC where t1.max_date = t2.wthr_date

# COMMAND ----------

# MAGIC %sql
# MAGIC create or replace temp view tmpr_for_extnd
# MAGIC select ls.id, amd.avg_tmpr,
# MAGIC case when ls.srch_ci = amd.min_date then min_day_tmpr
# MAGIC else null end as fd_tmpr,
# MAGIC case when ls.srch_co = amd.max_date then max_day_tmpr
# MAGIC else null end as ld_tmpr
# MAGIC from lng_stay ls
# MAGIC join avg_min_max_data amd
# MAGIC on ls.id = amd.id

# COMMAND ----------

df_1 = spark.sql("select * from max_dif_tmpr_hotels")
df_1.write.parquet(f"abfss://data@{settings.AZURE_ACC_2}.dfs.core.windows.net/module_2/task_1")
df_2 = spark.sql("select * from year_month_day")
df_2.write.parquet(f"abfss://data@{settings.AZURE_ACC_2}.dfs.core.windows.net/module_2/task_2")
df_3 = spark.sql("select * from tmpr_for_extnd")
df_3.write.parquet(f"abfss://data@{settings.AZURE_ACC_2}.dfs.core.windows.net/module_2/task_3")


import datetime
from calendar import Calendar, day_name

positionTable = {
    '1st': 0,
    '2nd': 1,
    '3rd': 2,
    '4th': 3,
    '5th': 4,
    'last': -1,
    'teenth': 2
}

def meetup_day(year, month, day, position):
	dates = Calendar().itermonthdates(year, month)
	if position != 'teenth':
		dates = list(filter(lambda _date:_date.month==month, dates))
	dates = list(filter(lambda _date:day_name[_date.weekday()]==day, dates))
	return dates[positionTable[position]]


from flask import Flask, request, make_response, abort, Response
from flask_cors import cross_origin

import json
from redis import Redis

import boto3
import botocore

from config import S3_BUCKET
from tasks import makePacket

app = Flask(__name__)
app.config.from_object('config')

redis = Redis()

@app.route('/')
def index():
    return 'A flask app that listens for requests from LA Metro Councilmatic. The app consolidates PDFs for Board Reports and Events, stores the merged documents, and provides a route that returns PDFs.'

@app.route('/pong/')
def pong():

    try:
        from deployment import DEPLOYMENT_ID
    except ImportError:
        abort(401)

    return DEPLOYMENT_ID

@app.route('/merge_pdfs/<slug>', methods=['POST'])
def merge_pdfs(slug):

    file_urls = json.loads(request.data.decode())

    makePacket.delay(slug, file_urls)

    return json.dumps({'success': True})

@app.route('/document/<ocd_id>')
@cross_origin()
def document(ocd_id):

    client = boto3.client('s3')

    try:
        document = client.get_object(Bucket=S3_BUCKET,
                                     Key='{}.pdf'.format(ocd_id))
    except botocore.exceptions.ClientError:
        response = make_response('Document not found', 404)
    else:
        # This closure just iterates the streaming response from S3 into a
        # streaming response from this route. That way we don't have to read
        # anything into memory
        def generate_response(doc):
            while doc._amount_read < int(doc._content_length):
                yield doc.read(4096)

        response = Response(generate_response(document['Body']))
        response.headers["Content-Disposition"] = 'attachment; filename={}.pdf'.format(ocd_id)
        response.headers['Content-Length'] = document['ContentLength']

    return response

if __name__ == "__main__":

    app.run(host='0.0.0.0', debug=True)


import sys
from PyQt4 import QtCore,QtGui

class UI(QtGui.QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("模拟发送信号")
        self.resize(500,500)

        label1 = QtGui.QLabel("点击窗体内的任意位置，程序会结束",self)

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(label1)
        hbox.addStretch(1)

        vbox = QtGui.QVBoxLayout()
        vbox.addLayout(hbox)
        self.setLayout(vbox)

        self.connect(self,QtCore.SIGNAL("func666()"),QtCore.SLOT("close()"))

    def mousePressEvent(self, QMouseEvent):
        print("通过鼠标点击窗体关闭")
        self.emit(QtCore.SIGNAL("func666()")) # 模拟发送信号

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = UI()
    w.show()
    sys.exit(app.exec_())

Python_QT/PyQt4练习/信号与槽/点击鼠标退出(模拟信号发送).py

点击鼠标退出(模拟信号发送).py


import numpy as np
import matplotlib.pyplot as plt

class HMM():
    def  __init__(self):
        pass

    def train(self, pi, A, B):
        self.pi = pi
        self.A = A
        self.B = B

    def setO(self, O):
        self.O = O
        self.K = self.O.shape[0]

    def setI(self, I):
        self.I = I
        self.N = self.I.shape[0]

    def setI_index(self, O_index):
        self.I_index = O_index
        #

    def setO_index(self, O_index):
        self.O_index = O_index
        self.T = O_index.shape[0]

    def updateAlpha(self, t):
        alpha_temp = np.dot(self.alpha.transpose(), self.A)
        self.alpha = np.multiply(alpha_temp.transpose(), self.B[:, self.O_index[t]])
        return self.alpha

    def updateBeta(self, t):
        beta_temp = np.multiply(self.B[:, self.O_index[t + 1]], self.beta)
        self.beta = np.dot(self.A, beta_temp)
        return self.beta

    def evaluate_direct(self, obervation):
        self.observation2index(obervation)
        pass

    def evaluate_direct_recurse(self, observation, last_i):
        pass

    def evaluate_forward(self, observation):
        self.observation2index(observation)
        # initialize alpha
        self.alpha = np.multiply(self.pi, self.B[:, self.O_index[0]])
        # loop updating
        for t in range(self.T - 1):
            self.updateAlpha(t + 1)
        P = np.sum(self.alpha)
        return P

    def evaluate_backward(self, observation):
        self.observation2index(observation)
        # initialize beta
        self.beta = np.ones([self.N, 1], dtype=np.float)
        # loop updating
        for t in range(self.T - 2, -1, -1):
            self.updateBeta(t)
        P = np.sum(np.multiply(np.multiply(self.pi, self.B[:, self.O_index[0]]), self.beta))
        return P

    def observation2index(self, observation):
        temp = np.zeros([observation.shape[0], 1], dtype=np.int32)
        for i in range(observation.shape[0]):
            temp[i] = np.where(self.O == observation[i])[0]
        self.setO_index(temp)

    def calcGama(self, t, N):
        pass

    def calcGamaAndXi(self, N, t):
        # calc beta
        # initialization
        self.beta = np.ones([self.pi.shape[0], 1])
        beta = np.zeros([t, N])
        beta[t - 1] = self.beta.transpose()
        for i in range(t - 2, -1, -1):
            self.updateBeta(i)
            beta[i] = self.beta.transpose()

        # calc alpha
        # initialization
        self.alpha = np.multiply(self.pi, self.B[:, self.O_index[0]])
        alpha = np.zeros([t, N])
        alpha[0] = self.alpha.transpose()
        for i in range(t - 1):
            self.updateAlpha(i + 1)
            alpha[i + 1] = self.alpha.transpose()
        # calc Gama
        self.Gama = np.multiply(alpha, beta)
        self.Gama = self.Gama/np.sum(self.Gama, axis=1).reshape([-1, 1])

        # calc Xi
        self.Xi = np.zeros([t - 1, N, N])
        for i in range(t - 1):
            temp = alpha[i, :].reshape([-1, 1])
            temp = np.multiply(temp, self.A)
            temp = np.multiply(temp, self.B[:, self.O_index[i + 1]].transpose())
            temp = np.multiply(temp, beta[i + 1, :])
            self.Xi[i] = temp/np.sum(temp)
        return (self.Gama, self.Xi)

    def calcXi(self, N, t):
        pass

    def learning(self, observation, hidden_num, num=2000):
        # 去重
        # self.seto(np.unique(observation))
        self.observation2index(observation)
        # initialization
        PLUS = 3
        self.N = hidden_num
        self.pi = np.random.normal(size=[self.N, 1]) + PLUS
        self.pi = self.pi/np.sum(self.pi)
        self.A = np.random.normal(size=[self.N, hidden_num]) + PLUS
        self.A = self.A/np.sum(self.A, axis=1).reshape([-1, 1])
        self.B = np.random.normal(size=[hidden_num, self.O.shape[0]]) + PLUS
        self.B = self.B/np.sum(self.B, axis=1).reshape([-1, 1])
        for n in range(num):
            self.calcGamaAndXi(self.N, self.T)
            # update A
            self.A = np.sum(self.Xi, axis=0)/((np.sum(self.Gama, axis=0)-self.Gama[self.T - 1, :]).reshape([-1, 1]))

            # update B
            temp = np.zeros([self.N, self.K])
            for j in range(self.N):
                temp_ = np.sum(np.dot(self.Gama[:, j].reshape([-1, 1]), self.B[j, :].reshape([1, -1])), axis=0)
                temp[j] = temp_ / np.sum(temp_)
            self.B = temp

            # update pi
            self.pi = self.Gama[0, :].reshape([-1, 1])

    def decoding(self, observation):
        # initialization
        self.observation2index(observation)
        self.delta = np.multiply(self.pi, self.B[:, self.O_index[0]])
        self.fi = np.zeros([self.T, self.N])
        # loop
        for i in range(self.T - 1):
            temp = np.multiply(self.delta, self.A)
            temp = np.multiply(temp, self.B[:, self.O_index[i + 1]].reshape([1, -1]))
            self.delta = np.max(temp, axis=0)
            self.fi[i + 1] = np.argmax(temp, axis=0)
        P = np.max(self.delta)
        I_star = np.zeros(self.T, dtype=int)
        I_star[self.T - 1] = np.argmax(self.delta)
        for i in range(self.T - 2, -1, -1):
            I_star[i] = self.fi[i + 1, I_star[i + 1]]
        return (P, I_star)

    def generate_observations_max_posibility(self, length):
        I = np.zeros([length], dtype=int)
        O = np.zeros([length], dtype=self.O.dtype)
        t = 0

        I[t] = np.argmax(self.pi)
        index = np.argmax(self.B[I[t], :])
        O[0] = self.O[index]
        for i in range(1, length, 1):
            I[i] = np.argmax(self.A[I[i - 1], :])
            index = np.argmax(self.B[I[i], :])
            O[i] = self.O[index]
        return O

    def generate_observations(self, length):
        I = np.zeros([length + 1], dtype=int)
        O = np.zeros([length], dtype=self.O.dtype)
        t = 0

        p = np.random.rand()
        p_sum = 0
        for i in range(self.N):
            p_sum += self.pi[i]
            if(p_sum >= p):
                I[t] = i
                break
        for t in range(0, length, 1):
            # generate O[t]
            p_sum = 0
            p = np.random.rand()
            index = 0
            for i in range(self.K):
                p_sum += self.B[I[t], i]
                if(p_sum >= p):
                    index = i
                    break
            O[t] = self.O[index]

            p = np.random.rand()
            p_sum = 0
            for i in range(self.N):
                p_sum += self.pi[i]
                if(p_sum >= p):
                    I[t + 1] = i
        return O

x = np.linspace(0, 4, 100).reshape([-1, 1])
y = np.sin(x)
hmm = HMM()
hmm.setO(y)

hmm.learning(y, 1000, num=400)

# print('final:\n')
print('Pi\n', hmm.pi)
print('A\n', hmm.A)
print("B\n", hmm.B)

plt.plot(x, y)
x = np.linspace(0, 31.4, 1000).reshape([-1, 1])
y = hmm.generate_observations(1000)
# print(y)
plt.plot(x, y)
plt.show()


import openpyxl

def dataGenerator():
    wb = openpyxl.load_workbook("/Users/navaneeth/Downloads/Flightz.xlsx")
    sh = wb['Sheet1']
    row = sh.max_row
    outer_list =[]
    inner_list = []
    for i in range(1, row+1):
        inner_list = []
        source = sh.cell(i,1)
        destination = sh.cell(i,2)
        inner_list.insert(0,source.value)
        inner_list.insert(1, destination.value)
        outer_list.insert(i-1, inner_list)
    return outer_list


import socket
import sys
from pathlib import Path

#---------------- Global --------------------

BUFFER = 1024
current_dir = []

#---------------- Functions --------------------

def print_current_dir():
    for i in current_dir:
        print(i + '/',end='')

def help():
    print("init - Initialize the storage on a new system, remove any existing file in the dfs root directory and return available size.")
    print("create *file name* -  create a new empty file")
    print("read *file name* - download a file from the DFS")
    print("write *file name* - upload a file from the Client side to the DFS")
    print("delete *file name* - delete file from DFS")
    print("info *file name* - information about the file")
    print("rename *file name* *new file name* - information about the file")
    print("copy *file name* *path* - create a copy of file")
    print("move *file name* *path* - move a file to the specified path")
    print("cd *path* - change directory")
    print("ls - list of files, which are stored in the directory")
    print("mkdir *path* - create a new directory")
    print("deldir *path* - delete directory")
    print("q - exit")

def init(in_str, s_to_name):
    s_to_name.send(bytes(in_str[0], 'utf-8'))
    print('Size available: ' + s_to_name.recv(BUFFER).decode('utf-8'))

def create(in_str, s_to_name):
    if (len(in_str) == 2):
        s_to_name.send(bytes(in_str[0] + ' ' + in_str[1], 'utf-8'))
    else:
        print('Error: Incorrect number of parameters')

def write(in_str, s_to_name):
    if (len(in_str) == 2):
        file_ = open (in_str[1], "rb")
        data = file_.read(BUFFER)
        if (not data):
            print('File is empty! use create')
            return
        s_to_name.send(bytes(in_str[0] + ' ' + in_str[1], 'utf-8'))
        res = s_to_name.recv(BUFFER).decode('utf-8')
        if (res == '1'):
            print('It\'s directory! Not the file')
            file_.close()
            return
        while(data):
            s_to_name.send(data)
            s_to_name.recv(BUFFER)
            data = file_.read(BUFFER)
        s_to_name.send(bytes('Eof0End0Eof', 'utf-8'))
        file_.close()
    else:
        print('Error: Incorrect number of parameters')

def read(in_str, s_to_name):
    if (len(in_str) == 2):
        s_to_name.send(bytes(in_str[0] + ' ' + in_str[1], 'utf-8'))
        ans = s_to_name.recv(BUFFER).decode('utf-8')
        if (ans == 'Empty'):
            print('Empty file or file does not exist')
        else:
            file_ = open(in_str[1],'wb+')
            data = s_to_name.recv(BUFFER)
            while (data):
                file_.write(data)
                s_to_name.send(bytes('Ok', 'utf-8'))
                data = s_to_name.recv(BUFFER)
                if (data.decode('utf-8') == 'Eof0End0Eof'):
                    break
            file_.close()
    else:
        print('Error: Incorrect number of parameters')

def info(input_str, s_to_name):
    if (len(in_str) == 2):
        s_to_name.send(bytes(in_str[0] + ' ' + in_str[1], 'utf-8'))
        ans = s_to_name.recv(BUFFER).decode('utf-8')
        if (ans == '1'):
            print('No such file')
        print(ans)
    else:
        print('Error: Incorrect number of parameters')

def delete(in_str, s_to_name):
    if (len(in_str) == 2):
        s_to_name.send(bytes(in_str[0] + ' ' + in_str[1], 'utf-8'))
        ans = s_to_name.recv(BUFFER).decode('utf-8')
        if (ans == '1'):
            print('No such file')
    else:
        print('Error: Incorrect number of parameters')

def rename(in_str, s_to_name):
    if (len(in_str) == 3):
        s_to_name.send(bytes(in_str[0] + ' ' + in_str[1] + ' ' + in_str[2], 'utf-8'))
        ans = s_to_name.recv(BUFFER).decode('utf-8')
        if (ans == '1'):
            print('No such file or directory')
    else:
        print('Error: Incorrect number of parameters')

def copy(in_str, s_to_name):
    if (len(in_str) == 3):
        s_to_name.send(bytes(in_str[0] + ' ' + in_str[1] + ' ' + in_str[2], 'utf-8'))
        ans = s_to_name.recv(BUFFER).decode('utf-8')
        if (ans == '1'):
            print('No such file')
        if (ans == '2'):
            print('No such directory')
    else:
        print('Error: Incorrect number of parameters')

def move(in_str, s_to_name):
    if (len(in_str) == 3):
        s_to_name.send(bytes(in_str[0] + ' ' + in_str[1] + ' ' + in_str[2], 'utf-8'))
        ans = s_to_name.recv(BUFFER).decode('utf-8')
        if (ans == '1'):
            print('No such file')
        if (ans == '2'):
            print('No such directory')
    else:
        print('Error: Incorrect number of parameters')

def cd(in_str, s_to_name):
    if (len(in_str) == 2):
        s_to_name.send(bytes(in_str[0] + ' ' + in_str[1], 'utf-8'))
        ans = s_to_name.recv(BUFFER).decode('utf-8')
        if (ans == 'Ok'):
            if (in_str[1] != '..'):
                current_dir.append(in_str[1])
            else:
                current_dir.pop()
        else:
            print('Command failed')
    else:
        print('Error: Incorrect number of parameters')

def ls(in_str, s_to_name):
    if (len(in_str) == 1):
        s_to_name.send(bytes(in_str[0], 'utf-8'))
        ans_d = s_to_name.recv(BUFFER * 2).decode("utf-8")
        s_to_name.send(bytes('Ok', 'utf-8'))
        ans_f = s_to_name.recv(BUFFER * 2).decode("utf-8")
        print('directories:' + ans_d)
        print('files:' + ans_f)
    else:
        print('Error: Incorrect number of parameters')

def mkdir(in_str, s_to_name):
    if (len(in_str) == 2):
        s_to_name.send(bytes(in_str[0] + ' ' + in_str[1], 'utf-8'))
    else:
        print('Error: Incorrect number of parameters')

def deldir(in_str, s_to_name):
    if (len(in_str) == 2):
        s_to_name.send(bytes(in_str[0] + ' ' + in_str[1], 'utf-8'))
        rep = s_to_name.recv(BUFFER).decode('utf-8')
        if (rep == 'Ok'):
            s_to_name.send(bytes('Ok', 'utf-8'))
        if (rep == 'Not empty'):
            print('Directory is not empty. Delete directory? (print ''Ok'' to accept)')
            s_to_name.send(bytes(input(), 'utf-8'))
        if (rep == '1'):
            print('No such directory')
    else:
        print('Error: Incorrect number of parameters')

#---------------- Program --------------------

# Get parameters from console
# filename = sys.argv[1]
host = sys.argv[1]
port = 8000 # int(sys.argv[2])

# Get size of file in bytes
# filesize = Path(filename).stat().st_size
# currentfilesize = 0

# Create socket
s = socket.socket(socket.AF_INET)
# Connect to server
s.connect((host,port))

# Send name of file
# s.send(bytes(filename, 'utf-8'))
# Send file data
# f = open (filename, "rb")
# l = f.read(1024)

while (True):
    print(">>",end='')
    print_current_dir()
    input_str = input().split()
    if (input_str[0] == "help"):
        help()
        continue
    if (input_str[0] == "create"):
        create(input_str, s)
        continue
    if (input_str[0] == "read"):
        read(input_str, s)
        continue
    if (input_str[0] == "write"):
        write(input_str, s)
        continue
    if (input_str[0] == "delete"):
        delete(input_str, s)
        continue
    if (input_str[0] == "init"):
        init(input_str, s)
        continue
    if (input_str[0] == "info"):
        info(input_str, s)
        continue
    if (input_str[0] == "rename"):
        rename(input_str, s)
        continue
    if (input_str[0] == "copy"):
        copy(input_str, s)
        continue
    if (input_str[0] == "move"):
        move(input_str, s)
        continue
    if (input_str[0] == "cd"):
        cd(input_str, s)
        continue
    if (input_str[0] == "ls"):
        ls(input_str, s)
        continue
    if (input_str[0] == "mkdir"):
        mkdir(input_str, s)
        continue
    if (input_str[0] == "deldir"):
        deldir(input_str, s)
        continue
    if (input_str[0] == "q"):
        s.send(bytes('close', 'utf-8'))
        break;
    print("Unknow command")
s.close()

# python client.py car.png "18.188.141.97" 8888


#! /usr/bin/env python
from __future__ import print_function
import os
import sys
import logging
import argparse

sys.path.append(
    os.path.realpath(
        os.path.join(
            os.path.dirname(__file__),
            "..")))

from mykatlas.version import __version__
from mykatlas.base import ArgumentParserWithDefaults
from mykatlas.base import DEFAULT_DB_NAME
from mykatlas.base import sequence_parser_mixin
from mykatlas.base import sequence_or_binary_parser_mixin
from mykatlas.base import probe_set_mixin
from mykatlas.base import force_mixin
from mykatlas.base import genotyping_mixin

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger(__name__)

DEFAULT_KMER_SIZE = os.environ.get("KMER_SIZE", 31)

def run_subtool(parser, args):
    # if args.command == 'add':
    #     from mykatlas.cmds.add import run
    # elif args.command == "add-gt":
    #     from mykatlas.cmds.atlasadd import run
    # elif args.command == "dump-probes":
    #     from mykatlas.cmds.dump import run
    # elif args.command == "make-probes":
    #     from mykatlas.cmds.makeprobes import run
    if args.command == "genotype":
        from mykatlas.cmds.genotype import run
    elif args.command == "walk":
        from mykatlas.cmds.walk import run
    elif args.command == "place":
        from mykatlas.cmds.place import run
    elif args.command == "diff":
        from mykatlas.cmds.diff import run
    # run the chosen submodule.
    run(parser, args)

def main():
    #########################################
    # create the top-level parser
    #########################################
    parser = argparse.ArgumentParser(
        prog='atlas',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("--version", help="atlas version",
                        action="version",
                        version="%(prog)s " + str(__version__))
    subparsers = parser.add_subparsers(
        title='[sub-commands]',
        dest='command',
        parser_class=ArgumentParserWithDefaults)

    db_parser_mixin = argparse.ArgumentParser(add_help=False)
    db_parser_mixin.add_argument(
        '--db_name',
        metavar='db_name',
        type=str,
        help='db_name',
        default="default")

    # ##########
    # # Add
    # ##########
    # parser_add = subparsers.add_parser(
    #     'add',
    #     help='adds a set of variants to the atlas',
    #     parents=[db_parser_mixin, force_mixin])
    # parser_add.add_argument('vcf', type=str, help='a vcf file')
    # parser_add.add_argument('reference_set', type=str, help='reference set')
    # parser_add.add_argument(
    #     '-m',
    #     '--method',
    #     type=str,
    #     help='variant caller method (e.g. CORTEX)',
    #     default="NotSpecified")
    # parser_add.set_defaults(func=run_subtool)

    # parser_add_gt = subparsers.add_parser(
    #     'add-gt',
    #     help='adds a set of atlas genotype calls to the atlas',
    #     parents=[db_parser_mixin, force_mixin])
    # parser_add_gt.add_argument('jsons', type=str, nargs='+',
    #                            help='json output from `atlas genotype`')
    # parser_add_gt.add_argument(
    #     '-m',
    #     '--method',
    #     type=str,
    #     help='variant caller method (e.g. CORTEX)',
    #     default="atlas")
    # parser_add_gt.set_defaults(func=run_subtool)

    # # ##########
    # # # Dump panel
    # # ##########
    # parser_dump = subparsers.add_parser(
    #     'dump-probes',
    #     help='dump a probe set of variant alleles',
    #     parents=[db_parser_mixin, force_mixin])
    # parser_dump.add_argument(
    #     'reference_filepath',
    #     metavar='reference_filepath',
    #     type=str,
    #     help='reference_filepath')
    # parser_dump.add_argument(
    #     '--kmer',
    #     metavar='kmer',
    #     type=int,
    #     help='kmer length',
    #     default=31)
    # parser_dump.add_argument(
    #     '-v',
    #     '--verbose',
    #     default=False,
    #     action="store_true")
    # parser_dump.set_defaults(func=run_subtool)

    # ##################
    # ### Make Probes ##
    # ##################

    # parser_make_probes = subparsers.add_parser(
    #     'make-probes', help='make probes from a list of variants',
    #     parents=[db_parser_mixin])
    # parser_make_probes.add_argument(
    #     'reference_filepath',
    #     metavar='reference_filepath',
    #     type=str,
    #     help='reference_filepath')
    # parser_make_probes.add_argument(
    #     '-f',
    #     '--vcf',
    #     type=str,
    #     help='Use variants defined in a VCF file',
    #     default=[])
    # parser_make_probes.add_argument(
    #     '-v',
    #     '--variant',
    #     type=str,
    #     action='append',
    #     help='Variant in DNA positions e.g. A1234T',
    #     default=[])
    # parser_make_probes.add_argument(
    #     '-t',
    #     '--text_file',
    #     type=str,
    #     help='Text file containing variants as rows A1234T')
    # parser_make_probes.add_argument(
    #     '-g',
    #     '--genbank',
    #     type=str,
    #     help='Genbank file containing genes as features')
    # parser_make_probes.add_argument(
    #     '-k',
    #     '--kmer',
    #     type=int,
    #     help='kmer length',
    #     default=31)
    # parser_make_probes.add_argument(
    #     '--no-backgrounds',
    #     help='Build probe set against reference only ignoring nearby variants',
    #     default=False,
    #     action="store_true")
    # parser_make_probes.set_defaults(func=run_subtool)

    # ##########
    # # Genotype
    # ##########
    parser_geno = subparsers.add_parser(
        'genotype',
        parents=[
            sequence_or_binary_parser_mixin,
            probe_set_mixin,
            force_mixin,
            genotyping_mixin],
        help='genotype a sample using a probe set')
    parser_geno.set_defaults(func=run_subtool)

    ##############
    ## Walk ##
    #############
    parser_walk = subparsers.add_parser(
        'walk',
        parents=[
            sequence_or_binary_parser_mixin,
            probe_set_mixin,
            force_mixin,
            genotyping_mixin],
        help='Walk through a graph using an existing sequence probe set as seeds. default walking algorithm is a depth first search')
    parser_walk.add_argument(
        '--also-genotype',
        default=False,
        action="store_true")
    parser_walk.add_argument('--show-all-paths', action="store_true")
    parser_walk.set_defaults(func=run_subtool)

    ##############
    ## Place ##
    #############
    parser_place = subparsers.add_parser(
        'place', help='Place a sample on a prebuilt tree', parents=[
            db_parser_mixin, force_mixin])
    parser_place.add_argument(
        'sample',
        metavar='sample',
        type=str,
        help='sample id')
    parser_place.add_argument('--tree', metavar='tree', type=str, help='tree')
    parser_place.add_argument(
        '--searchable_samples',
        metavar='searchable_samples',
        type=str,
        help='list of samples (file)')
    parser_place.add_argument(
        '--no-cache',
        default=False,
        action="store_true")
    parser_place.set_defaults(func=run_subtool)

    ##

    ##############
    ## Place ##
    #############
    parser_diff = subparsers.add_parser(
        'diff',
        help='Outputs novel sequence by calculating the difference between the sequence and combined graph',
        parents=[sequence_or_binary_parser_mixin])
    parser_diff.add_argument(
        'graph',
        metavar='graph',
        type=str,
        help='The graph to compare new sample against')
    parser_diff.add_argument(
        '--add',
        default=False,
        action="store_true",
        help="after comparing, add the new sample to the graph")
    parser_diff.set_defaults(func=run_subtool)
    ##

    args = parser.parse_args()
    args.func(parser, args)

if __name__ == "__main__":
    main()


import gi
import pathlib
from ventanagrafico import VentanaGrafico
from nuevo_simulacion import ejecutar
import matplotlib.pyplot as plt

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gtk, Gio, Pango, GObject

Adw.init()

def crear_grafica(s,i,r,m,d):
        fig,ax = plt.subplots()
        x = []
        for a in range(int(d)) :
            x.append(a+1)
        sir = {"s":s,"i":i,"r":r,"m":m}
        ax.set_title("Modelo. S.I.R.m", loc = "left")
        ax.set_xlabel("Dias",fontdict =
        {'fontsize':14, 'fontweight':'bold', 'color':'tab:blue'})
        ax.set_ylabel("Personas",fontdict =
        {'fontsize':14, 'fontweight':'bold', 'color':'tab:blue'})
        ax.plot(x,sir["s"],color= "tab:blue",label ="supseptible")
        ax.plot(x,sir["i"],color= "tab:purple",label ="infectado")
        ax.plot(x,sir["r"],color= "tab:green",label ="recuperados")
        ax.plot(x,sir["m"],color= "tab:red",label ="muertos")
        ax.legend(loc = 'upper right')
        plt.savefig("gra.png")

class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Simulador')
        self.set_default_size(width=int(620 / 2), height=int(768 / 2))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append('About', 'app.about')

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        self.vbox1 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.vbox1.set_homogeneous(homogeneous=True)
        self.set_child(child=self.vbox1)
        #poblacion, dias, tasa de infeccion, tasa recuperacion, tasa de muerte
        self.label = Gtk.Label()
        self.label.set_text("Bienvenidos al simulador")
        self.vbox1.append(self.label)
        self.label0 = Gtk.Label()
        self.label0.set_text(" ")
        self.vbox1.append(self.label0)
        self.label1 = Gtk.Label()
        self.label1.set_text("Población (500 a 5000)")
        self.vbox1.append(self.label1)
        self.poblacion = Gtk.SpinButton.new_with_range(500,5000,1)
        self.vbox1.append(self.poblacion)
        self.label2 = Gtk.Label()
        self.label2.set_text("Días (10 a 100)")
        self.vbox1.append(self.label2)
        self.dias = Gtk.SpinButton.new_with_range(  10,100,1)
        self.vbox1.append(self.dias)
        self.label3 = Gtk.Label()
        self.label3.set_text("Probabilidad de infectar (1 a 100)")
        self.vbox1.append(self.label3)
        self.tasa_inf = Gtk.SpinButton.new_with_range(1,100,1)
        self.vbox1.append(self.tasa_inf)
        self.label4 = Gtk.Label()
        self.label4.set_text("Probabilidad de recuperacion (1 a 100)")
        self.vbox1.append(self.label4)
        self.tasa_rec = Gtk.SpinButton.new_with_range(1,100,1)
        self.vbox1.append(self.tasa_rec)
        self.label5 = Gtk.Label()
        self.label5.set_text("""!!Esto afecta a la probabilidad de morir, si de
recuperacion es 60 por defecto la de morir sera 40!!""")
        self.vbox1.append(self.label5)
        self.button_action = Gtk.Button(label="Simular")
        self.button_action.connect('clicked', self.simular)
        self.vbox1.append(self.button_action)

    def simular(self, button):
        p,d = self.poblacion.get_text(),self.dias.get_text()
        ti = self.tasa_inf.get_text()
        tr = self.tasa_rec.get_text()
        p = p.replace(",",".")
        d = d.replace(",",".")
        ti = ti.replace(",",".")
        tr = tr.replace(",",".")
        g_s, g_i, g_r, g_m = ejecutar(int(p),int(d),int(ti),int(tr))
        crear_grafica(g_s,g_i,g_r,g_m,int(d))
        dialog = VentanaGrafico(parent=self.get_root())
        dialog.set_visible(True)

class ExampleApplication(Adw.Application):

    def __init__(self):
        super().__init__(application_id='cl.com.Example',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('about', self.on_about_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_about_action(self, action, param):
        self.about=Gtk.AboutDialog.new()
        self.about.set_authors(["Samantha Agurto","Matias Gajardo",
                                "Ricardo Macaya"])
        self.about.set_program_name("<<Simulador de Enfermedad>>")
        self.about.set_copyright("Ing. Civil en Bioinformática")
        self.about.set_visible(True)

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name, None)
        action.connect('activate', callback)
        self.add_action(action)
        if shortcuts:
            self.set_accels_for_action(f'app.{name}', shortcuts)

if __name__ == '__main__':
    import sys
    app = ExampleApplication()
    app.run(sys.argv)


from django.http.response import HttpResponse

from rest_framework.response import Response
from rest_framework.decorators import api_view

from .serializers import TasksSerializer
from .models import Tasks

# Create your views here.
@api_view(['GET'])
def apiOverview(request):
    api_urls = {
		'List':'/task-list/',
		'Detail View':'/task-detail/<str:pk>/',
		'Create':'/task-create/',
        'Update':'/task-update/<str:pk>/',
        'Delete':'/task-delete/<str:pk>/',
        }

    return Response(api_urls)

@api_view(['GET'])
def taskList(request):
    tasks=Tasks.objects.all()
    serializer=TasksSerializer(tasks,many=True)
    return Response(serializer.data)

@api_view(['GET'])
def detailedView(request, pk):
    tasks=Tasks.objects.get(id=pk)
    serializer=TasksSerializer(tasks,many=False)
    return Response(serializer.data)

#create a new entry
@api_view(['POST'])
def create(request):
    serializer=TasksSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()

    return Response(serializer.data)

#update a pre written entry
@api_view(['POST'])
def update(request, pk):
    task=Tasks.objects.get(id=pk)
    serializer=TasksSerializer(instance=task, data=request.data)
    if serializer.is_valid():
        serializer.save()

    return Response(serializer.data)

@api_view(['DELETE'])
def delete(request, pk):
    task=Tasks.objects.get(id=pk)
    task.delete()

    return HttpResponse('data selection deleted')


# 팰린드롬 만들기
# Gold 4, DP

import sys
input = sys.stdin.readline

n = int(input())
arr = tuple(map(int,input().split()))
dp = [[0]*(n+1) for _ in range(n+1)]

for i in range(1,n+1):
    for j in range(1,n+1):
        if arr[-i] == arr[j-1]:
            dp[i][j] = dp[i-1][j-1]+1
        else:
            dp[i][j] = max(dp[i-1][j],dp[i][j-1])

print(n-dp[-1][-1])

1695 팰린드롬만들기.py

1695 팰린드롬만들기.py


# checks if a hashtag exists.
# takes in a hashtag and if it is in the sqlite database as stored in the argmet conn then returns true. else false.
def hashtagExists(conn, hashtag):
    cur = conn.cursor()
    cur.execute("\
                SELECT term\
                FROM hashtags\
                WHERE term = :hashtag;",
                {"hashtag":hashtag})
    result = cur.fetchone()
    if result == None:
        return False
    else:
        return True


from PySide6.QtCore import Slot

from data.ui.widgets.shikimori import Ui_Form
from nlightreader.consts import LibList
from nlightreader.dialogs import FormAuth
from nlightreader.items import Manga, User
from nlightreader.parsers import ShikimoriLib
from nlightreader.utils import translate
from nlightreader.widgets.NlightContainers.manga_area import MangaArea
from nlightreader.widgets.NlightTemplates.BaseWidget import MangaItemBasedWidget
from nlightreader.widgets.NlightWidgets.manga_item import MangaItem

class FormShikimori(MangaItemBasedWidget):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.manga_area = MangaArea(self.ui.items_layout)

        self.ui.planned_btn.clicked.connect(lambda: self.change_list(LibList.planned))
        self.ui.reading_btn.clicked.connect(lambda: self.change_list(LibList.reading))
        self.ui.on_hold_btn.clicked.connect(lambda: self.change_list(LibList.on_hold))
        self.ui.completed_btn.clicked.connect(lambda: self.change_list(LibList.completed))
        self.ui.dropped_btn.clicked.connect(lambda: self.change_list(LibList.dropped))
        self.ui.re_reading_btn.clicked.connect(lambda: self.change_list(LibList.re_reading))
        self.ui.next_btn.clicked.connect(self.turn_page_next)
        self.ui.prev_btn.clicked.connect(self.turn_page_prev)
        self.ui.search_btn.clicked.connect(self.search)
        self.ui.auth_btn.clicked.connect(self.authorize)
        self.catalog = ShikimoriLib()
        self.Form_auth = FormAuth(self.catalog, parent=self)
        self.Form_auth.accepted.connect(self.auth_accept)
        self.update_user_info()

    def setup_manga_item(self, manga: Manga):
        item = MangaItem(manga, is_added_to_lib=False, pool=self.manga_thread_pool)
        item.manga_clicked.connect(self.manga_open.emit)
        return item

    def update_user_info(self):
        whoami = self.get_whoami()
        if whoami.nickname:
            self.ui.auth_btn.setText(whoami.nickname)
        else:
            self.ui.auth_btn.setText(translate("Other", "Sign in"))

    def update_page(self):
        self.ui.page_label.setText(f"{translate('Other', 'Page')} {self.request_params.page}")

    @Slot()
    def auth_accept(self):
        self.catalog.session.auth_login(self.Form_auth.get_user_data())
        whoami = self.get_whoami()
        if whoami.nickname:
            self.ui.auth_btn.setText(whoami.nickname)
        else:
            self.ui.auth_btn.setText(translate("Other", "Sign in"))

    @Slot()
    def authorize(self):
        self.Form_auth.exec()

    def get_whoami(self) -> User:
        return self.catalog.get_user()

    @Slot()
    def search(self):
        self.request_params.page = 1
        self.request_params.search = self.ui.title_line.text()
        self.get_content()


from pip._vendor import pkg_resources
from jupyter_client.kernelspecapp import KernelSpecManager
from pip._vendor import pkg_resources
from ipykernel.kernelspec import install

class Kernel():

    def __init__(self):
        location = None
        for pkg in pkg_resources.working_set:
            if pkg.project_name == "sparkmagic":
                location = pkg.location
                break
        self.location = location

    def install_spark_kernel(self):
        KernelSpecManager().install_kernel_spec(source_dir= self.location + "/sparkmagic/kernels/sparkkernel", user=True)
        print('done')

    def install_pyspark_kernel(self):
        KernelSpecManager().install_kernel_spec(source_dir= self.location + "/sparkmagic/kernels/pysparkkernel", user=True)
        print('done')

    def install_ipykernel(self):
        install(user=True)
        print('done')


import requests
from homeBlogData import extractBlogData
from singleTableDataExtraxtor import tableDataExtractor
from singleXpathDataExtractor import extractSinglePath

def getHomeBlogData(key, content, pathData, finalResult):
    print(pathData)
    if pathData.get('blogMainDivPath') and  pathData.get('blogPath') :
        finalResult[key] = extractBlogData(content, pathData.get('blogMainDivPath'), pathData.get('blogPath'))
    return finalResult
def getSingleTableDataExtractor(tableName, content, tablePath, finalResult):
    finalResult[tableName] = tableDataExtractor(content, tablePath)
    return finalResult

def getSingleXPathDataExtractor(key, content, singlePaths, finalResult):
    finalResult[key] = extractSinglePath(content, singlePaths)

if __name__ == "__main__":

    # jsonFile = {
    #     "mainUrl": "https://www.w3schools.com/html/html_tables.asp",
    #     "homeBlogData": {
    #         'url': "https://www.reuters.com/search/news?blob=bangalore+tech&sortBy=relevance&dateRange=pastYear",
    #         "blogMainDivPath": "#main > ul",
    #         "blogPath": [['Heading', 'text','#main > ul > li:nth-child(1)'],
    #                      ['Data', 'text','#main > ul > li:nth-child(1) > code']
    #         ]
    #
    #     },
    #     "tableData":'//*[@id="main"]/div[3]/div',
    #     "singlePath":['Heading', 'text', '//*[@id="main"]/h2[1]']
    #
    #
    # }

    jsonFile = {
        "mainUrl": "https://www.w3schools.com/html/html_tables.asp",
        "homeBlogData_sideNavigation": {
            'url': "https://www.reuters.com/search/news?blob=bangalore+tech&sortBy=relevance&dateRange=pastYear",
            "blogMainDivPath": "#leftmenuinnerinner",
            "blogPath": [['Heading', 'text', '#leftmenuinnerinner > a:nth-child(3)'],
                         ['Link', 'href', '#leftmenuinnerinner > a:nth-child(3)']
                         ]

        },
        "singlePath_tableName":['Heading', 'text', '//*[@id="main"]/div[3]/h3'],
        "tableData_firstTable":'//*[@id="main"]/div[3]/div',

        "singlePath_ChapterSummery":['Heading', 'text', '//*[@id="main"]/h2[11]'],

        "homeBlogData_ulData":{
            "blogMainDivPath":"#main > ul",
            "blogPath":[['Heading', 'text', '#main > ul > li:nth-child(1)'],
                        ['SubHeading', 'text', '#main > ul > li:nth-child(1) > code']]
        }
        # "tableData": '//*[@id="main"]/div[3]/div',
        # "singlePath": ['Heading', 'text', '//*[@id="main"]/h2[1]']

    }
    finalResult = dict()
    content = requests.get(jsonFile.get('mainUrl')).content

    for key,value in jsonFile.items():

        if 'homeBlogData' in key:
            if jsonFile.get(key):
                getHomeBlogData(key, content, jsonFile.get(key), finalResult)

        if 'tableData' in key:
            if jsonFile.get(key):
                getSingleTableDataExtractor(key, content, jsonFile.get(key), finalResult)

        if 'singlePath' in key:
            if jsonFile.get(key):
                getSingleXPathDataExtractor(key, content, jsonFile.get(key), finalResult)
    print(finalResult)


import math

import tensorflow as tf

from texar.tf.modules.embedders.embedder_base import EmbedderBase
from texar.tf.modules.embedders import embedder_utils
from texar.tf.utils.mode import is_train_mode
from texar.tf.utils.shapes import mask_sequences
from texar.tf.utils.shapes import shape_list

# pylint: disable=arguments-differ, invalid-name

__all__ = [
    "PositionEmbedder",
    "SinusoidsPositionEmbedder"
]

class PositionEmbedder(EmbedderBase):
    r"""Simple position embedder that maps position indexes into embeddings
    via lookup.

    Either :attr:`init_value` or :attr:`position_size` is required. If both are
    given, there must be ``init_value.shape[0]==position_size``.

    Args:
        init_value (optional): A Tensor or numpy array that contains the
            initial value of embeddings. It is typically of shape
            ``[position_size, embedding dim]``

            If `None`, embedding is initialized as specified in
            ``hparams["initializer"]``. Otherwise, the
            ``"initializer"`` and ``"dim"``
            hyperparameters in :attr:`hparams` are ignored.
        position_size (int, optional): The number of possible positions, e.g.,
            the maximum sequence length. Required if :attr:`init_value` is
            not given.
        hparams (dict, optional): Embedder hyperparameters. If it is not
            specified, the default hyperparameter setting is used. See
            :attr:`default_hparams` for the structure and default values.

    .. document private functions
    .. automethod:: _build
    """

    def __init__(self, init_value=None, position_size=None, hparams=None):
        EmbedderBase.__init__(self, hparams=hparams)

        if init_value is None and position_size is None:
            raise ValueError(
                "Either `init_value` or `position_size` is required."
            )

        self._init_parameterized_embedding(
            init_value, position_size, self._hparams
        )

        self._position_size = position_size
        if position_size is None:
            self._position_size = self._num_embeds
        if self._position_size != self._num_embeds:
            raise ValueError(
                "position_size must equal to init_value.shape[0]."
                "Got %d and %d" % (self._position_size, self._num_embeds)
            )

        self._built = True

    @staticmethod
    def default_hparams():
        r"""Returns a dictionary of hyperparameters with default values.

        .. code-block:: python

            {
                "dim": 100,
                "initializer": {
                    "type": "random_uniform_initializer",
                    "kwargs": {
                        "minval": -0.1,
                        "maxval": 0.1,
                        "seed": None
                    }
                },
                "regularizer": {
                    "type": "L1L2",
                    "kwargs": {
                        "l1": 0.,
                        "l2": 0.
                    }
                },
                "dropout_rate": 0,
                "trainable": True,
                "name": "position_embedder"
            }

        The hyperparameters have the same meaning as those in
        :meth:`texar.tf.modules.WordEmbedder.default_hparams`.
        """
        hparams = embedder_utils.default_embedding_hparams()
        hparams["name"] = "position_embedder"
        return hparams

    def _build(self, positions=None, sequence_length=None, mode=None, **kwargs):
        r"""Embeds the positions.

        Either :attr:`positions` or :attr:`sequence_length` is required:

            - If both are given, :attr:`sequence_length` is used to mask out
              embeddings of those time steps beyond the respective sequence
              lengths.
            - If only :attr:`sequence_length` is given, then positions
              from 0 to ``sequence_length-1`` are embedded.

        Args:
            positions (optional): An integer tensor containing the position
                ids to embed.
            sequence_length (optional): An integer tensor of shape
                ``[batch_size]``. Time steps beyond the respective sequence
                lengths will have zero-valued embeddings.
            mode (optional): A tensor taking value in
                :tf_main:`tf.estimator.ModeKeys <estimator/ModeKeys>`, including
                `TRAIN`, `EVAL`, and `PREDICT`. If `None`, dropout will be
                controlled by :func:`texar.tf.global_mode`.
            kwargs: Additional keyword arguments for
                :tf_main:`tf.nn.embedding_lookup <nn/embedding_lookup>` besides
                :attr:`params` and :attr:`ids`.

        Returns:
            A `Tensor` of shape `shape(inputs) + embedding dimension`.
        """
        # Gets embedder inputs
        # pylint:disable=too-many-locals
        inputs = positions
        if positions is None:
            if sequence_length is None:
                raise ValueError(
                    "Either `positions` or `sequence_length` is required."
                )
            max_length = tf.reduce_max(sequence_length)
            single_inputs = tf.range(start=0, limit=max_length, dtype=tf.int32)
            # Expands `single_inputs` to have shape [batch_size, max_length]
            expander = tf.expand_dims(tf.ones_like(sequence_length), -1)
            inputs = expander * tf.expand_dims(single_inputs, 0)
        ids_rank = len(inputs.shape.dims)

        embedding = self._embedding

        is_training = is_train_mode(mode)

        # Gets dropout strategy
        st = self._hparams.dropout_strategy
        if positions is None and st == "item":
            # If `inputs` is based on `sequence_length`, then dropout
            # strategies 'item' and 'item_type' have the same effect, we
            # use 'item_type' to avoid unknown noise_shape in the 'item'
            # strategy
            st = "item_type"

        # Dropouts as 'item_type' before embedding
        if st == "item_type":
            dropout_layer = self._get_dropout_layer(
                self._hparams, dropout_strategy=st
            )
            if dropout_layer:
                embedding = dropout_layer.apply(
                    inputs=embedding, training=is_training
                )

        # Embeds
        outputs = tf.nn.embedding_lookup(embedding, inputs, **kwargs)

        # Dropouts as 'item' or 'elements' after embedding
        if st != "item_type":
            dropout_layer = self._get_dropout_layer(
                self._hparams,
                ids_rank=ids_rank,
                dropout_input=outputs,
                dropout_strategy=st,
            )
            if dropout_layer:
                outputs = dropout_layer.apply(
                    inputs=outputs, training=is_training
                )

        # Optionally masks
        if sequence_length is not None:
            outputs = mask_sequences(
                outputs,
                sequence_length,
                tensor_rank=len(inputs.shape.dims) + self._dim_rank,
            )

        return outputs

    @property
    def embedding(self):
        r"""The embedding tensor.
        """
        return self._embedding

    @property
    def dim(self):
        r"""The embedding dimension.
        """
        return self._dim

    @property
    def position_size(self):
        r"""The position size, i.e., maximum number of positions.
        """
        return self._position_size

class SinusoidsPositionEmbedder(EmbedderBase):
    r"""Sinusoid position embedder that maps position indexes into embeddings
    via sinusoid calculation. This module does not have trainable parameters.
    Used in, e.g., Transformer models
    `(Vaswani et al.) "Attention Is All You Need"`.

    Each channel of the input Tensor is incremented by a sinusoid of a
    different frequency and phase.
    This allows attention to learn to use absolute and relative positions.

    Timing signals should be added to some precursors of both the query
    and the memory inputs to attention.
    The use of relative position is possible because `sin(x+y)` and
    `cos(x+y)` can be expressed in terms of `y`, `sin(x)`, and `cos(x)`.
    In particular, we use a geometric sequence of timescales starting with
    min_timescale and ending with max_timescale.  The number of different
    timescales is equal to ``dim / 2``. For each timescale, we
    generate the two sinusoidal signals `sin(timestep/timescale)` and
    `cos(timestep/timescale)`.  All of these sinusoids are concatenated in
    the dim dimension.

    Args:
        position_size (int): The number of possible positions, e.g., the maximum
            sequence length. Set ``position_size=None`` and
            ``hparams['cache_embeddings']=False`` to enable infinite large or
            negative position indexes.

    .. document private functions
    .. automethod:: _build
    """

    def __init__(self, position_size, hparams=None):
        EmbedderBase.__init__(self, hparams=hparams)

        self._num_embeds = position_size
        self._dim = self._hparams.dim
        self._cache_embeddings = self._hparams.cache_embeddings

        num_timescales = self._dim // 2
        min_timescale = self._hparams.min_timescale
        max_timescale = self._hparams.max_timescale

        log_timescale_increment = math.log(
            float(max_timescale) / float(min_timescale)
        ) / (tf.cast(num_timescales, tf.float32) - 1)
        num_range = tf.range(num_timescales, dtype=tf.float32)
        inv_timescales = min_timescale * tf.exp(
            num_range * -log_timescale_increment
        )
        self.inv_timescales = inv_timescales

        if self._cache_embeddings:
            if position_size is None:
                raise ValueError(
                    "'position_size' must not be None when "
                    "'cache_embeddings' is set to True")
            positions = tf.range(position_size, dtype=tf.float32)
            signal = self._compute_embeddings(positions)
            self.signal = signal

    @staticmethod
    def default_hparams():
        r"""Returns a dictionary of hyperparameters with default values
        We use a geometric sequence of timescales starting with
        min_timescale and ending with max_timescale. The number of different
        timescales is equal to ``dim/2``.

        .. code-block:: python

            {
                'min_timescale': 1.0,
                'max_timescale': 10000.0,
                'dim': 512,
                'cache_embeddings': True,
                'name':'sinusoid_posisiton_embedder',
            }

        Here:

        `"cache_embeddings"`: bool
            If `True`, precompute embeddings for positions in range
            `[0, position_size - 1]`. This leads to faster lookup but
            requires lookup indices to be within this range.

            If `False`, embeddings are computed on-the-fly during lookup.
            Set to `False` if your application needs to handle sequences
            of arbitrary length, or requires embeddings at negative
            positions.
        """
        hparams = {
            "min_timescale": 1.0,
            "max_timescale": 1.0e4,
            "dim": 512,
            "cache_embeddings": True,
            "name": "sinusoid_posisiton_embedder",
        }
        return hparams

    def _compute_embeddings(self, positions):
        inv_timescales = self.inv_timescales
        scaled_time = tf.reshape(tf.cast(positions, inv_timescales.dtype),
                                 (-1, 1)) * tf.expand_dims(inv_timescales, 0)
        signal = tf.concat(
            [tf.sin(scaled_time), tf.cos(scaled_time)], axis=1
        )
        signal = tf.pad(signal, [[0, 0], [0, tf.mod(self._dim, 2)]])
        signal = tf.reshape(signal, shape_list(positions) + [self._dim])
        return signal

    def _build(self, positions=None, sequence_length=None):
        r"""Embeds.
        Either :attr:`positions` or :attr:`sequence_length` is required:

        - If both are given, :attr:`sequence_length` is used to mask out
          embeddings of those time steps beyond the respective sequence \
          lengths.
        - If only :attr:`sequence_length` is given, then positions
          from `0` to `sequence_length-1` are embedded.

        Args:
            positions (optional): An integer tensor containing the position
                ids to embed.
            sequence_length (optional): An integer tensor of shape
                ``[batch_size]``. Time steps beyond
                the respective sequence lengths will have zero-valued
                embeddings.

        Returns:
            A Tensor of shape ``[batch_size, max_time, dim]``.
        """
        if positions is None:
            if sequence_length is None:
                raise ValueError(
                    "Either `positions` or `sequence_length` is required."
                )
            max_length = tf.reduce_max(sequence_length)
            single_inputs = tf.range(start=0, limit=max_length, dtype=tf.int32)
            # Expands `single_inputs` to have shape [batch_size, max_length]
            expander = tf.expand_dims(tf.ones_like(sequence_length), -1)
            inputs = expander * tf.expand_dims(single_inputs, 0)
        else:
            inputs = positions

        if self._cache_embeddings:
            outputs = tf.nn.embedding_lookup(self.signal, inputs)
        else:
            outputs = self._compute_embeddings(inputs)

        return outputs


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

# # 控制论

# ## 实数域的微分方程

# In[1]:

import sympy as sp
from sympy.abc import t

# In[2]:

f = sp.Function('f')(t)
A, B = sp.symbols('A B')
equ0 = sp.Eq(sp.Derivative(f, t, 2), A * f + B * sp.Derivative(f, t, 1))
display(equ0)
result0 = sp.dsolve(equ0, f)
display(result0)

M, N = sp.symbols('M N')
f1 = result0.rhs.args[0].args[1].args[0].coeff(t) # type:ignore
f2 = result0.rhs.args[1].args[1].args[0].coeff(t) # type:ignore
equ1 = sp.Eq(f1, M)
equ2 = sp.Eq(f2, N)
display(equ1)
display(equ2)

solution=sp.solve((equ1, equ2), (A, B))
equ3 = sp.Eq(A, solution[0][0])
equ4 = sp.Eq(B, solution[0][1])
display(equ3)
display(equ4)

equ5 = sp.Eq(sp.Derivative(f, t, 2), (solution[0][0]) * f + (solution[0][1]) * sp.Derivative(f, t, 1))
display(equ5)
result5 = sp.dsolve(equ5, f)
display(result5)

# 设初始位移$x_0$，初始速度为$v_0$，从上面的结果可以获得一个线性方程
# $$
# \begin{bmatrix} 1 & 1 \\ M & N \end{bmatrix} \begin{bmatrix} C_1\\ C_2 \end{bmatrix} = \begin{bmatrix} x_0\\ v_0 \end{bmatrix}
# $$
# 但是当 $M = N$ 并且 $v_0 / x_0 \neq M$ 时, 上面的结果非常令人费解。

# ## OED
#

# In[3]:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def nexty(cury, A, dt=0.001, deep=5):
    assert len(A.shape) == 2 and A.shape[0] == A.shape[1]
    K = np.eye(A.shape[0])
    k = 1
    for p in range(1, deep):
        k *= p
        K += A**p * dt**p / k
    return K @ cury

def getTrajectory(starty, A, dt=0.01, deep=5):
    cury = starty
    trajectory = [cury]
    for s in range(10000):
        cury = nexty(cury, A, 0.001, 10)
        trajectory.append(cury)
    trajectory = np.array(trajectory).squeeze()
    return trajectory

def plotA(A):
    fig = plt.figure(figsize=(8, 6))
    gs1 = gridspec.GridSpec(3, 4)
    ax1 = plt.subplot(gs1[0, 0])
    ax2 = plt.subplot(gs1[1, 0])
    ax3 = plt.subplot(gs1[2, 0])
    ax4 = plt.subplot(gs1[:, 1:])

    eigval, eigvec = np.linalg.eig(A)

    starty = np.array([[3.0], [3.0]])
    trajectory = getTrajectory(starty, A)
    ax1.plot(trajectory[:, 0], trajectory[:, 1])
    ax1.grid()

    starty = 3 * eigvec[:, 0]
    trajectory2 = getTrajectory(starty, A)
    ax2.plot(trajectory2[:, 0], trajectory2[:, 1])
    ax2.grid()

    starty = 3 * eigvec[:, 1]
    trajectory3 = getTrajectory(starty, A)
    ax3.plot(trajectory3[:, 0], trajectory3[:, 1])
    ax3.grid()

    x = np.linspace(-4, 4, 10)
    y = np.linspace(-4, 4, 10)
    X, Y = np.meshgrid(x, y)
    dX = A[0][0] * X + A[0][1] * Y
    dY = A[1][0] * X + A[1][1] * Y
    ax4.streamplot(X, Y, dX, dY)
    ax4.set(xlim=(-4.1, 4.1), ylim=(-4.1, 4.1))
    ax4.plot(trajectory[:, 0], trajectory[:, 1])
    ax4.plot(trajectory2[:, 0], trajectory2[:, 1])
    ax4.plot(trajectory3[:, 0], trajectory3[:, 1])
    ax4.grid()

# In[4]:

A = np.array([[0.0, 1.0], [-1.0, -2.0]])
plotA(A)

# In[5]:

A = np.array([[0.0, 1.0], [-1.0, -3.0]])
plotA(A)

# 不可对角化 <=> 等高线有一条直线
#
# 可以对角化 <=> 等高线有两条直线


from abc import abstractmethod, ABCMeta
from django.utils.functional import cached_property
from typing import List, Optional
from usaspending_api.common.etl.postgres.etl_object_base import ETLObjectBase
from usaspending_api.common.etl.postgres.primatives import ColumnOverrides, DataTypes, KeyColumns

class ETLWritableObjectBase(ETLObjectBase, metaclass=ABCMeta):
    def __init__(
        self,
        key_overrides: Optional[List[str]] = None,
        insert_overrides: Optional[ColumnOverrides] = None,
        update_overrides: Optional[ColumnOverrides] = None,
    ):
        self._key_overrides = key_overrides or []
        self._insert_overrides = insert_overrides or {}
        self._update_overrides = update_overrides or {}
        super(ETLWritableObjectBase, self).__init__()

    @cached_property
    def data_types(self) -> DataTypes:
        data_types = self._get_data_types()
        if not data_types:
            raise RuntimeError("No columns found.  Do we have permission to see the database object?")
        return data_types

    @cached_property
    def insert_overrides(self) -> ColumnOverrides:
        if self._insert_overrides:
            if not all(c in self.columns for c in self._insert_overrides):
                raise RuntimeError("All columns listed in insert_overrides must exist in database object.")
            key_columns = [k.name for k in self.key_columns]
            if any(c in key_columns for c in self._insert_overrides):
                raise RuntimeError("Overriding key columns is not currently supported.")
        return self._insert_overrides

    @cached_property
    def key_columns(self) -> KeyColumns:
        key_columns = self._get_key_columns()
        if not key_columns:
            raise RuntimeError("No columns found.  Do we have permission to see the database object?")
        return key_columns

    @cached_property
    def update_overrides(self) -> ColumnOverrides:
        if self._update_overrides:
            if not all(c in self.columns for c in self._update_overrides):
                raise RuntimeError("All columns listed in update_overrides must exist in database object.")
            key_columns = [k.name for k in self.key_columns]
            if any(c in key_columns for c in self._update_overrides):
                raise RuntimeError("Overriding key columns is not currently supported.")
        return self._update_overrides

    @abstractmethod
    def _get_data_types(self) -> DataTypes:
        """ Returns a mapping of columns names to database data types. """
        raise NotImplementedError("Must be implemented in subclasses of ETLWritableObjectBase.")

    def _get_key_columns(self) -> KeyColumns:
        """ Returns caller supplied or primary key columns (if caller did not supply keys). """
        if self._key_overrides:
            if not all(c in self.columns for c in self._key_overrides):
                raise RuntimeError("All columns listed in key_overrides must exist in database object.")
            keys = self._key_overrides
        else:
            keys = self._get_primary_key_columns()
            if not keys:
                raise RuntimeError(
                    "The database object either must have primary keys or key overrides must be supplied."
                )
        data_types = self.data_types
        return [data_types[c] for c in keys]

    @abstractmethod
    def _get_primary_key_columns(self) -> List[str]:
        """ Returns caller supplied or primary key columns (if caller did not supply keys). """
        raise NotImplementedError("Must be implemented in subclasses of ETLWritableObjectBase.")

__all__ = ["ETLWritableObjectBase"]


from MC_Hazard_Rate import MCHazardRate
from ModelParameters import ModelParameters
from Calibration import cir_q

import numpy as np

n_steps_int = 20

# integral of Z(s) and dQ(s)
def int_z_dq(t1, t2, n_steps, zero_rate, mc):

    int_times = []
    dx = (t2-t1) / n_steps

    for i in range(n_steps):
        int_times.append(t1 + (i + 1) * dx)

    value = np.exp(- zero_rate * int_times[0]) * (mc.get_survival_probability(int_times[0]) -
                                                  mc.get_survival_probability(t1))

    for i in range(n_steps - 1):
        value += np.exp(- zero_rate * int_times[i + 1]) * \
                    (mc.get_survival_probability(int_times[i + 1]) -
                        mc.get_survival_probability(int_times[i]))

    return value

def default_leg(notional, zero_rate, recovery, maturity, mc):
    return - notional * (1-recovery) * int_z_dq(0, maturity, n_steps_int, zero_rate, mc)

def premium_leg(maturity, zero_rate, f, mc):
    # CDS fee is payable annually

    s = 0
    for i in range(maturity):
        s += np.exp(- zero_rate * (i + 1)) * mc.get_survival_probability((i + 1))

    return f*s
    # accrued interest
    # ac = 0
    #for k in range(maturity):
    #    ac += int_z_dq(k, k+1, n_steps_int, zero_rate, mc)

    # risky annuity
    # ra = s - ac
    # return f*ra

def cds_spread(maturity, zero_rate, recovery, mc):
    return default_leg(1, zero_rate, recovery, maturity, mc) / premium_leg(maturity, zero_rate, 1, mc)

if __name__ == "__main__":
    # zero_rate
    r = 0.01

    # maturity
    m = 7

    # recovery rate
    rcv = 0.5

    #lbd0 = 0.00425745
    #k_ = 0.08669852
    #theta_ = 0.01538081
    #sigma_ = 0.02847497

    lbd0 = 0.00104975
    k_ = 0.89655486
    theta_ = 0.02803922
    sigma_ = 0.09404974

    mp = ModelParameters(time=m,
                         n_steps=100,
                         lambda0=lbd0,
                         cir_k=k_,
                         cir_theta=theta_,
                         sigma=sigma_)

    hazard_rate_process = MCHazardRate(mp)

    n_runs = 1000
    sum_ = 0
    for j in range(n_runs):
        hazard_rate_process.update()
        sum_ += cds_spread(m, r, rcv,  hazard_rate_process)

    print(sum_/n_runs)


from fbs_runtime.application_context import ApplicationContext

import sys
import os
import logging

from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtCore import Qt, QThread, pyqtSignal, pyqtSlot

from PIL import Image
from fysom import FysomError

from ayab.ayab_gui import Ui_MainWindow
from ayab.plugins.ayab_plugin import AyabPluginControl
from ayab.plugins.ayab_plugin.firmware_flash import FirmwareFlash
from ayab.ayab_about import Ui_AboutForm

# Temporal serial imports.
import serial
import serial.tools.list_ports

# from playsound import playsound

logging.basicConfig(filename='ayab_log.txt',
                    level=logging.DEBUG,
                    format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s',
                    datefmt='%y-%m-%d %H:%M:%S')
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
console.setFormatter(
    logging.Formatter('%(asctime)s %(name)-8s %(levelname)-8s %(message)s'))
logging.getLogger().addHandler(console)

# Fix PyQt5 for HiDPI screens
if hasattr(Qt, 'AA_EnableHighDpiScaling'):
    QtWidgets.QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
    QtWidgets.QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
# Remove Help Button
if hasattr(Qt, 'AA_DisableWindowContextHelpButton'):
    QtWidgets.QApplication.setAttribute(Qt.AA_DisableWindowContextHelpButton,
                                        True)

class GuiMain(QMainWindow):
    """GuiMain is the main object that handles the instance of AYAB's GUI from ayab_gui.UiForm .

    GuiMain inherits from QMainWindow and instanciates a window with the form components form ayab_gui.UiForm.
    """

    signalUpdateProgress = pyqtSignal(int, int, int)
    signalUpdateColor = pyqtSignal('QString')
    signalUpdateStatus = pyqtSignal(int, int, 'QString', int)
    signalUpdateNotification = pyqtSignal('QString')
    signalDisplayPopUp = pyqtSignal('QString', 'QString')
    signalUpdateNeedles = pyqtSignal(int, int)
    signalUpdateAlignment = pyqtSignal('QString')
    signalDisplayBlockingPopUp = pyqtSignal('QString', 'QString')
    signalPlaysound = pyqtSignal('QString')
    signalUpdateButtonKnitEnabled = pyqtSignal(bool)
    signalUpdateWidgetKnitcontrolEnabled = pyqtSignal(bool)

    def __init__(self, app_context):
        super(GuiMain, self).__init__(None)

        self.app_context = app_context

        self.image_file_route = None

        self.pil_image = None
        self.start_needle = 80
        self.stop_needle = 119
        self.imageAlignment = "center"
        self.var_progress = 0
        self.zoomlevel = 3

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.enabled_plugin = AyabPluginControl()
        self.enabled_plugin.setup_ui(self)
        self.showMaximized()
        self.setupBehaviour()

        self.ui.label_notifications.setText("")
        self.ui.label_current_row.setText("")
        self.ui.label_current_color.setText("")

    def update_progress(self, row, total=0, repeats=0):
        '''Updates the Progress Bar.'''
        #Store to local variable
        self.var_progress = row
        self.refresh_scene()

        # Update label
        if total != 0:
            text = "Row {0}/{1}".format(row, total)
            if repeats != 0:
                text += " ({0} repeats completed)".format(repeats)
        else:
            text = ""
        self.ui.label_current_row.setText(text)

        options_ui = self.enabled_plugin.options_ui
        options_ui.label_progress.setText("{0}/{1}".format(row, total))

    def update_color(self, color):
        '''Updates the current color.'''
        text = ""
        if color != "":
            text += "Color "
        self.ui.label_current_color.setText(text + color)

    def updateStatus(self, hall_l, hall_r, carriage_type, carriage_position):
        options_ui = self.enabled_plugin.options_ui
        options_ui.progress_hall_l.setValue(hall_l)
        options_ui.label_hall_l.setText(str(hall_l))
        options_ui.progress_hall_r.setValue(hall_r)
        options_ui.label_hall_r.setText(str(hall_r))
        options_ui.slider_position.setValue(carriage_position)
        options_ui.label_carriage.setText(carriage_type)

    def update_file_selected_text_field(self, route):
        '''Sets self.image_file_route and ui.filename_lineedit to route.'''
        self.ui.filename_lineedit.setText(route)
        self.image_file_route = route

    def slotUpdateNotification(self, text):
        '''Updates the Notification field'''
        logging.info("Notification: " + text)
        self.ui.label_notifications.setText(text)

    def slotUpdateNeedles(self, start_needle, stop_needle):
        '''Updates the position of the start/stop needle visualisation'''
        self.start_needle = start_needle
        self.stop_needle = stop_needle
        self.refresh_scene()

    def slotUpdateAlignment(self, alignment):
        '''Updates the alignment of the image between start/stop needle'''
        self.imageAlignment = alignment
        self.refresh_scene()

    def slotUpdateWidgetKnitcontrolEnabled(self, enabled):
        self.ui.widget_knitcontrol.setEnabled(enabled)

    def slotUpdateButtonKnitEnabled(self, enabled):
        self.ui.knit_button.setEnabled(enabled)

    def wheelEvent(self, event):
        '''Using mouse wheel events to zoom the pattern view'''
        if self.pil_image is not None:
            # angleDelta.y is 120 or -120 when scrolling
            zoom = event.angleDelta().y() / 120

            self.zoomlevel = self.zoomlevel + zoom
            if self.zoomlevel <= 1:
                self.zoomlevel = 1
            elif self.zoomlevel >= 5:
                self.zoomlevel = 5
            self.refresh_scene()

    def start_knitting_process(self):
        # Disable everything which should not be touched
        # during knitting
        self.ui.menuTools.setEnabled(False)
        self.ui.widget_imgload.setEnabled(False)
        self.ui.menuImage_Actions.setEnabled(False)
        self.ui.widget_optionsdock.setEnabled(False)
        self.ui.knit_button.setEnabled(False)
        self.ui.cancel_button.setEnabled(True)

        self.gt = GenericThread(self.enabled_plugin.knit, parent_window=self)
        self.gt.start()

    def cancel_knitting_process(self):
        self.enabled_plugin.cancel()

    def resetUI(self):
        # (Re-)enable UI elements
        self.ui.menuTools.setEnabled(True)
        self.ui.widget_imgload.setEnabled(True)
        self.ui.menuImage_Actions.setEnabled(True)
        self.ui.widget_optionsdock.setEnabled(True)
        self.ui.knit_button.setEnabled(False)
        self.ui.cancel_button.setEnabled(False)

    def setupBehaviour(self):
        # Connecting UI elements.
        self.ui.load_file_button.clicked.connect(self.file_select_dialog)
        self.ui.knit_button.clicked.connect(self.start_knitting_process)
        self.ui.cancel_button.clicked.connect(self.cancel_knitting_process)
        self.ui.actionLoad_AYAB_Firmware.triggered.connect(self.generate_firmware_ui)
        self.ui.image_pattern_view.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)
        # Connecting Signals.
        self.signalUpdateProgress.connect(self.update_progress)
        self.signalUpdateColor.connect(self.update_color)
        self.signalUpdateStatus.connect(self.updateStatus)
        self.signalUpdateNotification.connect(self.slotUpdateNotification)
        self.signalDisplayPopUp.connect(self.display_blocking_pop_up)
        self.signalUpdateNeedles.connect(self.slotUpdateNeedles)
        self.signalUpdateAlignment.connect(self.slotUpdateAlignment)
        self.signalPlaysound.connect(self.slotPlaysound)
        self.signalUpdateWidgetKnitcontrolEnabled.connect(self.slotUpdateWidgetKnitcontrolEnabled)
        self.signalUpdateButtonKnitEnabled.connect(self.slotUpdateButtonKnitEnabled)

        # This blocks the other thread until signal is done
        self.signalDisplayBlockingPopUp.connect(self.display_blocking_pop_up)

        self.ui.actionQuit.triggered.connect(QtCore.QCoreApplication.instance().quit)
        self.ui.actionAbout.triggered.connect(self.open_about_ui)
        self.ui.actionMirror.triggered.connect(self.mirror_image)
        self.ui.actionInvert.triggered.connect(self.invert_image)
        self.ui.actionRepeat.triggered.connect(self.repeat_image)
        self.ui.actionRotate_Left.triggered.connect(self.rotate_left)
        self.ui.actionRotate_Right.triggered.connect(self.rotate_right)
        self.ui.actionVertical_Flip.triggered.connect(self.flip_image)

    def load_image_from_string(self, image_str):
        '''Loads an image into self.ui.image_pattern_view using a temporary QGraphicsScene'''

        # TODO Check for maximum width before loading the image
        self.pil_image = Image.open(image_str)

        self.pil_image = self.pil_image.convert("RGBA")

        self.refresh_scene()
        self.statusBar().showMessage(image_str)
        # Enable plugin elements after first load of image
        self.ui.widget_optionsdock.setEnabled(True)
        self.ui.menuImage_Actions.setEnabled(True)
        # Tell loaded plugin elements about changed parameters
        width, height = self.pil_image.size
        self.enabled_plugin.slotSetImageDimensions(width,
                                                   height)

    def refresh_scene(self):
        '''Updates the current scene '''
        width, height = self.pil_image.size

        data = self.pil_image.convert("RGBA").tobytes("raw", "RGBA")
        qim = QtGui.QImage(data,
                           self.pil_image.size[0],
                           self.pil_image.size[1],
                           QtGui.QImage.Format_ARGB32)
        pixmap = QtGui.QPixmap.fromImage(qim)

        self.set_dimensions_on_gui(pixmap.width(), pixmap.height())

        qscene = QtWidgets.QGraphicsScene()

        # TODO move to generic configuration
        machine_width = 200
        bar_height = 5.0

        # add pattern and move accordingly to alignment
        pattern = qscene.addPixmap(pixmap)
        if self.imageAlignment == 'left':
            pattern.setPos(
                (self.start_needle - 100),
                0)
        elif self.imageAlignment == 'center':
            pattern.setPos(
                -(pixmap.width()/2.0)+((self.start_needle+self.stop_needle)/2) - 100,
                0)
        elif self.imageAlignment == 'right':
            pattern.setPos(
                (self.stop_needle - 100 - pixmap.width()),
                0)
        else:
            logging.warning("invalid alignment")

        # Draw "machine"
        rect_orange = QtWidgets.QGraphicsRectItem(
            -(machine_width/2.0),
            -bar_height,
            (machine_width/2.0),
            bar_height)
        rect_orange.setBrush(QtGui.QBrush(QtGui.QColor("orange")))
        rect_green = QtWidgets.QGraphicsRectItem(
            0.0,
            -bar_height,
            (machine_width/2.0),
            bar_height)
        rect_green.setBrush(QtGui.QBrush(QtGui.QColor("green")))

        qscene.addItem(rect_orange)
        qscene.addItem(rect_green)

        # Draw limiting lines (start/stop needle)
        limit_bar_width = 0.5

        qscene.addItem(
            QtWidgets.QGraphicsRectItem(self.start_needle - 101,
                                        -bar_height,
                                        limit_bar_width,
                                        pixmap.height() + 2*bar_height))
        qscene.addItem(
            QtWidgets.QGraphicsRectItem(self.stop_needle - 100,
                                        -bar_height,
                                        limit_bar_width,
                                        pixmap.height() + 2*bar_height))

        # Draw knitting progress
        qscene.addItem(
            QtWidgets.QGraphicsRectItem(-(machine_width/2.0),
                                        pixmap.height() - self.var_progress,
                                        machine_width,
                                        limit_bar_width))

        qv = self.ui.image_pattern_view
        qv.resetTransform()
        qv.scale(self.zoomlevel, self.zoomlevel)
        qv.setScene(qscene)

    def set_dimensions_on_gui(self, width, height):
        text = "{} - {}".format(width, height)
        self.ui.label_notifications.setText("Image Dimensions: " + text)

    def display_blocking_pop_up(self, message="", message_type="info"):
        logging.debug("MessageBox {}: '{}'".format(message_type, message))
        box_function = {
            "error": QtWidgets.QMessageBox.critical,
            "info": QtWidgets.QMessageBox.information,
            "question": QtWidgets.QMessageBox.question,
            "warning": QtWidgets.QMessageBox.warning
        }
        message_box_function = box_function.get(message_type)

        ret = message_box_function(
            self,
            "AYAB",
            message,
            QtWidgets.QMessageBox.Ok,
            QtWidgets.QMessageBox.Ok)
        if ret == QtWidgets.QMessageBox.Ok:
            return True

    def conf_button_function(self):
        self.enabled_plugin.configure(self)

    def file_select_dialog(self):
        filenameValue = self.ui.filename_lineedit.text()
        if filenameValue == '':
            filePath = self.app_context.get_resource("patterns")
        else:
            filePath = ''
        file_selected_route, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open file", filePath, 'Images (*.png *.PNG *.jpg *.JPG *.jpeg *.JPEG *.bmp *.BMP *.gif *.GIF *.tiff *.TIFF *.tif *.TIF)')
        if file_selected_route:
            self.update_file_selected_text_field(file_selected_route)
            self.load_image_from_string(str(file_selected_route))

    def generate_firmware_ui(self):
        self.__flash_ui = FirmwareFlash(self)
        self.__flash_ui.show()

    def open_about_ui(self):
        __version__ = "package_version"
        filename_version = self.app_context.get_resource("ayab/package_version")
        with open(filename_version) as version_file:
            __version__ = version_file.read().strip()

        self.__AboutForm = QtWidgets.QFrame()
        self.__about_ui = Ui_AboutForm()
        self.__about_ui.setupUi(self.__AboutForm)
        self.__about_ui.label_3.setText("Version " + __version__)
        self.__AboutForm.show()

    def invert_image(self):
        '''Public invert current Image function.'''
        self.apply_image_transform("invert")

    def repeat_image(self):
        '''Public repeat current Image function.'''
        v = QtWidgets.QInputDialog.getInt(
            self,
            "Repeat",
            "Vertical",
            value=1,
            min=1
        )
        h = QtWidgets.QInputDialog.getInt(
            self,
            "Repeat",
            "Horizontal",
            value=1,
            min=1
        )
        self.apply_image_transform("repeat", v[0], h[0])

    def mirror_image(self):
        '''Public mirror current Image function.'''
        self.apply_image_transform("mirror")

    def flip_image(self):
        '''Public mirror current Image function.'''
        self.apply_image_transform("flip")

    def rotate_left(self):
        '''Public rotate left current Image function.'''
        self.apply_image_transform("rotate", 90.0)

    def rotate_right(self):
        '''Public rotate right current Image function.'''
        self.apply_image_transform("rotate", -90.0)

    def apply_image_transform(self, transform_type, *args):
        '''Executes an image transform specified by key and args.

        Calls a function from transform_dict, forwarding args and the image,
        and replaces the QtImage on scene.
        '''
        transform_dict = {
            'invert': self.__invert_image,
            'repeat': self.__repeat_image,
            'mirror': self.__mirror_image,
            'flip': self.__flip_image,
            'rotate': self.__rotate_image,
        }
        transform = transform_dict.get(transform_type)
        image = self.pil_image
        if not image:
            return
        # Executes the transform function
        try:
            image = transform(image, args)
        except:
            logging.error("Error on executing transform")

        # Update the view
        self.pil_image = image

        # Disable Knit Controls
        self.ui.widget_knitcontrol.setEnabled(False)

        # Update maximum values
        width, height = self.pil_image.size
        self.enabled_plugin.slotSetImageDimensions(width,
                                                   height)
        # Draw canvas
        self.refresh_scene()

    def __rotate_image(self, image, args):
        if not args:
            logging.debug("image not altered on __rotate_image.")
            return image
        logging.debug("rotating image")
        rotated_image = image.rotate(args[0], expand=1)
        return rotated_image

    def __invert_image(self, image, args):
        import PIL.ImageOps

        if image.mode == 'RGBA':
            r, g, b, a = image.split()
            rgb_image = Image.merge('RGB', (r, g, b))
            inverted_image = PIL.ImageOps.invert(rgb_image)
        else:
            inverted_image = PIL.ImageOps.invert(image)

        return inverted_image

    def __mirror_image(self, image, args):
        import PIL.ImageOps
        mirrored_image = PIL.ImageOps.mirror(image)
        return mirrored_image

    def __flip_image(self, image, args):
        import PIL.ImageOps
        flipped_image = PIL.ImageOps.flip(image)
        return flipped_image

    def __repeat_image(self, image, args):
        """
        Repeat image.
        Repeat pHorizontal times horizontally, pVertical times vertically
        Sturla Lange 2017-12-30
        """
        old_h = image.size[1]
        old_w = image.size[0]
        new_h = old_h*args[0] # pVertical
        new_w = old_w*args[1] # pHorizontal
        new_im = Image.new('RGB', (new_w,new_h))
        for h in range(0,new_h,old_h):
          for w in range(0,new_w,old_w):
            new_im.paste(image, (w,h))
        return new_im

    def getSerialPorts(self):
        """
        Returns a list of all USB Serial Ports
        """
        return list(serial.tools.list_ports.grep("USB"))

    def slotPlaysound(self, event):
        return
        #if event == "start":
        #    playsound(self.app_context.get_resource("assets/start.wav"))
        #if event == "nextline":
        #    playsound(self.app_context.get_resource("assets/nextline.wav"))
        #if event == "finished":
        #    playsound(self.app_context.get_resource("assets/finish.wav"))

class GenericThread(QThread):
    '''A generic thread wrapper for functions on threads.'''

    def __init__(self, function, *args, **kwargs):
        QtCore.QThread.__init__(self)
        self.function = function
        self.args = args
        self.kwargs = kwargs

    def __del__(self):
        #self.join()
        self.wait()

    def run(self):
        try:
            self.function(*self.args, **self.kwargs)
        except FysomError as fe:
            logging.error(fe)
        return

def run(app_context):
    translator = QtCore.QTranslator()
    ## Loading ayab_gui main translator.
    translator.load(QtCore.QLocale.system(), "ayab_gui", ".", app_context.get_resource("ayab/translations"), ".qm")
    app = QtWidgets.QApplication(sys.argv)
    app.installTranslator(translator)
    window = GuiMain(app_context)
    window.show()
    sys.exit(app.exec_())