#! /usr/bin/env python3

import OpenHowNet	#初始化，下载义原数据
#OpenHowNet.download()
hownet_dict = OpenHowNet.HowNetDict()
hownet_dict.initialize_sememe_similarity_calculation()

pairs=[]
zh_word_list=["矮墙","爱巢","替罪羊","布达拉宫","布什","布衣之交","擦伤","裁判","财产权","堤坝","敌舰","大百科","牛仔","额手礼","恩格尔系数","肥缺","匪酋","废井","暖气","高利贷","高堂","跑鞋","泼水节","湖震","虎克定律","饥馑","科研","脸书","列传","苹果"]
f=open("./result.txt",'a')
for word in zh_word_list:
	try:
		#获取HowNet中的词语对应概念的标注
		result_list = hownet_dict.get(word, language="zh")
		for i in range(len(result_list)):
			#只抽取名词的上下位关系
			if(result_list[i]["ch_grammar"] != "noun"):
				break

			#比较义原树的不同展开层数，获得上位词候选集，展开2、3、4、5层
			sememes_dict=hownet_dict.get_sememes_by_word(word,structured=False,lang="zh",merge=True,expanded_layer=2)

			for sememe in sememes_dict:
				#比较采取不同相似度取值的限制（0.5、0.6、0.7、0.8），对上位词候选作进一步筛选
				if(len(hownet_dict.get(sememe)) > 0 and word!=sememe and hownet_dict.calculate_word_similarity(word,sememe) >= 0.50):
					pair=[word,sememe]
					if pair not in pairs:
						pairs.append(pair)
				else:
					continue
	except:
		print("error")
	else:
		continue

for pair in pairs:
	f.write(pair[0]+'\t'+pair[1]+'\n')
f.close()


import json
from rauth import OAuth1Service, OAuth2Service
from flask import current_app, request, redirect, session

class OAuthSignIn(object):
    providers = None

    def __init__(self, provider_name):
        self.provider_name = provider_name
        credentials = current_app.config['OAUTH_CREDENTIALS'][provider_name]
        self.consumer_id = credentials['id']
        self.consumer_secret = credentials['secret']

    def authorize(self):
        pass

    def callback(self):
        pass

    def get_callback_url(self):
        return 'http://localhost:443/oauth/callback/<{}>'.format(self.provider_name)

    @classmethod
    def get_provider(self, provider_name):
        if self.providers is None:
            self.providers = {}
            for provider_class in self.__subclasses__():
                provider = provider_class()
                self.providers[provider.provider_name] = provider
        return self.providers[provider_name]

class FacebookSignIn(OAuthSignIn):
    def __init__(self):
        super(FacebookSignIn, self).__init__('facebook')
        self.service = OAuth2Service(
            name='facebook',
            client_id=self.consumer_id,
            client_secret=self.consumer_secret,
            authorize_url='https://graph.facebook.com/oauth/authorize',
            access_token_url='https://graph.facebook.com/oauth/access_token',
            base_url='https://graph.facebook.com/'
        )

    def authorize(self):
        return redirect(self.service.get_authorize_url(
            scope='email',
            response_type='code',
            redirect_uri=self.get_callback_url()),
            code=301
        )

    def callback(self):
        if 'code' not in request.args:
            return None, None, None
        oauth_session = self.service.get_auth_session(
            data={'code': request.args['code'],
                  'grant_type': 'authorization_code',
                  'redirect_uri': self.get_callback_url()
            },
            decoder=json.loads
        )
        me = oauth_session.get('me?fields=id,email,first_name,last_name').json()
        social_id = 'facebook$' + me['id']
        if 'email' not in me:
            return social_id, me.get('first_name'), social_id
        else:
            return (
                social_id,
                me.get('first_name'),
                me.get('email'),
            )

class TwitterSignIn(OAuthSignIn):
    def __init__(self):
        super(TwitterSignIn, self).__init__('twitter')
        self.service = OAuth1Service(
            name='twitter',
            consumer_key=self.consumer_id,
            consumer_secret=self.consumer_secret,
            request_token_url='https://api.twitter.com/oauth/request_token',
            authorize_url='https://api.twitter.com/oauth/authorize',
            access_token_url='https://api.twitter.com/oauth/access_token',
            base_url='https://api.twitter.com/1.1/'
        )

    def authorize(self):
        request_token = self.service.get_request_token(
            params={'oauth_callback': self.get_callback_url()}
        )
        session['request_token'] = request_token
        return redirect(self.service.get_authorize_url(
                            request_token[0]),
                            code=301
                        )

    def callback(self):
        request_token = session.pop('request_token')
        if 'oauth_verifier' not in request.args:
            return None, None, None
        oauth_session = self.service.get_auth_session(
            request_token[0],
            request_token[1],
            data={'oauth_verifier': request.args['oauth_verifier']}
        )
        me = oauth_session.get('account/verify_credentials.json', params={"include_email" : "true"}).json()
        print(me)
        social_id = 'twitter$' + str(me.get('id'))
        username = me.get('screen_name')
        try:
            email = me.get('email')
        except:
            email = None
        return social_id, username, email


# INTRODUÇÃO  FUNCOES
# len
# Criando funcao

from biblioteca import *

convite = 'Flavio Henrique Almeira'

parte1 = convite[0:4]
parte2 = convite[11:15]

posicao_final = len(convite)
posicao_inicial = posicao_final - 4

parte1 = convite[0:4]
parte2 = convite[posicao_inicial:posicao_final]

print ('parte 1 %s e parte 2 %s' % (parte1,parte2))

print('Obter tamanho da string len() %s' % len(convite))

## CHAMANDO FUNÇÃO EM OUTRO ARQUIVO
gera_nome_convite('Emerson Rodrigo Vital da Silva')
envia_convite(gera_nome_convite('Emerson Rodrigo Vital da Silva'))

gera_nome_convite('Flavio Almeida')
envia_convite(gera_nome_convite('Flavio Almeida'))

gera_nome_convite('Romulo Henrique')
envia_convite(gera_nome_convite('Romulo Henrique') )

## CHAMANDO FUNCAO QUE PROCESSA TUDO DO CONVITE
processa_convite('Emerson Rodrigo Vital da Silva')
processa_convite('Flavio Almeida')
processa_convite('Romulo Henrique')


nombre = " ";
nombres = [];
while nombre != "":
    nombre = input("Introduce un nombre: ");
    nombres.append(nombre);
nombres.pop();
while True:
    try:
        posicionAMostrar = int(input("Posición del nombre a buscar: "));
        print("El nombre seleccionado es: " + nombres[posicionAMostrar - 1]);
    except (IndexError, ValueError):
        print("El valor introducido no es válido.");

Sistemas de Gestión Empresarial/WorkSpace PyCharm/EjerciciosClase/08 Excepciones/ExcepcionLista.py


import glob

from fabenvs import *
from fabric.api import *

ROOT_DIR = os.path.join(os.path.dirname(__file__), "..")
INSTALL_DIR = "/home/the-best/the-best"

DIST_DIR = os.path.join(ROOT_DIR, "dist")
CONTINUOUS_INTEGRATION_DIR = os.path.join(ROOT_DIR, "ci")
DEPLOY_DIR = os.path.join(ROOT_DIR, "deploy")
SYSCONFIG_DIR = os.path.join(DEPLOY_DIR, "sysconfig")

@task
def make_and_deploy():

    make_packages()
    target_roles = ['application']
    # fabric.api.execute(deploy, roles=target_roles)
    fabric.api.execute(deploy)

@task
def make_packages():

    build_packages_script = os.path.join(CONTINUOUS_INTEGRATION_DIR, "build_packages.sh")
    local('rm -rf ' + DIST_DIR)
    local(build_packages_script + ' ' + ROOT_DIR + ' 000 cdlg2015')

@task
@parallel
def deploy():

    nginx_service = 'nginx'
    supervisor_service = 'supervisor'

    with settings(warn_only=True):
        sudo('service ' + nginx_service + ' stop')
        sudo('service ' + supervisor_service + ' stop')
        sudo("pkill -f thebest-runservice")
        sudo("rm -rf " + INSTALL_DIR)
        sudo("virtualenv " + INSTALL_DIR)

    package_name = 'thebest'
    package_file_path = glob.glob(os.path.join(DIST_DIR, package_name+"*.tar.gz"))[0]
    put(package_file_path, "/tmp/")
    sudo(". " + INSTALL_DIR + "/bin/activate; " + INSTALL_DIR + "/bin/pip install " + "/tmp/" +
         os.path.basename(package_file_path))

    sudo('chown -R the-best:the-best ' + INSTALL_DIR)
    sudo("service supervisor start")
    sudo("service nginx start")

    print("Service(s) successfully deployed!!!")

@task
def upload_deploy_scripts(deploy_scripts_file, target_dir):

    with lcd('/tmp'):
        local('tar cvzf ' + deploy_scripts_file + ' ' + DEPLOY_DIR)
        put(deploy_scripts_file, target_dir)

@task
def install_env_stack():

    fabric.api.execute(install_app_server)
    fabric.api.execute(install_elasticsearch)

@task
@fabric.api.roles(['application'])
@parallel
def install_app_server():
    deploy_scripts_file = 'deploy.tgz'
    target_dir = '/tmp'
    upload_deploy_scripts(deploy_scripts_file, target_dir)

    with cd(target_dir):
        sudo('rm -rf deploy/')
        run('tar xvzf ' + deploy_scripts_file)
        with cd('deploy'):
            sudo('./install_appserver.sh')

@task
@fabric.api.roles(['application'])
@parallel
def install_elasticsearch():
    deploy_scripts_file = 'deploy.tgz'
    target_dir = '/tmp'
    upload_deploy_scripts(deploy_scripts_file, target_dir)

    with cd(target_dir):
        sudo('rm -rf deploy/')
        run('tar xvzf ' + deploy_scripts_file)
        with cd('deploy'):
            sudo('./install_elasticsearch.sh')

@task
@fabric.api.roles(['application'])
@parallel
def service_status():
    run('ps -ef | grep thebest-runservice')


import re
from flask import render_template, flash, request, redirect, send_file
from app import app, db
from app.models import Plex, film_table, ep_table, season_table
import threading
import datetime
import os
import requests
import shutil
from app import scripts
from app.schedule import update_scheduler
from app.routes import log, version
from plexapi.server import PlexServer

date = datetime.datetime.now()
date = date.strftime("%y.%m.%d-%H%M")

def get_library(lib, plexserver):
    log.debug(lib)
    n = len(lib)
    if n <= 2:
        try:
            for l in range(n):
                films = plexserver.library.section(lib[l])
                db.session.close()
                return films
        except IndexError:
            pass
def get_poster(i, table):
    guid = str(i.guid)
    imgdir = './app/static/img/tmp/'
    imgdir_exists = os.path.exists(imgdir)
    if imgdir_exists == False:
        os.mkdir('./app/static/img/tmp')
    #log.debug(i.media[0].parts[0].file)
    imgurl = i.posterUrl
    img = requests.get(imgurl, stream=True)
    if 'movie' in guid:
        fname = re.sub('plex://movie/', '', guid)+'.png'
    elif 'season' in guid:
        fname = re.sub('plex://season/', '', guid)+'.png'
    elif 'episode' in guid:
        fname = re.sub('plex://episode/', '', guid)+'.png'
    filename = "poster.png"
    if img.status_code == 200:
        img.raw.decode_content = True
        with open(filename, 'wb') as f:
            shutil.copyfileobj(img.raw, f)
    shutil.copy(filename, './app/static/img/tmp/'+fname)
    r = table.query.filter(table.guid == guid).all()
    if r:
        backup_poster = r[0].poster
    else:
        backup_poster = '/static/img/404/poster_not_found.png'
    db.session.close()
    return backup_poster, fname

