"""
Scripts makes various plots for the report using log data saved to file.
"""
import matplotlib.pyplot as plt
from sklearn.externals import joblib
import numpy as np
import os
from utils.ImageFolderWithPaths import ImageFolderWithPaths
from torchvision import transforms
import models
import torch
from pathlib import Path
import torch.nn.functional as F

def smooth_data(data, window_width):
    cumsum_vec = np.cumsum(np.insert(data, 0, 0))
    ma_vec = (cumsum_vec[window_width:] - cumsum_vec[:-window_width]) / window_width
    return ma_vec

def plot_learning_curves(file_path):
    print('Plot learning curves -')
    print('Loading logs saved at: ', file_path)
    (train_logs, valid_logs) = joblib.load(file_path)

    train_logs = np.array(train_logs)
    valid_logs = np.array(valid_logs)
    print('train logs length ', len(train_logs))
    print('valid logs length ', len(valid_logs))

    plt.figure()

    # smooth accuracy
    window_width = 50
    train_steps = train_logs[:, 0]
    valid_steps = valid_logs[:, 0]
    train_accs_smooth = smooth_data(train_logs[:, 1], window_width)
    valid_accs_smooth = smooth_data(valid_logs[:,1], window_width)
    print('length of smooth train acc ', len(train_accs_smooth))
    print('length of smooth valid acc ', len(valid_accs_smooth))

    # plot accuracy
    plt.subplot(1,2,1)
    plt.plot(train_steps[:len(train_accs_smooth)], train_accs_smooth, label='training')
    plt.plot(valid_steps[:len(valid_accs_smooth)], valid_accs_smooth, label='validation')
    # plt.plot(train_logs[:, 0], train_logs[:, 1], label='training')
    # plt.plot(valid_logs[:,0], valid_logs[:,1], label='validation')
    plt.ylabel('accuracy(%)', fontsize=13)
    plt.xlabel('steps', fontsize=13)
    plt.title('(a)', fontsize=13)
    plt.grid()
    plt.legend(fontsize=13)

    # plot loss
    train_loss_smooth = smooth_data(train_logs[:, 2], window_width)
    valid_loss_smooth = smooth_data(valid_logs[:, 2], window_width)
    plt.subplot(1, 2, 2)
    plt.plot(train_steps[:len(train_loss_smooth)], train_loss_smooth, label='training')
    plt.plot(valid_steps[:len(valid_loss_smooth)], valid_loss_smooth, label='validation')
    plt.ylabel('loss', fontsize=13)
    plt.xlabel('steps', fontsize=13)
    plt.title('(b)', fontsize=13)
    plt.grid()
    plt.legend(fontsize=13)

    plt.show()

def print_misclassified_uncertain_examples(data_dir, model_name, model_path ):
    """
    This function runs tests a model on the validation data and outputs a list of images that:
    1. were misclassified
    2. had predicted probabilities around 50% for both classes.
    """

    # load validation data
    valdir = os.path.join(data_dir, 'valset')
    normalize = transforms.Normalize(mean=[0.490, 0.455, 0.416],
                                     std=[0.252, 0.245, 0.247])
    val_loader = torch.utils.data.DataLoader(
        ImageFolderWithPaths(valdir, transforms.Compose([
            transforms.ToTensor(),
            normalize,
        ])),
        batch_size=1000, shuffle=False)

    # load saved model
    device = torch.device("cuda:0")
    print('Loading saved model {} at {}'.format(model_name, model_path))
    model_class = models.find_model(model_name)
    model = model_class().to(device)
    model.load(model_path)

    # test model.
    model.eval()
    test_loss = 0
    test_correct = 0
    predictions = []
    targets = []
    img_paths = []  # get names of each image without full path or extension. (we need names to order result)
    outputs = []

    with torch.no_grad():
        for batch_idx, (data, target, paths) in enumerate(val_loader):
            data, target = data.to(device), target.to(device)
            output = model(data)
            outputs.append(output)
            pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
            predictions.append(pred)
            img_paths += [Path(path).name for path in paths]
            targets.append(target)
            test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
            test_correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(val_loader.dataset)
    test_acc = 100. * test_correct / len(val_loader.dataset)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, test_correct, len(val_loader.dataset), test_acc))

    predictions = torch.cat(predictions, 0).cpu().numpy().flatten()
    targets = torch.cat(targets, 0).cpu().numpy().flatten()
    img_paths = np.array(img_paths)
    misclassified_idx = targets != predictions
    print('Paths of {} misclassified examples:\n{}'.format(sum(misclassified_idx), img_paths[misclassified_idx]))

    outputs = torch.cat(outputs, 0).cpu().numpy()   # concatenate outputs from all batches
    exp_outputs = np.exp(outputs)                       # return all log estimates to probabilities
    exp_outputs = np.round(exp_outputs, 1)
    uncertain_idx = exp_outputs[:,0] == 0.5
    print('Paths of {} uncertain examples:\n{}'.format(sum(uncertain_idx), img_paths[uncertain_idx]))

def main():
    data_dir = r'C:\Users\Charles\Dropbox (NRP)\black-faces-db\ift6135data'
    output_dir = r'C:\Users\Charles\Dropbox (NRP)\black-faces-db\ift6135output'

    plot_learning_curves(output_dir + '\logs.pkl')
    print_misclassified_uncertain_examples(data_dir, 'BaseConvNet2', output_dir + '\saved_model.pt')

if __name__=='__main__':
    main()


#
# Use softmax regression to classify mnist dataset
# date: 2018-5-15
# a   : zhonghy
#
#

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

#load data
mnist = input_data.read_data_sets('F:\data\MNIST_data', one_hot=True)

#define regression model
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b #predict value

#define loss function and optimizer
y_ = tf.placeholder(tf.float32, [None, 10]) #input placeholder of real value
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = y, labels = y_))

#util SGD optimizer
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

#use interactive session
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

#Train, loop 1000 and batch size is 100
for _ in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x:batch_xs, y_:batch_ys})

#estimate model
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) #calculate predict and real value
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))#transform bool to float

#calculate accuracy in test dataset
print(sess.run(accuracy, feed_dict={x: mnist.test.images,
                                    y_: mnist.test.labels}))


import sqlite3
from typing import Callable, List, Union

from common import _L

MigrationFunc = Callable[[sqlite3.Connection, bool], bool]
migrationFunctions: dict[int, MigrationFunc] = {}

def register(version: int):
    from functools import wraps
    def wrap(func: MigrationFunc):
        @wraps(func)
        def wrapper(conn: sqlite3.Connection, silent: bool):
            try:
                if func(conn, silent):
                    conn.cursor().execute(f"PRAGMA user_version = {version}")
                    conn.commit()
                    return True
                return False
            except sqlite3.OperationalError:
                _L.error(f"There was an error while migrating database to version {version}."
                        "Please contact the developer @ github.com/fabbi")
                return False
        migrationFunctions[version] = wrapper
        return wrapper
    return wrap

@register(1)
def update_1(conn: sqlite3.Connection, silent=False):
    c = conn.cursor()
    if not silent:
        _L.warn("Some games and platforms have been renamed! "
                "Check `--help` or the README.md for further info.")

    steps: List[Union[str, tuple]] = [
        """
        ALTER TABLE keys
        RENAME COLUMN description TO reward;
        """
        ,
        """
        ALTER TABLE keys
        RENAME COLUMN key TO code;
        """
        , # renamed "ps" to "psn"
        """
        UPDATE keys
        SET platform="psn"
        WHERE platform="ps";
        """
        , # renamed "xbox" to "xboxlive"
        """
        UPDATE keys
        SET platform="xboxlive"
        WHERE platform="xbox";
        """
        , # renamed "bl" to "bl1"
        """
        UPDATE keys
        SET game="bl1"
        WHERE game="bl";
        """
        , # "pc" is now "epic" and "steam"
        """
        CREATE VIEW tmp AS
        SELECT * FROM keys
        WHERE platform="pc";
        -- AND redeemed=0;

        INSERT INTO keys(reward, code, platform, game, redeemed)
        SELECT reward, code, "epic", game, redeemed
        FROM tmp;

        UPDATE keys
        SET platform="steam"
        WHERE id in (select id from tmp);

        DROP VIEW tmp;
        """
        ,
        """
        CREATE TABLE IF NOT EXISTS seen_platforms
        (key TEXT primary key, name TEXT)
        """
        ,
        """
        CREATE TABLE IF NOT EXISTS seen_games
        (key TEXT primary key, name TEXT)
        """
    ]

    from query import known_games, known_platforms
    for game in known_games.items():
        steps.append(("""
        INSERT INTO seen_games(key, name)
        VALUES(?, ?)
        """, game))
    for platform in known_platforms.items():
        steps.append(("""
        INSERT INTO seen_platforms(key, name)
        VALUES(?, ?)
        """, platform))

    for i, step in enumerate(steps):
        _L.debug(f"executing step {i} of update_1")
        try:
            if isinstance(step, tuple):
                c.execute(*step)
            else:
                c.executescript(step)
        except sqlite3.OperationalError as e:
            _L.error(f"'{e}' in\n{step}")
            return False
    return True


# -*- coding: utf-8 -*-
'''
Задание 5.2

Запросить у пользователя ввод IP-сети в формате: 10.1.1.0/24

Затем вывести информацию о сети и маске в таком формате:

Network:
10        1         1         0
00001010  00000001  00000001  00000000

Mask:
/24
255       255       255       0
11111111  11111111  11111111  00000000

Проверить работу скрипта на разных комбинациях сеть/маска.

Ограничение: Все задания надо выполнять используя только пройденные темы.
'''

ip = input('Введите IP адрес: ')
mask = input('Введите маску: ')
ip_add = '{}/{}'.format(ip, mask)
ip = ip.split('.')
#ip = ', '.join(ip)
mask_spl = '1'*int(mask) + '0'*(32-int(mask))

ip1 = int(ip[0])
ip2 = int(ip[1])
ip3 = int(ip[2])
ip4 = int(ip[3])

mask1 = int(mask_spl[:8], 2)
mask2 = int(mask_spl[8:16], 2)
mask3 = int(mask_spl[16:24], 2)
mask4 = int(mask_spl[24:], 2)

ip_template = '''
Network:
{0:<8} {1:<8} {2:<8} {3:<8}
{0:08b} {1:08b} {2:08b} {3:08b}

Mask:
'/'{8:}
{4:<8} {5:<8} {6:<8} {7:<8}
{4:<08b} {5:<08b} {6:<08b} {7:<08b}
'''

print(ip_template.format(ip1, ip2, ip3, ip4, mask1, mask2, mask3, mask4, mask))


from _DATA_TOOLS._PARSING_TOOLS import *
from _DATA_TOOLS._DATES_TIMES import *

rootpath =  r'C:\\Users\\gjone\\__SADIE_WRK\\serf_041821_042621'
print("rootpath: {}".format(rootpath))
data_range =["01.2021", "01.02.2021", "02.2021"]
data_range =["01.2021", "02.2021"]
data_range =["02.2021", "01.2021"]
dirwalker = DIR_PARSER(root_dir=rootpath, data_range=data_range)
dirwalker.root_walker(rootpath=rootpath, walkerFunc=None, )

serftools = SERFTOOLS(root=rootpath)

startInfo, endInfo = serftools.directoryparsingtools.processDateRange(data_range)

