from flask import Blueprint, request, session, render_template
from werkzeug.exceptions import HTTPException

from src.modules.food.food import Food
from src.modules.diet_list.diet_list import DietList
from src.modules.result.result import Result
from src import decorators
from src.common.utils import Utils
from src.exceptions import food_exceptions
from src.modules.user.user import User
from src.modules.user.views import user_blueprint

list_blueprint = Blueprint("list", __name__)

list_blueprint.current_list = []
list_blueprint.result = Result()

@list_blueprint.route("add_to_list", methods=["POST"])
@decorators.requires_login
def add_to_list():
    try:
        food = Food.get_by_name(request.form['name'])
        gram = request.form['gram']
        if Utils.valid_amount(gram):
            food.gram = gram
            food.calculate_amount_value()
            list_blueprint.current_list.append(food)
            list_blueprint.result.add_to_result(food=food)
    except food_exceptions.NameNotFoundException:
        return render_template("user/profile.html", email=session['email'], ex="שם לא נמצא במאגר.",
                               current_food=None, all_food=user_blueprint.user_food, current_list=list_blueprint.current_list,
                               result=list_blueprint.result)
    except HTTPException:
        return render_template("user/profile.html", email=session['email'], ex="אנא בחר מוצר מתוך הטבלה.",
                               current_food=None, all_food=user_blueprint.user_food, current_list=list_blueprint.current_list,
                               result=list_blueprint.result)
    except food_exceptions.InvalidFoodAmount:
        return render_template("user/profile.html", email=session['email'], ex="אנא הוסף כמות.",
                               current_food=None, all_food=user_blueprint.user_food, current_list=list_blueprint.current_list,
                               result=list_blueprint.result)
    return render_template("user/profile.html", email=session['email'],
                           current_food=None, all_food=user_blueprint.user_food, current_list=list_blueprint.current_list,
                           result=list_blueprint.result)

@list_blueprint.route("my_lists")
@decorators.requires_login
def my_lists():
    user = User.get_by_email(session['email'])
    return render_template("list/my_lists.html", user_lists=DietList.get_user_lists(user._id))

@list_blueprint.route("get_list/<string:list_id>")
@decorators.requires_login
def get_list(list_id):
    user_list = DietList.get_list(list_id)
    return render_template("list/get_list.html", user_list=user_list)

@list_blueprint.route("save", methods=["POST"])
@decorators.requires_login
def save():
    user = User.get_by_email(session['email'])
    title = request.form['title']
    diet_list = DietList(user_id=user._id,
                         list_of_food=list_blueprint.current_list,
                         title=title)
    diet_list.save_to_mongo()
    list_blueprint.current_list = []
    list_blueprint.result = Result()
    return render_template("user/profile.html", all_food=user_blueprint.user_food, email=session['email'])

@list_blueprint.route("edit_list/<string:list_id>")
@decorators.requires_login
def edit_list(list_id):
    # give the user a page with the list items
    user_list = DietList.get_list(list_id=list_id)
    return render_template("list/edit_list.html", user_list=user_list)

@list_blueprint.route("add_to_my_list/<string:list_id>", methods=["POST", "GET"])
@decorators.requires_login
def add_to_my_list(list_id=None):
    if request.method == "POST":
        try:
            food = Food.get_food(request.form["id"])
            food.gram = int(request.form["gram"])
            DietList.add_to_list(list_id=list_id,
                                 food=food)
            user = User.get_by_email(session['email'])
        except food_exceptions.InvalidFoodAmount:
            return render_template("list/add_to_list.html", user_list=DietList.get_list(list_id),
                                   all_food=Food.get_foods(), ex="הכנס כמות אל התיבה.")
        return render_template("list/my_lists.html", user_lists=DietList.get_user_lists(user._id))
    return render_template("list/add_to_list.html", user_list=DietList.get_list(list_id),
                           all_food=Food.get_foods())

@list_blueprint.route("remove_from_list", methods=["POST"])
@decorators.requires_login
def remove_from_list():
    food = Food.get_food(request.form['id'])
    food.gram = int(request.form['gram'])
    DietList.remove_food_from_list(request.form['list_id'], food)
    user_list = DietList.get_list(request.form['list_id'])
    if user_list.list_of_food.__len__() == 0:
        DietList.remove_list(user_list._id)
        user = User.get_by_email(session['email'])
        return render_template("list/my_lists.html", user_lists=DietList.get_user_lists(user._id))
    return render_template("list/edit_list.html", user_list=user_list, list_of_food=user_list.list_of_food)

@list_blueprint.route("remove_list/<string:list_id>")
@decorators.requires_login
def remove_list(list_id=None):
    user = User.get_by_email(session['email'])
    user_lists = DietList.get_user_lists(user._id)
    if list_id in [each_list._id for each_list in user_lists]:
        DietList.remove_list(list_id)
    return render_template("list/my_lists.html", user_lists=DietList.get_user_lists(user._id))

@list_blueprint.route("clean_all")
@decorators.requires_login
def clean_all():
    list_blueprint.result = Result()
    list_blueprint.current_list = []
    return render_template("user/profile.html", all_food=user_blueprint.user_food, email=session['email'])


import pandas, error

DataFrame = pandas.DataFrame

class Generaliztion:
    def __init__(self, df:DataFrame):
        self.df = df

    def __errorControl(self, currentIndexList:list, column:str):
        try:
            if max(currentIndexList) > len(self.df):
                raise error.Error('설정된 범위가 전체 크기보다 큽니다.')
            elif self.df.loc[:, column].dtype != 'int64':
                raise error.Error('숫자형 데이터만 사용이 가능합니다.')

            return False
        except Exception as e:
            print('[Generaliztion Class Error]', e)
            return  True

    def local(self, column:str, currentIndexList:list) -> None:
        if self.__errorControl(currentIndexList, column):
            return

        datas = self.df.loc[currentIndexList[0]:currentIndexList[1], column]
        self.df.loc[currentIndexList[0]:currentIndexList[1], column] = [f'{min(datas)}~{max(datas)}' for _ in datas]

    def categorizion(self, column:str, replaceList:list, category:str):
        datas = self.df.loc[:, column]
        result = [category if data in replaceList else data for data in datas]
        self.df.loc[:, column] = result