##### DATABASE TASKS #########

@app.route('/delete_row/<path:var>')
def run_delete_row(var=''):
    scripts.delete_row(app, var)
    message = 'Deleted row'
    return render_template('result.html', message=message, pagetitle='Restored', version=version)

@app.route('/restore/film/<path:var>')
def restore_poster(var=""):
    scripts.restore_single(var)
    message = 'Sent poster to be restored.'
    config = Plex.query.filter(Plex.id == '1')
    lib = config[0].filmslibrary.split(',')
    plexserver = PlexServer(config[0].plexurl, config[0].token)
    n = len(lib)
    if n >=2:
        for l in range(n):
            library = get_library(l, plexserver)
    else:
        library = get_library(lib, plexserver)
    for i in library.search(guid=var):
        print(i)
        poster = get_poster(i, film_table)
        poster = '/static/img/tmp/'+poster[1]
    return render_template('result.html', message=message, pagetitle='Restored', version=version, poster=poster)

@app.route('/restore/episode/<path:var>')
def restore_episode_poster(var=""):
    scripts.restore_episode_from_database(app, var)
    message = 'Sent poster to be restored.'
    config = Plex.query.filter(Plex.id == '1')
    lib = config[0].tvlibrary.split(',')
    plexserver = PlexServer(config[0].plexurl, config[0].token)
    n = len(lib)
    if n >=2:
        for l in range(n):
            library = get_library(l, plexserver)
    else:
        library = get_library(lib, plexserver)
    for i in library.search(guid=var, libtype='episode'):
        poster = get_poster(i, ep_table)
        poster = '/static/img/tmp/'+poster[1]
    return render_template('result.html', message=message, pagetitle='Restored', version=version, poster=poster)

@app.route('/restore/season/<path:var>')
def restore_season_poster(var=""):
    scripts.restore_single_season(app, var)
    message = 'Sent poster to be restored.'
    config = Plex.query.filter(Plex.id == '1')
    lib = config[0].tvlibrary.split(',')
    plexserver = PlexServer(config[0].plexurl, config[0].token)
    n = len(lib)
    if n >=2:
        for l in range(n):
            library = get_library(l, plexserver)
    else:
        library = get_library(lib, plexserver)
    for i in library.search(guid=var, libtype='season'):
        poster = get_poster(i, season_table)
        poster = '/static/img/tmp/'+poster[1]
    return render_template('result.html', message=message, pagetitle='Restored', version=version, poster=poster)

@app.route('/restore/bannered_episode/<path:var>')
def restore_bannerred_episode_poster(var=""):
    msg = scripts.restore_single_bannered_episode(app, var)
    config = Plex.query.filter(Plex.id == '1')
    lib = config[0].tvlibrary.split(',')
    plexserver = PlexServer(config[0].plexurl, config[0].token)
    n = len(lib)
    if n >=2:
        for l in range(n):
            library = get_library(l, plexserver)
    else:
        library = get_library(lib, plexserver)
    for i in library.search(guid=var, libtype='episode'):
        print(i)
        poster = get_poster(i, ep_table)
        poster = '/static/img/tmp/'+poster[1]
    if 'error' not in str.lower(msg):
        return render_template('result.html', message=msg, pagetitle='Restored', version=version, poster=poster)
    else:
        return render_template('result.html', message=msg, pagetitle='Error', version=version, poster=poster)

@app.route('/restore/bannered_season/<path:var>')
def restore_bannerred_season_poster(var=""):
    msg = scripts.restore_single_bannered_season(app, var)
    config = Plex.query.filter(Plex.id == '1')
    lib = config[0].tvlibrary.split(',')
    plexserver = PlexServer(config[0].plexurl, config[0].token)
    n = len(lib)
    if n >=2:
        for l in range(n):
            library = get_library(l, plexserver)
    else:
        library = get_library(lib, plexserver)
    for i in library.search(guid=var, libtype='season'):
        print(i)
        poster = get_poster(i, season_table)
        poster = '/static/img/tmp/'+poster[1]
    if 'error' not in str.lower(msg):
        return render_template('result.html', message=msg, pagetitle='Restored', version=version, poster=poster)
    else:
        return render_template('result.html', message=msg, pagetitle='Error', version=version, poster=poster)

@app.route('/restore/bannered_film/<path:var>')
def restore_bannerred_poster(var=""):
    msg = scripts.restore_single_bannered(app, var)
    print(msg)
    if 'error' not in str.lower(msg):
        return render_template('result.html', message=msg, pagetitle='Restored', version=version)
    else:
        return render_template('result.html', message=msg, pagetitle='Error', version=version)

@app.route('/delete_database')
def delete_database():
    import sqlite3
    conn = sqlite3.connect('/config/app.db')
    c = conn.cursor()
    c.execute("SELECT * FROM plex_utills")
    query1 = """DROP TABLE films
        """
    table = """CREATE TABLE "films" (
            	"ID"	INTEGER NOT NULL UNIQUE,
            	"Title"	TEXT NOT NULL,
            	"GUID"	TEXT NOT NULL,
            	"GUIDS"	TEXT NOT NULL,
            	"size"	TEXT,
            	"res"	TEXT,
            	"hdr"	TEXT,
            	"audio"	TEXT,
            	"poster"	TEXT NOT NULL,
            	"checked"	INTEGER,
                "bannered_poster" TEXT,
                "url" TEXT,
            	PRIMARY KEY("ID" AUTOINCREMENT)
            ); """
    c.execute(query1)
    c.execute(table)
    conn.commit()
    c.close()
    file_paths = '/config/backup/films/'
    for root, dirs, files in os.walk(file_paths):
        for filename in files:
            f = filename
            if f.endswith('.png'):
                os.remove(file_paths+f)
    file_paths = '/config/backup/bannered_films/'
    for root, dirs, files in os.walk(file_paths):
        for filename in files:
            f = filename
            if f.endswith('.png'):
                os.remove(file_paths+f)
    return redirect('/films')

@app.route('/delete_tv_database')
def delete_tv_database():
    import sqlite3
    conn = sqlite3.connect('/config/app.db')
    c = conn.cursor()
    c.execute("SELECT * FROM plex_utills")
    query1 = """DROP TABLE episodes
        """
    table = """CREATE TABLE "episodes" (
            	"ID"	INTEGER NOT NULL UNIQUE,
                "show_season" TEXT,
            	"Title"	TEXT NOT NULL,
            	"GUID"	TEXT NOT NULL,
            	"GUIDS"	TEXT NOT NULL,
            	"size"	TEXT,
            	"res"	TEXT,
            	"hdr"	TEXT,
            	"audio"	TEXT,
            	"poster"	TEXT NOT NULL,
                "bannered_poster" TEXT,
            	"checked"	INTEGER,
                "blurred"    INTEGER,
            	PRIMARY KEY("ID" AUTOINCREMENT)
            ); """
    c.execute(query1)
    c.execute(table)
    conn.commit()
    c.close()

    file_paths = '/config/backup/tv/episodes/'
    for root, dirs, files in os.walk(file_paths):
        for filename in files:
            f = filename
            if f.endswith('.png'):
                os.remove(file_paths+f)
    file_paths = '/config/backup/tv/bannered_episodes/'
    for root, dirs, files in os.walk(file_paths):
        for filename in files:
            f = filename
            if f.endswith('.png'):
                os.remove(file_paths+f)
    return redirect('/episodes')

@app.route('/delete_season_database')
def delete_season_database():
    import sqlite3
    conn = sqlite3.connect('/config/app.db')
    c = conn.cursor()
    c.execute("SELECT * FROM plex_utills")
    query1 = """DROP TABLE seasons
        """
    table = """CREATE TABLE "seasons" (
                    	"ID"	INTEGER NOT NULL UNIQUE,
                    	"Title"	TEXT NOT NULL,
                    	"GUID"	TEXT NOT NULL,
                        "poster" TEXT,
                        "bannered_poster" TEXT,
                        "checked" INTEGER,
                    	PRIMARY KEY("ID" AUTOINCREMENT)
                    ); """
    c.execute(query1)
    c.execute(table)
    conn.commit()
    c.close()

    file_paths = '/config/backup/tv/seasons/'
    for root, dirs, files in os.walk(file_paths):
        for filename in files:
            f = filename
            if f.endswith('.png'):
                os.remove(file_paths+f)
    file_paths = '/config/backup/tv/bannered_seasons/'
    for root, dirs, files in os.walk(file_paths):
        for filename in files:
            f = filename
            if f.endswith('.png'):
                os.remove(file_paths+f)

    return redirect('/seasons')

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

    def export_config():
        import csv
        import shutil
        f = open('/logs/support.csv', 'w')
        out = csv.writer(f)
        out.writerow(['plexurl', 'filmslibrary', 'library3d' ,'plexpath', 'manualplexpath', 'mountedpath', 'backup', 'posters4k', 'mini4k', 'hdr', 'posters3d', 'mini3d', 'disney', 'pixar', 'hide4k', 'transcode', 'tvlibrary', 'tv4kposters', 'films4kposters', 'tmdb_restore', 'recreate_hdr', 'new_hdr', 'default_poster', 'autocollections', 'tautulli_server', 'mcu_collection', 'tr_r_p_collection', 'audio_posters', 'loglevel', 'manualplexpathfield', 'skip_media_info'])

        for item in Plex.query.all():
            out.writerow([item.plexurl, item.filmslibrary, item.library3d, item.plexpath, item.manualplexpath, item.mountedpath, item.backup, item.posters4k, item.mini4k, item.hdr, item.posters3d, item.mini3d, item.disney, item.pixar, item.hide4k, item.transcode, item.tvlibrary, item.tv4kposters, item.films4kposters, item.tmdb_restore, item.recreate_hdr, item.new_hdr, item.default_poster, item.autocollections, item.tautulli_server, item.mcu_collection, item.tr_r_p_collection, item.audio_posters, item.loglevel, item.manualplexpathfield, item.skip_media_info])
        f.close
        shutil.copy('./version', '/logs/version')

    def additional_info():
        import platform
        uname = platform.uname()
        f = open('/logs/system_info.txt', "a")
        mpath = [f for f in os.listdir('/films') if not f.startswith('.')]
        f.write("System Information"+"\n"+"System: "+uname.system+"\n"+"Node Name: "+uname.node+"\n"+"Release: "+uname.release+"\n"+"Version: "+uname.version+"\n"+"Machine: "+uname.machine+"\n"+"/films content: ")
        f.write(str(mpath))
        f.close()

    from zipfile import ZipFile
    def get_all_file_paths(directory):
        file_paths = []
        for root, directories, files in os.walk(directory):
            for filename in files:
                filepath = os.path.join(root, filename)
                file_paths.append(filepath)
        return file_paths

    def zip():
        additional_info()
        export_config()
        directory = '/logs'
        file_paths = get_all_file_paths(directory)

        print('Following files will be zipped:')
        for file_name in file_paths:
            print(file_name)

        with ZipFile('app/support.zip','w') as zip:
            for file in file_paths:
                zip.write(file)
    zip()

    os.remove('/logs/support.csv')
    path = 'support.zip'
    return send_file(path, as_attachment=True)