print("Start Info: {}".format(startInfo))
print("End Info: {}".format(endInfo))

# now get the stuff from the root that meets the date reqs


def lengthOfLongestSubstring(s):
    d={}
    l = 0
    res=0
    for i in range(len(s)):
        if s[i] in d:
            l = max(d[s[i]]+1,l)
        d[s[i]]=i
        res = max(res,i-l+1)
    return res
print(lengthOfLongestSubstring("pwwkew"))


import logging
import os
import shutil
import sys
import threading
import time

from daemoniker import Daemonizer

from gfl.api.listener import HttpListener
from gfl.conf import GflConf
from gfl.core.lfs import Lfs
from gfl.core.manager.node import GflNode
from gfl.core.manager.holder import ManagerHolder
from gfl.core.manager.manager import NodeManager
from gfl.shell import Shell
from gfl.utils import PathUtils

class Application(object):

    logger = None

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

    @classmethod
    def init(cls, force):
        if os.path.exists(GflConf.home_dir):
            if force:
                logging.shutdown()
                shutil.rmtree(GflConf.home_dir)
            else:
                raise ValueError("homedir not empty.")
        # create home dir
        os.makedirs(GflConf.home_dir)

        # generate config file
        GflConf.generate_config(PathUtils.join(GflConf.home_dir, "config.yaml"))
        # generate node address and key
        GflNode.init_node()
        # create data directories
        Lfs.init()

    @classmethod
    def run(cls, role, console, **kwargs):
        sys.stderr = open(os.devnull, "w")
        cls.logger = logging.getLogger("gfl")
        with Daemonizer() as (is_setup, daemonizer):
            main_pid = None
            if is_setup:
                main_pid = os.getpid()
            pid_file = PathUtils.join(GflConf.home_dir, "proc.lock")
            stdout_file = PathUtils.join(GflConf.logs_dir, "console_out")
            stderr_file = PathUtils.join(GflConf.logs_dir, "console_err")
            is_parent = daemonizer(pid_file, stdout_goto=stdout_file, stderr_goto=stderr_file)
            if is_parent:
                if console and main_pid == os.getpid():
                    Shell.startup()

        GflNode.load_node()

        if GflConf.get_property("net.mode") == "standalone":
            client_number = GflConf.get_property("net.standalone.client_number")
            for _ in range(len(GflNode.standalone_nodes), client_number):
                GflNode.add_standalone_node()

            ManagerHolder.default_manager = NodeManager(node=GflNode.default_node, role="server")

            for i in range(client_number):
                client_manager = NodeManager(node=GflNode.standalone_nodes[i], role="client")
                ManagerHolder.standalone_managers.append(client_manager)
        else:
            ManagerHolder.default_manager = NodeManager(node=GflNode.default_node, role=role)

        # cls.__startup_node_managers()
        HttpListener.start()

        while HttpListener.is_alive():
            time.sleep(2)

    @classmethod
    def __startup_node_managers(cls):
        # 遍历所有的NodeManager
        threading.Thread(target=ManagerHolder.default_manager.run).start()
        for nm in ManagerHolder.standalone_managers:
            t = threading.Thread(target=nm.run)
            t.start()

    @classmethod
    def __stop_node_managers(cls):
        if ManagerHolder.default_manager is not None:
            ManagerHolder.default_manager.stop()
        for nm in ManagerHolder.standalone_managers:
            nm.stop()


from datetime import timedelta

import requests
from django.conf import settings
from django.core.exceptions import ValidationError
from django.http import JsonResponse

class VantageRequestError(Exception):
    pass

session = requests.Session()

def vantage_request(params: dict):
    base_url = 'https://www.alphavantage.co/query'
    r = session.request('GET', base_url, params={'apikey': settings.VANTAGE_API_KEY, **params})
    if r.status_code != 200:
        raise VantageRequestError('Problem accessing URL', r.content.decode())
    data = r.json()
    if data.get('Note'):
        raise VantageRequestError("We've used up all our API calls. Try again in a few minutes.")
    errors = data.get('Error Message')
    if errors:
        raise VantageRequestError('Error accessing Vantage (%s): %r' % (r.url, errors))
    return data

REGION_ORDER = {'United Kingdom': 1, 'United States': 2}

def search_company_symbols(request):
    params = {'function': 'SYMBOL_SEARCH', 'keywords': request.GET.get('q')}
    r = vantage_request(params)
    data = [
        {'symbol': d['1. symbol'], 'name': d['2. name'], 'region': d['4. region'], 'currency': d['8. currency']}
        for d in r['bestMatches']
    ]
    data = sorted(data, key=lambda x: REGION_ORDER.get(x['region'], 10))
    return JsonResponse(data, safe=False)

def get_stock_data(date, symbol):
    params = {'function': 'TIME_SERIES_DAILY', 'symbol': symbol, 'outputsize': 'compact'}
    data = vantage_request(params)
    stocks_data = data['Time Series (Daily)']
    days = 0
    stock_data = None
    while not stock_data:
        # The market is closed on bank hols and public holidays
        date = (date - timedelta(days=days)).strftime('%Y-%m-%d')
        stock_data = stocks_data.get(date)
        if stock_data:
            return stock_data
        if days == 7:
            dates = list(stocks_data.keys())
            raise ValidationError(
                f"As we're only testing, you can only choose from the first 100 records."
                f"We have figures between {dates[-1]} - {dates[0]}"
            )
        days += 1
    return stock_data


import pandas as pd
import mbuild as mb
import foyer
import unyt as u
import numpy as np
import math
import time
import parmed as pmd
import mosdef_cassandra as mc

T = 298.15 * u.K

mu_ideal_100box = -48.860310174012 * u.Unit('kJ/mol')

beta = 1/(u.kb*T)

N_goal = 40

cbrt_N_goal = N_goal ** (1.0/3.0)

mu_gas_5 = np.array([-49.04, -39.4, -36.4, -35.2, -35.0]) * u.Unit('kJ/mol')

P_gas = np.linspace(0.5, 15.0, 30, endpoint=True) * u.bar

P_n60 = 1.9121951616833333 * u.bar

mu_n60 = mu_gas_5[1]

mu_gas = mu_n60 + u.kb*T*np.log(P_gas/P_n60)

L = np.exp((-beta/3*(mu_gas - mu_ideal_100box)).to(''))*(100 * u.angstrom)*cbrt_N_goal

r32_struct = pmd.load_file('topology/r32.top', xyz='topology/r32.gro')
species_list = [r32_struct]

ensemble = 'gcmc'
moveset = mc.MoveSet(ensemble, species_list)
moveset.max_translate = [[14.0*u.angstrom]]
moveset.max_rotate = [[180.0*u.degree]]

eq_length = 1000000
prod_length = eq_length*10

property_list = ["nmols", "density", "pressure", "energy_total"]

def read_prp(filename):
    with open(filename) as fprp:
        fprp.readline()
        colnames = fprp.readline()[1:].strip().split()
        colunits = fprp.readline()[1:].strip().split()
        df = pd.read_csv(fprp, delim_whitespace=True, index_col=False, names=colnames)
    return df

statdf = pd.DataFrame(
        columns=['mu', 'Nmols', 'Nmols_SEM', 'Density', 'Density_SEM', 'Pressure', 'Pressure_SEM', 'Energy_Total', 'Energy_Total_SEM', 'Sim_Time'],
        index=pd.RangeIndex(len(mu_gas)))

for i, mu in enumerate(mu_gas):
    eq_name = "eq"+str(i)
    prod_name = "prod"+str(i)
    boxlength = L[i]
    cutoff = boxlength/2 - 0.1*u.angstrom
    nm_L = boxlength.to_value('nm')
    box = mb.Box([nm_L, nm_L, nm_L])
    box_list = [box]
    system = mc.System(box_list, species_list, mols_to_add=[[N_goal]])
    starttime = time.time()
    mc.run(
            system=system,
            moveset=moveset,
            run_type="equilibration",
            run_length=eq_length,
            temperature=T,
            chemical_potentials=[mu],
            prop_freq=1000,
            coord_freq=10000,
            properties=property_list,
            vdw_cutoff=cutoff,
            charge_cutoff=cutoff,
            run_name=eq_name
    )
    mc.restart(
            restart_from=eq_name,
            run_name=prod_name,
            run_type="production",
            total_run_length=prod_length
    )
    endtime = time.time()
    prpdf = read_prp(prod_name+".out.prp")
    prp_mean = prpdf.mean(axis=0)
    prp_sem = prpdf.sem(axis=0)
    statdf['mu'][i] = mu.to_value('kJ/mol')
    statdf['Pressure'][i] = prp_mean['Pressure']
    statdf['Pressure_SEM'][i] = prp_sem['Pressure']
    statdf['Nmols'][i] = prp_mean['Nmols']
    statdf['Nmols_SEM'][i] = prp_sem['Nmols']
    statdf['Density'][i] = prp_mean['Density']
    statdf['Density_SEM'][i] = prp_sem['Density']
    statdf['Energy_Total'][i] = prp_mean['Energy_Total']
    statdf['Energy_Total_SEM'][i] = prp_sem['Energy_Total']
    statdf['Sim_Time'][i] = endtime-starttime

statdf.to_csv('property_data.csv', index=False)


import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import matplotlib
from functools import partial
from datetime import datetime

from firmware import Firmware
from GUI.tooltip import create_tool_tip

class App:
    def __init__(self, firmware: Firmware):
        matplotlib.use('TkAgg')
        self.firmware = firmware
        self.root = tk.Tk()
        self.root.geometry("800x600")
        self.root.title('Состояние контроллеров')
        self.show_interface()
        self.root.mainloop()

    def show_interface(self):
        status_frame = tk.Frame(self.root)
        self.show_status_page(status_frame)
        status_frame.pack(expand=1)

    @staticmethod
    def hide_page(page):
        page.pack_forget()

    def show_status_page(self, canvas):
        font = "Arial 12"
        for i, cont in enumerate(self.firmware.controllers[:20]):
            name_lab = tk.Label(canvas, text=f'{cont.name}:', font=font, padx=5)
            btn = tk.Button(canvas, text='Перейти к контроллеру', padx=5,
                            command=partial(self.go_to_cont, cont.name, canvas))
            if cont.is_active:
                status_lab = tk.Label(canvas, text='Активен', fg='green', font=font, padx=5)
                time_from_error = datetime.now() - cont.last_error_time
                time_overall = datetime.now() - cont.start_time
                errors_amount = len(self.firmware.get_controller_errors(cont.name))
                create_tool_tip(status_lab, text=f'Время работы после последнего сбоя: {str(time_from_error)}\n'
                                                 f'Время работы: {str(time_overall)}\n'
                                                 f'Число сбоев за время работы: {str(errors_amount)}')
            else:
                status_lab = tk.Label(canvas, text='Отключен', fg='red', font=font, padx=5)
                btn.configure(state=tk.DISABLED)

            name_lab.grid(row=i, column=0)
            status_lab.grid(row=i, column=1)
            btn.grid(row=i, column=2)

    def go_to_cont(self, cont_name: str, canvas):
        self.hide_page(canvas)
        self.show_controller_page(cont_name)

    def show_controller_page(self, cont_name):
        cont_frame = tk.Frame(self.root)
        self.draw_graph(cont_frame, cont_name)
        cont_frame.pack(expand=1)

    def draw_graph(self, cont_frame, cont_name):
        fig, ax = plt.subplots()
        canvas = FigureCanvasTkAgg(fig, master=cont_frame)
        plot_widget = canvas.get_tk_widget()

        date = []
        activ = []

        log = self.firmware.get_controller_log(cont_name)

        for elem in log['data']:
            if isinstance(elem, dict):
                date.append(elem['timestamp'])
                activ.append(0)
            else:
                date.append(elem)
                activ.append(1)
        ax.set_title('Статус работы')
        ax.step(date, activ, linewidth=1)
        ax.set_xticklabels([])
        ax.set_yticklabels([])

        data = self.firmware.get_controller_data(cont_name)
        btn_frame = tk.Frame(cont_frame)
        btn = tk.Button(btn_frame, text='<-', padx=10,
                        command=partial(self.back_page, cont_frame))
        btn.pack(side=tk.LEFT)
        sensors = list(data[0].keys())[:-1]
        for i, sensor in enumerate(sensors, 1):
            btn = tk.Button(btn_frame, text=sensor, padx=5,
                            command=partial(self.update_graph, sensor, cont_name, fig, ax))
            btn.pack(side=tk.LEFT)

        btn_frame.grid(row=0, column=0)
        plot_widget.grid(row=1, column=0)

    def update_graph(self, sensor, cont, fig, ax):
        plt.cla()
        data = self.firmware.get_controller_data(cont)

        date = []
        value = []

        for elem in data:
            date.append(elem['timestamp'])
            value.append(elem[sensor])
        ax.set_title(sensor)
        ax.plot(date, value, linewidth=1)
        ax.set_xticklabels([])
        fig.canvas.draw()

    def back_page(self, cur_page):
        self.hide_page(cur_page)
        self.show_interface()