if __name__ == '__main__':
    excel = pandas.read_csv('../../../Sample/kTest_Full.csv', index_col=0)
    print(excel.head())

    test = Generaliztion(excel)
    test.local('총 구매 금액', [0, 2])
    test.categorizion('주소', ['전라남도', '전라북도'], '전라도')
    print(excel.head())


class Solution:
    def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
        if t == 0 and len(nums) == len(set(nums)):
            return False

        for i in range(0, len(nums)):
            for j in range(1, len(nums)):
                if i == j:
                    continue
                elif abs(nums[j]-nums[i]) <= t and abs(j-i) <= k:
                    return True

        return False


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 21 09:31:56 2018

@author: ashish
"""

import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas.plotting import scatter_matrix
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder,StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint

train=pd.read_csv('../houseprices/train.csv')
test=pd.read_csv('../houseprices/test.csv')

##difference between train and test
train.columns.difference(test.columns)

##COMBINE train and test data .Separate labels from train data

target='SalePrice'
labels=train[target]
train['Test']=0
test['Test']=1
full=pd.concat([train.drop(target,axis=1),test])

##LOOK at data
full.info()
full.describe()

full.hist(bins=50,figsize=(30,20))
plt.show()

#DATA EXploration
data_explore=train.copy()

#correlations
correl_matrix=data_explore.corr()
correl_matrix=correl_matrix[target].sort_values(ascending=False)
correl_matrix

high_correl=[]
for i in correl_matrix.index:
    if abs(correl_matrix[i])>=0.5:
        high_correl.append(i)

high_correl

scatter_matrix(data_explore[high_correl],figsize=(20,15))
plt.show()

linear_corr=['GrLivArea','GarageArea','TotalBsmtSF','1stFlrSF']
for i in linear_corr:
    data_explore.plot(kind='scatter',x=target,y=i)

#Preprocessing data
#filling missing values case by case describe(),alue_counts()
full.info()

#applying imputer to mostattributes
median_imputer=SimpleImputer(strategy='median')
freq_imputer=SimpleImputer(strategy='most_frequent')
median_fix= ['LotFrontage']
freq_fix = ['MSZoning', 'Utilities', 'Exterior1st', 'Exterior2nd', 'MasVnrType', 'MasVnrArea',
    'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinSF1', 'BsmtFinType2',
    'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'Electrical', 'BsmtFullBath', 'BsmtHalfBath',
    'KitchenQual', 'Functional', 'GarageType', 'GarageYrBlt', 'GarageFinish', 'GarageCars',
    'GarageArea', 'GarageQual', 'GarageCond', 'SaleType']
drop_columns = ['Alley', 'FireplaceQu', 'PoolQC', 'Fence', 'MiscFeature']

def impute(data,predictor,imputer):
    for i in predictor:
        data[i]=imputer.fit_transform(data[[i]]).ravel()

#missing values filled
impute(full,median_fix,median_imputer)
impute(full,freq_fix,freq_imputer)
full=full.drop(drop_columns,axis=1)
full.info()

#one hot encoding categorical variables

def onehot_encode(data):
    predictor=data.select_dtypes(include=[object]).columns.tolist()
    encoder=OneHotEncoder(sparse=False)
    for i in predictor:
        data[i]=encoder.fit_transform(data[[i]])

full_coded=full.copy()
onehot_encode(full_coded)

#SCALING

#separate data n scale separately
train_coded=full_coded.loc[full_coded['Test']==0].drop('Test',axis=1)
test_coded=full_coded.loc[full_coded['Test']==1  ].drop('Test',axis=1)

def std_scaled(data,scaler,is_train):
    preds=data.select_dtypes(include=[np.int,np.float]).columns.tolist()[1:]
    if is_train:
        for i in preds:
            data[i]=scaler.fit_transform(data[[i]])
    else:
        for i in preds:
            data[i]=scaler.transform(data[[i]])
    return data

##CAPTURE data

scaler=StandardScaler()
train_prepared=std_scaled(train_coded,scaler,True)
test_prepared=std_scaled(test_coded,scaler,False)

#MOdelling

forest_reg=RandomForestRegressor()
##capture
forest_reg.fit(train_prepared,labels)

test_data=train_prepared[:5]
actual_value=labels[:5]
print("forest regression predictions",forest_reg.predict(test_data))
print("actual labels",list(actual_value))
forest_reg_predicted=forest_reg.predict(train_prepared)
forest_reg_rmse=np.sqrt(mean_squared_error(labels,forest_reg_predicted))
forest_reg_rmse

    ##orest regression predictions [206250. 172450. 222390. 146430. 250000.]
############################actual labels [208500, 181500, 223500, 140000, 250000]
    ##tuning

##capture

parameters={'n_estimators':randint(low=1,high=200),
            'max_features':randint(low=1,high=80)}

forest_reg = RandomForestRegressor(random_state=7)
rnd_search = RandomizedSearchCV(forest_reg, param_distributions=parameters,                                n_iter=10, cv=5, scoring='neg_mean_squared_error', random_state=7)
rnd_search.fit(train_prepared, labels)
final_model = rnd_search.best_estimator_
final_model_predicted = final_model.predict(train_prepared)
final_model_rmse = np.sqrt(mean_squared_error(labels, final_model_predicted))
print("final_model_rmse",final_model_rmse)


from devices import EMG
import csv
import time
from time import sleep

def collect_emg():
	"""
	collect the data from the emg sensor and store it in a csv file
	"""
	emg = EMG(channel=0)
	tester = input('name of tester: ')
	tester += '_emg.csv'
	# open the emg log (csv format) to start data collection
	with open(tester, mode='a') as emglog:
		# set the column header
		fieldnames = ['emg_reading', 'time']
		writer = csv.DictWriter(emglog, fieldnames=fieldnames)
		writer.writeheader()
		# start timer
		start = time.process_time()
		time.clock()
		# collect and write data to the csv file
		while True:
			emg_val = emg.read_analog()
			elapsed = time.process_time() - start
			print('emg: ', emg_val)
			writer.writerow({'emg_reading': emg_val, 'time': elapsed})
			sleep(0.5)

collect_emg()


import sys
from collections import defaultdict

r = sys.stdin.readline

class Node:
    def __init__(self, i: int, a: int):
        self.i = i
        self.a = a

class Tree:
    def __init__(self, node: Node):
        self.root = node
        self.edges = defaultdict(defaultdict(int))

def solution():
    answer = []

    N = int(r())
    a = list(map(int, r().split()))
    input_data = []

    tree = Tree(Node(1, a[0]))
    for i in range(N - 1):
        i = i + 1
        p, c = map(int, r().split())
        input_data.append([i, p, c])

        n = Node(i, a[i])
        tree[i][p] = c

    print(input_data)
    print(tree)

if __name__ == "__main__":
    solution()


# Copyright 2012 Managed I.T.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import logging

from conohadnsclient.cli import base
from conohadnsclient.v1.domains import Domain

LOG = logging.getLogger(__name__)

class ListDomainsCommand(base.ListCommand):
    """List Domains"""

    columns = ['id', 'name', 'serial']

    def execute(self, parsed_args):
        return self.client.domains.list()

class GetDomainCommand(base.GetCommand):
    """Get Domain"""

    def get_parser(self, prog_name):
        parser = super(GetDomainCommand, self).get_parser(prog_name)

        parser.add_argument('id', help="Domain ID or name.")

        return parser

    def execute(self, parsed_args):
        id = self.find_resourceid_by_name_or_id('domains', parsed_args.id)
        return self.client.domains.get(id)

class CreateDomainCommand(base.CreateCommand):
    """Create Domain"""

    def get_parser(self, prog_name):
        parser = super(CreateDomainCommand, self).get_parser(prog_name)

        parser.add_argument('--name', help="Domain name.", required=True)
        parser.add_argument('--email', help="Domain email.", required=True)
        parser.add_argument('--ttl', type=int, help="Time to live (seconds).")
        parser.add_argument('--description', help="Description.")

        return parser

    def execute(self, parsed_args):
        domain = Domain(
            name=parsed_args.name,
            email=parsed_args.email,
        )

        if parsed_args.description:
            domain.description = parsed_args.description

        if parsed_args.ttl is not None:
            domain.ttl = parsed_args.ttl

        return self.client.domains.create(domain)

class UpdateDomainCommand(base.UpdateCommand):
    """Update Domain"""

    def get_parser(self, prog_name):
        parser = super(UpdateDomainCommand, self).get_parser(prog_name)

        parser.add_argument('id', help="Domain ID or name.")
        parser.add_argument('--name', help="Domain name.")
        parser.add_argument('--email', help="Domain email.")
        parser.add_argument('--ttl', type=int, help="Time to live (seconds).")
        description_group = parser.add_mutually_exclusive_group()
        description_group.add_argument('--description', help="Description.")
        description_group.add_argument('--no-description', action='store_true')

        return parser

    def execute(self, parsed_args):
        # TODO(kiall): API needs updating.. this get is silly
        id = self.find_resourceid_by_name_or_id('domains', parsed_args.id)
        domain = self.client.domains.get(id)

        if parsed_args.name:
            domain.name = parsed_args.name

        if parsed_args.email:
            domain.email = parsed_args.email

        if parsed_args.ttl is not None:
            domain.ttl = parsed_args.ttl

        if parsed_args.no_description:
            domain.description = None
        elif parsed_args.description:
            domain.description = parsed_args.description

        return self.client.domains.update(domain)

class DeleteDomainCommand(base.DeleteCommand):
    """Delete Domain"""

    def get_parser(self, prog_name):
        parser = super(DeleteDomainCommand, self).get_parser(prog_name)

        parser.add_argument('id', help="Domain ID or name.")

        return parser

    def execute(self, parsed_args):
        id = self.find_resourceid_by_name_or_id('domains', parsed_args.id)
        return self.client.domains.delete(id)

class ListDomainServersCommand(base.ListCommand):
    """List Domain Servers"""

    columns = ['name']

    def get_parser(self, prog_name):
        parser = super(ListDomainServersCommand, self).get_parser(prog_name)

        parser.add_argument('id', help="Domain ID or name.")

        return parser

    def execute(self, parsed_args):
        id = self.find_resourceid_by_name_or_id('domains', parsed_args.id)
        return self.client.domains.list_domain_servers(id)


#!/usr/bin/env python
from argparse import ArgumentParser
from os import environ
from prometheus_client import start_http_server
from prometheus_client.core import CounterMetricFamily
from prometheus_client.core import REGISTRY
from smeterd import __default_serial__
from smeterd.meter import SmartMeter
from sys import exit
from sys import exit
from time import sleep

__version__ = '0.9.6'

class SmeterdCollector(object):
    def __init__(self, serial_port):
        self._serial_port = serial_port

    def collect(self):
        with SmartMeter(self._serial_port) as meter:
            p = meter.read_one_packet()

        yield CounterMetricFamily('smart_meter_gas_total', 'The total gas consumed', value=int(p['gas']['total']*1000))

        kwh = CounterMetricFamily('smart_meter_kwh_total', 'The total kwh consumed', labels=["tariff"])
        kwh.add_metric(['low'], int(p['kwh']['low']['consumed']*1000))
        kwh.add_metric(['high'], int(p['kwh']['high']['consumed']*1000))

        yield kwh

def parse_args():
    parser = ArgumentParser(
        description='A prometheus exporter for you smart meter.'
    )
    parser.add_argument(
        '-s', '--serial-port',
        metavar=__default_serial__,
        required=False,
        help='device name to read packets from',
        default=environ.get('SMETERD_EXPORTER_SERIAL_PORT', __default_serial__)
    )
    parser.add_argument(
        '-p', '--port',
        metavar='port',
        required=False,
        type=int,
        help='Listen to this port',
        default=int(environ.get('SMETERD_EXPORTER_PORT', '8090'))
    )
    return parser.parse_args()

def main():
    try:
        args = parse_args()
        port = int(args.port)
        REGISTRY.register(SmeterdCollector(args.serial_port))
        start_http_server(port)
        print("Serving at port: {}".format(port))
        while True:
            sleep(1)
    except KeyboardInterrupt:
        print("Interrupted")
        exit(0)

if __name__ == '__main__':
    main()


import sys
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class Event(FileSystemEventHandler):
    def on_created(self, event):
        print("on_created", event.src_path)
        f = open(event.src_path, "r")
        if f.mode == "r":
            contents = f.read()
            print(contents)

    def on_deleted(self, event):
        print("on_deleted", event.src_path)

if __name__=="__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else './../gcode/'
    event_handler = Event()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


from threading import Timer
from time import sleep

class Repeat:
    def __init__(self, i):
        self.i = i
        self.timer = None
        self.dp = self.prime()
        self.start()

    def start(self):
        self.timer = Timer(1.0, self.start)
        self.timer.start()
        print(self.dp[self.i])
        self.i += 1

    def prime(self):
        l = [1]
        for num in range(1, 100):
            if num > 1:
                for i in range(2, num):
                    if (num % i) == 0:
                        break
                else:
                    l.append(num)
        return l

    def stop(self):
        self.timer.cancel()

r = Repeat(0)
try:
    sleep(10)
finally:
    r.stop()


import numpy as np
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) #dados de entrada(features)
y = np.array([1, 1, 2, 2]) #dados de saida(labels)
from sklearn.svm import SVC #importação do suport vector machine
clf = SVC(gamma=1.0,kernel = 'linear',C = 1.0)
''' kernel:o parametro kernel serve, para dizer qual função voce quer para classificar os atributos(linear,sigmoid,precomputed,callabe,poly)

    gamma: quanto menor for maior é o alcance dos atributos, quanto maior for, menor é o alcance(gama alto significa que ele levará em consideração
    os atributos que estão perto da margem( a reta fica regular,porem,mais suscetivel a erros),quando o gamma for menor, levará em consideraçãos os
    que estão mais longe(fica desregular, porem mais inteligente))

    C: valor alto para C significa mais erros a serem considerados(fica mais facil de manejar),menores valores para C, significa mais acuracia no algoritmo(mais complexo)
'''
clf.fit(X, y) #treinamento

print(clf.predict([[-0.8, -1]])) #adcionando novos dados

IA/classifação,regressao e clusterização/classificadores(aprendizado supervisionado)/svm_sintaxe.py


import os
import argparse

class DirectoryWalk:
    def __init__(self):
        self.path = ''

    def get_args(self):
        parser = argparse.ArgumentParser()
        parser.add_argument("path", help = "Path to folder")

        return parser.parse_args()

    def scan_path(self):
        with open(self.path) as iter_path:
            for entry in iter_path:
                print(entry.name)

    def main(self):
        args = self.get_args()
        self.path = args.path
        self.scan_path()

if __name__ == "__main__":
    walk_instance = DirectoryWalk()
    walk_instance.main()


import random as t

bot = t.randint(0,1000)

t = 10

print(f"Let's play a game. You have {t} attempts")

a = 0

while True:
    y = int(input("Type a number: "))
    a+=1

    if a == t:
        print(f"You lose. The number was {bot}")
        break
    if y == bot:
        print("You win")
        break

    print("big" if y > bot else "small")

print(f"attempts: {a}")


import sys

n = int(sys.argv[1])

lastPrime = 2
prime = [lastPrime]

while len(prime) < n:
    lastPrime += 1
    possiblePrime = True
    for i in range(len(prime)):
        if lastPrime % prime[i] == 0: possiblePrime = False; break
    if possiblePrime: prime.append(lastPrime)

print(prime)


# !/usr/bin/env python
#  -*- coding: utf-8 -*-
import logging
import os
import smtplib

from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import requests
from jinja2 import Template, Environment, FileSystemLoader

jinja_environment = Environment(autoescape=True,loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))

def email_log_in():
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(os.environ['EMAIL_ADDRESS'], os.environ['EMAIL_PASSWORD'])
    return server

def mail_update(server, data, mail_to):
    try:
        msg = MIMEMultipart()
        msg['Subject'] = "Today's filings!"
        msg['From'] = os.environ['EMAIL_ADDRESS']
        msg['BCC'] = mail_to
        template = jinja_environment.get_template('working_filings.html')
        text = template.render(data)
        msg.attach(MIMEText(text, 'html'))
        text = msg.as_string()
        server.sendmail(os.environ['EMAIL_ADDRESS'], mail_to, text)
        server.quit()
    except:
        mail_update('ERROR FOR {0}'.format(mail_to), os.environ['ADMIN_EMAIL'])
        exit()


import random
import subprocess
import time
import tempfile
import threading

from dtest import debug, Tester
from tools import new_node, query_c1c2, since, InterruptBootstrap
from assertions import assert_almost_equal
from ccmlib.node import NodeError
from cassandra import ConsistencyLevel
from cassandra.concurrent import execute_concurrent_with_args

class TestMetadata(Tester):

    def force_compact(self):
        cluster = self.cluster
        (node1, node2) = cluster.nodelist()
        if cluster.version() < "2.1":
            node1.nodetool("compact Keyspace1 Standard1")
        else:
            node1.nodetool("compact keyspace1 standard1")

    def force_repair(self):
        cluster = self.cluster
        (node1, node2) = cluster.nodelist()
        if cluster.version() < "2.1":
            node1.nodetool('repair Keyspace1 Standard1')
        else:
            node1.nodetool('repair keyspace1 standard1')

    def do_read(self):
        cluster = self.cluster
        (node1, node2) = cluster.nodelist()

        if cluster.version() < "2.1":
            node1.stress(['-o', 'read', '-n', '30000', '-l', '2', '-t', '1', '-I', 'LZ4Compressor'])
        else:
            node1.stress(['read', 'no-warmup', 'n=30000', '-schema', 'replication(factor=2)', 'compression=LZ4Compressor',
                              '-rate', 'threads=1', '-pop', 'dist=UNIFORM(1..30000)'])

    def metadata_reset_while_compact_test(self):
        """ Resets the schema while a compact, read and repair happens.
            All kinds of glorious things can fail.
        """
        cluster = self.cluster
        cluster.populate(2).start(wait_other_notice=True)
        (node1, node2) = cluster.nodelist()

        node1.nodetool("disableautocompaction")
        node1.nodetool("setcompactionthroughput 1")

        for i in range(3):
            if cluster.version() < "2.1":
                node1.stress(['-o', 'insert', '-n', '30000', '-l', '2', '-t', '5', '-I', 'LZ4Compressor'])
            else:
                node1.stress(['write', 'no-warmup', 'n=30000', '-schema', 'replication(factor=2)', 'compression=LZ4Compressor',
                              '-rate', 'threads=5', '-pop', 'dist=UNIFORM(1..30000)'])
            node1.flush()

        thread = threading.Thread(target=self.force_compact)
        thread.start()
        time.sleep(1)

        thread2 = threading.Thread(target=self.force_repair)
        thread2.start()
        time.sleep(5)

        thread3 = threading.Thread(target=self.do_read)
        thread3.start()
        time.sleep(5)

        node1.nodetool("resetlocalschema")

        thread.join()
        thread2.join()
        thread3.join()


#!/bin/env python
# coding=utf-8
import sys
import json

body1 = {
    "module": "tdpos",
    "method": "nominate_candidate",
    "args": {
        "candidate": "提名address",
        "neturl": "提名neturl"
    }
}

body2 = {
    "module": "tdpos",
    "method": "vote",
    "args": {
        "candidates": ["提名过的address"]
    }
}

body3 = {
    "module": "proposal",
    "method": "Thaw",
    "args": {
        "txid": "提名或者投票addresss时返回的txid"
    }
}

body4 = {
    "module_name": "xkernel",
    "method_name": "NewAccount",
    "args": {
        "account_name": "1559479167343170",
        "acl": "{\"pm\": {\"rule\": 1,\"acceptValue\": 0.6},\"aksWeight\": {\"dpzuVdosQrF2kmzumhVeFQZa1aYcdgFpN\": 0.5,\"TH\": 0.5}}"
    }
}

body5 = {
    "version": "1",
    "predistribution": [
        {
            "address": "dpzuVdosQrF2kmzumhVeFQZa1aYcdgFpN",
            "quota": "100000000000000000000"
        }
    ],
    "maxblocksize": "128",
    "award": "1000000",
    "decimals": "8",
    "award_decay": {
        "height_gap": 31536000,
        "ratio": 1
    },
    "gas_price": {
        "cpu_rate": 1000,
        "mem_rate": 1000000,
        "disk_rate": 1,
        "xfee_rate": 1
    },
    "new_account_resource_amount": 1000,
    "genesis_consensus": {
        "name": "tdpos",
        "config": {
            "timestamp": "1559021720000000000",
            "proposer_num": "1",
            "period": "3000",
            "alternate_interval": "3000",
            "term_interval": "6000",
            "block_num": "20",
            "vote_unit_price": "1",
            "init_proposer": {
                "1": ["dpzuVdosQrF2kmzumhVeFQZa1aYcdgFpN", "nodeaddress"]
            },
            "init_proposer_neturl": {
                "1": ["/ip4/127.0.0.1/tcp/47101/p2p/QmVxeNubpg1ZQjQT8W5yZC9fD7ZB1ViArwvyGUB53sqf8e", "nodeneturl"]
            }
        }
    }
}

body_dict = {'./relate_file/nominate.json': body1, './relate_file/vote.json': body2,
             './relate_file/revoke.json': body3, './relate_file/account.json': body4, './relate_file/xuper.json': body5}
for key in body_dict:
    body_file = json.dumps(body_dict[key], indent=4)
    f = open(key, 'w')
    f.writelines(body_file)
    f.close()


from flask import Flask, render_template, request;
import cv2;
from predict import predict;
import numpy as np;

import tensorflow as tf;

app = Flask(__name__, template_folder='static')
app.config['DEBUG'] = True

@app.route('/', methods=['GET'])
def get():
    return render_template('./index.html')

@app.route('/processing', methods=['POST'])
def processing():
    image = request.files["filename"]
    image.save("./photos/"+image.filename)
    img = "./photos/"+image.filename
    # img = img.resize(224,224,1)

    model_path = "./model"
    # print(model)
    predictions = predict(model_path, img)
    print(predictions)
    return "hey"


import tensorflow as tf
import os

def brain_dataset(path, image_size=None, augment_function=None, num_parallel_calls=tf.data.experimental.AUTOTUNE):
    def get_subdirectory_files(subdir):
        sub_path = os.path.join(path, subdir)
        return sorted([os.path.join(dp, f) for dp, dn, fn in
                       os.walk(os.path.expanduser(sub_path), followlinks=True) for f in
                       fn if f.endswith('.png')])

    def parse_function(image_path, labels_path):
        image = _read_image(image_path)
        labels = _read_labels(labels_path)

        if augment_function:
            image, labels = augment_function(image, labels)

        if image_size:
            image = tf.image.resize(image, image_size)
            labels = tf.image.resize(labels, image_size, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)

        return image, labels

    data_files = get_subdirectory_files('images/images')
    target_files = get_subdirectory_files('labels/labels')

    assert len(data_files) == len(target_files)

    ds = tf.data.Dataset.from_tensor_slices((data_files, target_files)) \
        .shuffle(len(data_files)) \
        .map(parse_function, num_parallel_calls)
    return ds, len(data_files)

@tf.function
def _read_image(path):
    x = tf.io.read_file(path)
    x = tf.image.decode_png(x, 3)
    x = tf.image.convert_image_dtype(x, tf.float32)
    return x

@tf.function
def _read_labels(path):
    x = tf.io.read_file(path)
    x = tf.image.decode_png(x, 1)
    x = tf.cast(x, tf.int32)
    return x


import threading

'''
threading:Python中线程的使用
'''

class BuckysMessenger(threading.Thread):
    def run(self):
        for _ in range(100):
            print(threading.current_thread().getName())

x=BuckysMessenger(name="Send out Messages")
y=BuckysMessenger(name="Receive messages")
x.start()
y.start()


"""
OaiHarvesterMetadataFormatSet model
"""

from django_mongoengine import fields, Document
from mongoengine import errors as mongoengine_errors
from mongoengine.queryset.base import CASCADE

from core_main_app.commons import exceptions
from core_oaipmh_harvester_app.components.oai_harvester_metadata_format.models import OaiHarvesterMetadataFormat
from core_oaipmh_harvester_app.components.oai_harvester_set.models import OaiHarvesterSet

class OaiHarvesterMetadataFormatSet(Document):
    """Association table between OaiHarvesterMetadataFormat and OaiHarvesterSet"""
    harvester_set = fields.ReferenceField(OaiHarvesterSet, reverse_delete_rule=CASCADE)
    harvester_metadata_format = fields.ReferenceField(OaiHarvesterMetadataFormat, reverse_delete_rule=CASCADE,
                                                      unique_with='harvester_set')
    last_update = fields.DateTimeField(blank=True)

    @staticmethod
    def get_by_metadata_format_and_set(oai_harvester_metadata_format, oai_harvester_set):
        """ Get an OaiHarvesterMetadataFormatSet by its OaiHarvesterMetadataFormat and OaiHarvesterSet.

            Args:
                oai_harvester_metadata_format:
                oai_harvester_set:

            Returns:
                OaiHarvesterMetadataFormatSet instance.

        """
        try:
            return OaiHarvesterMetadataFormatSet.objects.get(harvester_metadata_format=oai_harvester_metadata_format,
                                                             harvester_set=oai_harvester_set)
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(str(e))
        except Exception as e:
            raise exceptions.ModelError(str(e))

    @staticmethod
    def upsert_last_update_by_metadata_format_and_set(harvester_metadata_format, harvester_set,
                                                      last_update):
        """ Update the last_update date for a given metadata_format and set. Create an
        OaiHarvesterMetadataFormatSet if doesn't exist.

            Args:
                harvester_metadata_format: Metadata format.
                harvester_set: Set.
                last_update: Last update date.

        """
        try:
            OaiHarvesterMetadataFormatSet.objects(
                harvester_metadata_format=harvester_metadata_format,
                harvester_set=harvester_set).update_one(last_update=last_update, upsert=True)
        except Exception as e:
            raise exceptions.ModelError(str(e))


import logging
from collections import defaultdict

from api.stats.db_queries.leaderboard import (
    get_leaderboard_rows,
)
from api.stats.model_layer import (
    get_active_nodes_count,
    get_sessions_count,
    get_average_session_time,
    get_total_data_transferred,
    get_available_nodes,
    get_node_info,
    get_sessions_country_stats,
)
from api.stats.node_list import get_nodes
from dashboard.settings import (
    METRICS_CACHE_TIMEOUT,
    VIEW_SESSIONS_CACHE_TIMEOUT
)
from api.settings import DB_CONFIG
from werkzeug.contrib.cache import SimpleCache
from dashboard.helpers import get_month_range
from flask import Flask, render_template, request, abort, jsonify
from datetime import datetime
from models import db
from dashboard.filters import initialize_filters
from dashboard.discovery_api import fetch_sessions, ApiError, fetch_session

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

cache = SimpleCache()

initialize_filters(app)

def _generate_database_uri(db_config):
    return 'mysql+pymysql://{}:{}@{}/{}'.format(
        db_config['user'], db_config['passwd'], db_config['host'],
        db_config['name'])

app.config['SQLALCHEMY_DATABASE_URI'] =\
    _generate_database_uri(DB_CONFIG)

def collect_metrics():
    metrics = cache.get('metrics')
    if metrics is None:
        metrics = {
            'active_nodes_count': get_active_nodes_count(),
            'sessions_count': get_sessions_count(),
            'active_sessions_count': get_sessions_count(
                only_active_sessions=True
            ),
            'average_session_time': get_average_session_time(),
            'total_data_transferred': get_total_data_transferred(),
        }
        cache.set(
            'metrics',
            metrics,
            timeout=METRICS_CACHE_TIMEOUT
        )
    return metrics

@app.route('/')
def main():
    available_nodes = list(get_available_nodes())

    available_nodes_count_by_country = defaultdict(int)
    seen = set()
    for n in available_nodes:
        if n.node_key not in seen:
            available_nodes_count_by_country[n.country_string] += 1
            seen.add(n.node_key)

    dashboard_data = {
        'available_nodes': available_nodes,
        'available_nodes_count_by_country': available_nodes_count_by_country
    }

    page_content = render_template(
        'dashboard.html',
        **collect_metrics(),
        **dashboard_data
    )
    return page_content

@app.route('/leaderboard')
def leaderboard():
    date_from, date_to = get_month_range(datetime.utcnow().date())
    leaderboard_rows = get_leaderboard_rows(date_from, date_to)
    page_data = {
        'date_from': date_from.strftime('%b %d, %Y'),
        'date_to': date_to.strftime('%b %d, %Y'),
        'leaderboard_rows': leaderboard_rows,
    }
    page_content = render_template(
        'leaderboard.html',
        **page_data,
    )
    return page_content

@app.route('/node/<key>/<service_type>')
def node(key, service_type):
    node = get_node_info(key, service_type)
    return render_template(
        'service.html',
        node=node,
    )

@app.route('/services')
def nodes():
    return render_template(
        'services.html',
        nodes=get_nodes()
    )

# TODO: change to `/sessions/<key>`
@app.route('/session/<key>')
def session(key):
    session = fetch_session(key)

    return render_template(
        'session.html',
        session=session,
    )

@app.route('/sessions')
def sessions():
    sessions = cache.get('all-sessions')
    if sessions is None:
        sessions = fetch_sessions(limit=500)
        cache.set(
            'all-sessions',
            sessions,
            timeout=VIEW_SESSIONS_CACHE_TIMEOUT
        )

    return render_template(
        'sessions.html',
        sessions=sessions
    )

@app.route('/sessions-country')
def sessions_country():
    results = get_sessions_country_stats()

    return render_template(
        'sessions-country.html',
        stats=results
    )

@app.route('/ping')
def ping():
    return jsonify({'status': 'ok'})

@app.errorhandler(ApiError)
def handle_api_error(e):
    logging.exception('Request to discovery failed')
    return 'Request to discovery failed', 503

def init_db():
    db.init_app(app)

if __name__ == '__main__':
    app.run(debug=True)


class InputCheck:
    def __init__(self):
        self._min_value = 1
        self._max_value = 9

    def is_in_range(self, user_input):
        int_input = 0
        try:
            int_input = int(user_input)
        except:
            return False
        return int_input >= self._min_value \
            and int_input <= self._max_value


from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status

from main_app.serializers import *
from main_app.models import *

@api_view(['GET'])
def list(request):

    try:
        model = Customer.objects.all()
        serializer = CustomerSerializer(
            model, many=True, context={"request": request})

        return Response({"status": True, "getList": serializer.data})

    except BaseException as error:
        return Response({"status": "error", "errorMessage": str(error)})

@api_view(['GET'])
def single(request, id):

    try:
        model = Customer.objects.get(pk=id)
        serializer = CustomerSerializer(
            model, context={"request": request})

        return Response({"status": True, "getSingle": serializer.data})

    except BaseException as error:
        return Response({"status": "error", "errorMessage": str(error)})

@api_view(['POST'])
def create(request):

    try:
        serializer = CustomerSerializer(
            data=request.data, context={"request": request})

        if serializer.is_valid():
            serializer.save()
            return Response({"status": True, "postMessage": "Create Success"})

        return Response({"status": False, "postError": serializer.errors})

    except BaseException as error:
        return Response({"status": "error", "errorMessage": str(error)})

@api_view(['PATCH'])
def edit(request, id):

    try:
        model = Customer.objects.get(pk=id)
        serializer = CustomerSerializer(model, data=request.data, context={
            "request": request}, partial=True)

        if serializer.is_valid():
            serializer.save()
            return Response({"status": True, "patchMessage": "Update Success"})

        return Response({"status": False, "patchError": serializer.errors})

    except BaseException as error:
        return Response({"status": "error", "errorMessage": str(error)})

@api_view(['DELETE'])
def delete(request, id):

    try:
        model = Customer.objects.get(pk=id)
        model.delete()

        return Response({"status": True, "deleteMessage": "Delete Success"})

    except BaseException as error:
        return Response({"status": "error", "errorMessage": str(error)})


"""
Copyright: Intel Corp. 2018
Author: Wenyi Tang
Email: wenyi.tang@intel.com
Created Date: May 9th 2018
Updated Date: May 9th 2018