@app.route("/update_schedules", methods=['GET'])
def update_schedules():
    return update_scheduler()

@app.route('/help')
def help():
    import os
    from plexapi.server import PlexServer
    import re
    import requests
    import shutil
    from pathlib import PureWindowsPath, PurePosixPath
    file_paths = './app/static/img/tmp/'
    config = Plex.query.filter(Plex.id == '1')
    plexserver = PlexServer(config[0].plexurl, config[0].token)
    lib = config[0].filmslibrary.split(',')
    for root, dirs, files in os.walk(file_paths):
        for f in files:
            if f.endswith('.png'):# and 'poster_not_found' not in f):
                print(f)
                os.remove(file_paths+f)
    try:
        os.remove("app/support.zip")
        os.remove('./app/static/img/poster.png')
        os.remove('./app/static/img/poster_bak.png')
    except FileNotFoundError as e:
        pass

    mpath = [f for f in os.listdir('/films') if not f.startswith('.')]
    try:
        films = get_library(lib, plexserver)
    except requests.exceptions.ConnectionError as e:
        log.error(e)
        message = "Can not connect to your plex server, please check your config"
        return render_template('error.html', pagetitle="Error - Connection Error", pageheading="Connection Error", error=e, message=message, version=version), 500

    advanced_filter = {
        'or': [
            {'resolution': '4k'},
            {'hdr': True}
        ]
    }
    for i in films.search(sort='random', limit='1', filters=advanced_filter):
        p = get_poster(i, film_table)
        backup_poster = p[0]
        current_poster = '/static/img/tmp/'+p[1]
        log.debug('Running help script')
        plex_filepath = i.media[0].parts[0].file
        filmtitle = i.title
        try:
            p = PureWindowsPath(i.media[0].parts[0].file)
            p1 = re.findall('[A-Z]', p.parts[0])
            if p1 != []:
                log.debug(p1)
                newdir = PurePosixPath('/films', *p.parts[1:])
                log.debug(newdir)
            elif config[0].manualplexpath == 1:
                newdir = re.sub(config[0].manualplexpathfield, '/films', i.media[0].parts[0].file)
            else:
                newdir = re.sub(config[0].plexpath, '/films', i.media[0].parts[0].file)
        except:
            newdir = 'Can not be converted'
        log.debug(newdir)
        if os.path.exists(newdir) == True:
            exists = 'True'
            log.debug("PATH EXISTS")
        else:
            exists = 'False'
            log.debug("PATH DOES NOT EXIST")
    return render_template('help.html', exists=exists, pagetitle='Help', plex=config, plex_filepath=plex_filepath, filmtitle=filmtitle, newdir=newdir, mpath=mpath, backup_poster=backup_poster, current_poster=current_poster, pageheadding='Help', version=version)

@app.route('/webhook',methods=['POST'])
def recently_added():
    if request.method == 'POST':
        data = request.json
        log.debug(data)
        try:
            if 'tautulli' in str.lower(data['server']):
                title = data['title']
                mediatype = data['type']
                guid = data['id']
                action = data['action']
                log.debug(title+" "+mediatype+" "+guid+" "+action)
                if (mediatype == 'episode' and action != 'watched'):
                    log.debug('running episode webhook')
                    threading.Thread(target=scripts.tv_episode_poster, args=[app, guid, ''],    name='TV_webhook').start()
                    return 'ok', 200
                #elif (mediatype == 'episode' and action == 'watched'):
                #    from time import sleep
                #    sleep(600)
                #    threading.Thread(target=scripts.spoilers(guid), name='Spoiler_webhook').start   ()
                #    return 'ok', 200
                elif mediatype == 'movie':
                    #threading.Thread(target=scripts.hide4k,  args=[app], name='hide4K_Webhook').start()
                    threading.Thread(target=scripts.posters4k, args=[app, title], name='4k_posters_webhook').start()
                    return 'ok', 200
        except:
            if 'series' in data:
                tv_show = data['series']['title']
                mediatype = 'episode'
                season = data['episodes'][0]['seasonNumber']
                episode = data['episodes'][0]['episodeNumber']
                guid = scripts.get_tv_guid(tv_show, season, episode)
                log.debug(guid)
                threading.Thread(target=scripts.tv_episode_poster, args=[app, guid, ''], name='TV_webhook').    start()
                return 'ok', 200
            elif 'movie' in data:
                movie = data['movie']['title']
                threading.Thread(target=scripts.posters4k, args=[app, movie], name='4k_posters_webhook').   start()
                return 'ok', 200
            else:
                log.error("Webhook not running")
                return 'Error', 500

@app.route('/api/data')
def data():
    query = film_table.query

    search = request.args.get('search[value]')
    if search:
        query = query.filter(db.or_(
            film_table.title.like(f'%{search}%'),
            film_table.res.like(f'%{search}%'),
            film_table.hdr.like(f'%{search}%'),
            film_table.audio.like(f'%{search}%'),
        ))

    total_filtered = query.count()

    order = []
    i = 0
    while True:
        col_index = request.args.get(f'order[{i}][column]')
        if col_index is None:
            break
        col_name = request.args.get(f'columns[{col_index}][data]')
        if col_name not in ['title', 'res', 'hdr', 'audio']:
            col_name = 'title'
        descending = request.args.get(f'order[{i}][dir]') == 'desc'
        col = getattr(film_table, col_name)
        if descending:
            col = col.desc()
        order.append(col)
        i += 1
    if order:
        query = query.order_by(*order)

    start = request.args.get('start', type=int)
    length = request.args.get('length', type=int)
    query = query.offset(start).limit(length)

    return {
        'data': [films.to_dict() for films in query],
        'recordsFiltered': total_filtered,
        'recordsTotal': film_table.query.count(),
        'draw': request.args.get('draw', type=int),
    }

@app.route('/api/episodes')
def ep_data():
    query = ep_table.query

    search = request.args.get('search[value]')
    if search:
        query = query.filter(db.or_(
            ep_table.show_season.like(f'%{search}%'),
            ep_table.title.like(f'%{search}%'),
            ep_table.res.like(f'%{search}%'),
            ep_table.hdr.like(f'%{search}%'),
            ep_table.audio.like(f'%{search}%')
        ))

    total_filtered = query.count()

    order = []
    i = 0
    while True:
        col_index = request.args.get(f'order[{i}][column]')
        if col_index is None:
            break
        col_name = request.args.get(f'columns[{col_index}][data]')
        if col_name not in ['title', 'res', 'hdr', 'audio', 'show_season']:
            col_name = 'title'
        descending = request.args.get(f'order[{i}][dir]') == 'desc'
        col = getattr(ep_table, col_name)
        if descending:
            col = col.desc()
        order.append(col)
        i += 1
    if order:
        query = query.order_by(*order)

    start = request.args.get('start', type=int)
    length = request.args.get('length', type=int)
    query = query.offset(start).limit(length)

    return {
        'data': [title.to_dict() for title in query],
        'recordsFiltered': total_filtered,
        'recordsTotal': ep_table.query.count(),
        'draw': request.args.get('draw', type=int),
    }

@app.route('/api/seasons')
def season_data():
    query = season_table.query

    search = request.args.get('search[value]')
    if search:
        query = query.filter(db.or_(
            season_table.title.like(f'%{search}%'),
        ))

    total_filtered = query.count()

    order = []
    i = 0
    while True:
        col_index = request.args.get(f'order[{i}][column]')
        if col_index is None:
            break
        col_name = request.args.get(f'columns[{col_index}][data]')
        if col_name not in ['title']:
            col_name = 'title'
        descending = request.args.get(f'order[{i}][dir]') == 'desc'
        col = getattr(season_table, col_name)
        if descending:
            col = col.desc()
        order.append(col)
        i += 1
    if order:
        query = query.order_by(*order)

    start = request.args.get('start', type=int)
    length = request.args.get('length', type=int)
    query = query.offset(start).limit(length)

    return {
        'data': [title.to_dict() for title in query],
        'recordsFiltered': total_filtered,
        'recordsTotal': season_table.query.count(),
        'draw': request.args.get('draw', type=int),
    }

@app.route('/api/upload/<path:var>')
def upload_tmdb_posters(var=''):
    config = Plex.query.filter(Plex.id == '1')
    plexserver = PlexServer(config[0].plexurl, config[0].token)
    guid = var.split('&')
    guid = guid[1]
    poster=''
    print(var)
    #print(guid)
    if 'movie' in guid:
        scripts.upload_tmdb_film(app, var)
        lib = config[0].filmslibrary.split(',')
        n = len(lib)
        if n >=2:
            for l in range(n):
                library = get_library(l, plexserver)
        else:
            library = get_library(lib, plexserver)
        for i in library.search(guid=guid):
            print(i)
            poster = get_poster(i, film_table)
            poster = '/static/img/tmp/'+poster[1]
    if 'season' in guid:
        scripts.upload_tmdb_season(app, var)
        lib = config[0].tvlibrary.split(',')
        n = len(lib)
        if n >=2:
            for l in range(n):
                library = get_library(l, plexserver)
        else:
            library = get_library(lib, plexserver)
        for i in library.search(guid=guid, libtype='season'):
            print(i)
            poster = get_poster(i, season_table)
            poster = '/static/img/tmp/'+poster[1]
    if 'episode' in guid:
        scripts.upload_tmdb_episode(app, var)
        lib = config[0].tvlibrary.split(',')
        n = len(lib)
        if n >=2:
            for l in range(n):
                library = get_library(l, plexserver)
        else:
            library = get_library(lib, plexserver)
        for i in library.search(guid=guid, libtype='episode'):
            poster = get_poster(i, ep_table)
            poster = '/static/img/tmp/'+poster[1]
    return render_template('result.html', pagetitle='Upload', version=version, poster=poster)

@app.route('/api/process/<path:var>')
def api_process(var=''):
    config = Plex.query.filter(Plex.id == '1')
    plexserver = PlexServer(config[0].plexurl, config[0].token)
    print(var)
    if 'movie' in var:
        scripts.guid_to_title(app, var)
        lib = config[0].filmslibrary.split(',')
        n = len(lib)
        if n >=2:
            for l in range(n):
                library = get_library(l, plexserver)
        else:
            library = get_library(lib, plexserver)
        for i in library.search(guid=var):
            print(i)
            poster = get_poster(i, film_table)
            poster = '/static/img/tmp/'+poster[1]
    if 'season' in var:
        scripts.upload_tmdb_season(app, var)
    if 'episode' in var:
        scripts.upload_tmdb_episode(app, var)
    return render_template('result.html', pagetitle='Upload', version=version, poster=poster)

@app.route('/api/migrate')
def migrate():
    from threading import Thread
    Thread(target=scripts.fill_database, args=[app]).start()
    return render_template('script_log_viewer.html', pagetitle='Migrate', version=version)


from service import Service
import config
import os
import sys
import re
import log
import time
import select
from subprocess import Popen
from subprocess import PIPE
from service_ovpn import ServiceOvpn
import services
import pathlib
ON_POSIX = 'posix' in sys.builtin_module_names