import unittest
import csv
from penny.inspectors import (rows_types_probabilities, row_simple_types,
    categories_from_list, column_types_probabilities)
import os

class InspectorsTest(unittest.TestCase):
    def test_row_simple_types(self):
        cur_dir = os.path.dirname(os.path.realpath(__file__))
        fileobj = open(cur_dir + '/data/banklist.csv')

        reader = csv.reader(fileobj)
        row = reader.next()
        types = row_simple_types(row)

        # First row is headers, should all be strings
        assert types[1:] == types[:-1]

        row = reader.next()
        types = row_simple_types(row)
        assert types == ['str', 'str', 'str', 'int', 'str', 'date', 'date']

    def test_column_types_probabilities(self):
        cur_dir = os.path.dirname(os.path.realpath(__file__))
        fileobj = open(cur_dir + '/data/banklist.csv')

        rows = list(csv.reader(fileobj))
        column = [x[2] for x in rows]

        p = column_types_probabilities(column, ['region'])

        assert 'region' in p
        assert p['region'] == 1

    def test_rows_types_probabilties(self):
        cur_dir = os.path.dirname(os.path.realpath(__file__))

        fileobj = open(cur_dir + '/data/banklist.csv')

        rows = list(csv.reader(fileobj))
        probs = rows_types_probabilities(rows)

        assert probs[2]['category'] >= 0.9
        assert probs[3]['int'] >= 0.9
        assert probs[5]['date'] >= 0.9
        assert probs[6]['date'] >= 0.9

        fileobj = open(cur_dir + '/data/test_csv.csv')

        rows = list(csv.reader(fileobj))
        probs = rows_types_probabilities(rows)

        assert probs[2]['int'] > .9
        assert probs[3]['category'] > .9

        fileobj = open(cur_dir + '/data/EGViolatorsFinal.csv','rU')

        rows = list(csv.reader(fileobj))
        probs = rows_types_probabilities(rows)

        assert probs[1]['date'] > .9
        assert probs[8]['region'] > .9

    def test_categories_from_list(self):
        cur_dir = os.path.dirname(os.path.realpath(__file__))
        fileobj = open(cur_dir + '/data/banklist.csv')

        rows = list(csv.reader(fileobj))
        cats = categories_from_list(map(lambda x: x[2], rows))

        for st in ['FL', 'CA', 'IL', 'GA']:
            assert st in cats

def main():
    unittest.main()

if __name__ == "__main__":
    main()


from django.shortcuts import render, redirect, HttpResponse
from django.views.generic import TemplateView
from .models import Vegetables, Category
from .forms import VegetableCreateForm

class AboutView(TemplateView):
    template_name = "about.html"

def homepage(request):
    products = Vegetables.objects.all()  # return list
    context = {"all_vegetables": products}
    return render(request, "product_list.html", context=context)

def vegetable_detail(request, id):
    try:
        vegetable = Vegetables.objects.get(id=id)
        context = {"vegetable": vegetable}
        return render(request, "vegetable_info.html", context)
    except Vegetables.DoesNotExist:
        return HttpResponse('Такой страницы не существует!', status=404)