virtual file is an abstraction of a file or
a collection of ordered frames
"""
from pathlib import Path
from io import SEEK_END, BytesIO
from PIL import Image
import numpy as np

from ..Util.Utility import to_list

class File:

    def __init__(self, path, rewind=False):
        """
        If path is a file, File opens it and calculates its length.
        If path is a folder, File organize each file in the folder as alphabet order

        Args:
             path: path to a node (can be a file or just a folder)
             rewind: rewind the file when reaches EOF
        """
        self.path = Path(path)
        self.file = []
        self.length = dict()
        mode = 'rb'  # mode must be 'rb'
        if self.path.is_file():
            self.name = self.path.stem
            self.file = [self.path]
            with self.path.open(mode) as fd:
                fd.seek(0, SEEK_END)
                self.length[self.path.name] = fd.tell()
        elif self.path.is_dir():
            self.name = self.path.stem  # TODO: is this right?
            for _file in self.path.glob('*'):
                self.file.append(_file)
                with _file.open(mode) as fd:
                    fd.seek(0, SEEK_END)
                    self.length[_file.name] = fd.tell()
        self.read_file = []
        self.read_pointer = 0
        self.end_pointer = sum(self.length.values())
        self.cur_fd = None
        self.rewind = rewind

    def __len__(self):
        return self.end_pointer

    def reopen(self):
        self.file = self.read_file + self.file
        self.read_file.clear()
        self.read_pointer = 0
        self.cur_fd = None

    def split(self, depth):
        pass

    def read(self, count=None):
        """
        Read `count` bytes

        Args:
            count: number of bytes to be read, if None, read all bytes of **1** file

        Return:
            bytes read
        """
        if count == 0:
            return b''
        if not self.cur_fd and self.file:
            self.cur_fd = self.file[0].open('rb')
            self.read_file.append(self.file[0])
            self.file.pop(0)
        elif not self.cur_fd:
            raise FileNotFoundError('No frames in File')
        read_bytes = self.cur_fd.read(count)
        if read_bytes:
            self.read_pointer += len(read_bytes)
            if count and count > len(read_bytes):
                return read_bytes + self.read(count - len(read_bytes))
            else:
                return read_bytes
        else:
            if self.file:
                self.cur_fd.close()
                self.cur_fd = self.file[0].open('rb')
                self.read_file.append(self.file[0])
                self.file.pop(0)
                return self.read(count)
            elif self.rewind and self.read_file:
                self.file = self.read_file.copy()
                self.read_file.clear()
                self.cur_fd = None
                return self.read(count)
            else:
                raise EOFError('End of File!')

    def read_frame(self, frames=1, *args):
        pass

    def seek(self, offset, where):
        """
        Seek the position by `offset` relative to `where`

        Args:
             offset: move the read pointer by `offset` bytes
             where: could be io.SEEK_END, io.SEEK_CUR, io.SEEK_SET
        """
        pass

    def tell(self):
        """
        Tell the current position of the read pointer
        """
        return self.read_pointer

    def size(self, name):
        """
        Get the length of the file named `name`

        Return:
            length in bytes
        """
        path = Path(name)
        name = path.stem if path.exists() else name
        return self.length.get(name)

_ALLOWED_RAW_FORMAT = [
    'YV12',
    'YV21',
    'NV12',
    'NV21',
    'RGB4',
    'BGR4'
]

class RawFile(File):

    def __init__(self, path, mode, size, rewind=False):
        """
        Initiate Raw object. The file is lazy loaded, which means
        the file is opened but not loaded into memory.

        Arguments:
             path: file path or handle
             mode: since raw file has no headers, type must be explicitly given
             size: a tuple of (width, height), must be explicitly given
             rewind: rewind the file when reaches EOF

        Raise:
            TypeError
        """

        if not mode.upper() in _ALLOWED_RAW_FORMAT:
            raise TypeError('unknown mode: ' + mode)
        self.mode = mode.upper()
        self.size = to_list(size)
        self.pitch, self.channel_pitch = self._get_frame_pitch()
        super(RawFile, self).__init__(path, rewind)

    def _get_frame_pitch(self):
        """Get bytes length of one frame.
        For the detail of mode fourcc, please see https://www.fourcc.org/

        RGB, BGR, and UV channel of NV12, NV21 is packed, while YV12 and YV21 is planar, hence we have:
          - **channel0** of YV12, YV21, NV12, NV21 if Y
          - **channel1** of YV12 is U, of YV21 is V, of NV12 is UV, of NV21 is VU
          - **channel2** of YV12 is V, of YV21 is U
        """
        mode = self.mode
        width, height = self.size
        if mode in ('YV12', 'YV21'):
            return height * width * 3 // 2, [height * width, height * width // 4, height * width // 4]
        if mode in ('NV12', 'NV21'):
            return height * width * 3 // 2, [height * width, height * width // 2]
        if mode in ('RGB', 'BGR'):
            return height * width * 3, [height * width * 3]

    def _get_frame_channel_shape(self):
        """Get each channel's shape according to mode and frame length.
        For the detail of mode fourcc, please see https://www.fourcc.org/
        """
        mode = self.mode
        width, height = self.size
        if mode in ('YV12', 'YV21'):
            return np.array([1, height, width]), np.array([1, height // 2, width // 2]), np.array(
                [1, height // 2, width // 2])
        if mode in ('NV12', 'NV21'):
            return np.array([1, height, width]), np.array([2, height // 2, width // 2])
        if mode in ('RGB', 'BGR'):
            return np.array([height, width, 3])

    def read_frame(self, frames=1, *args):
        """
        read number `frames` of the file.

        Arguments:
            frames: number of frames to be loaded
            id: specify frame format to store (default gray-scale)

        Raise:

        """
        if self.mode in ('YV12', 'YV21', 'NV12', 'NV21',):
            # discard uv plain for acceleration
            _image_mode = 'L'
        else:
            _image_mode = 'RGB'
        return [Image.frombytes(_image_mode, self.size, self.read(self.pitch)) for _ in range(frames)]

    @property
    def shape(self):
        return self.size

    @property
    def frames(self):
        return (self.end_pointer - self.read_pointer) // self.pitch

class ImageFile(File):

    def __init__(self, path, rewind):
        """Open image1 file or a sequence of image1 frames

        Args:
            path: file path or handle
            rewind: rewind the file when reaches EOF
        """
        super(ImageFile, self).__init__(path, rewind)

    def read_frame(self, frames=1, *args):
        """read number `frames` of the file.

        Args:
            frames: number of frames to be loaded
        """
        image_bytes = [BytesIO(self.read()) for _ in range(frames)]
        return [Image.open(fp) for fp in image_bytes]

    @property
    def shape(self):
        with Image.open(self.file[0]) as img:
            return img.width, img.height

    @property
    def frames(self):
        return len(self.file)


# import the libraries
import pandas as pd
import dash
import dash_html_components as html
#from dash import html
import dash_core_components as dcc
#from dash import dcc
from dash.dependencies import Input, Output
import plotly.express as px

from prep_data import dashboard_data,genre

# Create the Dash app
app = dash.Dash()

# Set up the app layout
app.layout = html.Div(children=[
    html.H1(children='Imdb vs Rotten tomatoes Ratings Dashboard'),
    html.H2(children='Year Released'),
    dcc.RangeSlider(
            id='year-released-range-slider',
            min=dashboard_data.year.min(),
            max=dashboard_data.year.max(),
            marks={str(y): str(y) for y in range(int(dashboard_data.year.min()), int(dashboard_data.year.max()), 5)},
            value=[dashboard_data.year.min(), dashboard_data.year.max()]
        ),
    html.Br(),
    html.H2(children='Box Office Earnings (in millions)'),
    dcc.RangeSlider(
            id='box-office-range-slider',
            min=dashboard_data.worldwide_gross_income.min(),
            max=dashboard_data.worldwide_gross_income.max(),
            marks={str(y): str(y) for y in range(int(dashboard_data.worldwide_gross_income.min()), \
                                                 int(dashboard_data.worldwide_gross_income.max()), 200)},
            value=[dashboard_data.worldwide_gross_income.min(), dashboard_data.worldwide_gross_income.max()]
        ),
    html.Br(),
    html.H2(children='Genre'),
    dcc.Dropdown(
        id = 'genre-dropdown',
        options=[{'label':i,'value':i} for i in genre],
        value='All Genre'
    ),
    html.Br(),
    dcc.Graph(id='rating-graph')
])

# Set up the callback function
@app.callback(
    Output(component_id='rating-graph', component_property='figure'),
    [
     Input(component_id='year-released-range-slider', component_property='value'),
     Input(component_id='box-office-range-slider',component_property='value'),
     Input(component_id='genre-dropdown',component_property='value')
    ]
)
def update_graph(selected_year,gross_income,genre_name):
    year_released_start, year_released_end = selected_year
    gross_income_start,gross_income_end = gross_income
    filtered_df1 = dashboard_data.loc[(dashboard_data['year'] >= year_released_start)&(dashboard_data['year'] <= year_released_end)]
    filtered_df2 = filtered_df1.loc[(filtered_df1['worldwide_gross_income']>=gross_income_start)&(filtered_df1['worldwide_gross_income']<=gross_income_end)]
    if genre_name == 'All Genre':
        genre_name_select = ''
    else:
        genre_name_select = genre_name
    filtered_final = filtered_df2.loc[filtered_df2['genre'].str.contains(genre_name_select)]
    scatter_fig = px.scatter(filtered_final,
                       x='imdb_scaled', y='tomatometer_rating',hover_name='original_title',
                       hover_data=['genre','worldwide_gross_income','year'],
                       range_x = [0,100],range_y=[-10,110],
                       title=f'Rating comparison - years selected {selected_year} - box office range {gross_income} - genre {genre_name}')
    return scatter_fig

# Run local server
# Run local server
if __name__ == '__main__':
    app.run_server(debug=True)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/1/19 22:23
# @Author  : Paulson
# @File    : 字符转义.py
# @Software: PyCharm
# @define  : function

'''
如何将字母转换为ASCII码？
Python中提供函数ord()将字母转换成ASCII码，
提供函数chr()将相对应的ASCII码转化为字母，
'''
text = """g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj"""
def ma_solution(text):
    o =''
    for each in text:
        if ord(each) >= ord('a') and ord(each) <= ord('z'):
            o += chr((ord(each)+2 - ord('a'))%26 + ord('a'))
        else:
            o += each
    print(o)

'''
maketrans() 方法用于创建字符映射的转换表，
对于接受两个参数的最简单的调用方式，
第一个参数是字符串，表示需要转换的字符，
第二个参数也是字符串表示转换的目标。
两个字符串的长度必须相同，为一一对应的关系。
'''
import string
def std_solution(text):
    table = str.maketrans(
        string.ascii_lowercase,
        string.ascii_lowercase[2:]+string.ascii_lowercase[:2]
    )
    print(text.translate(table))

if __name__ == '__main__':
    std_solution(text)