class ServiceOvpnClient(ServiceOvpn):
    """
    Openvpn service client class
    """

    OPTS = dict(
        outbound_proxy_host=None, outbound_proxy_port=3128,
        crt = None, key = None, crtkey = None,
        paymentid='authid1',
        tundev = "tun1",
        mgmtport = "11193",
        reneg = 600,
        enabled = True
    )
    OPTS_HELP = dict(
        http_proxy_host = "HTTP proxy used for connection to ovpn",
        reneg = "Renegotiation interval"
    )

    def connect(self, sdp):
        while True:
            services.SERVICES.sleep(10)

    def orchestrate(self):
        ret = super().orchestrate()
        return True

    def createConfig(self):
        if (not os.path.exists(self.dir)):
            os.mkdir(self.dir)
        os.chdir(self.dir)
        tfile = config.Config.PREFIX + "/etc/openvpn_client.tmpl"
        try:
            tf = open(tfile, "rb")
            tmpl = tf.read()
        except (IOError, OSError):
            log.L.error("Cannot open openvpn template file %s" % (tfile))
            sys.exit(1)
        ca = services.SERVICES.sdp.getCertificates()
        cafile = self.dir + "ca.crt"
        try:
            caf = open(cafile, "wb")
            caf.write(ca.encode())
            caf.close()
        except (IOError, OSError):
            log.L.error("Cannot write ca file %s" % (cafile))
            sys.exit(1)
        if (config.Config.CAP.servicePort):
            self.cfg['port'] = config.Config.CAP.servicePort
        elif ('port' not in self.cfg):
            self.cfg['port'] = self.json['vpn'][0]['port'].split('/')[0]
        if (config.Config.CAP.serviceProto):
            self.cfg['proto'] = config.Config.CAP.serviceProto
        elif ('proto' not in self.cfg):
            self.cfg['proto'] = self.json['vpn'][0]['port'].split('/')[1]
        if (config.Config.CAP.serviceFqdn):
            self.cfg['endpoint'] = config.Config.CAP.serviceFqdn
        elif ('endpoint' not in self.cfg):
            self.cfg['endpoint'] = self.json['vpn'][0]['endpoint']
        if (config.CONFIG.CAP.vpncStandalone):
            mgmt_comment = '#'
            authfile=str(pathlib.Path(self.dir + 'vpnc.auth')).replace('\\','\\\\')
            try:
                af = open(authfile, "w")
                af.write(self.cfg["paymentid"].upper() + "\n")
                af.write(self.cfg["paymentid"].upper() + "\n")
                af.close()
            except (IOError, OSError):
                log.L.error("Cannot write auth file %s" % (authfile))
                sys.exit(1)
        else:
            mgmt_comment = ''
            authfile=''
        if (config.CONFIG.CAP.httpsProxyHost):
            proxy_comment = ''
            http_proxy = config.CONFIG.CAP.httpsProxyHost
            http_proxy_port = config.CONFIG.CAP.httpsProxyPort
        elif 'outbound_proxy_host' in self.cfg:
            proxy_comment = ''
            http_proxy = self.cfg['outbound_proxy_host']
            http_proxy_port = self.cfg['outbound_proxy_port']
        else:
            proxy_comment = '#'
            http_proxy = ''
            http_proxy_port = ''
        if self.cfg['proto']=='UDP' and proxy_comment!='#':
            log.L.error("Cannot use outbound HTTP proxy to proxy UDP connection to OpenVPN!. Exiting.")
            sys.exit(14)
        if (config.CONFIG.CAP.vpncBlockDns):
            bdns_comment='#'
            log.L.warning("block-outside-dns not supported yet.")
        else:
            bdns_comment='#'
        if (config.CONFIG.CAP.vpncBlockRoute):
            rgw_comment='#'
        else:
            rgw_comment=''
        pull_filter=""
        if (config.CONFIG.CAP.vpncBlockDns):
            pull_filter += "pull-filter ignore dhcp-option\n"
        if (config.CONFIG.CAP.vpncBlockRoute):
            pull_filter += "pull-filter ignore route\n"
            pull_filter += "pull-filter ignore route-gateway\n"
        self.cfg["tundev"] = config.Config.CAP.vpncTun
        self.cfg["mgmtport"] = config.Config.CAP.vpncMgmtPort
        if (config.CONFIG.isWindows()):
            wc='#'
        else:
            wc=''

        out = tmpl.decode("utf-8").format(
                          port=self.cfg['port'],
                          proto=self.cfg['proto'].lower(),
                          ip=self.cfg['endpoint'],
                          f_ca=ca,
                          tundev=self.cfg["tundev"],
                          tunnode=str(pathlib.Path(config.Config.PREFIX + '/dev/net/tun')).replace('\\','\\\\'),
                          reneg=60,
                          mtu=1400,
                          mssfix=1300,
                          hproxy_comment=proxy_comment,
                          http_proxy=http_proxy,
                          http_proxy_port=http_proxy_port,
                          payment_header=config.Config.CAP.authidHeader,
                          mgmt_header=config.Config.CAP.mgmtHeader,
                          mgmt_sock="127.0.0.1 %s" % self.cfg["mgmtport"],
                          rgw_comment=rgw_comment,
                          bdns_comment=bdns_comment,
                          auth_file=authfile,
                          pull_filters=pull_filter,
                          mgmt_comment=mgmt_comment,
                          comment_dn=wc,
                          comment_syslog=wc
                          )
        try:
            cf = open(self.cfgfile, "wb")
            cf.write(out.encode())
            log.L.warning("Configuration files created at %s" % (self.dir))
        except (IOError, OSError):
            log.L.error("Cannot write haproxy config file %s" % (self.cfgfile))


import numpy as np
from numpy.polynomial import Polynomial as pm

def basis_sh_chebyshev(degree):
    basis = [pm([-1, 2]), pm([1])]
    for i in range(degree):
        basis.append(pm([-2, 4])*basis[-1] - basis[-2])
    del basis[0]
    return basis

def basis_sh_legand(degree):
    basis = [pm([1])]
    for i in range(degree):
        if i == 0:
            basis.append(pm([-1, 2]))
            continue
        basis.append((pm([-2*i - 1, 4*i + 2])*basis[-1] - i * basis[-2]) / (i + 1))
    return basis

def basis_ermit(degree):
    basis = [pm([0]), pm([1])]
    for i in range(degree):
        basis.append(pm([0,2])*basis[-1] - 2 * i * basis[-2])
    del basis[0]
    return basis

def basis_lager(degree):
    basis = [pm([1])]
    for i in range(degree):
        if i == 0:
            basis.append(pm([1, -1]))
            continue
        basis.append(pm([2*i + 1, -1])*basis[-1] - i * i * basis[-2])
    return basis

class MyPolynom(object):
    #NOTE: eps was 1e-15
    def __init__(self, ar, symbol = 'X', eps = 1e-8):
        self.ar = ar
        self.polynom_symbol = symbol
        self.eps = eps

    def __repr__(self):
        #joinder[first, negative] = str
        joiner = {
            (True, True):'-',
            (True, False): '',
            (False, True): ' - ',
            (False, False): ' + '}

        result = []
        for deg, coef in reversed(list(enumerate(self.ar))):
            deg = deg+1
            sign = joiner[not result, coef < 0]
            coef  = abs(coef)

            if coef == 1 and deg != 0:
                coef = ''

            if coef < self.eps:
                continue

            f = {0: '{}{}', 1: '{}{}' + self.polynom_symbol}.get(deg, '{}{}' + self.polynom_symbol + '^{}')
            result.append(f.format(sign, coef, deg))

        return ''.join(result) or '0'