def vegetable_add(request):
    context = {}

    if request.method == "GET":
        vegetable_form = VegetableCreateForm()
        context["vegetable_form"] = vegetable_form
        return render(request, 'vegetable_form.html', context)
    elif request.method == "POST":
        vegetable_form = VegetableCreateForm(request.POST)
        if vegetable_form.is_valid():
            new_vegetable = vegetable_form.save()
            return redirect(vegetable_detail, id=new_vegetable.id)
        else:
            return HttpResponse('
Форма не валидна!
', status=400)

def vegetable_update(request, id):
    context = {}
    vegetable_object = Vegetables.objects.get(id=id)

    if request.method == "POST":
        vegetable_form = VegetableCreateForm(request.POST, instance=vegetable_object)
        if vegetable_form.is_valid():
            vegetable_object = vegetable_form.save()
            return HttpResponse(f"Данные обновлены успешно!", status=200)

    vegetable_form = VegetableCreateForm(instance=vegetable_object)
    context["vegetable_form"] = vegetable_form
    return render(request, 'vegetable_form.html', context)

def vegetable_delete(request, id):
    if request.method == "POST":
        vegetable_object = Vegetables.objects.get(id=id)
        vegetable_object.delete()
        return HttpResponse("Информация успешно удалено!", status=200)

def categories_view(request):
    categories = Category.objects.all()
    c = {"categories": categories}
    return render(request, "categories.html", c)

def category_detail(request, id):
    try:
        category_object = Category.objects.get(id=id)
        vegetables_list = Vegetables.objects.filter(category=category_object)
        context = {"all_vegetables": vegetables_list}
        return render(request, 'product_list.html', context)
    except Vegetables.DoesNotExist:
        return HttpResponse('Такой страницы не существует!', status=404)


import os
import pickle
import numpy as np
import tensorflow as tf
"""=================================================================================================================="""
class TFRecordDB:
    """
    - This class is designed to handle only four cases:
        +) input data is in integer type (python datatype) => Use to handle label, description (using integer values)
        +) input data is in float type (python datatype) => Use to handle the label, description (using float values)
        +) input data is in string (python datatype) => Use to handle image name, path, description
        +) input data is in np.ndarray => Use to handle image data
    - According to type of data, we automically choose the Types between 'FixedLenFeature', or 'VarLenFeature'
    - For image, we input it as np.ndarray. Using tf.image.encode_jpeg to encode it (convert to a series of bytes) to write to tfrecord
    - For string (name, path) => We use the .encode() method (of string class) to convert it to bytes
      => Need to use .decode() method to decode the original string. (See the main function for example usage)
    - This class will write two files:
      +) a tfrecord file that store data
      +) a pkl file (field file) that is used to read the tfrecord file.
    - Use the zip() to prepare data to the TFRecordDB.write() function as this function only accept list (tuple) of records
    - Finally, the important things is the specifying the field dicts that contain the name of fields in the data.
      Example: fields = {'image_path':[],'image':[],'label':[]}
    - Note:
        tfio is official supports from google. I used this one to implement encode_bmp for lossless compresion.
    - if lossy = True, then we use the jpeg compression method to encode and decode image => The input and the reconstruected
                       image can be different because jpeg is a lossy image compression method
    - if lossy = False, then we use the png compression method to encode and decode image => The input and the reconstructed
                       images are same because png is a lossless image compressoin method
    Note: The png only accept image in unit8 datatype, but also integer datatype (uint16)
    Note: This script is only used for images (matrix in matrixs) as it uses encode() opts.
    """
    lossy  = True #If set to False, then use the lossless encoding method (png) to encode image.
    rdtype = tf.dtypes.uint8 #Please use tf.dtypes.uint16 if the input range of image is not uint8. But this case is seldomly use.
    Types  = ['FixedLenFeature','VarLenFeature']              #Fixed this one
    DTypes = ['tf.int64','tf.float64','tf.string','tf.image'] #Fixed this one
    def __init__(self):
        pass
    @staticmethod
    def init_field_path(i_tfrecord_path=None):
        save_path,save_file = os.path.split(i_tfrecord_path)
        assert len(save_file)>8
        save_file_name = save_file[0:len(save_file)-9]
        return os.path.join(save_path,save_file_name+'_field.pkl')
    @staticmethod
    def init_tfrecord_paths(i_basic_tfrecord_file_path=None):
        """Find all name_index.tfrecord file in a directory when name.tfrecord file is given"""
        assert os.path.exists(i_basic_tfrecord_file_path)
        tfrecord_path,tfrecord_file = os.path.split(i_basic_tfrecord_file_path)
        assert len(tfrecord_file)>8
        tfrecord_file_name = tfrecord_file[0:len(tfrecord_file)-9]
        tfrecord_list = [f for f in os.listdir(tfrecord_path) if f.endswith('.tfrecord')]
        tfrecord_list = [os.path.join(tfrecord_path,f) for f in tfrecord_list if f.find(tfrecord_file_name)==0]
        return tfrecord_list
    @staticmethod
    def convert_bytes_features(i_value):
        if isinstance(i_value, type(tf.constant(0))):
            i_value = i_value.numpy()  # BytesList won't unpack a string from an EagerTensor.
        if isinstance(i_value, bytes):
            return tf.train.Feature(bytes_list=tf.train.BytesList(value=[i_value]))
        elif isinstance(i_value, (list, tuple)):
            for item in i_value:
                assert isinstance(item, bytes)
            return tf.train.Feature(bytes_list=tf.train.BytesList(value=i_value))
        else:
            return None
    @staticmethod
    def convert_float_features(i_value):
        """Returns a float_list from a float / double."""
        assert isinstance(i_value,(float,list,tuple))
        if isinstance(i_value, float):
            return tf.train.Feature(float_list=tf.train.FloatList(value=[i_value]))
        elif isinstance(i_value, (list, tuple)):
            return tf.train.Feature(float_list=tf.train.FloatList(value=i_value))
        else:
            return None
    @staticmethod
    def convert_int64_feautures(i_value):
        """Returns an int64_list from a bool / enum / int / uint."""
        assert isinstance(i_value,(bool,int,list,tuple))
        if isinstance(i_value, (bool, int)):
            return tf.train.Feature(int64_list=tf.train.Int64List(value=[i_value]))
        elif isinstance(i_value, (list, tuple)):
            return tf.train.Feature(int64_list=tf.train.Int64List(value=i_value))
        else:
            return None
    @classmethod
    def convert_to_features(cls,i_value):
        """Algorithm: np.ndarray => bytes => using convert_bytes_features"""
        assert i_value is not None
        #print('Writing data with DType = ',type(i_value))
        if isinstance(i_value,float):#type(i_value)==float (python dtype)
            return TFRecordDB.convert_float_features(i_value),cls.Types.index('FixedLenFeature'),cls.DTypes.index('tf.float64')
        elif isinstance(i_value,(str,bytes)):#type(i_value)==bytes (python dtype)
            if isinstance(i_value,str):
                """Lets use string.encode() to convert string to bytes"""
                i_value = i_value.encode()
            else:
                pass
            return TFRecordDB.convert_bytes_features(i_value),cls.Types.index('VarLenFeature'),cls.DTypes.index('tf.string')
        elif isinstance(i_value,(bool,int)):#type(i_value)==int (python dtype)
            return TFRecordDB.convert_int64_feautures(i_value),cls.Types.index('FixedLenFeature'),cls.DTypes.index('tf.int64')
        elif isinstance(i_value,np.ndarray):#list,tuple or numpy array
            """This option is to process image. So, its shape must be 2 (gray), or 3 (RGB)"""
            assert isinstance(i_value,np.ndarray)
            assert len(i_value.shape) in (2,3)
            if len(i_value.shape)==2:
                i_value = np.expand_dims(i_value,-1)
            assert len(i_value.shape)==3
            if cls.lossy:
                """Using encode_jpeg for lossy compression"""
                i_value = tf.io.encode_jpeg(i_value, quality=100)  # Set to 100 for best quality (lossess compression)
            else:
                i_value = tf.io.encode_png(i_value,compression=-1) #Use 9 for smallest file size (slowest).0 for largest file size(fastest). Use -1 for default (similar to 9)
            return TFRecordDB.convert_bytes_features(i_value), cls.Types.index('VarLenFeature'), cls.DTypes.index('tf.image')
        else:
            """Numpy number such as numpy.uint8, numpy.int16 etc. """
            """Check this one again for better performance and exceptions"""
            return TFRecordDB.convert_to_features(i_value.item())
    @staticmethod
    def serialize(i_features=None,i_fields=None):
        """Serialize one record"""
        assert isinstance(i_features,(list,tuple))
        assert isinstance(i_fields,dict)
        field_keys = list(i_fields.keys())
        assert len(field_keys)==len(i_features)
        feature       = {}
        serial_types  = []
        serial_dtypes = []
        for index, item in enumerate(i_features):
            key   = '{}'.format(field_keys[index])
            value,types,dtypes = TFRecordDB.convert_to_features(item)
            feature.update({key:value})
            serial_types.append(types)
            serial_dtypes.append(dtypes)
        example = tf.train.Example(features=tf.train.Features(feature=feature))
        serial_data = example.SerializeToString()
        return serial_data,serial_types,serial_dtypes
    @staticmethod
    def write_single_file(i_n_records=None,i_fields=None,i_save_file=None):
        """i_save_file is the path to tfrecord file that we want to create, Example: C:\\...\\db.tfrecord"""
        assert isinstance(i_n_records,(list,tuple))
        assert isinstance(i_fields,dict)
        save_path,save_file = os.path.split(i_save_file)
        assert save_file.endswith('.tfrecord')
        if os.path.exists(save_path):
            pass
        else:
            os.makedirs(save_path)
        if os.path.exists(i_save_file):
            return False
        else:
            pass
        gtypes,gdtypes = [],[]
        with tf.io.TFRecordWriter(i_save_file) as writer:
            for record in i_n_records:
                example,types,dtypes = TFRecordDB.serialize(record,i_fields)
                writer.write(example)
                """Assertion of gtypes and gdtypes"""
                if len(gtypes)==0:
                    gtypes = types
                else:
                    for index in range(len(gtypes)):
                        assert gtypes[index]==types[index]
                if len(gdtypes)==0:
                    gdtypes = dtypes
                else:
                    for index in range(len(gdtypes)):
                        assert gdtypes[index]==dtypes[index]
        """Save i_fields,gtypes, and gdtypes to file that will be used for reading (parsig) tfrecord fields"""
        zip_types = list(zip(gtypes,gdtypes))
        for index, key in enumerate(i_fields.keys()):
            i_fields.update({key:zip_types[index]})
        save_field_path = TFRecordDB.init_field_path(i_save_file)
        if os.path.exists(save_field_path):
            print('Did not write field file (.pkl) for this case?')
        else:
            with open(save_field_path,'wb') as field_file:
                pickle.dump(i_fields,field_file)
        return i_fields
    @staticmethod
    def write(i_n_records=None,i_size = 1000, i_fields=None,i_save_file=None):
        """i_size is the number of records to be written in single tfrecord files"""
        assert isinstance(i_n_records,(list,tuple))
        num_records = len(i_n_records)
        save_paths = []
        if num_records<=i_size:
            TFRecordDB.write_single_file(i_n_records=i_n_records,i_fields=i_fields,i_save_file=i_save_file)
            save_paths.append(i_save_file)
        else:
            num_files = num_records//i_size
            if num_records%i_size==0:
                pass
            else:
                num_files +=1
            print('Num files: ',num_files)
            save_path,save_file = os.path.split(i_save_file)
            assert len(save_file)>8
            save_file_name = save_file[0:len(save_file)-9]
            for index in range(num_files):
                print('Writing {}(th) block!...'.format(index))
                if index == 0:
                    c_save_file_path = os.path.join(save_path,'{}.tfrecord'.format(save_file_name,index))
                else:
                    c_save_file_path = os.path.join(save_path,'{}_{}.tfrecord'.format(save_file_name,index))
                size_records = []
                for item in range(index*i_size,(index+1)*i_size):
                    if item>=len(i_n_records):
                        pass
                    else:
                        size_records.append(i_n_records[item])
                TFRecordDB.write_single_file(i_n_records=size_records,i_fields=i_fields,i_save_file=c_save_file_path)
                save_paths.append(c_save_file_path)
        return save_paths
    @staticmethod
    def init_file_path(i_main_tfrecord_path=None,i_segment_index=1):
        """This support function is to create file name of the n(th) tfrecord file"""
        """It is used when we need to create a tfrecord file which contain very big number of samples"""
        """See the VinBigData dataset for an example in the libs"""
        assert isinstance(i_main_tfrecord_path,str)
        assert isinstance(i_segment_index,int)
        assert i_segment_index>=0
        file_path,file_name = os.path.split(i_main_tfrecord_path)
        assert file_name.endswith('.tfrecord')
        file_name = file_name[0:len(file_name)-len('.tfrecord')]
        if i_segment_index>0:
            rtn_path = os.path.join(file_path,'{}_{}.tfrecord'.format(file_name,i_segment_index))
        else:
            rtn_path = i_main_tfrecord_path
        return rtn_path
    @classmethod
    def reads(cls,i_tfrecord_paths=None,i_original=False):
        assert isinstance(i_original, bool)
        def parse(i_record):#Return list of data of original data
            """Note: This function must be customed according to the datatype of each fields in data structure"""
            """Here is example of reading data struture with three fields of (image_path, image, label)"""
            """Here we use tf.io.parse_single_example() to Parses a single Example proto"""
            """Resulting: A dict mapping feature keys to Tensor and SparseTensor values."""
            return_vals = {} if i_original else []
            data        =  tf.io.parse_single_example(i_record,features=features)
            for record_key in fields.keys():
                record_indicator = fields[record_key]
                record_types     = TFRecordDB.Types[record_indicator[0]]
                record_dtypes    = TFRecordDB.DTypes[record_indicator[1]]
                if record_types == 'FixedLenFeature':
                    val = data[record_key]
                elif record_types  == 'VarLenFeature':
                    val = data[record_key].values[0]
                else:
                    raise Exception('Invalid')
                if record_dtypes == 'tf.image':
                    """Decode the data as image using tf.io.decode_image() ops"""
                    val = tf.io.decode_image(contents=val,dtype=cls.rdtype)
                else:
                    pass
                if i_original:
                    return_vals.update({record_key: val})
                else:
                    return_vals.append(val)
            return return_vals
        assert isinstance(i_tfrecord_paths,(list,tuple))
        fields = {}
        for index, tfrecord_path in enumerate(i_tfrecord_paths):
            field_path = TFRecordDB.init_field_path(tfrecord_path)
            print('Read field file at: ',field_path)
            assert os.path.exists(field_path)
            assert os.path.exists(tfrecord_path)
            with open(field_path,'rb') as pfile:
                c_field = pickle.load(pfile)
            if index == 0:
                fields = c_field
                assert isinstance(fields,dict)
                for key in fields.keys():
                    assert isinstance(fields[key],(list,tuple))
                    assert len(fields[key])==2
            else:
                assert isinstance(fields,dict)
                for key in fields.keys():
                    for ind,el in enumerate(fields[key]):
                        assert el == c_field[key][ind]
        assert isinstance(fields,dict)
        field_keys = list(fields.keys())
        features   = {}
        for key in field_keys:
            indicator = fields[key]
            assert isinstance(indicator,(list,tuple))
            assert len(indicator)==2
            types  = TFRecordDB.Types[indicator[0]]
            dtypes = TFRecordDB.DTypes[indicator[1]]
            if dtypes == 'tf.int64':
                dtypes = tf.int64
            elif dtypes == 'tf.float64':
                dtypes = tf.float64
            elif dtypes == 'tf.string':
                dtypes = tf.string
            elif dtypes == 'tf.image':
                dtypes = tf.string
            else:
                raise Exception('Invalid dtypes')
            if types == 'FixedLenFeature':
                features.update({key: tf.io.FixedLenFeature(shape=[], dtype=dtypes)})
            elif types == 'VarLenFeature':
                features.update({key:tf.io.VarLenFeature(dtype=dtypes)})
            else:
                raise Exception('Invalid types')
        """Loading tfrecord files and create tf.data.Dataset object"""
        tfdataset = tf.data.TFRecordDataset(i_tfrecord_paths)
        tfdataset = tfdataset.map(parse)
        return tfdataset
    @staticmethod
    def read(i_tfrecord_path=None,i_original=False):
        assert os.path.exists(i_tfrecord_path), 'Got path: {}'.format(i_tfrecord_path)
        list_of_tfrecord_files = TFRecordDB.init_tfrecord_paths(i_tfrecord_path)
        return TFRecordDB.reads(i_tfrecord_paths=list_of_tfrecord_files,i_original=i_original)
"""====================================================="""
if __name__ == "__main__":
    print('This module is to create tfrecord files')
    import matplotlib.pyplot as plt
    def make_image(i_label=0):
        mimage = np.zeros(shape=(32,32,1),dtype=np.uint8)
        mimage[10:20,10:20,:]=i_label+1
        return mimage
    """For writing, only need to specify the field's keys"""
    db_fields    = {'image_path':[],'image':[],'mask':[],'label':[]}
    to_save_path = os.path.join(os.getcwd(),'minst.tfrecord')
    """Load data"""
    val_data,train_data = tf.keras.datasets.mnist.load_data()
    train_images,train_labels=train_data
    train_paths = ['{}.jpg'.format(i) for i in range(0,train_images.shape[0])]
    """Input to the write function is the list (tuple) of fields"""
    train_masks = [make_image(label) for label in train_labels]
    train_data  = list(zip(train_paths, train_images, train_masks, train_labels))
    TFRecordDB.lossy = False
    saved_paths      = TFRecordDB.write(i_n_records=train_data,i_size = 100000, i_fields=db_fields,i_save_file=to_save_path)
    dataset = TFRecordDB.read(i_tfrecord_path=to_save_path,i_original=True) #Same as: dataset = TFRecordDB.reads(saved_paths)
    for db_item in dataset:
        if isinstance(db_item,dict):
            name  = db_item['image_path']
            image = db_item['image']
            mask  = db_item['mask']
            label = db_item['label']
        else:
            name,image,mask,label = db_item
        plt.subplot(1,2,1)
        plt.imshow(image)
        plt.title('{} with label = {}'.format(name.numpy().decode(),label.numpy()))
        plt.subplot(1,2,2)
        plt.imshow(mask)
        plt.title('{} with label = {}'.format(name.numpy().decode(), label.numpy()))
        plt.show()
"""====================================================="""


from bs4 import BeautifulSoup
import requests, os, base64
from selenium import webdriver
from . import singleton

class CrawlTool(metaclass=singleton.Singleton):
    def __init__(self):

        options = webdriver.ChromeOptions()
        options.add_argument('--headless')
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')

        self.driver = webdriver.Chrome('chromedriver', options=options)
        self.driver.implicitly_wait(3)

    def getSoupContentFromUrl(self, url, **args):

        if type(url) is not str:
            return ""

        url += "?"

        for k, v in args.items():
            url += f'{k}={v}&'

        self.driver.get(url)

        soup = BeautifulSoup(self.driver.page_source, 'html.parser')

        return soup

    def getDaumNews(self, date):

        url = 'https://media.daum.net/ranking/'
        soup = self.getSoupContentFromUrl(url, regDate=date)

        soup = soup.select('a.link_txt')
        news = [ dict(news_link = tag.get('href'), news_text = tag.get_text()) for tag in soup if tag.get('href') is not None ]

        return news

    def getDaumNewsBestReply(self, date):

        url = 'https://media.daum.net/ranking/bestreply'
        soup = self.getSoupContentFromUrl(url, regDate=date)

        soup = soup.select('a.link_txt')
        news = [ dict(news_link = tag.get('href'), news_text = tag.get_text()) for tag in soup if tag.get('href') is not None ]

        return news

    def getReplyOfNews(self, news_link, reply_count):

        news_id = news_link.split("/")[-1]

        print(news_id)

        reply_url = f"https://comment.daum.net/apis/v1/posts/@{news_id}/comments?parentId=0&offset=0&limit={reply_count}&sort=RECOMMEND&isInitial=true"

        soup = self.getSoupContentFromUrl(reply_url)

        print(soup)

        return soup

    def getTextNews(self, url):

        soup = self.getSoupContentFromUrl(url)
        soup = soup.select('div.article_view > section > p')

        text_news = [ article.get_text() for article in soup ]
        text_news = " ".join(text_news)

        return text_news

    def getGoogleImages(self, keyword):
        url = f'https://www.google.com/search?q={keyword}&rlz=1C1CHBD_koKR896KR896&source=lnms&tbm=isch&sa=X&ved=2ahUKEwiAua_v2rTpAhVUVN4KHdZOBIkQ_AUoAXoECBYQAw&biw=1536&bih=674&dpr=1.25'

        self.driver.get(url)
        soup = BeautifulSoup(self.driver.page_source, 'html.parser')
        soup = soup.select('img.rg_i')
        img_binary_type = [ tag.get('src') for tag in soup if tag.get('src') is not None ]
        img_binaries = [ base64.b64decode(img_data.split(',')[1]) for img_data in img_binary_type ]
        img_links = [ tag.get('data-src') for tag in soup if tag.get('data-src') is not None ]

        return img_binaries, img_links


import pygame
from debug import debug
class Player(pygame.sprite.Sprite):
    def __init__(self, pos, groups, obstacles):
        super().__init__(groups)
        self.image = pygame.image.load('src/assets/testAssets/player.png');
        self.rect = self.image.get_rect(topleft = pos)
        self.direction = pygame.math.Vector2()
        self.speed = 5
        self.obstacles = obstacles
        self.hitbox = self.rect.inflate(-30, -30)

    def move(self, speed):
        # normalizado de velocidad diagonal
        if self.direction.magnitude() != 0:
            self.direction = self.direction.normalize()

        self.hitbox.x += self.direction.x * speed
        self.collision("horizontal")
        self.hitbox.y += self.direction.y * speed
        self.collision("vertical")
        self.rect.center = self.hitbox.center

    # detectar coliciones con otros objetos de manera vertical y horizontal
    def collision(self, direction):
        if(direction == "horizontal"):
            for obstacle in self.obstacles:
                if obstacle.hitbox.colliderect(self.hitbox):
                    if self.direction.x > 0:
                        self.hitbox.right = self.hitbox.left
                    if self.direction.x < 0:
                        self.hitbox.left = self.hitbox.right
        if(direction == 'vertical'):
            for obstacles in self.obstacles:
                if obstacles.hitbox.colliderect(self.hitbox):
                    if self.direction.y > 0:
                        self.hitbox.bottom = self.hitbox.top
                    if self.direction.y < 0:
                        self.hitbox.top = self.hitbox.bottom

    def input(self):
        # inputs del jugador
        keys = pygame.key.get_pressed()
        if(keys[pygame.K_UP]):
            self.direction.y = -1
        elif(keys[pygame.K_DOWN]):
            self.direction.y = 1
        else:
            self.direction.y = 0

        if(keys[pygame.K_LEFT]):
            self.direction.x = -1
        elif(keys[pygame.K_RIGHT]):
            self.direction.x = +1
        else:
            self.direction.x = 0

    def update(self):
        self.input()
        self.move(self.speed)


from distutils.log import error
import requests
import json
import time

# Global variables with values to be replaced for each customer
# Change values accordingly
auth_token_get_url = "https://api.korewireless.com/Api/api/token"
client_id="<<YOUR CLIENT_ID>>"
client_secret="<<YOUR CLIENT_SECRET>>"
api_gateway_key="<<YOUR API_KEY>>"
api_base_path = "https://api.korewireless.com/connectivity"

#API Parameters
accountid='cmp-pp-org-xxx'
iccid='999XXXX25010000XXXX'
activationprofileid="cmp-prov-ap-xxx"

# =======================================================================================
#                               Get Authentication Token
# ======================================================================================
def getauthtoken():
    try:
        headers = {
            'cache-control': 'no-cache',
            'content-type': 'application/x-www-form-urlencoded',
        }
        # Set the required body values for getting Authentication token
        data = {
            'grant_type': 'client_credentials',
            'client_id': client_id,
            'client_secret': client_secret
        }
        # Raise the request for getting the Authentication token
        response = requests.post(auth_token_get_url, headers=headers, data=data)
        # Convert the response string to Json object so that token value can be extracted
        responseJson = json.loads(response.content)
        return responseJson["access_token"]
    except requests.exceptions.RequestException as err:
        print(err)

# =======================================================================================
#                               Get Scbscription id from iccid
# ======================================================================================
def getSubscriptionId(aceesstoken,accountid,iccid):
    try:
        headers = {
        'Content-Type': 'application/json',
        'Authorization': 'bearer ' + aceesstoken,
        'x-api-key': api_gateway_key
        }
        api_url = "{api_base_path}/v1/accounts/{accountid}/subscriptions?page-index=0&max-page-item=100&iccid={iccid}&show-state-history=false".format(api_base_path=api_base_path,accountid=accountid,iccid=iccid)
        payload={}
        subscriptionresponse = requests.request("GET", api_url, headers=headers)
        subscriptionresponseJson = json.loads(subscriptionresponse.text)
        if(subscriptionresponseJson["page-info-result"]["total-count"]>0):
            return subscriptionresponseJson["subscriptions"][0]["subscription-id"]
        else:
            return ""
    except requests.exceptions.RequestException as err:
        print(err)

def createProvisioningRequest(aceesstoken, accountid, subscriptionid, activationprofileid):
    try:
        headers = {
        'Content-Type': 'application/json',
        'Authorization': 'bearer ' + aceesstoken,
        'x-api-key': api_gateway_key
        }

        api_url = "{api_base_path}/v1/accounts/{accountid}/provisioning-requests".format(api_base_path=api_base_path,accountid=accountid)
        payload = json.dumps({
            "activate": {
                "subscriptions": [
                    {
                        "subscription-id": subscriptionid
                    }
                ],
                "activation-state": "active",
                "activation-profile-id": activationprofileid
            }
        })
        response = requests.request("POST", api_url, headers=headers, data=payload)
        return response.text
    except requests.exceptions.RequestException as err:
        print(err)

def checkProvisioningStatus(aceesstoken, accountid,provisioningrequestid):
    try:
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'bearer ' + aceesstoken,
            'x-api-key': api_gateway_key
        }
        api_url = "{api_base_path}/v1/accounts/{accountid}/provisioning-requests/{provisioningrequestid}".format(api_base_path=api_base_path,accountid=accountid,provisioningrequestid=provisioningrequestid)
        payload={}
        response = requests.request("GET", api_url, headers=headers, data=payload)
        return response.text
    except requests.exceptions.RequestException as err:
        print(err)

# =======================================================================================
#                               API Access Process
# ======================================================================================
# Get the API Token
accesstoken=getauthtoken()

#Get the Subscription id for the iccid
subscriptionid=getSubscriptionId(accesstoken,accountid,iccid)
#If we got a subscription id to proceed to the next step
if(len(subscriptionid)>0):
    # Provision a SIM
    # A success response will be something like this
    # {"status": "success","data": {"provisioning-request-id": "cmp-cpro-request-1460","message": "Your request has been acknowledged"} }
    provisioningrequestresponse=createProvisioningRequest(accesstoken,accountid,subscriptionid,activationprofileid)
    print(provisioningrequestresponse)
    provisioningrequestJson = json.loads(provisioningrequestresponse)
    if(provisioningrequestJson["status"].casefold() =="success"):
        #Wait for the request to complete
        print('Deliberately waiting 1 minute for request to get completed')
        time.sleep(60)
        #Check Provisioning status
        provisioningrequeststatusresponse=checkProvisioningStatus(accesstoken,accountid,provisioningrequestJson["data"]["provisioning-request-id"])
        print(provisioningrequeststatusresponse)
    else:
        print('Request Failed')
else:
    print('No Subscription id recieved for the iccid')


from collections import deque

N = int(input())
S = list(input())
A = deque([])

for i in range(N):
    if S[i] == "L":
        A.appendleft(i+1)
    elif S[i] == "R":
        A.append(i+1)
    elif S[i] == "A":
        if len(A) == 0:
            print("ERROR")
        else:
            print(A.popleft())
    elif S[i] == "B":
        if len(A) <= 1:
            print("ERROR")
        else:
            q = A.popleft()
            print(A.popleft())
            A.appendleft(q)
    elif S[i] == "C":
        if len(A) <= 2:
            print("ERROR")
        else:
            q1 = A.popleft()
            q2 = A.popleft()
            print(A.popleft())
            A.appendleft(q2)
            A.appendleft(q1)

    elif S[i] == "D":
        if len(A) == 0:
            print("ERROR")
        else:
            print(A.pop())
    elif S[i] == "E":
        if len(A) <= 1:
            print("ERROR")
        else:
            q = A.pop()
            print(A.pop())
            A.append(q)
    elif S[i] == "F":
        if len(A) <= 2:
            print("ERROR")
        else:
            q1 = A.pop()
            q2 = A.pop()
            print(A.pop())
            A.append(q2)
            A.append(q1)