class Output(object):
    def __init__(self, computation):
        self.computation = computation
        max_pow = max(self.computation.pol_pow_x1,
                      self.computation.pol_pow_x2,
                      self.computation.pol_pow_x3) + 1

        if computation.polynom_type == "cheb_value_in_point":
            self.polynom_symbol = "T"
            self.basis = basis_sh_chebyshev(max_pow)

        elif computation.polynom_type == "Lejan_value_in_point":
            self.polynom_symbol = "P"
            self.basis = basis_sh_legand(max_pow)

        elif computation.polynom_type == "Lag_value_in_point":
            self.polynom_symbol = "L"
            self.basis = basis_lager(max_pow)

        elif computation.polynom_type == "Ermit_value_in_point":
            self.polynom_symbol = "H"
            self.basis = basis_ermit(max_pow)

        self.deg = [np.array(self.computation.data.data_x1).shape[1],
                    np.array(self.computation.data.data_x2).shape[1],
                    np.array(self.computation.data.data_x3).shape[1],
                    np.array(self.computation.data.data_y).shape[1]]

        self.minX = [np.array([min(x) for x in self.computation.data.data_x1]),
                     np.array([min(x) for x in self.computation.data.data_x2]),
                     np.array([min(x) for x in self.computation.data.data_x3])]

        self.maxX = [np.array([max(x) for x in self.computation.data.data_x1]),
                     np.array([max(x) for x in self.computation.data.data_x2]),
                     np.array([max(x) for x in self.computation.data.data_x3])]

        self.minY = np.array([min(x) for x in self.computation.data.data_y])
        self.maxY = np.array([max(x) for x in self.computation.data.data_y])

        self.a = np.array(self.computation.a)
        self.c = np.array(self.computation.c)

        self.psi = list()
        for i in range(self.deg[3]):
            shift = 0
            psi_i = list()
            psi_i_1 = list()
            for k in range(self.deg[0]):
                psi_i_1_k = list()
                for n in range(self.computation.pol_pow_x1 + 1):
                    psi_i_1_k.append(
                        self.computation.lambdas_for_all[i][shift + n]
                    )
                shift += self.computation.pol_pow_x1 + 1
                psi_i_1.append(np.array(psi_i_1_k))
            psi_i.append(psi_i_1)

            psi_i_2 = list()
            for k in range(self.deg[1]):
                psi_i_2_k = list()
                for n in range(self.computation.pol_pow_x2 + 1):
                    psi_i_2_k.append(
                        self.computation.lambdas_for_all[i][shift + n]
                    )
                shift += self.computation.pol_pow_x2 + 1
                psi_i_2.append(np.array(psi_i_2_k))
            psi_i.append(psi_i_2)

            psi_i_3 = list()
            for k in range(self.deg[2]):
                psi_i_3_k = list()
                for n in range(self.computation.pol_pow_x3 + 1):
                    psi_i_3_k.append(
                        self.computation.lambdas_for_all[i][shift + n]
                    )
                shift += self.computation.pol_pow_x3 + 1
                psi_i_3.append(np.array(psi_i_3_k))
            psi_i.append(psi_i_3)
            self.psi.append(psi_i)

    def _clever_join(self, key, strs):
        result = strs[0]
        for s in strs[1:]:
            if s.startswith('-') and key == ' + ':
                result += ' - ' + s[1:]
            else:
                result += key + s
        return result

    def transform_to_standard(self, _coeffs):
        coeffs = np.array(_coeffs)
        std_coeffs = np.zeros(coeffs.shape)
        for index in range(coeffs.shape[0]):
            cp = self.basis[index].coef.copy()
            cp.resize(coeffs.shape, refcheck = False)
            std_coeffs += coeffs[index] * cp
        return std_coeffs

    def form_F_i_polynomial(self, i):
        strings = list()
        constant = 0
        for j in range(3):
            for k in range(len(self.psi[i][j])):
                shift = sum(self.deg[:j]) + k
                current_poly = np.poly1d(self.transform_to_standard(
                    self.c[i][j] * self.a[i][shift] * self.psi[i][j][k])[::-1],
                    variable = '(X{0}{1})'.format(j + 1, k + 1))
                constant += current_poly[0]
                current_poly[0] = 0
                strings.append(str(MyPolynom(current_poly, '(X{0}{1})'.format(j + 1, k + 1))))
        strings.append(str(constant))
        return self._clever_join(' + ', strings)

    def form_F_i_polynomial_denormed(self, i):
        strings = list()
        constant = 0
        for j in range(3):
            for k in range(len(self.psi[i][j])):
                shift = sum(self.deg[:j]) + k
                raw_coeffs = self.transform_to_standard(self.c[i][j] * self.a[i][shift] * self.psi[i][j][k])
                diff = self.maxX[j][k] - self.minX[j][k]
                mult_poly = np.poly1d([1 / diff, - self.minX[j][k]] / diff)
                add_poly = np.poly1d([1])
                current_poly = np.poly1d([0])
                for n in range(len(raw_coeffs)):
                    current_poly += add_poly * raw_coeffs[n]
                    add_poly *= mult_poly
                current_poly = current_poly * (self.maxY[i] - self.minY[i]) + self.minY[i]
                constant += current_poly[0]
                current_poly[0] = 0
                current_poly = np.poly1d(current_poly.coeffs, variable='(X{0}{1})'.format(j + 1, k + 1))
                strings.append(str(MyPolynom(current_poly, '(X{0}{1})'.format(j + 1, k + 1))))
        strings.append(str(constant))
        return self._clever_join(' + ', strings)

    def form_result_string(self):
        result = ''

        result += 'Lambdas: \n'
        result += str(np.array(self.computation.lambdas_for_all)) + '\n'

        result += '\n\na: \n'
        for i in range(len(self.a)):
            result += 'Y' + str(i) + ': '
            result += str(self.a[i]) + '\n'

        result += '\n\nc: \n'
        for i in range(len(self.a)):
            result += 'Y' + str(i) + ': '
            result += str(self.c[i]) + '\n'

        result += '\n\n'
        for i in range(len(self.c)):
            result += 'F' + str(i + 1) + '(' + ', '.join([
                'X' + str(j+1) for j in range(
                    len(self.c[i]))
            ]) + ') = '

            result += self._clever_join(' + ', [
                str(self.c[i][j]) +
                ' * ' +
                'F' + str(i + 1) + str(j + 1) +
                '(X' + str(j + 1) + ')'
                for j in range(len(self.c[i]))
            ])

            result += '\n'

        result += '\n\n'
        for i in range(len(self.a)):
            result += 'F' + str(i + 1) + '1' + '(X1) = '
            shift = 0
            result += self._clever_join(' + ', [
                str(self.a[i][shift + j]) +
                ' * ' +
                'PSI1' + str(j + 1) +
                '[' + str(i + 1) + ']' +
                '(X1' + str(j + 1) + ')'
                for j in range(self.deg[0])
            ])

            result += '\n'

            result += 'F' + str(i + 1) + '2' + '(X2) = '
            shift += self.deg[0]
            result += self._clever_join(' + ', [
                str(self.a[i][shift + j]) +
                ' * ' +
                'PSI2' + str(j + 1) +
                '[' + str(i + 1) + ']' +
                '(X2' + str(j + 1) + ')'
                for j in range(self.deg[1])
            ])

            result += '\n'

            result += 'F' + str(i + 1) + '3' + '(X3) = '
            shift += self.deg[1]
            result += self._clever_join(' + ', [
                str(self.a[i][shift + j]) +
                ' * ' +
                'PSI3' + str(j + 1) +
                '[' + str(i + 1) + ']' +
                '(X3' + str(j + 1) + ')'
                for j in range(self.deg[2])
            ])

            result += '\n\n'

        result += '\n'

        for l in range(len(self.computation.lambdas_for_all)):
            shift = 0
            for i in range(self.deg[0]):
                result += 'PSI1' + str(i + 1) + '[' + str(l + 1) + '] = '
                result += self._clever_join(' + ', [
                        str(self.computation.lambdas_for_all[l][shift + j]) +
                        ' * ' +
                        self.polynom_symbol + str(j) +
                        '(X1' + str(i + 1) + ')'
                        for j in range(self.computation.pol_pow_x1 + 1)
                    ])
                shift += self.computation.pol_pow_x1 + 1
                result += '\n'

            for i in range(self.deg[1]):
                result += 'PSI2' + str(i + 1) + '[' + str(l + 1) + '] = '
                result += self._clever_join(' + ', [
                        str(self.computation.lambdas_for_all[l][shift + j]) +
                        ' * ' +
                        self.polynom_symbol + str(j) +
                        '(X2' + str(i + 1) + ')'
                        for j in range(self.computation.pol_pow_x2 + 1)
                    ])
                shift += self.computation.pol_pow_x2 + 1
                result += '\n'

            for i in range(self.deg[2]):
                result += 'PSI3' + str(i + 1) + '[' + str(l + 1) + '] = '
                result += self._clever_join(' + ', [
                        str(self.computation.lambdas_for_all[l][shift + j]) +
                        ' * ' +
                        self.polynom_symbol + str(j) +
                        '(X3' + str(i + 1) + ')'
                        for j in range(self.computation.pol_pow_x3 + 1)
                    ])
                shift += self.computation.pol_pow_x3 + 1
                result += '\n'

            result += '\n'

        result += '\nFi in polynomial form:\n'
        result += '\n'.join([
            'F' + str(i + 1) + ' = ' +
            self.form_F_i_polynomial(i)
            for i in range(self.deg[3])
        ])

        result += '\n\n\nFi in polynomial denormed form:\n'
        result += '\n'.join([
            'F' + str(i + 1) + ' = ' +
            self.form_F_i_polynomial_denormed(i)
            for i in range(self.deg[3])
        ])

        return result


import os
import sys

import pygame

def load_image(name, colorkey=-1):
    fullname = os.path.join('data', name)
    if not os.path.isfile(fullname):
        print(f"Файл с изображением '{fullname}' не найден")
        sys.exit()
    image = pygame.image.load(fullname)
    if colorkey is not None:
        image = image.convert()
    if colorkey == -1:
        colorkey = image.get_at((0, 0))
        image.set_colorkey(colorkey)
    else:
        image = image.convert_alpha()
    return image

if __name__ == '__main__':
    pygame.init()
    size = width, height = 800, 600
    screen = pygame.display.set_mode(size)
    image = load_image('arrow.png')
    fps = 120
    clock = pygame.time.Clock()
    running = True
    pygame.mouse.set_visible(False)
    while running:
        if not pygame.mouse.get_focused():
            screen.fill((0, 0, 0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEMOTION:
                screen.fill((0, 0, 0))
                x, y = event.pos
                screen.blit(image, (x, y))
        pygame.display.flip()
        clock.tick(fps)
    pygame.quit()


def dfs(i, j, w):
    if save[i][j]:
        return save[i][j]

    if w == len(word) - 1:
        save[i][j] = 1
        return 1

    bias = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    for dx, dy in bias:
        x = i + dx
        y = j + dy
        if 0 <= x < row and 0 <= y < col and matrix[x][y] == word[w + 1]:
            save[i][j] += dfs(x, y, w + 1)
    return save[i][j]

matrix = [['C', 'H', 'I', 'A'],
          ['C', 'A', 'N', 'T'],
          ['G', 'R', 'A', 'C'],
          ['B', 'B', 'D', 'E']]
word = 'CHINA'

row = len(matrix)
col = len(matrix[0])
save = [[0 for j in range(col)] for i in range(row)]

val = 0
for i in range(row):
    for j in range(col):
        if matrix[i][j] == word[0]:
            dfs(i, j, 0)
            val = max(val, save[i][j])
print(val)


import logging
from random import shuffle, choice
from collections import Counter

from Environment import Card
from GamePlayer import Featurizers
from GamePlayer import Policies
from GamePlayer.Estimators import ValueEstimators, PolicyEstimators

class CardPlayer(object):

    def __init__(self):
        self.logger = logging.getLogger('wizard-rl.CardPlayer')
        self.hand = []
        self.score = 0
        self.reward = 0
        self.wins = 0
        self.whole_hand = None
        super(CardPlayer, self).__init__()

    def get_playable_cards(self, first):
        playable_cards = []
        first_colors = []
        if first is None:
            return self.hand
        for card in self.hand:
            # White cards can ALWAYS be played.
            if card.color == "White":
                playable_cards.append(card)
            # First card color can ALWAYS be played.
            elif card.color == first.color:
                first_colors.append(card)
            # Other colors can only be played if there
            # no cards of the first color in the hand.
        if len(first_colors) > 0:
            return playable_cards + first_colors
        else:
            # Cannot follow suit, use ANY card.
            return self.hand

    def play_card(self, trump, first, played, players, played_in_game):
        raise NotImplementedError("This needs to be implemented by your Player class")

    def get_trump_color(self):
        return choice(Card.Card.colors[1:])

class RandomCardPlayer(CardPlayer):

    def __init__(self):
        super(RandomCardPlayer, self).__init__()

    def play_card(self, trump, first, played, players, played_in_game):
        """Randomly play any VALID card.
        Returns:
            card_to_play: (Card) the chosen card from the player hand.
            """
        possible_actions = super().get_playable_cards(first)
        if not isinstance(possible_actions, list):
            possible_actions = list(possible_actions)
        shuffle(possible_actions)
        card_to_play = possible_actions[0]
        self.hand.remove(card_to_play)
        # self.logger.info("Playing card {} from {}".format(card_to_play, self.hand))
        return card_to_play

class RLCardPlayer(CardPlayer):

    def __init__(self):
        self.logger = logging.getLogger('wizard-rl.RLAgent')
        self.session = None
        self.path = None
        self.featurizer = None
        self.estimator = None
        self.policy = None
        self.old_state = None
        self.old_score = 0
        self.old_action = None
        self.whole_hand = None
        self.training_mode = True
        super(RLCardPlayer, self).__init__()

    def init_player(self, session, path, estimator=None, policy=None, featurizer=None):
        self.session = session
        self.path = path
        if featurizer is None:
            self.featurizer = Featurizers.Featurizer()
        else:
            self.featurizer = featurizer
        if estimator is None:
            assert session is not None
            self.estimator = ValueEstimators.DQNEstimator(session, input_shape=self.featurizer.get_state_size(), path=path)
        else:
            self.estimator = estimator
        if policy is None:
            self.policy = Policies.EGreedyPolicy(self.estimator, epsilon=0.1)
        else:
            self.policy = policy

    def play_card(self, trump, first, played, players, played_in_game):
        """Plays a card according to the estimator Q function and learns
        on-line.
        Relies on scores being updated by the environment to calculate reward.
        Args:
            trump: (Card) trump card.
            first: (Card) first card.
            played: (list(Card)) list of cards played in Trick, may be empty.
            players: (list(Player)) list of players in the game, including this
            player.
            played_in_game: (list(Card)) list of cards played so far in the
            game, may be empty.

        Returns:
            card_to_play: (Card) the card object that the player
             decided to play.
        """
        state = self.featurizer.transform(self, trump, first, played, players,
                                          played_in_game)
        terminal = False
        if self.old_state is not None and self.old_action is not None and self.training_mode:
            r = self.reward
            if r != 0:
                terminal = True
                # If we got a reward, it's a terminal state.
                # We signal this with an s_prime == None
                self.estimator.update(self.old_state, self.old_action, r, None)
            else:
                self.estimator.update(self.old_state, self.old_action, r, state)

        a = self.policy.get_action(state)
        card_to_play = self._remove_card_played(a)
        self.old_state = None if terminal else state
        self.old_action = a
        self.give_reward(0)  # After playing a card, the reward is 0.
        # Unless it's the last card of the game, then the Game object will
        # call give_reward before the next play_card, setting the correct reward
        return card_to_play

    def _remove_card_played(self, a):
        """
        Given an action (integer) remove a card equivalent to it from the
        player's hand and return it.

        Args:
            a: (int) The action taken. Remove a card with the same code.
            If there is more than one that matches, it does not matter which,
            but just remove one.

        Returns:
            card_to_play: The card corresponding to the action.

        Raises:
            RuntimeError when the action does not correspond to any card.

        """
        card_to_return = None
        for card in self.hand:
            if int(card) == a:
                card_to_return = card
                self.hand.remove(card)
                break
        if card_to_return is None:
            raise RuntimeError("Computer did not find a valid card for this"
                               "action.\nHand: {}\nAction: {}".format(self.hand,
                                                                      a))
        return card_to_return

    def get_trump_color(self):
        # Return the color the agent has the most of in its hand.
        color_counter = Counter()
        for card in self.hand:
            color = card.color
            if color == "White":
                continue
            color_counter[color] += 1
        if not color_counter.most_common(1):
            return super().get_trump_color()
        else:
            return color_counter.most_common(1)[0][0]


import os
import keyboard
# on window platform
clear = lambda: os.system('cls')
#on linux platform
#clear = lambda: os.system('clear')
f = open('demofile.txt', encoding = 'utf-8')
content = f.readlines()
current = 0
def printLineUp():
     clear()
     global current
     current -=1
     if current <= -(len(content)):
        current = 0
     print(content[current])

def printLineDown():
     clear()
     global current
     current +=1
     if(current >= len(content)):
        current =0
     print(content[current%len(content)])

keyboard.add_hotkey('up', printLineUp)
keyboard.add_hotkey('down', printLineDown)
keyboard.wait('esc')


import toml
from pathlib import Path
import logging

logging.basicConfig(level=logging.DEBUG)

pyproject = Path(__file__).parents[4] / 'pyproject.toml'
logging.debug(pyproject)

versionfile = Path(__file__).parent / 'version.txt'
logging.debug(versionfile)

# versionfile.write_text('0.1.0')
versionfile.write_text(f"{toml.load(pyproject)['tool']['poetry']['version']}")

__version__ = versionfile.read_text().strip()
logging.debug(__version__)


import SOMEIP
import queue

if __name__ == "__main__":
    queueObj = queue.Queue()

    ifacestr = "enp0s3"  # Network port name, you need to change this variable to your own network card name
    filterstr = "udp port 30490"  # BPF filter to apply (Please make sure that only someip or someipsd packets exist after filtering)

    sniffer = SOMEIP.Sniffer(ifacestr, filterstr, queueObj)
    while True:
        if not queueObj.empty():
            print("=================================")
            resp = queueObj.get()
            # print the detail of the resp
            resp.show()
            print("=================================")


import logging
import logging.handlers
import sys
import os
import time

def listener_process(queue):
    """
    logging from from the logging queue
    can be run as a proocess or a thread
    """

    while True:
        try:
            record = queue.get()
            if record is None:  # We send this as a sentinel to tell the listener to quit.
                break
            logger = logging.getLogger(record.name)
            logger.handle(record)  # No level or filter logic applied - just do it!
        except Exception:
            import sys, traceback
            print('Whoops! Problem:', file=sys.stderr)
            traceback.print_exc(file=sys.stderr)

def setup_listen_logger(folder=".", file_name='logs.log', console=True):
    """
    setup logger for the listener process
    """
    root = logging.getLogger()
    formatter = logging.Formatter('{asctime}:  {message}', style='{')
    root.setLevel(logging.INFO)

    if folder:
        assert os.path.isdir(folder), f'log dir \'{folder}\' does not exist.'

        fh = logging.FileHandler(os.path.join(folder, file_name))
        fh.setFormatter(formatter)
        root.addHandler(fh)

    if console:
        ch = logging.StreamHandler(sys.stderr)
        ch.setFormatter(formatter)
        root.addHandler(ch)

def setup_worker_logger(queue):
    """
    setup logger for the worker process
    """
    h = logging.handlers.QueueHandler(queue)  # Just the one handler needed
    root = logging.getLogger()
    root.addHandler(h)
    # send all messages, for demo; no other level or filter logic applied.
    root.setLevel(logging.INFO)

class AverageMeter(object):
    """Computes and stores the average and current value"""

    def __init__(self, cache=False, dtype=float):
        self.cache = cache
        self.reset()
        self.dtype = dtype

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0
        self.array = [] if self.cache else None

    def update(self, val, n=1):
        if not isinstance(val, self.dtype):
            val = self.dtype(val)

        self.val = val
        if self.cache: self.array.append(val)
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

    def __str__(self):
        return f"{self.val:.4f}({self.avg:.4f})"

class Timer:

    def __init__(self):
        self._timer = AverageMeter(cache=False, dtype=float)

    def reset(self):
        self._timer.reset()

    def start(self):
        self.start_time = time.perf_counter()

    def stop(self):
        elapsed_time = time.perf_counter() - self.start_time
        self._timer.update(elapsed_time)

    def __str__(self):
        return str(self._timer)

def get_log(name, folder=".", file_name='logs.log', console=True):
    """
    return logger for the main
    NOTE: only use in single process run
    """
    assert os.path.isdir(folder), f'log dir \'{folder}\' does not exist.'
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)

    log_format = logging.Formatter(
        '{asctime}:{name}:  {message}',
        style='{'
    )
    if folder:
        fh = logging.FileHandler(os.path.join(folder, file_name))
        fh.setFormatter(log_format)
        logger.addHandler(fh)
    # multiprocessing_logging.install_mp_handler()
    if console:
        ch = logging.StreamHandler(sys.stderr)
        ch.setFormatter(log_format)
        logger.addHandler(ch)

    return logger


from dataclasses import dataclass
from tqdm import tqdm
from time import sleep

from asanitize.data_structure.linked_list import LinkedList
from asanitize.services.discord.data.message import Message

@dataclass
class MessageList:
    messages: LinkedList

    sanitize_curr: int
    total_results: int

    def __init__(self, total_results: int = 0) -> None:
        self.messages = LinkedList()
        self.total_results = total_results

    def init_progress_bar(self):
        self.progress_bar = tqdm(total=self.total_results)

    def append(self, message_list: list):
        for message in message_list:
            self.messages.append(Message(
                id=message[0].get('id'),
                type=message[0].get('type'),
                content=message[0].get('content'),
                channel_id=message[0].get('channel_id'),
                author=message[0].get('author'),
                attachments=message[0].get('attachments'),
                embeds=message[0].get('embeds'),
                mentions=message[0].get('mentions'),
                mention_roles=message[0].get('mention_roles'),
                pinned=message[0].get('pinned'),
                mention_everyone=message[0].get('mention_everyone'),
                tts=message[0].get('tts'),
                timestamp=message[0].get('timestamp'),
                edited_timestamp=message[0].get('edited_timestamp'),
                flags=message[0].get('flags'),
                components=message[0].get('components'),
                hit=message[0].get('hit'),
            ))

    def sanitize_all(self, is_fast_mode: bool) -> None:
        for i in range(0, self.messages.count):
            message = self.messages.find(i)
            message.item.sanitize(is_fast_mode)
            self.progress_bar.update(1)

        self.messages = LinkedList()

    def __exit__(self):
        self.progress_bar.close()


from mitmproxy import http
from concurrent.futures import ThreadPoolExecutor
import bs4
import htmlmin

from utils import Utils

class OpenWRT:
    @staticmethod
    def hide_ripe(row: bs4.Tag) -> None:
        cell_nums = [6, 8, 12, 14, 15, 21]

        targets = []

        for num in cell_nums:
            targets.append(row.select_one(f"td:nth-child({num})"))
            targets.append(row.select_one(f"th:nth-child({num})"))

        for target in targets:
            if target is not None:
                target.decompose()

    @staticmethod
    def filter(row: bs4.Tag) -> None:
        # delete devices with unknown cpu cores amount
        target = row.find('td', {'class': 'cpu_cores'})
        if target is not None:
            if not target.text.isdigit():
                row.decompose()

        # delete devices with unknown cpu freq
        target = row.find('td', {'class': 'cpu_mhz'})
        if target is not None:
            if not target.text.isdigit():
                row.decompose()

        # delete devices with unknown ram size
        target = row.find('td', {'class': 'ram_mb'})
        if target is not None:
            if not target.text.isdigit():
                row.decompose()

        # delete devices with unknown gbit ports amount
        # 4+ gbit ports is required
        target = row.find('td', {'class': 'ethernet_gbit_ports'})
        if target is not None:
            if not target.text.isdigit():
                row.decompose()
            elif int(target.text) < 4:
                row.decompose()

        # delete devices with unknown usb ports amount
        # target = row.find('td', {'class': 'usb_ports'})
        # if target is not None:
        #     if target.text.strip() == "-":
        #         row.decompose()

        # no broadcom
        target = row.find('td', {'class': 'cpu'})
        if target is not None:
            if target.text.lower().find('broadcom') > -1:
                row.decompose()

        # Wi-Fi routers only
        target = row.find('td', {'class': 'device_type'})
        if target is not None:
            text = target.text.lower().strip()
            if text.find('wifi') == -1 or text.find('router') == -1:
                row.decompose()

    async def response(self, flow: http.HTTPFlow) -> None:
        if flow.request.pretty_url != 'https://openwrt.org/toh/views/toh_extended_all': return # strict url

        if flow.response.status_code != 200: return  # process HTTP 200 only
        if len(flow.response.content) == 0: return  # skip empty responses
        if not Utils.is_html(flow): return # proccess html only

        soup = bs4.BeautifulSoup(flow.response.content, 'lxml')
        rows = soup.select("table.dataplugin_table tr")

        with ThreadPoolExecutor() as executor:
            executor.map(OpenWRT.filter, rows, timeout=30)
            executor.map(OpenWRT.hide_ripe, rows, timeout=30)

        flow.response.content = htmlmin.minify(soup.prettify(), remove_empty_space=True).encode(encoding='utf-8')

        await Utils.inject(
			flow,
			{
                "scripts": [
                    {"path": Utils.local_injector_url("openwrt.org/js/sort.js")},
                ],
            }
        )


import pandas as pd
from csv import writer

csv = pd.read_csv('HumorDB-Quatrain-to-Clean.csv', sep=';')

rowz = []

for index, row in csv.iterrows():
    fila = []

    texto = ''

    c = row["Column1"]
    p = row["Column2"]

    claim = f'Claim: {c} \n'
    poem = f'Poem:'

    samplez = claim + poem + '\n\n###\n\n'
    texto += samplez

    pp = f' {p}'
    poema = ''
    poema = pp + '  END '

    fila.append(texto)
    fila.append(poema)
    rowz.append(fila)

with open('GPT-3 Prepared Data HumorDB-Quatrain.csv', 'a+', newline='', encoding='utf-8') as f_object:
    for rowl in rowz:
        writer_object = writer(f_object)
        writer_object.writerow(rowl)
    f_object.close()

print('donezo')

Models Fine-Tuning/Scripts/humor claim adder.py


state1 = "Alabama"
state2 = "Arizona"
state3 = "Arkansas"

# Instead of creating different variable state like we did above, we could put all these in a python list like this

states_of_america = ["Alabama","Arizona","Arkansas","California", "Colorado", "Connecticut", "Delaware"]
print(states_of_america[0]) # Prints the first element in the list
print(states_of_america[-1]) # Prints the last element in the list

# Changes the string at last index[-1] -> starts counting from the end of the list of the List
states_of_america[-1] = "Delamere"

# Add an item "Terryland" to the end of the list at index[-1]
states_of_america.append("Terryland")

# Extend the list by appending all the items given e.g
states_of_america.extend(["Maryland", "MariaAntonett"])

# Insert an item "Merryland" at the given index 0 position.
states_of_america.insert(0,"Merryland")

print(states_of_america)

# Test it here: https://replit.com/@terrykirungo/3-list#main.py


#
# @lc app=leetcode id=26 lang=python
#
# [26] Remove Duplicates from Sorted Array
#
class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        #@0301,不需要从1开始
        l = 0
        for i in range(len(nums)):
            if nums[i] != nums[l]:
                l +=1
                nums[l] = nums[i]
        return l+1

        '''
        l = 0
        for i in range(1, len(nums)):
            if nums[l] != nums[i]:
                l += 1
                nums[l] = nums[i]
        return l +1
        '''


# Solution with slicing

class Solution:
    def stringShift(self, s: str, shift: List[List[int]]) -> str:
        for move in shift:
            amount = move[1] % len(s)
            if move[0] == 0:  # left shift
                s = s[amount:] + s[:amount]
            elif move[0] == 1:  # right shift
                s = s[-amount:] + s[:-amount]

        return s


route = input('Вы находитесь в лабиринте, перед вам три пути, \n'
              'налево, направо, прямо, даже можете пойти обратно, \n'
              'написав слово назад \n')
item = ''
room = 0
while room > -1:
    if room == 0:
        if route == 'налево':
            print('Вы зашли в библиотеку, ')
            room += 1
            route = input()
        elif route == 'прямо':
            print('Вы зашли в комнату с высокими колоннами, куда вы пойдете дальше?')
            room += 1
            route = input()
        elif route == 'направо':
            print('Вы вошли в тоннель, путь назад вы потеряли, пути снова три')
            room += 2
            route = input()
        elif route == 'назад':
            print('Вы вышли из тоннеля, игра окончена')
            room -= 1
    if room == 1:
        if route == 'направо':
            print('Вы нашли катану, она очень острая, выберите дорогу дальше')
            room += 1
            item = 'катана'
            route = input()
        elif route == 'налево':
            print('Ваше приключение на этом завершилась, вы проснулись и ничего не помнили')
            room = -1
        elif route == 'прямо':
            print('Вы вошли в зал, выберите дорогу дальше')
            room += 1
            route = input()
    if room == 2:
        if route == 'прямо' or route == 'налево' or route == 'направо':
            print('Вы прошли в комнату с монстром, начался бой')
            if item == '':
                print('Монстр съел вас, игра окончена')
                room = -1
            else:
                print('Вы достали катану и уничтожили монстра, дверь в комнате вела к выходу,',
                      'игра окончена')
                room = -1


'''
Created on 14 mars 2023

@author: Fab
'''
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import  QPainter, QPaintEvent, QColor, QFont
from PyQt5.Qt import QRect, QImage, QRegion, QLabel, QPushButton
from visualexperiments.Block import Block

class WWWFed(QtWidgets.QWidget):

    def __init__(self, x , y , *args, **kwargs):
        super().__init__( *args, **kwargs)

        self.x = x*200+100
        self.y = y*200+100
        self.angle = 0
        self.setGeometry( int( self.x ), int ( self.y ), 100, 100)

        self.name= "fed"

        '''
        layout = QtWidgets.QVBoxLayout()
        title = QLabel( "Fed" , objectName="balanceTitle" )
        title.setAlignment(Qt.AlignCenter)
        layout.addWidget( title )
        self.balanceWidget = MplCanvas (self, width=5, height=3 )
        self.balanceWidget.axes.plot([0,1,2,3,4], [10,1,20,3,40])
        self.balanceAx = self.balanceWidget.axes
        self.balanceAx.set_ylabel("weight (g)")
        plt.tight_layout()
        layout.addWidget( self.balanceWidget )
        tareButton= QPushButton("Force tare balance")
        layout.addWidget( tareButton )
        tareButton.clicked.connect( self.tare )
        layout.addStretch()
        self.setLayout(layout)
        '''

    '''
    def tare(self):
        print( "tare")
        self.balanceAx.clear()

        a = []
        b = []
        for i in range(10):
            a.append( randint(0,40) )
            b.append( randint(0,40) )

        self.balanceWidget.axes.plot(a,b)
        self.balanceWidget.fig.canvas.draw()
    '''

    def setAngle(self , angle ):
        self.angle = angle
        self.update()

    def setName(self, name ):
        self.name = name

    def paintEvent(self, event: QPaintEvent):

        super().paintEvent( event )

        painter = QPainter()
        painter.begin(self)

        painter.translate(self.width()/2,self.height()/2);
        painter.rotate(self.angle);
        painter.translate(-self.width()/2,-self.height()/2);

        # block
        painter.fillRect(0, int ( self.height()/2 ) , int ( self.width() ) , int ( self.height()/2 ), QColor(255, 165, 0))
        painter.setPen(QtGui.QPen(QtGui.QColor(100,100,100), 4))
        painter.drawRect(0, int ( self.height()/2 ), int ( self.width() ), int ( self.height()/2 ) )

        # nose poke 1
        painter.fillRect( int ( 1*self.width()/6 ), int ( 3*self.height()/4 ), int ( self.width()/6 ), int ( self.height( ) ), QColor(100, 100, 100))
        # nose poke 2
        painter.fillRect( int ( 4*self.width()/6 ), int ( 3*self.height()/4 ), int ( self.width()/6 ), int ( self.height() ), QColor(100, 100, 100))
        # fed area

        painter.fillRect(int (self.width()/2-self.width()/7 ), int ( 5*self.height()/6 ), int ( self.width()/3.5 ), int ( self.height()/6 ) , QColor(50, 200, 50))

        font = QFont('Times', 20)
        font.setBold(True)
        painter.setFont( font )
        painter.drawText( QRect( 0, int( self.height()/2.5 ) , int ( self.width() ) , int ( self.height()/2) ), Qt.AlignCenter, self.name )

        painter.end()

    def mousePressEvent(self, event):
        self.__mousePressPos = None
        self.__mouseMovePos = None
        if event.button() == QtCore.Qt.LeftButton:
            self.__mousePressPos = event.globalPos()
            self.__mouseMovePos = event.globalPos()

        super(WWWFed, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            # adjust offset from clicked point to origin of widget
            currPos = self.mapToGlobal(self.pos())
            globalPos = event.globalPos()
            diff = globalPos - self.__mouseMovePos
            newPos = self.mapFromGlobal(currPos + diff)
            self.move(newPos)

            self.__mouseMovePos = globalPos

        super(WWWFed, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if self.__mousePressPos is not None:
            moved = event.globalPos() - self.__mousePressPos
            if moved.manhattanLength() > 3:
                event.ignore()
                return

        super(WWWFed, self).mouseReleaseEvent(event)


"""Support Vulture."""
from argparse import ArgumentParser

from vulture.core import ERROR_CODES, Vulture, make_config

from pylama.context import RunContext
from pylama.lint import LinterV2 as BaseLinter

class Linter(BaseLinter):
    """vulture runner."""

    name = "vulture"

    @classmethod
    def add_args(cls, parser: ArgumentParser):
        """Add --max-complexity option."""
        parser.add_argument(
            "--vulture-min-confidence",
            type=int,
            help="Minimum confidence (between 0 and 100) for code to be reported as unused.",
        )
        parser.add_argument(
            "--vulture-ignore-names",
            help="Comma-separated list of names to ignore",
        )
        parser.add_argument(
            "--vulture-ignore-decorators",
            help="Comma-separated list of decorators to ignore",
        )

    def run_check(self, ctx: RunContext):  # noqa
        """Check code with vulture."""
        params = ctx.get_params("vulture")
        options = ctx.options
        if options:
            params.setdefault("min-confidence", options.vulture_min_confidence)
            params.setdefault("ignore-names", options.vulture_ignore_names)
            params.setdefault("ignore-decorators", options.vulture_ignore_decorators)

        config = make_config(parse_params(ctx.filename, params))
        vulture = Vulture(
            verbose=config["verbose"],
            ignore_names=config["ignore_names"],
            ignore_decorators=config["ignore_decorators"],
        )
        vulture.scan(ctx.source, filename=ctx.filename)
        unused_code_items = vulture.get_unused_code(
            min_confidence=config["min_confidence"], sort_by_size=config["sort_by_size"]
        )
        for item in unused_code_items:
            error_code = ERROR_CODES[item.typ]
            ctx.push(
                source="vulture",
                type="R",
                lnum=item.first_lineno,
                number=error_code,
                text=f"{item.message} ({item.confidence}% confidence)",
            )

def parse_params(path, params=None):
    """Convert params from pylama."""
    return [f"--{key}={value}" for key, value in params.items() if value] + [path]


from copy import copy, deepcopy

class field:
    def __init__(self, data):
        self.data = data
        self.height = len(data)
        self.width = len(data[0])

    def updateAll(self):
        newData = deepcopy(self.data)
        self.update(2, newData)
        self.update(3, newData)
        self.data = newData

    def getNeigh(self, h, w, id):
        nNeigh = 0
        steps = [[0, 1], [0, -1],
                 [-1, -1], [-1, 0], [-1, 1],
                 [1, -1], [1, 0], [1, 1]]
        for move in steps:
            newH = h + move[0]
            newW = w + move[1]
            if (0 <= newH < self.height and 0 <= newW < self.width and
                    self.data[newH][newW] == id):
                nNeigh += 1
        return nNeigh

    def update(self, id, newData):
        for h, line in enumerate(self.data):
            for w, row in enumerate(line):
                if (self.data[h][w] == id and
                        (self.getNeigh(h, w, id) >= 4 or
                            self.getNeigh(h, w, id) <= 1)):
                    newData[h][w] = 0

                if self.data[h][w] == 0 and self.getNeigh(h, w, id) == 3:
                    newData[h][w] = id

steps = int(input())

sizes = [int(x) for x in input().split(" ")]
n = sizes[0]
m = sizes[1]
data = [[0 for x in range(m)] for y in range(n)]

for h in range(n):
    line = input().split(" ")
    for w in range(m):
        data[h][w] = int(line[w])

f = field(data)

for s in range(steps):
    f.updateAll()
for h in range(n):
    for w in range(m):
        print(f.data[h][w], end=" ")
    print("\n")


from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By

import time
import schedule
from message_sender import send_msg

driver = webdriver.Chrome(ChromeDriverManager().install())
# driver.get("http://m.ticket.yes24.com/Perf/36086")
driver.get("http://m.ticket.yes24.com/Perf/Detail/PerfInfo.aspx?IdPerf=43506")

cnt = 0

def get_site_info():
    driver.refresh()
    global cnt
    cnt += 1
    available = False
    book_btn = False
    closed_btn = driver.find_element(By.CLASS_NAME, "btn_dGray")

    try:
        book_btn = driver.find_element(By.CLASS_NAME, "btn_red")
    except:
        pass

    if closed_btn:
        available = False

    if book_btn:
        available = True

    if available:
        send_msg('지금! 예매 가능합니다!')
    else:
        print('예매 불가합니다 ' + str(cnt) + '초 동안 진행중')

def send_check_msg():
    send_msg(f'걱정마세요! {cnt}동안 잘 실행되고 있습니다!')

schedule.every(1).seconds.do(get_site_info)
schedule.every(1).hours.do(send_check_msg)

while True:
    schedule.run_pending()
    time.sleep(1)


import os
from subprocess import Popen, PIPE
from shutil import rmtree

import unittest

if __name__ == "__main__":
    import utils
    utils.import_depends()

from brokertest import TestBrokerCommand

class TestConsistency(TestBrokerCommand):
    def test_010_add_filesystem_only(self):
        # Create a dummy domain directory, not in the database and neither in
        # template-king
        dir = os.path.join(self.config.get("broker", "domainsdir"),
                           'filesystem-only')
        try:
            os.makedirs(dir, 0o755)
        except OSError:
            # Directory may already exist
            pass

    def test_020_add_branch_only(self):
        kingdir = self.config.get("broker", "kingdir")
        self.gitcommand(["branch", "branch-only", "prod"], cwd=kingdir)

    def test_030_add_domain_no_fileystem(self):
        self.successtest(["add_domain", "--domain", "domain-no-filesystem"] + self.valid_just_tcm)
        dir = os.path.join(self.config.get("broker", "domainsdir"),
                           "domain-no-filesystem")
        rmtree(dir)

    def test_040_add_domain_no_template_king(self):
        kingdir = self.config.get("broker", "kingdir")
        self.successtest(["add_domain", "--domain", "domain-no-template-king"] + self.valid_just_tcm)
        self.gitcommand(["branch", "-D", "domain-no-template-king"], cwd=kingdir)

    def test_050_add_sandbox_no_template_king(self):
        kingdir = self.config.get("broker", "kingdir")
        self.successtest(["add_sandbox", "--sandbox",
                          "sandbox-no-template-king", "--noget"])
        self.gitcommand(["branch", "-D", "sandbox-no-template-king"], cwd=kingdir)

    def test_100_consistency(self):
        # Run the checker and collect its output
        command = 'aqd_consistency_check.py'
        dir = os.path.dirname(os.path.realpath(__file__))
        checker = os.path.join(dir, '..', '..', 'sbin', command)
        env = os.environ.copy()
        env['AQDCONF'] = self.config.baseconfig
        out, err = Popen(checker, stdout=PIPE, stderr=PIPE,
                         env=env).communicate()
        self.assertEmptyErr(err, command)

        # 1. BranchChecker
        #
        # "Domain XXXX found in the database but not in template-king"
        self.matchoutput(out, "Domain domain-no-template-king found in the "
                         "database but not in template-king", command)
        self.matchoutput(out, "Sandbox sandbox-no-template-king found in the "
                         "database but not in template-king", command)
        self.matchclean(out, "Domain prod found", command)

        # "Branch XXXX found in template-king but not in the database"
        self.matchoutput(out, "Branch branch-only found in template-king "
                         "but not in the database", command)

        # The trash branch does not exist in the DB and that's OK
        trash = self.config.get("broker", "trash_branch")
        self.matchclean(out, trash, command)

        # 2. SandboxChecker
        #
        # "Sandbox XXXX found in the database but not on the filesystem"
        self.matchoutput(out, "Sandbox sandbox-no-template-king found in the "
                         "database but not on the filesystem", command)
        self.matchclean(out, "Sandbox managetest1 found", command)

        # 3. DomainChecker
        #
        # "Branch XXXX found in the database but not on the filesystem"
        self.matchoutput(out, "Domain domain-no-filesystem found in the "
                         "database but not on the filesystem", command)
        self.matchclean(out, "Domain prod found in the database", command)

        # "Domain XXXX found on filesystem (%s) but not in database"
        dir = os.path.join(self.config.get("broker", "domainsdir"),
                           "filesystem-only")
        self.matchoutput(out, "Domain filesystem-only found on the filesystem "
                         "(%s) but not in the database" % dir,
                         command)
        self.matchclean(out, "Domain prod found", command)

    def test_110_repair_branch(self):
        command = 'aqd_consistency_check.py'
        dir = os.path.dirname(os.path.realpath(__file__))
        checker = os.path.join(dir, '..', '..', 'sbin', command)
        env = os.environ.copy()
        env['AQDCONF'] = self.config.baseconfig
        out, err = Popen([checker, "--repair", "--only=BranchChecker"],
                         stdout=PIPE, stderr=PIPE, env=env).communicate()
        self.assertEmptyErr(err, command)

        self.matchoutput(out, "Deleting branch branch-only", command)

        # The trash branch should not get deleted
        trash = self.config.get("broker", "trash_branch")
        self.matchclean(out, trash, command)

    def test_115_verify_delete_orphaned_branch(self):
        kingdir = self.config.get("broker", "kingdir")
        command = ["show", "--no-patch", "--format=%B",
                   self.config.get("broker", "trash_branch")]
        out, _ = self.gitcommand(command, cwd=kingdir)
        self.matchoutput(out, "Delete orphaned branch branch-only", command)

    def test_120_repair_domain(self):
        command = 'aqd_consistency_check.py'
        dir = os.path.dirname(os.path.realpath(__file__))
        checker = os.path.join(dir, '..', '..', 'sbin', command)
        env = os.environ.copy()
        env['AQDCONF'] = self.config.baseconfig
        out, err = Popen([checker, "--repair", "--only=DomainChecker"],
                         stdout=PIPE, stderr=PIPE, env=env).communicate()
        self.assertEmptyErr(err, command)

        dir = os.path.join(self.config.get("broker", "domainsdir"),
                           "filesystem-only")
        self.matchoutput(out, "Removing %s" % dir, command)
        self.assertFalse(os.path.exists(dir))

        dir = os.path.join(self.config.get("broker", "domainsdir"),
                           "domain-no-filesystem")
        self.matchoutput(out, "Checking out domain domain-no-filesystem",
                         command)
        self.assertTrue(os.path.exists(dir))

    def test_800_cleanup(self):
        self.noouttest(["update_domain", "--domain", "domain-no-filesystem",
                        "--archived"])
        self.statustest(["del_domain", "--domain", "domain-no-filesystem"] + self.valid_just_tcm)

        self.noouttest(["update_domain", "--domain", "domain-no-template-king",
                        "--archived"])
        self.statustest(["del_domain", "--domain", "domain-no-template-king"] + self.valid_just_tcm)

        self.statustest(["del_sandbox", "--sandbox", "sandbox-no-template-king"])

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestConsistency)
    unittest.TextTestRunner(verbosity=2).run(suite)


def perfect_number(number):

    perfect_numbers = []  # We define an empty list to record perfect numbers within the given range.

    for i in range(1, number):  # We use a for loop to find and record the perfect numbers in the given range.
        divisors = [j for j in range(1, i) if i % j == 0]  # We use list comprehension to find divisors of each number.
        if i == sum(divisors):  # If sum of the divisors of a number is equal to the number, we add it to the list.
            perfect_numbers.append(sum(divisors))
    return perfect_numbers

print(*perfect_number(1000))


##### MAIN MENU #####
from Budget import Budget
from Transaction import Transaction
from datetime import date

def mainMenu():
    my_budget = Budget()
    my_record = Transaction()

    while(True):
        print("\n--------------------------MENU-------------------------------")
        print("1 = SET BUDGET")
        print("2 = SET TRANSACTION")
        print("3 = SEE TRANSACTION HISTORY")
        print("4 = SEE BUDGET HISTORY")
        print("5 = EXIT")
        print("-------------------------------------------------------------\n")

        selection = 0
        try:
            selection = int(input("Enter choice: "))
        except:
            print("Wrong format!!!")
            mainMenu()

        if selection == 1:
            try:
                budgetName = input("Enter budget name: ")
                budgetAmount = int(input("Enter your budget amount: "))
                my_budget.date = date.today()
                my_budget.setBudget(budgetName, budgetAmount)
                print("\n")
            except:
                print("Wrong format!!!")
                mainMenu()

        elif selection == 2:
            try:
                recordName = input("Enter transaction name: ")
                recordAmount = int(input("Enter your transaction amount: "))
                recordDate = input("Enter your transaction date: ")

                my_record.Add_Transaction(recordName, recordAmount, recordDate)
            except:
                print("Wrong format!!!")
                mainMenu()

        elif selection == 3:
            my_record.get_all_transc()

        elif selection == 4:
            my_budget.seeHistory()

        elif selection == 5:
            break

        else:
            break

print("\n** WELCOME TO ULTIMATE TRACKER **")
print("WHAT DO YOU WANT TO DAY?:")
mainMenu()


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

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

from django import forms
from mytask.models import Task , Comment , Type
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit
from crispy_forms.bootstrap import InlineCheckboxes, FormActions

class TaskForm(forms.ModelForm):
    LEVEL_CHOICES = (
        ('delay', 'delay'), ('normal', 'normal'),
        ('quick', 'quick'), ('now', 'now'),
    )

    PROGRESS_CHOICES = (
        ('0', '0'), ('10', '10'), ('20', '20'),
        ('30', '30'), ('40', '40'), ('50', '50'),
        ('60', '60'), ('70', '70'), ('80', '80'),
        ('90', '90'), ('100', '100'),
    )

    # name
    name = forms.CharField(
        label=u'任务名称',
        max_length=20 ,
        required=True ,
        error_messages={'required': u'请输入任务名称', 'error':u'任务名称输入太长，请精简'},
    )
    # 文章类型
    type = forms.ModelChoiceField(
        label=u'类型 ',
        empty_label=u'请选择文章类别' ,
        queryset=Type.objects.filter(state=True),
        to_field_name='id',
        required=True ,
        error_messages={'required': u'请选择任务类型'},
    )
    # 关键字
    level = forms.ChoiceField(
        label=u'任务级别',
        choices=LEVEL_CHOICES,
        error_messages={'required': u'请选择任务级别'},
        required=True,
    )
    progress = forms.ChoiceField(
        label=u'任务进度',
        choices=PROGRESS_CHOICES,
        error_messages={'required': u'请选择任务进度'},
        required=True,
    )
    is_fixed = forms.BooleanField(
        label=u'是否结束',
        required=False,
    )
    # 文章内容
    content = forms.Textarea()

    class Meta:
        model = Task
        fields = [ 'name' , 'type', 'level' , 'progress', 'content' , 'is_fixed' ]

    def __init__(self , *args, **kwargs):
        super(TaskForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-2'
        self.helper.field_class = 'col-lg-8'
        self.helper.layout = Layout(
            'name',
            'type' ,
            'level',
            'progress' ,
            'content',
            'is_fixed',
            FormActions(
                Submit('save', u'保存'),
            )
        )

class CommentForm(forms.ModelForm):
    content = forms.Textarea()

    class Meta:
        model = Comment
        fields = ['content' ]

    def __init__(self , *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-2'
        self.helper.field_class = 'col-lg-8'
        self.helper.layout = Layout(
            'content',
            FormActions(
                Submit('save', u'发布'),
            )
        )