# coding=utf-8
"""
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
==================

"""
class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        i = j = nums[0]
        n = nums[1:]
        for k in n:
            i = max(i + k, k)
            j = max(i, j)
        return j


# Priority-Based Keyword Matching (PBKM)
#
# Folder pointed by <name> must contain at least these files:
#
#   <name>_training.json
#   <name>_verify.json
#
# It may also contain a map file for mapping metadata names in
# the above two files to names we expect.
#
#   <name>_map.json

import os
import re
import os.path
import sys
import ijson
import nltk
import mapfile
import priority
from collections import Counter

from nltk.corpus import stopwords
from nltk.corpus import wordnet as wn

# Top 10 keywords

kp = ()

# Corpus

stop_words = set(stopwords.words('english'))

# Tokenise the description and filter out any word in the
# English language corpus.

def text_to_tokens(d):

    # Make all tokens lower-case, limit to 3..15 characters and
    # filter out stop-words
    tk = nltk.word_tokenize(d)
    tk = [x.lower() for x in tk if (len(x) > 2 and len(x) <= 15)]
    tk = [x for x in tk if x not in stop_words]

    # Remove any words which have non-alphabetic characters
    tk = [x for x in tk if re.search('^[a-zA-Z]+$', x)]

    # Filter further to just nouns and specific verbs.
    tagged = nltk.pos_tag(tk)
    tags = ['NN', 'JJ', 'VBG', 'VBD', 'NNP', 'NNS', 'NNPS']
    tk = [x for (x,y) in tagged if y in tags]

    # Restrict results to those in the wordnet corpus
    return [x for x in tk if len(wn.synsets(x)) == 0]

# Build the priority map from the training input file

def build_training(filename):

    global kp

    bn = os.path.basename(filename)
    tf = filename + '/' + bn + '_training.json'

    k_map = Counter()

    with open(tf, "r") as f2:
        bugs = ijson.items(f2, 'item')
        for bug in bugs:

            d = bug[mapfile.map['description']]
            p = bug[mapfile.map['priority']]
            wp = priority.weight_from_priority(p)

            if d and wp > 0:

                tks = text_to_tokens(d)
                for tk in tks:
                    if (wp == 4):   # 4 = Major pri bugs
                        if tk in k_map:
                            k_map[tk] += 1
                        else:
                            k_map[tk] = 1

    # List of 10 most common words in major bugs
    kp = [x for (x,y) in k_map.most_common(10)]

    # Report
    print ('Most common words are ' + ",".join(kp))

# Verify the computed priority against the verification
# input file

def verify(filename):

    global kp

    bn = os.path.basename(filename)
    tf = filename + '/' + bn + '_verify.json'

    with open(tf, "r") as f2:
        bugs = ijson.items(f2, 'item')
        success0 = 0
        success1 = 0
        count = 0
        for bug in bugs:
            d = bug[mapfile.map['description']]
            p = bug[mapfile.map['priority']]
            wp = priority.weight_from_priority(p)
            if d and wp > 0:
                tks = text_to_tokens(d)
                cp = 0
                for tk in tks:
                    if tk in kp:
                        cp = 1

                if cp == 1 and wp == 4:
                    success0 = success0 + 1
                if cp == 1 and (wp >= 3 and wp <= 5):
                    success1 = success1 + 1

                count = count + 1

        if count == 0:
            print (bn + ' : Failed to match any bugs')
        else:
            success0p = int((100/count) * success0)
            success1p = int((100/count) * success1)
            print (bn, ':', str(count), 'records :', success0p, '% success (exact),', success1p, '% success (+/-1)')

# Main program starts here

if len(sys.argv) < 2:
    print ('Syntax: pbkm.py <name>')
    exit()

mapfile.load_map(sys.argv[1])
build_training(sys.argv[1])
verify(sys.argv[1])


# write by Mrlv
# coding:utf-8
import time

import tensorflow as tf
import os
from tensorflow.keras import optimizers
from tools import LSTM
from DeepLearn.rnn_classfication import rnnlayer

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
batchsz = 128
total_words = 10000
embedding_len = 100
max_words_len = 80
data_train = rnnlayer.train_data
data_test = rnnlayer.test_data

def main():
    units = 64
    epochs = 10
    model = LSTM(units, embedding_len, max_words_len, total_words)

    time0 = time.time()
    model.compile(optimizer=optimizers.Adam(lr=0.001),
                  loss=tf.losses.BinaryCrossentropy(),
                  metrics=['accuracy'])

    model.fit(data_train, epochs=epochs, validation_data=data_test)

    model.evaluate(data_test)
    time1 = time.time()
    print()

if __name__ == '__main__':
    main()


import logging
import os

import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from module.api import v1
from module.conf import VERSION, settings, setup_logger

setup_logger(reset=True)
logger = logging.getLogger(__name__)
uvicorn_logging_config = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": logger.handlers,
    "loggers": {
        "uvicorn": {
            "level": logger.level,
        },
        "uvicorn.access": {
            "level": "WARNING",
        },
    },
}

def create_app() -> FastAPI:
    app = FastAPI()

    # mount routers
    app.include_router(v1, prefix="/api")

    return app

app = create_app()

@app.get("/posters/{path:path}", tags=["posters"])
def posters(path: str):
    return FileResponse(f"data/posters/{path}")

if VERSION != "DEV_VERSION":
    app.mount("/assets", StaticFiles(directory="dist/assets"), name="assets")
    app.mount("/images", StaticFiles(directory="dist/images"), name="images")
    # app.mount("/icons", StaticFiles(directory="dist/icons"), name="icons")
    templates = Jinja2Templates(directory="dist")

    @app.get("/{path:path}")
    def html(request: Request, path: str):
        files = os.listdir("dist")
        if path in files:
            return FileResponse(f"dist/{path}")
        else:
            context = {"request": request}
            return templates.TemplateResponse("index.html", context)
else:
    @app.get("/", status_code=302, tags=["html"])
    def index():
        return RedirectResponse("/docs")

if __name__ == "__main__":
    if os.getenv("IPV6"):
        host = "::"
    else:
        host = os.getenv("HOST", "0.0.0.0")
    uvicorn.run(
        app,
        host=host,
        port=settings.program.webui_port,
        log_config=uvicorn_logging_config,
    )


# import sys
#
# input = sys.stdin.readline
#
# M, N = map(int, input().split())
#
# def isPrime(a):
#   if(a<2):
#     return False
#   for i in range(2,a):
#     if(a%i==0):
#       return False
#   return True
#
# for i in range(M, N + 1):
#   if(isPrime(i)):
#     print(i)

import sys

input = sys.stdin.readline

M, N = map(int, input().split())

a = [False,False] + [True]*(N-1)
primes=[]

for i in range(2, N+1):
    if a[i]:
        primes.append(i)
    for j in range(2*i, N+1, i):
        a[j] = False

# print(primes)

for i in primes:
    if M <= i <=N:
        print(i)


import requests
import json

from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse, HttpResponse
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.generic import TemplateView

from carts.utils import done, get_cart, get_cart_from_session, send_request_to_zp
from carts.models import Cart
from eCommerce.utils import required_ajax
from orders.models import Order, Payments

@login_required
def verify(request):
    payment = Payments.objects.filter(user=request.user).latest()

    if request.GET.get('Status') != 'OK':
        payment.status = 'failed'
        payment.save(update_fields=['status'])
        messages.error(request, 'Transaction failed')
        return HttpResponse('Transaction failed or canceled by user')

    t_status = request.GET.get('Status')
    t_authority = request.GET['Authority']
    req_header = {"accept": "application/json", "content-type": "application/json"}
    req_data = {
        "merchant_id": settings.MERCHANT,
        "amount": payment.total,
        "authority": t_authority,
    }

    req = requests.post(url=settings.ZP_API_VERIFY, data=json.dumps(req_data), headers=req_header)

    if len(req.json()['errors']) != 0:
        e_code = req.json()['errors']['code']
        e_message = req.json()['errors']['message']

        payment.status = 'error'
        payment.save(update_fields=['status'])
        messages.error(request, 'Transaction was success but an error accrued')
        return HttpResponse(f"Error code: {e_code}, Error Message: {e_message}")

    request_data = req.json()['data']  # https://docs.zarinpal.com/paymentGateway/guide/
    t_status = request_data['code']
    if t_status == 100:
        # response = HttpResponse("Transaction success.\nRefID: " + str(request_data["ref_id"]))
        messages.success(request, 'Your transaction was successful.')
        payment.status = 'success'
        payment.ref_id = request_data['ref_id']
        payment.fee = request_data['fee']
        done(request)

    elif t_status == 101:
        # response = HttpResponse("Transaction submitted : " + str(request_data['message']))
        messages.error(request, 'Your transaction was submitted before.')
        payment.status = 'submit'

    else:
        # response = HttpResponse('Transaction failed.\nStatus: ' + str(request_data['message']))
        messages.error(request, 'Transaction failed')
        payment.status = 'failed'

    payment.save()
    return render(request, 'carts/verify.html', context={'payment': payment})

@login_required
def cart_home(request):
    user = request.user
    if not user.is_active or not user.is_registered:
        messages.error(request, "You don't have permission to this page.")
        return redirect('home')

    cart = get_cart_from_session(request, allow_none=True)
    products = None
    if cart is not None:
        products = cart.products.values('id', 'name', 'price')

    context = {
        'cart': cart,
        'products': products,
    }
    return render(request, 'carts/cart_home.html', context)

@required_ajax
@get_cart
def add_rmv_product(request, cart):
    product_id = request.POST.get('product_id')
    product, added = Cart.objects.add_or_remove_product(cart, product_id)
    cart_items = cart.products.count()
    request.session['cart_items'] = cart_items

    msg = 'Added to your cart.' if added else 'Removed from your cart.'
    messages.success(request, msg)
    return JsonResponse({
        'added': added,
        'removed': not added,
        'cart_items': cart_items
    })

@login_required
@required_ajax
@get_cart
def remove(request, cart):
    product_id = request.POST['product_id']
    product = cart.products.get(id=product_id)
    cart.products.remove(product)
    request.session['cart_items'] = cart.products.count()
    data = {'total': cart.total, 'subtotal': cart.subtotal}
    return JsonResponse(data)

@login_required
@get_cart
def finalization(request, cart):
    order = Order.objects.filter(cart=cart) \
        .select_related('cart') \
        .first()  # We need cart in check_done() => self.cart

    if not order.check_done():  # address_shipping and address_billing is exists
        messages.error(request, 'You have to fill both of billing and shipping addresses.')
        return redirect('carts:home')

    context = {
        'order': order,
        'cart': cart,
    }
    return render(request, 'carts/finalization.html', context)

@login_required
@get_cart
def send_to_payment(request, cart):
    if request.method == "GET":
        user = request.user
        order = Order.objects.filter(cart=cart, user=user).only('total').first()
        if not order.check_done():
            messages.error(request, 'You are not done,yet.')
            return redirect('home')

        order.status = 'shipped'
        order.save(update_fields=['status'])
        Payments.objects.get_or_create(full_name=user.full_name, order=order,
                                       user=user, amount=order.total)
        return send_request_to_zp(request, int(order.total) * 1000, user.email)

class CheckoutTemplateView(LoginRequiredMixin, TemplateView):
    template_name = 'carts/checkout.html'

    def __init__(self):
        super(CheckoutTemplateView, self).__init__()
        self.cart = None

    def get_context_data(self, **kwargs):
        cart = self.cart or get_cart_from_session(self.request)
        order, created = Order.objects.get_or_create(user=self.request.user, cart=cart)

        context = super(CheckoutTemplateView, self).get_context_data(**kwargs)
        context['order'] = order
        context['cart'] = cart
        return context

    def get(self, request, *args, **kwargs):
        self.cart = get_cart_from_session(request)

        order, created = Order.objects.get_or_create(user=request.user, cart=self.cart)

        if not self.cart.order.check_done():
            addr_type = 'shipping' if not self.cart.is_all_digital and order.address_billing_id else 'billing'
            return redirect(reverse('address:set_address') + f'?type={addr_type}&next={request.META.get("HTTP_REFERER")}')
        return super(CheckoutTemplateView, self).get(request, *args, **kwargs)


score = input('Enter a score between 0 and 1: ')

try:
    score = float(score)
    assert score >= 0 and score <= 1
except:
    print('Bad score')
    exit()

if score >= 0.9:
    grade = 'A'
elif score >= 0.8:
    grade = 'B'
elif score >= 0.7:
    grade = 'C'
elif score >= 0.6:
    grade = 'D'
else:
    grade = 'F'

print('Your grade:', grade)


#-*-encoding:utf-8-*-
'''
Created on 2015年11月24日

@author: chris
'''
from api.utils import post
from setting import baseUrl

class SalesRange():

    salesDict = {'cpid':'产品ID','cpxsqy':'产品销售区域'}

    def querySalesRange(self,cpid=None,pagenum=1):
        assert cpid != None
        param = {}
        param['cpid'] = cpid
        if pagenum:
            param['pagenum']=pagenum
        queryUrl = '%s/cpxsqyQuery.go'%baseUrl
        data = post(queryUrl,param)
        rangeList = data.get('List')
        if rangeList[0]!=None:
            return [{'cpid':cpid,'cpxsqy':i.get('cpxsqy')} for i in rangeList]
        else:
            return None


import os
import zipfile
import socket

from UNETv3_TrainFunc import TrainingLoop

host_ip = "192.168.86.24"

def communication_send(message_to_send):
    # create a socket object
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        # connect to the server
        s.connect((host_ip, 22))
        print('Connected to', host_ip)

        # send data to the server
        message = message_to_send
        s.sendall(message.encode())
    s.close
    return

def communication_rec():
    # create a socket object
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    # bind the socket to a specific network interface and port number
        s.bind(("0.0.0.0", 1024))
        # listen for incoming connections
        s.listen()
        print('waiting for host message at {}:{}...'.format("0.0.0.0", 1024))

        # accept a nano connection
        conn, addr = s.accept()
        with conn:
            print('Connected by', addr)

            # receive data from the nano
            data = conn.recv(1024)
            print('Received data:', data.decode())
            received_msg = data.decode()
    s.close
    return received_msg

LOAD_DIR = "."
def main():
    print("running nano.py")

    # check and send communication confirmation
    print("sending communication ack.")
    communication_send("connected")
    print("connection established and confirmed")

    for i in range(2):
        print("federated learning loop #", i)
        # wait for files to be sent
        print("waiting for model to be sent")
        while(True):
            if(communication_rec() == "model_sent"):
                break

        # send file size to host for file size confirmation
        file_size = os.path.getsize(r"{}/global_model.zip".format(LOAD_DIR))
        communication_send("{}".format(file_size))

        print("waiting for \"start_train\" function")
        while(True):
            if(communication_rec() == "start_train"):
                break

        # unzip file
        with zipfile.ZipFile("{}/{}".format(LOAD_DIR, "global_model.zip"), 'r') as zip_ref:
            zip_ref.extractall("{}/".format(LOAD_DIR))
            os.remove("{}/{}".format(LOAD_DIR, "global_model.zip"))

        print("starting to train")
        # start training, call train python file
        model = TrainingLoop(2, 1, .0001)

        # zip model file
        with zipfile.ZipFile("trained_model.zip", mode = 'w') as archive:
            archive.write(r"UNET_MBIMAGENET.pth")
        print("training finished")
        communication_send("train_finish")

        print("waiting for model to be transferred back")
        while(True):
            if(communication_rec() == "model_sent_back"):
                break
        # send file size to host for file size confirmation
        file_size = os.path.getsize(r"{}/trained_model.zip".format(LOAD_DIR))
        communication_send("{}".format(file_size))

        os.remove("{}/{}".format(LOAD_DIR, "UNET_MBIMAGENET.pth"))
        os.remove("{}/{}".format(LOAD_DIR, "trained_model.zip"))

    return

if __name__ == "__main__":
    main()


import random as r
s_age = r.randint(1,10)
flag=True

def game_func(guessed_age,secret):
    if guessed_age<secret:
        return 'Too low'
    elif guessed_age>secret:
        return 'Too high'
    else:
        return 'CORRECT'

for i in range(6):
    guesses_age = int(input(f'Take a guesse, you have {6-i} guesses left : '))
    result=game_func(guesses_age,s_age)
    if result =='CORRECT':
        flag=False
        print("CONGRATULATIONS !! , You  Are Win")
        break
    else:
        print(f"{result}, TRY AGAIN....")

if flag:
    print("Sorry !! You are Lost The game....")


from flask import Flask, render_template  # 플라스크 라이브러리 불러오기
import datetime
import RPi.GPIO as GPIO                     # 시간 라이브러리
app = Flask(__name__)                     # 플라스크 객체 만들기

GPIO.setmode(GIPO.BCM) #BCM 모드

@app.route("/")   # <변수>
def hello():
    now = datetime.datetime.now()
    time = now.strftime("%Y-%m-%d %H:%M")
    templateData = {   #딕션너리 변수
        'title' : "안녕하세요!",
        'time' : time
    }
    return render_template('main.html', **templateData) # 딕셔너리 안에 있는 templateData 변수를 전달
#    return render_template('index.html', name = username)

@app.route("/<pin>") # <변수>
def readPin():
    try:
        GPIC.setup(int(pin), GPIO.IN)
        if GPIO.input(int(pin)) == True:
            response = "핀 넘버"+pin+"은 HIGH"
        else:
            response = "핀 넘버"+pin+"은 LOW"
    except:
        response = "핀을 읽는데 문제가 있음"+pin+"번 핀"
    templateData = {
        'pin' : "핀상태" + pin,
        'response' : response
    }
    return render_template('pin.html', **templataDate)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)


from collections import namedtuple
from collections.abc import Iterable, Iterator
from typing import NamedTuple
import datetime as dt

def read_line(line:str)->list:
    return line.strip('\n').split(',')

def parse_date(str_date:str)->dt.date:
    return dt.datetime.strptime(str_date, "%m/%d/%Y").date()

# example = (4006478550, 'VAD7274', 'VA', 'PAS', '10/5/2016', 5, '4D', 'BMW', 'BUS LANE VIOLATION',)
dtypes =    (int,       str,        str,  str,  parse_date,  int, str,  str,     str )
def type_cast(data: Iterable)->Iterator:
    return ( dtype(item) for dtype, item in zip(dtypes, data) )

def make_namedtuple_from_header( tuple_name:str, header:str)->NamedTuple:
    field_names = (
        name.replace(' ','_').lower()
        for name in read_line(header)
    )
    return namedtuple(tuple_name, field_names)

def parse_tickets(
        lines: Iterable,
        tuple_class: NamedTuple,
        )->Iterator:
    return (
        tuple_class(
            *type_cast(
                read_line(line)
            )
        ) for line in lines
    )

def count_in_field(tickets: Iterator, field_name: str)->dict:
    count = {}
    for ticket in tickets:
        field_value = getattr(ticket, field_name)
        count[field_value] = count.get(field_value, 0) + 1
    return count

def sort_dict(dct:dict)->dict:
    dict(sorted(
        dct.items(),
        key = lambda item: item[1],
        reverse= True
    ))

def count_tickets_by_make(
        file_path: str,
        *, sort = True
    )->dict:
    with open(file_path) as file:
        Ticket = make_namedtuple_from_header('Ticket', next(file))
        tickets = parse_tickets(file, Ticket)
        count = count_in_field(tickets, 'vehicle_make')
    count = sort and sort_dict(count) or count
    return count

if __name__ == '__main__':
    count_by_maker = count_tickets_by_make('nyc_parking_tickets_extract.csv')
    [print(f'{maker}\t{times}') for maker, times in count_by_maker.items()]


import numpy as np
import pandas as pd
import time, sys, os

def getFolders(files):
    folders = []
    for file in files:
        if 'csv' not in file:
            folders.append(file)
        else:
            pass
    return folders

def monthly(interval):
    base_path = 'data/spot/monthly/klines/'
    files = os.listdir(base_path)
    for file in files:
        files2 = os.listdir(base_path+file+'/'+interval+'/')
        print(files2)
        for file2 in files2:
            try:
                fantasy_zip = zipfile.ZipFile(base_path+file+'/'+interval+'/'+file2)
                fantasy_zip.extractall(f'data/{interval}/')
            except Exception as e:
                print(file2, e)
    print('done...')

def getTickerFromFileName(fileName):
    fileList = list(fileName)
    tickerName = ''
    for i in range(len(fileList)):
        if fileList[i] != '-' and fileList[i] !='_':
            tickerName+=str(fileList[i])
        else:
            break
    return tickerName

def getDateFromFileName(fileName):
    fileList = list(fileName)
    date = ''
    for i in range(len(fileList)):
        if int(fileList[i]) == fileList[i]:
            for o in range(10):
                date += fileList[i]
            break
        else:
            pass
    return date

def getTimeFrameFromFile(fileName):
    if '30m' in fileName:
        return '30m'
    elif '15m' in fileName:
        return '15m'
    elif '1h' in fileName:
        return '1h'
    elif '1d' in fileName:
        return '1d'
    elif '2h' in fileName:
        return '2h'
    else:
        return False

def getLiquidTickers():

    base_path = 'data/30mspot/'
    files = os.listdir(base_path)
    strTickers = ''
    tickers = []

    for file in files:
        tickers.append(getTickerFromFileName(file))
    for ticker in tickers:
        strTickers += f' {ticker}'

    return strTickers


import numpy as np

class MF():
    def __init__(self, R, K, lr, reg_para, epochs, verbose = False):
        """
        R: rating
        K: latent  dimension para
        lr: learning rate = alpha on weight update
        reg_para: beta on weight update (regulation term coefficient)
        verbose: 상세한 로깅 출력여부  0 = 출력x, 1 = 자세히, 2 = 함축적 정보
        """
        self._R = R
        self._num_users, self._num_items = R.shape # R = U x I (rating matrix = user matrix x item matrix)
        self._k = K
        self._lr = lr
        self._reg_para = reg_para
        self._epochs = epochs
        self._verbose = verbose

    def fit(self):
        # init user & item latent features
        self._U = np.random.normal(size = (self._num_users, self._k))
        self._I = np.random.normal(size = (self._num_items, self._k))

        """
        [논문 기준]
        global bias = ovarall rating average (total mean) + user bias + item bias
        [코드 기준]
        rating 존재하는 overall rating average 만 global bias로 사용
        """
        # init user & item & global bias
        self._b_U = np.zeros(self._num_users)
        self._b_I = np.zeros(self._num_items)
        self._b = np.mean(self._R[np.where(self._R != 0)]) # global bias /  np.where: 조건 충족 index 찾기

        # training
        self._training_process = []

        for epoch in range(self._epochs):
            for i in range(self._num_users):
                for j in range(self._num_items):
                    if self._R[i, j] > 0:
                        self.gradient_descent(i, j, self._R[i,j])
            cost = self.cost()
            self._training_process.append((epoch, cost))
        # print status
        if self._verbose ==  True and ((epoch + 1) % 10 == 0):
            print(f"Iteration: {epoch + 1} ; cost = {cost:.4f}")

    def cost(self):
        # RMSE cost return
        xi, yi = self._R.nonzero() # 값이 0이 아닌 index 반환
        pred = self.get_complete_matrix()
        cost = 0
        for x,y in zip(xi, yi): # zip 함수 통해 tuple 형태로 만들어서 반환
            cost += pow(self._R[x, y] - pred[x,y], 2)
        return np.sqrt(cost / len(xi)) # RMSE = root(sum {(y - y_pred)^2} / n)

    def gradient(self, pred_error, i, j):
        # prediction error (pred_error) = rating - pred
        # user i & item j (index)
        grad_u = pred_error*self._I[j,:] - self._reg_para*self._U[i,:]
        grad_i = pred_error*self._U[i,:] - self._reg_para*self._I[j,:]
        return grad_u, grad_i

    def gradient_descent(self, i, j, rating):
        pred = self.get_prediction(i, j)
        pred_error = rating - pred

        # update biases -> 이 부분 왜 이렇게 구현된 것인지 잘 이해안됨,,
        # user i & item j index
        self._b_U[i] += self._lr * (pred_error - self._reg_para * self._b_U[i])
        self._b_I[j] += self._lr * (pred_error - self._reg_para * self._b_I[j])

        # update latent feature
        grad_u, grad_i = self.gradient(pred_error, i, j)
        self._U[i,:] += self._lr * grad_u
        self._I[j,:] += self._lr * grad_i

    def get_prediction(self, i, j):
        # user i & item j index
        # prediction =  overall avg (total bias) + user bias + item bias + latent user * latent item
        return self._b + self._b_U[i] + self._b_I[j] + self._U[i,:].dot(self._I[j,:].T)

    def get_complete_matrix(self):
        return self._b + self._b_U[:, np.newaxis] + self._b_I[np.newaxis,:] + self._U.dot(self._I.T)

    def print_results(self):
        """
        print fit results
        """

        print("User Latent U:")
        print(self._U)
        print("Item Latent I:")
        print(self._I.T)
        print("U x I:")
        print(self._U.dot(self._I.T))
        print("bias:")
        print(self._b)
        print("User Latent bias:")
        print(self._b_U)
        print("Item Latent bias:")
        print(self._b_I)
        print("Final R matrix:")
        print(self.get_complete_matrix())
        print("Final RMSE:")
        print(self._training_process[self._epochs-1][1])

# run example
if __name__ == "__main__":
    # rating matrix - User X Item : (7 X 5)
    R = np.array([
        [1, 0, 0, 1, 3],
        [2, 0, 3, 1, 1],
        [1, 2, 0, 5, 0],
        [1, 0, 0, 4, 4],
        [2, 1, 5, 4, 0],
        [5, 1, 5, 4, 0],
        [0, 0, 0, 1, 0],
    ])

    # P, Q is (7 X k), (k X 5) matrix
    factorizer = MF(R, K=3, lr=0.01, reg_para=0.01, epochs=300, verbose=True)
    factorizer.fit()
    factorizer.print_results()


# -*- coding: utf-8 -*-
# @Time    : 2017/9/4 11:53
# @Author  : liqianyu
# @Email   : liqianyuwork@163.com
# @File    : eight 获取断言信息.py
# @Software: PyCharm Community Edition
"""
-------------------------------------------------------------------------------

code is far away from bugs with the god animal protecting
               ┏┓      ┏┓
            ┏┛┻━━━┛┻┓
            ┃      ☃      ┃
            ┃  ┳┛  ┗┳  ┃
            ┃      ┻      ┃
            ┗━┓      ┏━┛
                ┃      ┗━━━┓
                ┃  神兽保佑    ┣┓
                ┃　永无BUG！   ┏┛
                ┗┓┓┏━┳┓┏┛
                  ┃┫┫  ┃┫┫
                  ┗┻┛  ┗┻┛
-------------------------------------------------------------------------------
"""

import login,time
driver = login.come().driver
url = login.come().url
driver.get(url)
print('before search.===================')

# 打印当前页面title
pagetitle = driver.title
print(pagetitle)

driver.find_element_by_id('kw').send_keys('selenium')
driver.find_element_by_id('su').click()
time.sleep(1)

print('after search.===================')
# 再次打印title
title = driver.title
print(title)
time.sleep(1)

#现在的网址
nowurl = driver.current_url
print(nowurl)
time.sleep(1)

# 获取结果数目
user = driver.find_element_by_class_name('nums').text
print(user)

time.sleep(1)


import math
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Path and filename settings
def path_set():
	path = "C:/AG/course notes/111_2/IC design/HW5/HW5/file/mosaic/"
	data_name = []
	for i in range(6):
		data_name.append("test"+str(i+1)+".dat")
	return path, data_name

# Hexadecimal to decimal
def H2D(num_str):
	return int(num_str, 16)

# read data(pd) and transfer to np
def read_img(path):
	img_pd = pd.read_csv(path, sep=" ", names=["pixel"])
	img_pd = img_pd.to_numpy()
	img_np = []
	for i in range(img_pd.shape[0]):
		img_np.append(H2D(str(img_pd[i])[2:-2]))
	return np.array(img_np)

# image show
def img_show_gray(img):
	plt.imshow(img,"gray")
	plt.show()

def psnr(img1, img2):
   mse = np.mean( (img1/255. - img2/255.) ** 2 )
   if mse < 1.0e-10:
      return 100
   PIXEL_MAX = 1
   return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))

if __name__=='__main__':
	print(0)


# -*- coding: utf-8 -*-
from odoo import fields, models, api
import logging
from datetime import datetime
import requests
import base64
from odoo.exceptions import UserError
from odoo import api, fields, models, _

_logger = logging.getLogger(__name__)

class Res_Users(models.Model):
    _inherit = 'res.users'

    zoom_client_id = fields.Char(help="The client ID you obtain from the developer dashboard.", string="Consumer Key")
    zoom_client_secret = fields.Char(help="The client secret you obtain from the developer dashboard.",
                                     string="Consumer Secret")
    zoom_auth_base_url = fields.Char('Authorization URL', default="https://zoom.us/oauth/authorize",
                                     help="User authenticate uri")
    zoom_access_token_url = fields.Char('Authorization Token URL', default="https://zoom.us/oauth/token",
                                        help="Exchange code for refresh and access tokens")
    zoom_request_token_url = fields.Char('Redirect URL', default="http://localhost:8069/get_auth_code",
                                         help="One of the redirect URIs listed for this project in the developer dashboard.")
    # used for api calling, generated during authorization process.
    zoom_auth_code = fields.Char('Auth Code', help="")
    zoom_access_token = fields.Char('Access Token', help="The token that must be used to access the ZOOM API.")
    zoom_refresh_token = fields.Char('Refresh Token')
    outgoing_server_mail_id = fields.Many2one("ir.mail_server", string="Outgoing mail server")

    @api.model
    def _default_update_datetime(self):
        date = str(datetime.strptime("1870-01-01 00:00:00", "%Y-%m-%d %H:%M:%S"))
        return datetime.strptime("1870-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")

    def Authenticate(self):
        try:
            if self.zoom_client_id or self.zoom_request_token_url:
                url = self.zoom_auth_base_url + '?&response_type=code&client_id=' + self.zoom_client_id + '&redirect_uri=' + self.zoom_request_token_url
                # print("\n\n\nurl:::::::::",url)
                return {
                    "type": "ir.actions.act_url",
                    "url": url,
                    "target": "new"
                }
            else:
                raise UserError('Please Enter Valid credentials...!')
        except:
            raise UserError('Please Enter credentials...!')

            # @api.multi

    def refresh_token_from_access_token(self):
        '''
            This method gets access token from refresh token
            and grant type is refresh_token,
            This token will be long lived.
        '''
        if not self.zoom_refresh_token:
            raise UserError("Please authenticate first.")
        payload = {}
        headers = {
            'content-type': "application/x-www-form-urlencoded"
        }
        zoom_refresh_token = self.sanitize_data(self.zoom_refresh_token)
        zoom_client_id = self.sanitize_data(self.zoom_client_id)
        zoom_client_secret = self.sanitize_data(self.zoom_client_secret)
        zoom_access_token_url = self.sanitize_data(self.zoom_access_token_url)

        combine = zoom_client_id + ':' + zoom_client_secret
        userAndPass = base64.b64encode(combine.encode()).decode("ascii")

        headers = {'Authorization': 'Basic {}'.format(userAndPass)}

        payload = {
            'grant_type': 'refresh_token',
            'refresh_token': zoom_refresh_token,
        }
        try:
            refresh_token_response = requests.request("POST", zoom_access_token_url, headers=headers, data=payload)

            if refresh_token_response.status_code == 200:

                try:
                    # try getting JSON repr of it
                    parsed_response = refresh_token_response.json()
                    if 'access_token' in parsed_response:
                        _logger.info("REFRESHING ACCESS TOKEN {}".format(parsed_response.get('access_token')))
                        self.zoom_access_token = parsed_response.get('access_token')
                        self.zoom_refresh_token = parsed_response.get('refresh_token')
                except Exception as ex:
                    raise Warning("EXCEPTION : {}".format(ex))
            elif refresh_token_response.status_code == 401:
                _logger.error("Access token/refresh token is expired")
            else:
                raise Warning("We got a issue !!!! Desc : {}".format(refresh_token_response.text))
        except Exception as e:
            _logger.error(_("Error : %s"%e))

    def sanitize_data(self, field_to_sanitize):
        '''
            This method sanitizes the data to remove UPPERCASE and
            spaces between field chars
            @params : field_to_sanitize(char)
            @returns : field_to_sanitize(char)
        '''
        return field_to_sanitize.strip()

    def get_headers(self, type=False):
        headers = {}
        headers['Authorization'] = 'Bearer ' + str(self.zoom_access_token)
        headers['accept'] = 'application/json'
        if type:
            headers['Content-Type'] = 'application/json'
        else:
            headers['Content-Type'] = 'text/plain'
        return headers

    @api.model
    def _scheduler_login_authentication(self):
        user_id = self.env['res.users'].search([])
        if user_id:
            for user in user_id:
                if user.zoom_refresh_token:
                    user.refresh_token_from_access_token()
                else:
                    _logger.warning('Please Authenticate for User %s' % user.name)