import scrapy
from scrapy import Request

class TrilhasTDC(scrapy.Spider):
    name = "trilhas_tdc"

    start_urls = [
        "http://www.thedevelopersconference.com.br/tdc/2018/saopaulo/trilhas"
    ]

    def parse(self, response):
        colunas = response.xpath('//div[contains(@class, "col-sp")]')

        for coluna in colunas:
            dia = coluna.xpath('./h4/text()').extract_first()
            links_trilhas = coluna.xpath('./a/@href').extract()
            for link_trilha in links_trilhas:
                yield Request(
                    url=response.urljoin(link_trilha),
                    callback=self.parse_trilha,
                    meta={
                        'dia' : dia,
                    }
                )
    def parse_trilha(self,response):
        yield{
            'dia' : response.meta.get('dia'),
            'titulo' : response.xpath('//h1[@class="titulo-trilha"]/text()').extract_first(),
            'subtitulo': response.xpath('//h1[@class="titulo-trilha"]/small/text()').extract_first(),
            'descricao': response.xpath('//div[@class="lead"]//p/text()').extract(),
            'link' : response.url,
        }


"""
Main launching point of the Top Patch Server
"""
import base64
import uuid
import os
import logging
import logging.config

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.options

from redis import StrictRedis
from rq import Connection, Queue

from server.handlers import RootHandler, RvlLoginHandler, RvlLogoutHandler
from server.handlers import WebSocketHandler, AdminHandler
from receiver.api.core.newagent import NewAgentV1
from receiver.api.core.checkin import CheckInV1
from receiver.api.core.startup import StartUpV1
from receiver.api.rv.results import *
from receiver.api.core.results import *
from receiver.api.rv.updateapplications import UpdateApplicationsV1
from receiver.api.ra.results import RemoteDesktopResults
from receiver.api.monitoring.monitoringdata import UpdateMonitoringStatsV1

from db.client import *
from scheduler.jobManager import start_scheduler

from tornado.options import define, options

#import newrelic.agent
#newrelic.agent.initialize('/opt/TopPatch/conf/newrelic.ini')

define("port", default=9001, help="run on port", type=int)
define("debug", default=True, help="enable debugging features", type=bool)

class Application(tornado.web.Application):
    def __init__(self, debug):
        handlers = [

            #Operations for the Monitoring Plugin
            (r"/rvl/v1/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})/monitoring/monitordata/?", UpdateMonitoringStatsV1),

            #RA plugin
            (r"/rvl/ra/rd/results/?", RemoteDesktopResults),

            #Login and Logout Operations
            (r"/rvl/?", RootHandler),
            (r"/rvl/login/?", RvlLoginHandler),
            (r"/rvl/logout/?", RvlLogoutHandler),

            #Operations for the New Core Plugin
            (r"/rvl/v1/core/newagent/?", NewAgentV1),
            (r"/rvl/v1/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})/core/startup/?", StartUpV1),
            (r"/rvl/v1/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})/core/checkin/?", CheckInV1),
            (r"/rvl/v1/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})/rv/updatesapplications/?", UpdateApplicationsV1),
            (r"/rvl/v1/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})/core/results/reboot/?", RebootResultsV1),
            (r"/rvl/v1/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})/core/results/shutdown/?", ShutdownResultsV1),

            #New Operations for the New RV Plugin
            (r"/rvl/v1/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})/rv/results/install/apps/os?",
                InstallOsAppsResults),
            (r"/rvl/v1/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})/rv/results/install/apps/custom?",
                InstallCustomAppsResults),
            (r"/rvl/v1/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})/rv/results/install/apps/supported?",
                InstallSupportedAppsResults),
            (r"/rvl/v1/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})/rv/results/install/apps/agent?",
                InstallAgentAppsResults),
            (r"/rvl/v1/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})/rv/results/uninstall?",
                UnInstallAppsResults),

        ]

        template_path = "/opt/TopPatch/tp/templates"
        settings = {
            "cookie_secret": "patching-0.7",
            "login_url": "/rvl/login",
        }
        tornado.web.Application.__init__(self, handlers,
                                         template_path=template_path,
                                         debug=True, **settings)

    def log_request(self, handler):
        logging.config.fileConfig('/opt/TopPatch/conf/logging.config')
        log = logging.getLogger('rvweb')
        log_method = log.debug
        if handler.get_status() <= 299:
            log_method = log.info
        elif handler.get_status() <= 399 and \
                handler.get_status() >= 300:
            log_method = log.warn
        elif handler.get_status() <= 499 and \
                handler.get_status() >= 400:
            log_method = log.error
        elif handler.get_status() <= 599 and \
                handler.get_status() >= 500:
            log_method = log.error
        request_time = 1000.0 * handler.request.request_time()
        real_ip = handler.request.headers.get('X-Real-Ip', None)
        #remote_ip = handler.request.remote_ip
        #uri = handler.request.remote_ip
        forwarded_ip = handler.request.headers.get('X-Forwarded-For', None)
        user_agent = handler.request.headers.get('User-Agent')
        log_message = '%d %s %s, %.2fms' % (handler.get_status(), handler._request_summary(), user_agent, request_time)
        if real_ip:
            log_message = (
                '%d %s %s %s %s, %.2fms' %
                (
                    handler.get_status(), handler._request_summary(),
                    real_ip, forwarded_ip, user_agent, request_time
                )
            )
        log_method(log_message)

if __name__ == '__main__':
    tornado.options.parse_command_line()
    https_server = tornado.httpserver.HTTPServer(
        Application(options.debug),
        ssl_options={
            "certfile": os.path.join(
                "/opt/TopPatch/tp/data/ssl/",
                "server.crt"),
            "keyfile": os.path.join(
                "/opt/TopPatch/tp/data/ssl/",
                "server.key"),
        }
    )
    https_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()


#!/usr/bin/env python

import tensorflow as tf
import numpy as np
# from tensorflow.examples.tutorials.mnist import input_data

def init_weights(shape):
    return tf.Variable(tf.random_normal(shape, stddev=0.01))

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
trX = trX.reshape(-1, 28, 28, 1)  # 28x28x1 input img
teX = teX.reshape(-1, 28, 28, 1)  # 28x28x1 input img

X = tf.placeholder("float", [None, 28, 28, 1])
Y = tf.placeholder("float", [None, 10])

w = init_weights([3, 3, 1, 32])       # 3x3x1 conv, 32 outputs
w2 = init_weights([3, 3, 32, 64])     # 3x3x32 conv, 64 outputs
w3 = init_weights([3, 3, 64, 128])    # 3x3x32 conv, 128 outputs
w4 = init_weights([128 * 4 * 4, 625]) # FC 128 * 4 * 4 inputs, 625 outputs
w_o = init_weights([625, 10])         # FC 625 inputs, 10 outputs (labels)

p_keep_conv = tf.placeholder("float")
p_keep_hidden = tf.placeholder("float")
py_x = model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y))
train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)
predict_op = tf.argmax(py_x, 1)

def model(X, w_o):
    l1a = tf.nn.relu(tf.nn.conv2d(X, w,                       # l1a shape=(?, 28, 28, 32)
                        strides=[1, 1, 1, 1], padding='SAME'))
    l1 = tf.nn.max_pool(l1a, ksize=[1, 2, 2, 1],              # l1 shape=(?, 14, 14, 32)
                        strides=[1, 2, 2, 1], padding='SAME')
    l1 = tf.nn.dropout(l1, p_keep_conv)

    l2a = tf.nn.relu(tf.nn.conv2d(l1, w2,                     # l2a shape=(?, 14, 14, 64)
                        strides=[1, 1, 1, 1], padding='SAME'))
    l2 = tf.nn.max_pool(l2a, ksize=[1, 2, 2, 1],              # l2 shape=(?, 7, 7, 64)
                        strides=[1, 2, 2, 1], padding='SAME')
    l2 = tf.nn.dropout(l2, p_keep_conv)

    l3a = tf.nn.relu(tf.nn.conv2d(l2, w3,                     # l3a shape=(?, 7, 7, 128)
                        strides=[1, 1, 1, 1], padding='SAME'))
    l3 = tf.nn.max_pool(l3a, ksize=[1, 2, 2, 1],              # l3 shape=(?, 4, 4, 128)
                        strides=[1, 2, 2, 1], padding='SAME')
    l3 = tf.reshape(l3, [-1, w4.get_shape().as_list()[0]])    # reshape to (?, 2048)
    l3 = tf.nn.dropout(l3, p_keep_conv)

    l4 = tf.nn.relu(tf.matmul(l3, w4))
    l4 = tf.nn.dropout(l4, p_keep_hidden)

    pyx = tf.matmul(l4, w_o)
    return pyx


__author__ = "Vanessa Sochat, Alec Scott"
__copyright__ = "Copyright 2021-2022, Vanessa Sochat and Alec Scott"
__license__ = "Apache-2.0"

from paks.utils.names import namer
from paks.logger import logger
import paks.utils
import paks.defaults
import paks.templates
import paks.commands
import paks.settings

import subprocess
import select
import string
import pty
import termios
import tty
import os
import sys
import re

class ContainerName:
    """
    Parse a container name into named parts
    """

    def __init__(self, raw):
        self.raw = raw
        self.registry = None
        self.repository = None
        self.tool = None
        self.version = None
        self.digest = None
        self.parse(raw)
        self._name = None

    @property
    def extended_name(self):
        if not self._name:
            self._name = namer.generate()
        return self.slug + "-" + self._name

    @property
    def name(self):
        if not self._name:
            self._name = namer.generate()
        return self._name

    @property
    def slug(self):
        slug = ""
        for attr in [self.registry, self.repository, self.tool, self.version]:
            if attr and not slug:
                slug = attr.replace(".", "")
            elif attr and slug:
                slug = slug + "-" + attr.replace(".", "")
        return slug

    def parse(self, raw):
        """
        Parse a name into known pieces
        """
        match = re.search(paks.templates.docker_regex, raw)
        if not match:
            logger.exit("%s does not match a known identifier pattern." % raw)
        for key, value in match.groupdict().items():
            value = value.strip("/") if value else None
            setattr(self, key, value)

class ContainerTechnology:
    """
    A base class for a container technology
    """

    def __init__(self, settings=None):
        if not settings:
            settings = paks.settings.Settings(paks.defaults.settings_file)
        self.settings = settings

    def get_history(self, line, openpty):
        """
        Given an input with some number of up/down and newline, derive command.
        """
        up = line.count("[A")
        down = line.count("[B")
        change = up - down

        # pushed down below history
        if change <= 0:
            return ""
        history = self.hist.run(
            container_name=self.uri.extended_name,
            out=openpty,
            history_file=self.settings.history_file,
            user=self.settings.user,
        )
        history = [x for x in history.split("\n") if x]

        if not history:
            return ""

        if change > len(history):
            return ""

        # here we are looking back up into history (negative index)
        newline = history[-1 * change]

        # Add back any characters typed
        newline += re.split("(\[A|\[B)", line, 1)[-1]
        return newline

    def encode(self, msg):
        return bytes((msg).encode("utf-8"))

    def interactive_command(self, cmd):
        """
        Ensure we always restore original TTY otherwise terminal gets messed up
        """
        # Controller to get history
        self.hist = self.commands.history

        # save original tty setting then set it to raw mode
        old_tty = termios.tcgetattr(sys.stdin)
        old_pty = termios.tcgetattr(sys.stdout)
        try:
            self._interactive_command(cmd)
        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
            termios.tcsetattr(sys.stdout, termios.TCSADRAIN, old_pty)

    def run_executor(self, string_input, openpty):
        """
        Given a string input, run executor
        """
        string_input = string_input.replace("[A", "").replace("[B", "")
        if not string_input.startswith("#"):
            return

        executor = self.commands.get_executor(string_input, out=openpty)
        if executor is not None:

            # Provide pre-command message to the terminal
            if executor.pre_message:
                print("\n\r" + executor.pre_message)

            # If we have an executor for the command, run it!
            # All commands require the original / current name
            result = executor.run(
                name=self.image,
                container_name=self.uri.extended_name,
                original=string_input,
            )
            if result.message:
                print("\r" + result.message)

    def clean(self, string_input):
        string_input = re.sub(
            r"[^a-zA-Z0-9%s\n\r\w ]" % string.punctuation, "", string_input
        )
        return string_input.replace("\x1b", "")

    def welcome(self, openpty):
        """
        Welcome the user and clear terminal
        """
        # Don't add commands executed to history
        os.write(openpty, self.encode(" export PROMPT_COMMAND='history -a'\r"))
        os.write(openpty, self.encode(" clear\r"))
        os.write(openpty, self.encode(" ### Welcome to PAKS! ###\r"))

    def _interactive_command(self, cmd):
        """
        Run an interactive command.
        """
        tty.setraw(sys.stdin.fileno())

        # open pseudo-terminal to interact with subprocess
        openpty, opentty = pty.openpty()

        # use os.setsid() make it run in a new process group, or bash job control will not be enabled
        p = subprocess.Popen(
            cmd,
            preexec_fn=os.setsid,
            stdin=opentty,
            stdout=opentty,
            stderr=opentty,
            universal_newlines=True,
        )

        # Welcome to Paks!
        self.welcome(openpty)
        string_input = ""

        while p.poll() is None:
            r, w, e = select.select([sys.stdin, openpty], [], [])
            if sys.stdin in r:
                terminal_input = os.read(sys.stdin.fileno(), 10240)
                new_char = terminal_input.decode("utf-8")

                # if we have a backspace (ord 127)
                if len(new_char) == 1 and ord(new_char) == 127:

                    # Backspace to empty line
                    if len(string_input) > 0:
                        string_input = string_input[:-1]
                    if not string_input:
                        os.write(openpty, terminal_input)
                        continue
                else:
                    string_input = string_input + new_char

                # Get rid of left/right
                string_input = string_input.replace("[D", "").replace("[C", "")
                has_newline = "\n" in string_input or "\r" in string_input

                # Replace weird characters and escape sequences
                string_input = self.clean(string_input)

                # Universal exit command
                if "exit" in string_input and has_newline:
                    print("\n\rContainer exited.\n\r")
                    return self.uri.extended_name

                # Pressing up or down, but not enter
                if ("[A" in string_input or "[B" in string_input) and not has_newline:
                    string_input = self.get_history(string_input, openpty)
                    os.write(openpty, terminal_input)
                    continue

                # Pressing up or down with enter
                if ("[A" in string_input or "[B" in string_input) and has_newline:
                    string_input = self.get_history(string_input, openpty)
                    os.write(openpty, terminal_input)

                if not string_input:
                    continue

                # If we have a newline (and possibly a command)
                if has_newline:
                    self.run_executor(string_input, openpty)

                    # Add derived line to the history
                    os.write(openpty, terminal_input)
                    string_input = ""
                else:
                    os.write(openpty, terminal_input)

            elif openpty in r:
                o = os.read(openpty, 10240)
                if o:
                    os.write(sys.stdout.fileno(), o)

    def __str__(self):
        return str(self.__class__.__name__)


import os

import yaml

def book_ids_from_frontmatter(frontmatter):
    '''Return a list of book id hashes from frontmatter of list file.'''
    sections = yaml.load(frontmatter)['sections']

    books = []
    for section in sections:
        for source in section['listings']:
            if source['type'] == 'book':
                books.append(source['id'])

    return books

def get_asins_from_files(book_data_paths):
    '''Given list of file paths, return list of ASIN strings in YAML \
    frontmatter in specified files.'''
    asins = []

    for path in book_data_paths:
        book_file = open(path)
        book_yaml = grab_yaml_frontmatter(book_file)
        asins.append(str(yaml.load(book_yaml)['amzn']))
        book_file.close()

    return asins

def get_book_data_paths(list_file_path, books):
    '''Given root book data directory, return list of paths to files that \
    match book id hashes in given list of hashes.'''
    book_data_dir = os.path.abspath(list_file_path) + '/../../../../../_books'
    book_data_dir = os.path.abspath(book_data_dir)

    book_data_paths = []
    for path, visit, arg in os.walk(book_data_dir):
        for filename in arg:
            if os.path.splitext(filename)[1] == '.bib':
                for book in books:
                    if filename.find(book) >= 0:
                        book_data_paths.append(path + '/' + filename)

    return book_data_paths

def grab_yaml_frontmatter(f):
    '''Given a file, return YAML frontmatter as string, if present'''
    yaml_result = ''

    if f.readline() == '---\n':
        yaml_active = True
        for line in f.readlines():
            if yaml_active:
                if line != '---\n':
                    yaml_result += line
                else:
                    yaml_active = False

    return yaml_result


# enter a no and print the sum of the 1st and last digits of that no
number = int(input("Enter a no:"))
first = number % 10
while number != 0:
    rem = number % 10
    number = number // 10

print("the sum of the 1st and last digits is:", first+rem)


import os
import re
from pathlib import Path
summary = ""

def get_sql(name, docs, cat, markdown, docs_url):
    return f"INSERT INTO `ae-expression` ( `name`, `docs`, `cat`, `markdown`, `docs_url`) VALUES ( {name}, {docs}, {cat}, {markdown}, {docs_url});"

def get_content(file_path, docs, cat):

    with open(file_path, "r", encoding='utf-8') as file:
        markdown_text = file.read()
        # print(markdown_text)
        reg = r'^##.+\n[^#]+'
        result = re.findall(reg, markdown_text, re.M)
        for res in result:
            name = res.split("\n\n")[0]
            markdown = "\n".join(res.split("\n\n")[1:])
            # get_sql()
            cat = Path(file_path).name
            print(name.replace("## ", "").replace("(", "").replace(")", ""))
            docs = docs
            cat = cat.replace(".md", "")
            get_sql(name, docs, cat, markdown, "")
            print(markdown)

def print_folder_tree(folder_path, cat=""):
    # 遍历文件夹中的所有文件和子文件夹
    global summary
    global index
    index += 1
    for entry in os.scandir(folder_path):
        if index > 2:
            return
        summary += "\n"
        if entry.is_dir():
            print_folder_tree(entry.path, entry.name)
            ...
        elif entry.name != "summary.md":
            get_content(entry.path)

# with open('data.txt', "r+", encoding='utf-8') as file:
#     file_content = file.read()
#     file.seek(0)
#     file.truncate()
#     file.write("# Title\n" + file_content)

root_dir = r"H:\Scripting\Vue Projects\docs2_yuelili_com\AE\expression"

# print_folder_tree(root_dir)
# get_content(
#     r"H:\Scripting\Vue Projects\docs2_yuelili_com\AE\expression\General\Global.md")


import json
from socket import *
import base64

def client_json(ip, port, obj):
    # 创建TCP Socket并连接
    sockobj = socket(AF_INET, SOCK_STREAM)
    sockobj.connect((ip, port))

    if 'exec_cmd' in obj.keys():
        send_obj = obj
    elif 'upload_file' in obj.keys():
        with open('{0}'.format(obj['upload_file']), 'rb') as f:
            read_data = f.read()
            bytes_b64code = base64.b64encode(read_data)
            send_obj = {'upload_file': obj['upload_file'], 'file_bit': bytes_b64code.decode()}
    elif 'download_file' in obj.keys():
        send_obj = obj

    # 把obj转换为JSON字节字符串
    send_message = json.dumps(send_obj).encode()
    # 读取1024字节长度数据, 准备发送数据分片
    send_message_fragment = send_message[:1024]
    # 剩余部分数据
    send_message = send_message[1024:]

    while send_message_fragment:
        sockobj.send(send_message_fragment)  # 发送数据分片（如果分片的话）
        send_message_fragment = send_message[:1024]  # 读取1024字节长度数据
        send_message = send_message[1024:]  # 剩余部分数据

    recieved_message = b''  # 预先定义接收信息变量
    recieved_message_fragment = sockobj.recv(1024)  # 读取接收到的信息，写入到接收到信息分片

    while recieved_message_fragment:
        recieved_message = recieved_message + recieved_message_fragment  # 把所有接收到信息分片重组装
        recieved_message_fragment = sockobj.recv(1024)

    return_data = json.loads(recieved_message.decode())

    if 'download_file' not in return_data.keys():
        print('收到确认数据:', return_data)
    else:
        print('收到确认数据:', return_data)
        # 应该考虑写入下载的文件名！但是由于使用了相同的目录测试！所以使用了’download_file.py‘
        with open('download_file.py', 'w+') as f:
            b4code_back = bytes(return_data['file_bit'], 'GBK')
            file_info = base64.b64decode(b4code_back)
            f.write(file_info.decode())
        print('下载文件{0}保存成功！'.format((obj.get('download_file'))))
    sockobj.close()

if __name__ == '__main__':
    # 使用Linux解释器 & WIN解释器
    port = 6666

    # 执行命令
    exec_cmd = {'exec_cmd': 'pwd'}
    client_json('192.168.0.188', port, exec_cmd)

    # 上传文件
    upload_file = {'upload_file': 'snmpv2_get_file.py'}
    client_json('192.168.0.188', port, upload_file)

    # 下载文件
    download_file = {'download_file': 'snmpv2_get_file.py'}
    client_json('192.168.0.188', port, download_file)


# -*- coding: utf-8 -*-
import scrapy
from junyang_spider.items import YouzySchoolBadgeItem

class SchoolBadgeSpider(scrapy.Spider):
    name = "school_badge"
    allowed_domains = ["youzy.cn"]
    start_urls = [
        "https://www.youzy.cn/college/search?page=1",
    ]
    custom_settings = {
        'ITEM_PIPELINES': {'gaokao.pipelines.SchoolBadgePipeline': 200}
    }

    def parse(self, response):
        for school in response.css("li.clearfix"):
            image_url = school.css('a img::attr("src")').extract_first()
            if image_url.find("http") != -1:
                item = YouzySchoolBadgeItem()
                item['school_name'] = school.css('a.name::text').extract_first()
                item['image_url'] = image_url
                yield item
        for i in range(2, 144):
            yield scrapy.Request('https://www.youzy.cn/college/search?page=%d' % i, callback=self.parse)


import numpy as np
import math
import matplotlib.pyplot as plt

class LotkaVolterra:
    """This class defines the Lotka--Voltera prey-predator
    system. There are 4 parameters in this class which
    define the evoluion of the system.

    Attributes:
        k_a     reproduction rate of the antelopes
        k_ca    death rate of antelopes when the meet cheetahs
        k_c     death rate of cheetahs
        k_a     reproduction rate of the cheetahs when they meet antelopes
    """
    def __init__(self,k_a,k_ca,k_c,k_ac):
        self.k_a = k_a
        self.k_ca = k_ca
        self.k_c = k_c
        self.k_ac = k_ac

    def __call__(self,x,t):
        y = np.zeros(len(x))
        y[0] = self.k_a*x[0]-self.k_ca*x[0]*x[1]
        y[1] = -self.k_c*x[1]+self.k_ac*x[0]*x[1]

        return y

class Logistic:
    """This class defines the Logistic population
    growth of a population which has a limited size C
    and a growth rate of nu.

    Attributes:
        nu    Growth rate of the population
        C     Limit sizeof the population
    """
    def __init__(self,nu,C):
        self.nu = nu
        self.C = C

    def __call__(self,x,t):
        return self.nu*(1-x/self.C)*x

class ExplicitEuler:
    """This class defines the Explicit Euler
    scheme for the numerical resolution of
    a differentiel equation.
    """
    def __init__(self,f):
        self.f = f

    def iterate(self,x0,t,dt):
        return x0+dt*self.f(x0,t)

class RK2:
    """This class defines the Runge-Kutta 2
    scheme for the numerical resolution of
    a differentiel equation.
    """
    def __init__(self,f):
        self.f = f

    def iterate(self,x0,t,dt):
        return x0+dt*self.f(x0+dt/2*self.f(x0,t),t+dt/2)

class Integrator:
    """This class defines the Integration
    of a differential equation between tMin and tMax
    with N discretization steps and x0 as an initial condition
    """
    def __init__(self,method,x0,tMin,tMax,N):
        self.x0   = x0
        self.tMin = tMin
        self.tMax = tMax
        self.dt   = (tMax - tMin)/(N-1)

        self.f = method

    def getIntegrationTime(self):
        return np.arange(self.tMin,self.tMax+self.dt,self.dt)

    def integrate(self):
        x = np.array([self.x0])
        for t in np.arange(self.tMin,self.tMax,self.dt):
            x = np.append( x, [self.f.iterate(x[-1,:],t,self.dt)],axis=0)
        return x

# Plots the data in a 2d plot
def plotData(x,y,color,legend):
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')

    plt.rc('xtick', labelsize=20)
    plt.rc('ytick', labelsize=20)
    plt.ylabel('$a(t),c(t)$',fontsize=20)
    plt.xlabel('$t$', fontsize=20)

    plt.plot(x,y,color,linewidth=2.0,label=legend)
    plt.legend(loc=2,prop={'size':20})

# Parametric plot of x vs y
def parametricPlotData(x,y,color,xAxis,yAxis,legend):
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')

    plt.rc('xtick', labelsize=20)
    plt.rc('ytick', labelsize=20)
    plt.xlabel('$'+xAxis+'$',fontsize=20)
    plt.ylabel('$'+yAxis+'$',fontsize=20)

    plt.plot(x,y,color,linewidth=2.0,label=legend)
    plt.legend(loc=2,prop={'size':20})

# Plot the population of the antelope and the cheetah
x0 = np.array([2, 4])
tmin = 0
tmax = 100

rk2 = Integrator(RK2(LotkaVolterra(1,1,0.5,0.5)),x0,tmin,tmax,2000)
eul = Integrator(ExplicitEuler(LotkaVolterra(1,1,0.5,0.5)),x0,tmin,tmax,2000)

plotData(rk2.getIntegrationTime(),rk2.integrate()[:,0],'r-',"antelope (RK)")
plotData(rk2.getIntegrationTime(),rk2.integrate()[:,1],'b-',"cheetah (RK)")
plotData(eul.getIntegrationTime(),eul.integrate()[:,0],'g-',"antelope (E)")
plotData(eul.getIntegrationTime(),eul.integrate()[:,1],'m-',"cheetah (E)")

plt.show()

parametricPlotData(rk2.integrate()[:,0], rk2.integrate()[:,1],'r-','a(t)','c(t)',"6 ini (RK)")
parametricPlotData(eul.integrate()[:,0], eul.integrate()[:,1],'b-','a(t)','c(t)',"6 ini (E)")

plt.show()

# Compues the errror between 2 solutions with a given ratio
# in term of resolution points
def computeError(x,xRef,ratio):
    iMax = np.size(xRef,axis=0)
    totError = 0
    for i in np.arange(0,np.size(xRef,axis=1)):
        totError += math.sqrt(np.sum(np.square(x[:,i]-xRef[0:iMax:ratio,i])))/np.size(x[:,i])

    return totError

n_rk = np.array([1000, 2000, 4000, 8000])
n_e = np.array([1000, 2000, 4000, 8000])

n_ref = 16000
tmin = 0
tmax = 13

rk2 = Integrator(RK2(LotkaVolterra(1,1,0.5,0.5)),x0,tmin,tmax,n_ref)
solRefRK = rk2.integrate()

eul = Integrator(ExplicitEuler(LotkaVolterra(1,1,0.5,0.5)),x0,tmin,tmax,n_ref)
solRefE = eul.integrate()

errRK = []
for i in n_rk:
	rk = Integrator(RK2(LotkaVolterra(1,1,0.5,0.5)),x0,tmin,tmax,i)
	r_rk = n_ref//i
	errRK.append(computeError(rk.integrate(),solRefRK,r_rk))
	print(computeError(rk.integrate(),solRefRK,r_rk))

plt.loglog(n_rk,errRK,'ro',linewidth=2.0,label="RK2 error")
plt.loglog(n_rk,np.power(n_rk/10,-2),'k-',linewidth=2.0,label="-2 slope")
plt.legend(loc=3)
plt.show()

errE = []
for i in n_rk:
	e = Integrator(ExplicitEuler(LotkaVolterra(1,1,0.5,0.5)),x0,tmin,tmax,i)
	r_rk = n_ref//i
	errE.append(computeError(e.integrate(),solRefRK,r_rk))
	print(computeError(e.integrate(),solRefRK,r_rk))

plt.loglog(n_rk,errE,'ro',linewidth=2.0,label="Euler error")
plt.loglog(n_rk,np.power(n_e/100,-2),'k-',linewidth=2.0,label="-1 slope")
plt.legend(loc=3)
plt.show()


import MDAnalysis
import sys
import itertools
import tool
from argparse import ArgumentParser
"""
a = sys.argv
a.pop(0)
kai1 = [i for i in a if ".trr" in i]
kai2 = [i for i in a if ".pdb" in i]
kai3 = [i for i in a if "prob" in i]
kai4 = [i for i in a if ".trr" not in i and ".pdb" not in i
        and ".txt" not in i and ".dat" not in i]
a = []
a.append([0, 0])
a.append(kai1)
a.append(kai2)
a.append(kai3)
a.append(kai4)
"""
# a = [i.split() for i in a]
# a[1]:trr_path_list
# a[2]:pdb_path_list
# a[3]:prob_path_list
# a[4]:data processing
"""
1:only CA coordinates
2:chain A and chain B | only CA
3:select residue coordinates like["3","C","N","O"]
4:chain A and chain B | selesct ATOM
"""
a=[]
def get_option():
    argparser = ArgumentParser()
    argparser.add_argument("-trr","--trajectory",type=str,help="path of trr")
    argparser.add_argument("-pdb","--protein",type=str,help="path of pdb")
    argparser.add_argument("-prob","--probtxt",type=str,help="path of prob")
    argparser.add_argument("-cal","--caluculation",type=str,help="way of data processing")
    return argparser.parse_args()

def PDB_cal1(num1):
    num_pdb = []
    for i in open(a[1][num1], "r"):
        f = i.split()
        if f[2] == "CA":
            num_pdb.append(int(f[1]))
    return num_pdb

def PDB_cal2(num1):
    num_pdb = []
    kai_a = []
    kai_b = []
    for i in open(a[1][num1], "r"):
        f = i.split()
        if f[4] == "A" and f[2] == "CA":
            kai_a.append(int(f[1]))
        if f[4] == "B" and f[2] == "CA":
            kai_b.append(int(f[1]))
    num_pdb.append(kai_a)
    num_pdb.append(kai_b)
    return num_pdb

def PDB_cal3(num1):
    num_pdb = []
    for i in open(a[1][num1], "r"):
        f = i.split()
        if f[2] in a[3]:
            num_pdb.append(int(f[1]))
    return num_pdb

def PDB_cal4(num1):
    num_pdb = []
    kai_a = []
    kai_b = []
    for i in open(a[1][num1], "r"):
        f = i.split()
        if f[4] == "A" and f[2] in a[3]:
            kai_a.append(int(f[1]))
        if f[4] == "B" and f[2] in a[3]:
            kai_b.append(int(f[1]))
    num_pdb.append(kai_a)
    num_pdb.append(kai_b)
    return num_pdb

def PROB_cal(num1):
    num_prob = []
    num2 = 0
    for i in open(a[2][num1], "r"):
        if float(i) != 0:
            num_prob.append(num2)
        num2 += 1
    return num_prob

def main():
    global a
    args = get_option()
    a.append(str(args.trajectory).split(","))
    a.append(str(args.protein).split(","))
    a.append(str(args.probtxt).split(","))
    a.append(str(args.caluculation).split(","))
    if len(a[0]) == len(a[1]) and len(a[1]) == len(a[2]):
        print("go")
        for i in a[0]:
            num1 = a[0].index(i)
            if len(a[3]) > 1:
                if int(a[3][0]) == 4:
                    num_pdb = PDB_cal4(num1)
                elif int(a[3][0]) == 3:
                    num_pdb = PDB_cal3(num1)
            else:
                if int(a[3][0]) == 1:
                    num_pdb = PDB_cal1(num1)
                elif int(a[3][0]) == 2:
                    num_pdb = PDB_cal2(num1)
            num_prob = PROB_cal(num1)
            u = MDAnalysis.Universe(i)
            frm = u.trajectory
            del u
            if int(a[3][0]) == 2 or int(a[3][0]) == 4:
                for i in safe_mem_distance(frm, num_prob, num_pdb):
                    k = i.replace(",", "")
                    k = k.replace("[", "")
                    k = k.replace("]", "")
                    print(k)
            else:
                for i in safe_mem_coordinates(frm, num_prob, num_pdb):
                    k = i.replace(",", "")
                    k = k.replace("[", "")
                    k = k.replace("]", "")
                    print(k)
        else:
            print("not match kind of trr or pdb, prob")

def safe_mem_distance(frm, num_prob, num_pdb):
    num2 = 0
    for frm_num in frm:
        try:
            kai = []
            if num2 in num_prob:
                for i in safe_safe_distance(num_pdb, frm_num):
                    kai.append(i)
                yield str(kai)
                # del x, y, z, FRM, kai
        except StopIteration:
            del kai
            break
        num2 += 1

def safe_safe_distance(num_pdb, FRM):
    for j1, j2 in itertools.product(num_pdb[0], num_pdb[1]):
        yield tool.contact(float(FRM[j1][0]),
                           float(FRM[j1][1]),
                           float(FRM[j1][2]),
                           float(FRM[j2][0]),
                           float(FRM[j2][1]),
                           float(FRM[j2][2]))

def safe_mem_coordinates(frm, num_prob, num_pdb):
    frm_itr = iter(frm)
    num2 = 0
    while True:
        try:
            kai = []
            FRM = next(frm_itr)
            if num2 in num_prob:
                for j1 in num_pdb:
                    for j2 in range(3):
                        kai.append(float(FRM[j1][j2]))
                yield str(kai)
                # del x, y, z, FRM, kai
        except StopIteration:
            del kai
            break
        num2 += 1

if __name__ == '__main__':
    main()


'''
start: 7:58
end: 8:11
13 mins
constraint:
|nodes| > 0
'''
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        maxdiam = 0
        def helper(curr: TreeNode) -> int:
            nonlocal maxdiam
            if not curr:
                return 0
            leftdepth = helper(curr.left)
            rightdepth = helper(curr.right)
            maxdiam = max(maxdiam, leftdepth + rightdepth)
            return 1 + max(leftdepth, rightdepth)

        helper(root)
        return maxdiam


import sys
import pandas as pd
from sklearn.feature_selection import SelectKBest, mutual_info_regression
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt

# Load the dataset
#filename = sys.argv[1]
data = pd.read_csv('uploads/BigBasket.csv')

# Encode categorical variables using label encoding
le = LabelEncoder()
for column in data.columns:
    data[column] = le.fit_transform(data[column])

X = data[['index','product','category','sub_category','brand','sale_price','market_price','type','rating','description']]

y = data['brand']

# Use SelectKBest with mutual information to find the top 5 features
selector = SelectKBest(score_func=mutual_info_regression, k=5)
selector.fit(X, y)

# Print the top 5 features and their mutual information scores
top_features = selector.scores_
top_features_index = selector.get_support(indices=True)
feature_names = []
scores = []
for i, feature in enumerate(X.columns[top_features_index]):
    feature_names.append(feature)
    scores.append(top_features[top_features_index[i]])

# Sort the features based on their scores in descending order
sorted_features = sorted(zip(feature_names, scores), key=lambda x: x[1], reverse=True)
print("Top 5 features:")
for i in range(5):
    print(f'{i+1}. {sorted_features[i][0]} ({sorted_features[i][1]:.4f})')

# Define k-anonymity rules for the top 5 features
k_anonymity_rules = {
    'index': None,
    'product': 2,
    'category': 3,
    'sub_category': 3,
    'brand': 2
}

# Apply k-anonymity to the top 5 features based on the defined rules
for feature in sorted_features[:5]:
    feature_name = feature[0]
    k = k_anonymity_rules.get(feature_name, None)
    if k is not None:
        X[feature_name] = X[feature_name] // k * k

# Save the anonymized data to a new CSV file
output_filename = 'BigBasket_anonymized.csv'
X.to_csv(output_filename, index=False)

# Plot the feature selection scores
plt.bar(feature_names, scores)

# # Add labels and title
plt.xlabel('Feature')
plt.ylabel('Score')
plt.title('Feature Selection Scores')

# Show the plot
plt.show()

# Print the filenames of the output files
print(f'Anonymized dataset saved to {output_filename}')
# print(f'Feature selection scores plot saved to {plot_filename}')


import tkinter
from tkinter import *
from PIL import ImageTk, Image

# configure window
root = Tk()
windowColor = "#F2F2F2"
root.geometry("827x1500")
root.configure(bg = windowColor)
root.title("Train Build")

# create a container for canvas so window is scrollable
# window is a frame inside canvas that is a container for rest of application
container = Frame(root, bg = windowColor)
canvas = Canvas(container, bg = windowColor, bd=0, highlightthickness=0)
scrollbar = Scrollbar(container, orient="vertical", command=canvas.yview)
window = Frame(canvas, bg = windowColor)

# make canvas and window scrollable
window.bind(
    "<Configure>",
    lambda e: canvas.configure(
        scrollregion=canvas.bbox("all")
    )
)

canvas.create_window((0, 0), window=window, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)

# pack containers into root
container.pack(side="left", fill="both", expand=True)
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")

image1 = Image.open("Asset 4.png")
test = ImageTk.PhotoImage(image1)
label1 = tkinter.Label(image=test, width = 753, height = 355, bg=windowColor)
label1.place(x=150, y=25)

# span information frame
framea = LabelFrame(
    root,
    bg="#FFFFFF",
    bd=0,
    highlightthickness=0

)
framea.place(
    x=60,
    y=48,
    width=334,
    height=390
)

infoSpan = Label(root, text="Span Information", bg="#FFFFFF", font='Helvetica 22 bold')
infoSpan.place(x = 72, y = 64)

# start span name and label
startSpanEntry = Entry(
    bd=0,
    bg="#E6E6E6",
    fg="#000716",
    highlightthickness=0
)
startSpanEntry.configure(highlightbackground="black", highlightcolor="black")
startSpanEntry.place(
    x=292,
    y=104,
    width=87,
    height=22
)
startSpanLabel = Label(root, text="Start Span", bg="#FFFFFF")
startSpanLabel.place(x = 100, y = 108)

# end span name and label
endSpanEntry = Entry(
    bd=0,
    bg="#E6E6E6",
    fg="#000716",
    highlightthickness=0
)
endSpanEntry.configure(highlightbackground="black", highlightcolor="black")
endSpanEntry.place(
    x=292,
    y=139,
    width=87,
    height=22
)
endSpanLabel = Label(root, text="End Span", bg="#FFFFFF")
endSpanLabel.place(x = 100, y = 142)

# span increment name and label
incrementSpanEntry = Entry(
    bd=0,
    bg="#E6E6E6",
    fg="#000716",
    highlightthickness=0
)
incrementSpanEntry.configure(highlightbackground="black", highlightcolor="black")
incrementSpanEntry.place(
    x=292,
    y=174,
    width=87,
    height=22
)
incrementSpanLabel = Label(root, text="Span Increment", bg="#FFFFFF")
incrementSpanLabel.place(x = 100, y = 178)

llTypeOptionList = ["Custom", "Option", "Option", "Option"]

lltext = StringVar()
lltext.set(llTypeOptionList[0])
lloption = OptionMenu(root, lltext, *llTypeOptionList)
lloption.configure(highlightbackground="#FFFFFF")
lloption.place(x = 279, y = 215)

llTypeLabel = Label(root, text="LL Type", bg="#FFFFFF")
llTypeLabel.place(x = 100, y = 213)

infoSpan = Label(root, text="Moment/Stress Calculation Interval Locations", bg="#FFFFFF", font='Helvetica 13 bold')
infoSpan.place(x = 77, y = 248)

# start location name and label
startLocationEntry = Entry(
    bd=0,
    bg="#E6E6E6",
    fg="#000716",
    highlightthickness=0
)
startLocationEntry.configure(highlightbackground="black", highlightcolor="black")
startLocationEntry.place(
    x=292,
    y=279,
    width=87,
    height=22
)
startLocationLabel = Label(root, text="Start Location", bg="#FFFFFF")
startLocationLabel.place(x = 100, y = 283)

# end location name and label
endLocationEntry = Entry(
    bd=0,
    bg="#E6E6E6",
    fg="#000716",
    highlightthickness=0
)
endLocationEntry.configure(highlightbackground="black", highlightcolor="black")
endLocationEntry.place(
    x=292,
    y=314,
    width=87,
    height=22
)
endLocationLabel = Label(root, text="End Location", bg="#FFFFFF")
endLocationLabel.place(x = 100, y = 318)

# interval name and label
intervalEntry = Entry(
    bd=0,
    bg="#E6E6E6",
    fg="#000716",
    highlightthickness=0
)
intervalEntry.configure(highlightbackground="black", highlightcolor="black")
intervalEntry.place(
    x=292,
    y=349,
    width=87,
    height=22
)
intervalLabel = Label(root, text="Interval", bg="#FFFFFF")
intervalLabel.place(x = 100, y = 353)

# step size name and label
stepSizeEntry = Entry(
    bd=0,
    bg="#E6E6E6",
    fg="#000716",
    highlightthickness=0
)
stepSizeEntry.configure(highlightbackground="black", highlightcolor="black")
stepSizeEntry.place(
    x=292,
    y=384,
    width=87,
    height=22
)
stepSizeLabel = Label(root, text="Step Size", bg="#FFFFFF")
stepSizeLabel.place(x = 100, y = 388)

# loads frame
framec = LabelFrame(
    root,
    bg="#FFFFFF",
    bd=0,
    highlightthickness=0

)
framec.place(
    x=60,
    y=473,
    width=334,
    height=286
)

loadsDead = Label(root, text="Dead Loads", bg="#FFFFFF", font='Helvetica 22 bold')
loadsDead.place(x = 75, y = 489)

# girder type name and label

girderTypeOptionList = ["Custom", "Option", "Option", "Option"]

girdertext = StringVar()
girdertext.set(girderTypeOptionList[0])
girderoption = OptionMenu(root, girdertext, *girderTypeOptionList)
girderoption.configure(highlightbackground="#FFFFFF")
girderoption.place(x = 292, y = 529)

typeGirderLabel = Label(root, text="Girder Type", bg="#FFFFFF")
typeGirderLabel.place(x = 100, y = 533)

# deck type name and label
deckTypeOptionList = ["Custom", "Option", "Option", "Option"]

decktext = StringVar()
decktext.set(deckTypeOptionList[0])
deckoption = OptionMenu(root, decktext, *deckTypeOptionList)
deckoption.configure(highlightbackground="#FFFFFF")
deckoption.place(x = 292, y = 564)

typeDeckLabel = Label(root, text="Deck Type", bg="#FFFFFF")
typeDeckLabel.place(x = 100, y = 568)

loadsDead = Label(root, text="Cooper Loads", bg="#FFFFFF", font='Helvetica 22 bold')
loadsDead.place(x = 75, y = 597)

# cooper type name and label

cooperTypeOptionList = ["Custom", "Option", "Option", "Option"]

coopertext = StringVar()
coopertext.set(cooperTypeOptionList[0])
cooperoption = OptionMenu(root, coopertext, *cooperTypeOptionList)
cooperoption.configure(highlightbackground="#FFFFFF")
cooperoption.place(x = 292, y = 635)

typeCooperLabel = Label(root, text="Cooper Type", bg="#FFFFFF")
typeCooperLabel.place(x = 100, y = 639)

# cooper year name and label
cooperYearTypeOptionList = ["Custom", "Option", "Option", "Option"]

cooperYeartext = StringVar()
cooperYeartext.set(cooperYearTypeOptionList[0])
cooperYearoption = OptionMenu(root, cooperYeartext, *cooperYearTypeOptionList)
cooperYearoption.configure(highlightbackground="#FFFFFF")
cooperYearoption.place(x = 292, y = 670)

yearCooperLabel = Label(root, text="Cooper Year", bg="#FFFFFF")
yearCooperLabel.place(x = 100, y = 674)

# girder connection name and label
girderTypeOptionList = ["Custom", "Option", "Option", "Option"]

girdertext = StringVar()
girdertext.set(girderTypeOptionList[0])
girderoption = OptionMenu(root, girdertext, *girderTypeOptionList)
girderoption.configure(highlightbackground="#FFFFFF")
girderoption.place(x = 292, y = 705)

connectionGirderLabel = Label(root, text="Girder Connection", bg="#FFFFFF")
connectionGirderLabel.place(x = 100, y = 709)

valueImpact = Label(root, text="Impact Value", bg=windowColor, font='Helvetica 22 bold')
valueImpact.place(x = 448, y = 64)

# impact option and bridge
impactTypeOptionList = ["Unknown", "Option", "Option", "Option"]

impacttext = StringVar()
impacttext.set(impactTypeOptionList[0])
impactoption = OptionMenu(root, impacttext, *impactTypeOptionList)
impactoption.configure(highlightbackground="#FFFFFF")
impactoption.place(x = 633, y = 103)

impactTypeLabel = Label(root, text="Design Impact and Year", bg=windowColor)
impactTypeLabel.place(x = 474, y = 104)

# section modulus frame
frameb = LabelFrame(
    root,
    bg="#FFFFFF",
    bd=0,
    highlightthickness=0

)
frameb.place(
    x=433,
    y=282,
    width=334,
    height=477
)

# column labels
modulusSection = Label(root, text="Section Modulus", bg="#FFFFFF", font='Helvetica 22 bold')
modulusSection.place(x = 448, y = 300)

# section area load name and label
areaCheck1Value = IntVar()
areaCheck1 = Checkbutton(
    root,
    text = "Gross",
    variable = areaCheck1Value,
    onvalue = 1,
    offvalue = 0,
    bg = "#ffffff"
)
areaCheck1.place(
    x = 665,
    y = 341
)
areaCheck2Value = IntVar()
areaCheck2 = Checkbutton(
    root,
    text = "Net",
    variable = areaCheck2Value,
    onvalue = 1,
    offvalue = 0,
    bg = "#ffffff"
)
areaCheck2.place(
    x = 665,
    y = 368
)

areaSectionLabel = Label(root, text="Section Area", bg="#FFFFFF")
areaSectionLabel.place(x = 473, y = 340)

# number of girders name and label
girderSectionEntry = Entry(
    bd=0,
    bg="#E6E6E6",
    fg="#000716",
    highlightthickness=0
)
girderSectionEntry.configure(highlightbackground="black", highlightcolor="black")
girderSectionEntry.place(
    x=665,
    y=406,
    width=87,
    height=22
)
girderSectionLabel = Label(root, text="Number of Girders", bg="#FFFFFF")
girderSectionLabel.place(x = 473, y = 410)

# S value name and label
sValueEntry = Entry(
    bd=0,
    bg="#E6E6E6",
    fg="#000716",
    highlightthickness=0
)
sValueEntry.configure(highlightbackground="black", highlightcolor="black")
sValueEntry.place(
    x=665,
    y=445,
    width=87,
    height=22
)
sValueLabel = Label(root, text="S Value", bg="#FFFFFF")
sValueLabel.place(x = 473, y = 449)

# Hammer Blow name and label
blowCheck1Value = IntVar()
blowCheck1 = Checkbutton(
    root,
    text = "Yes",
    variable = blowCheck1Value,
    onvalue = 1,
    offvalue = 0,
    bg = "#ffffff"
)
blowCheck1.place(
    x = 665,
    y = 489
)
blowCheck2Value = IntVar()
blowCheck2 = Checkbutton(
    root,
    text = "No",
    variable = blowCheck2Value,
    onvalue = 1,
    offvalue = 0,
    bg = "#ffffff"
)
blowCheck2.place(
    x = 665,
    y = 516
)

blowHammerLabel = Label(root, text="Hammer Blow", bg="#FFFFFF")
blowHammerLabel.place(x = 473, y = 488)

modulusSection = Label(root, text="Fatigue", bg="#FFFFFF", font='Helvetica 22 bold')
modulusSection.place(x = 448, y = 547)

# mean impact load name and label
impactTypeOptionList = ["Custom", "Option", "Option", "Option"]

impacttext = StringVar()
impacttext.set(impactTypeOptionList[0])
impactoption = OptionMenu(root, impacttext, *impactTypeOptionList)
impactoption.configure(highlightbackground="#FFFFFF")
impactoption.place(x = 665, y = 587)

meanImpactLoadLabel = Label(root, text="Mean Impact Load", bg="#FFFFFF")
meanImpactLoadLabel.place(x = 473, y = 591)

# fatigue category name and label
fatigueTypeOptionList = ["Custom", "Option", "Option", "Option"]

fatiguetext = StringVar()
fatiguetext.set(fatigueTypeOptionList[0])
fatigueoption = OptionMenu(root, fatiguetext, *fatigueTypeOptionList)
fatigueoption.configure(highlightbackground="#FFFFFF")
fatigueoption.place(x = 665, y = 622)

categoryFatigueLabel = Label(root, text="Fatigue Category", bg="#FFFFFF")
categoryFatigueLabel.place(x = 473, y = 626)

# ignore stress name and label
ignoreStressEntry = Entry(
    bd=0,
    bg="#E6E6E6",
    fg="#000716",
    highlightthickness=0
)
ignoreStressEntry.configure(highlightbackground="black", highlightcolor="black")
ignoreStressEntry.place(
    x=665,
    y=657,
    width=87,
    height=22
)
ignoreStressLabel = Label(root, text="Ignore Stress", bg="#FFFFFF")
ignoreStressLabel.place(x = 473, y = 661)

#####################################################

# train frame
framet = LabelFrame(
    root,
    bg="#FFFFFF",
    bd=0,
    highlightthickness=0

)
framet.place(
    x=60,
    y=794,
    width=707,
    height=211
)

chooseTrain = Label(root, text="Choose Train", bg="#FFFFFF", font='Helvetica 22 bold')
chooseTrain.place(x = 92, y = 810)

#####################################################

# save button

# close button

##########################  tk mainloop ##########################
root.resizable(True, True)
root.mainloop()


#setuptools.setup is looking at one argv parameter; to "build" and "install":
#python3 setup.py install

#libtorrent from pypi has bindings and library now, before was:
#	python-libtorrent-bin is at extra require now, but, if was at install requires:
#		ok, package python-libtorrent-bin is old. install with pip install --no-deps but add somehow appdirs
#			and python-libtorrent on ubuntu
#			if it's not old python-libtorrent at pip:
#				that+(libtorrent-rasterbar2.0 on ubuntu) can be a solution

pkname='torra'

import pathlib
HERE = pathlib.Path(__file__).parent
#here README is ok, else will be README.md not found for pypi
README = (HERE / "info.md").read_text()
ver=(HERE / "v2").read_text()

from setuptools import setup
setup(name=pkname,
	version=ver,
	packages=[pkname],
	#opt
	python_requires='>=3',
	install_requires=["appdirs>=1.4.3"
		,"libtorrent"
		#python-libtorrent-bin it's not updated at pypi (old 3.9)
		#,'python-libtorrent-bin>=1.2.9' #;platform_system=="Linux" and platform_machine=="x86_64"'
		#,"python-apt"#is from 2012 0.7.8, missing DistUtilsExtra, sudo apt install python-apt is 2.2., verify with pip3 install python-apt
	],
	#extras_require={
	#	'bin': ['python-libtorrent-bin>=1.2.9']
	#	#,'apt': ['python-apt']
	#},
	description='Torrent client',
	long_description=README,
	long_description_content_type="text/markdown",
	url='https://github.com/colin-i/tora',
	author='cb',
	author_email='costin.botescu@gmail.com',
	license='MIT',
	entry_points = {
		'console_scripts': [pkname+'='+pkname+'.main:main']
	}
)


import logging
logger = logging.getLogger('camelot.view.controls.formview')

from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtCore import Qt

import sip

from camelot.view.art import Icon
from camelot.view.model_thread import post
from camelot.view.model_thread import model_function
from camelot.view.controls.view import AbstractView
from camelot.view.controls.statusbar import StatusBar
from camelot.view import register
from camelot.view.action import ActionFactory

class ContextMenuAction(QtGui.QAction):

    default_icon = Icon('tango/16x16/categories/applications-system.png')

    def __init__(self, parent, title, icon = None):
        """
        :param parent: the widget on which the context menu will be placed
        :param title: text displayed in the context menu
        :param icon: camelot.view.art.Icon object
        """
        super(ContextMenuAction, self).__init__(title, parent)
        self.icon = icon
        if self.icon:
            self.setIcon(self.icon.getQIcon())
        else:
            self.setIcon(self.default_icon.getQIcon())

class FormWidget(QtGui.QWidget):
    """A form widget comes inside a form view or inside an embedded manytoone editor"""

    changed_signal = QtCore.pyqtSignal()

    def __init__(self, parent, admin):
        QtGui.QWidget.__init__(self, parent)
        self._admin = admin
        widget_mapper = QtGui.QDataWidgetMapper(self)
        widget_mapper.setObjectName('widget_mapper')
        widget_layout = QtGui.QHBoxLayout()
        widget_layout.setSpacing(0)
        widget_layout.setMargin(0)
        self._index = 0
        self._model = None
        self._form = None
        self._columns = None
        self._delegate = None
        self.setLayout(widget_layout)

    def get_model(self):
        return self._model

    def set_model(self, model):
        self._model = model
        self._model.dataChanged.connect( self._data_changed )
        self._model.layoutChanged.connect( self._layout_changed )
        self._model.item_delegate_changed_signal.connect( self._item_delegate_changed )
        self._model.setObjectName( 'model' )
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if widget_mapper:
            widget_mapper.setModel( model )
            register.register( model, widget_mapper )

        def get_columns_and_form():
            return (self._model.getColumns(), self._admin.get_form_display())

        post(get_columns_and_form, self._set_columns_and_form)

    def clear_mapping(self):
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if widget_mapper:
            widget_mapper.clearMapping()

    def _data_changed(self, index_from, index_to):
        #@TODO: only revert if this form is in the changed range
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if widget_mapper:
            widget_mapper.revert()
        if not sip.isdeleted(self):
            self.changed_signal.emit()

    def _layout_changed(self):
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if widget_mapper:
            widget_mapper.revert()
        self.changed_signal.emit()

    @QtCore.pyqtSlot()
    def _item_delegate_changed(self):
        from camelot.view.controls.delegates.delegatemanager import \
            DelegateManager
        self._delegate = self._model.getItemDelegate()
        self._delegate.setObjectName('delegate')
        assert self._delegate != None
        assert isinstance(self._delegate, DelegateManager)
        self._create_widgets()

    def set_index(self, index):
        self._index = index
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if widget_mapper:
            widget_mapper.setCurrentIndex(self._index)

    def get_index(self):
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if widget_mapper:
            return widget_mapper.currentIndex()

    def submit(self):
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if widget_mapper:
            widget_mapper.submit()

    def to_first(self):
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if widget_mapper:
            widget_mapper.toFirst()
            self.changed_signal.emit()

    def to_last(self):
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if widget_mapper:
            widget_mapper.toLast()
            self.changed_signal.emit()

    def to_next(self):
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if widget_mapper:
            widget_mapper.toNext()
            self.changed_signal.emit()

    def to_previous(self):
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if widget_mapper:
            widget_mapper.toPrevious()
            self.changed_signal.emit()

    def export_ooxml(self):
        from camelot.view.export.word import open_stream_in_word

        def create_ooxml_export(row):
            # print self._columns
            def ooxml_export():
                # TODO insert delegates
                fields = self._admin.get_all_fields_and_attributes()
                delegates = {}
                for field_name, attributes in fields.items():
                    delegates[field_name] = attributes['delegate'](**attributes)
                obj = self._model._get_object(row)
                document = self._form.render_ooxml(obj, delegates)
                open_stream_in_word( document )

            return ooxml_export

        post(create_ooxml_export(self.get_index()))

    @QtCore.pyqtSlot(tuple)
    def _set_columns_and_form(self, columns_and_form ):
        self._columns, self._form = columns_and_form
        self._create_widgets()

    def _create_widgets(self):
        """Create value and label widgets"""
        from camelot.view.controls.field_label import FieldLabel
        from camelot.view.controls.editors.wideeditor import WideEditor
        #
        # Dirty trick to make form views work during unit tests, since unit
        # tests have no event loop running, so the delegate will never be set,
        # so we get it and are sure it will be there if we are running without
        # threads
        #
        if not self._delegate:
            self._delegate = self._model.getItemDelegate()
        #
        # end of dirty trick
        #
        # only if all information is available, we can start building the form
        if not (self._form and self._columns and self._delegate):
            return
        widgets = {}
        widget_mapper = self.findChild(QtGui.QDataWidgetMapper, 'widget_mapper' )
        if not widget_mapper:
            return
        widget_mapper.setItemDelegate(self._delegate)
        option = QtGui.QStyleOptionViewItem()
        # set version to 5 to indicate the widget will appear on a
        # a form view and not on a table view
        option.version = 5

        #
        # this loop can take a while to complete, so processEvents is called
        # regulary
        #
        for i, (field_name, field_attributes ) in enumerate( self._columns):
#            if i%10==0:
#                QtCore.QCoreApplication.processEvents(
#                    QtCore.QEventLoop.ExcludeSocketNotifiers,
#                    100
#                )
            model_index = self._model.index(self._index, i)
            hide_title = False
            if 'hide_title' in field_attributes:
                hide_title = field_attributes['hide_title']
            widget_label = None
            widget_editor = self._delegate.createEditor(
                self,
                option,
                model_index
            )
            widget_editor.setObjectName('%s_editor'%field_name)
            if not hide_title:
                widget_label = FieldLabel(
                    field_name,
                    field_attributes['name'],
                    field_attributes,
                    self._admin
                )
                widget_label.setObjectName('%s_label'%field_name)
                if not isinstance(widget_editor, WideEditor):
                    widget_label.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

            # required fields font is bold
            if ('nullable' in field_attributes) and \
               (not field_attributes['nullable']):
                font = QtGui.QApplication.font()
                font.setBold(True)
                widget_label.setFont(font)

            assert widget_editor != None
            assert isinstance(widget_editor, QtGui.QWidget)

            widget_mapper.addMapping(widget_editor, i)
            widgets[field_name] = (widget_label, widget_editor)

        widget_mapper.setCurrentIndex(self._index)
        self.layout().insertWidget(0, self._form.render(widgets, self))
        #self._widget_layout.setContentsMargins(7, 7, 7, 7)

class FormView(AbstractView):
    """A FormView is the combination of a FormWidget, possible actions and menu
    items

    .. form_widget: The class to be used as a the form widget inside the form
    view"""

    form_widget = FormWidget

    def __init__(self, title, admin, model, index):
        AbstractView.__init__(self)

        layout = QtGui.QVBoxLayout()
        form_and_actions_layout = QtGui.QHBoxLayout()
        form_and_actions_layout.setObjectName('form_and_actions_layout')
        layout.addLayout(form_and_actions_layout)

        self.model = model
        self.admin = admin
        self.title_prefix = title

        form = FormWidget(self, admin)
        form.setObjectName( 'form' )
        form.changed_signal.connect( self.update_title )
        form.set_model(model)
        form.set_index(index)
        form_and_actions_layout.addWidget(form)

        statusbar = StatusBar(self)
        statusbar.setObjectName('statusbar')
        statusbar.setSizeGripEnabled(False)
        layout.addWidget(statusbar)
        layout.setAlignment(statusbar, Qt.AlignBottom)
        self.setLayout(layout)

        self.change_title(title)

        if hasattr(admin, 'form_size') and admin.form_size:
            self.setMinimumSize(admin.form_size[0], admin.form_size[1])

        self.validator = admin.create_validator(model)
        self.validate_before_close = True

        def get_actions():
            return admin.get_form_actions(None)

        post(get_actions, self.setActions)
        self.update_title()
        #
        # Define actions
        #
        self.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.addAction( ActionFactory.view_first(self, self.viewFirst) )
        self.addAction( ActionFactory.view_last(self, self.viewLast) )
        self.addAction( ActionFactory.view_next(self, self.viewNext) )
        self.addAction( ActionFactory.view_previous(self, self.viewPrevious) )
        self.addAction( ActionFactory.refresh(self, self.refresh_session) )
        self.addAction( ActionFactory.export_ooxml(self, form.export_ooxml) )

    @QtCore.pyqtSlot()
    def refresh_session(self):
        from elixir import session
        from camelot.core.orm import refresh_session
        refresh_session( session )

    @QtCore.pyqtSlot()
    def refresh(self):
        """Refresh the data in the current view"""
        self.model.refresh()

    def update_title(self):

        def get_title():
            obj = self.getEntity()
            return u'%s %s' % (
                self.title_prefix,
                self.admin.get_verbose_identifier(obj)
            )

        post(get_title, self.change_title)

    def getEntity(self):
        form = self.findChild(QtGui.QWidget, 'form' )
        if form:
            return self.model._get_object(form.get_index())

    @QtCore.pyqtSlot(list)
    def setActions(self, actions):
        form = self.findChild(QtGui.QWidget, 'form' )
        layout = self.findChild(QtGui.QLayout, 'form_and_actions_layout' )
        if actions and form and layout:
            side_panel_layout = QtGui.QVBoxLayout()
            from camelot.view.controls.actionsbox import ActionsBox
            logger.debug('setting Actions for formview')
            actions_widget = ActionsBox(self, self.getEntity)
            actions_widget.setObjectName('actions')
            action_widgets = actions_widget.setActions(actions)
            for action_widget in action_widgets:
                form.changed_signal.connect( action_widget.changed )
                action_widget.changed()
            side_panel_layout.insertWidget(1, actions_widget)
            side_panel_layout.addStretch()
            layout.addLayout(side_panel_layout)

    def viewFirst(self):
        """select model's first row"""
        form = self.findChild(QtGui.QWidget, 'form' )
        if form:
            form.submit()
            form.to_first()

    def viewLast(self):
        """select model's last row"""
        # submit should not happen a second time, since then we don't want
        # the widgets data to be written to the model
        form = self.findChild(QtGui.QWidget, 'form' )
        if form:
            form.submit()
            form.to_last()

    def viewNext(self):
        """select model's next row"""
        # submit should not happen a second time, since then we don't want
        # the widgets data to be written to the model
        form = self.findChild(QtGui.QWidget, 'form' )
        if form:
            form.submit()
            form.to_next()

    def viewPrevious(self):
        """select model's previous row"""
        # submit should not happen a second time, since then we don't want
        # the widgets data to be written to the model
        form = self.findChild(QtGui.QWidget, 'form' )
        if form:
            form.submit()
            form.to_previous()

    @QtCore.pyqtSlot(bool)
    def showMessage(self, valid):
        form = self.findChild(QtGui.QWidget, 'form' )
        if not valid and form:
            reply = self.validator.validityDialog(
                form.get_index(), self
            ).exec_()
            if reply == QtGui.QMessageBox.Discard:
            # clear mapping to prevent data being written again to the model,
            # then we reverted the row
                form.clear_mapping()
                self.model.revertRow(form.get_index())
                self.validate_before_close = False
                self.close()
        else:
            self.validate_before_close = False
            self.close()

    def validateClose(self):
        logger.debug('validate before close : %s' % self.validate_before_close)
        form = self.findChild(QtGui.QWidget, 'form' )
        if self.validate_before_close and form:
            # submit should not happen a second time, since then we don't
            # want the widgets data to be written to the model
            form.submit()

            def validate():
                return self.validator.isValid(form.get_index())

            post(validate, self.showMessage)
            return False

        return True

    def closeEvent(self, event):
        #print 'close event'
        logger.debug('formview closed')
        if self.validateClose():
            event.accept()
        else:
            event.ignore()

    @model_function
    def toHtml(self):
        """generates html of the form"""
        from jinja2 import Environment

        def to_html(d = u''):
            """Jinja 1 filter to convert field values to their default html
            representation
            """

            def wrapped_in_table(env, context, value):
                if isinstance(value, list):
                    return u'

' + \
                           u'

'.join(
                                [unicode(e) for e in value]
                           ) + u'

'
                return unicode(value)

            return wrapped_in_table

        entity = self.getEntity()
        fields = self.admin.get_fields()
        table = [dict( field_attributes = field_attributes,
                      value = getattr(entity, name ))
                      for name, field_attributes in fields]

        context = {
          'title': self.admin.get_verbose_name(),
          'table': table,
        }

        from camelot.view.templates import loader
        env = Environment(loader = loader)
        env.filters['to_html'] = to_html
        tp = env.get_template('form_view.html')

        return tp.render(context)


from cumulusci.tasks.apex.anon import AnonymousApexTask
from cumulusci.core.exceptions import TaskOptionsError
import time

class SetBDIMappingMode(AnonymousApexTask):
    """Change the mapping mode for NPSP BGE/BDI."""
    task_docs = """
    Use the 'mode' argument to specify either 'Help Text' or 'Data Import Field Mapping'
    """

    help_text_apex = """
        BDI_MigrationMappingUtility.updateCustomSettings(
            BDI_MigrationMappingUtility.HELP_TEXT,
            String.valueOf(Metadata.DeployStatus.Succeeded));
    """

    data_import_field_mapping_apex = """
        BDI_MigrationMappingUtility migrationMappingUtility =
            new BDI_MigrationMappingUtility(
                new BDI_MigrationMappingHelper());
        migrationMappingUtility.migrateHelpTextToCustomMetadata();
        Id deploymentId = CMT_MetadataAPI.deployMetadata(
            migrationMappingUtility.queuedMetadataTypesForDeploy,
            new BDI_MigrationMappingUtility.DeploymentCallback());
    """

    task_options = {
        "mode": {
            "description": "'Help Text' or 'Data Import Field Mapping'",
            "required": True,
        },
    }

    def get_org_namespace_prefix(self):
        managed = self.options.get("managed") or False
        namespaced = self.options.get("namespaced") or False

        if managed or namespaced:
            return "npsp__"
        else:
            return ""

    def _validate_options(self):
        if self.options.get("mode") == "Help Text":
            self.options["apex"] = self.help_text_apex
        elif self.options.get("mode") == "Data Import Field Mapping":
            self.options["apex"] = self.data_import_field_mapping_apex
        else:
            raise TaskOptionsError(
                "You must specify mode as either 'Help Text' or 'Data Import Field Mapping'"
            )

        super()._validate_options()

    def _run_task(self):
        super()._run_task()
        self.logger.info("Deploying BDI mode {mode}".format(mode=self.options.get("mode")))
        for i in range(0, 600):
            if self._get_di_mode() == self.options.get("mode"):
                return
            self.logger.info("Waiting for BDI metadata to deploy.")
            time.sleep(3)
        raise AssertionError("Data Import mode never updated!")

    def _get_di_mode(self):
        soql = "SELECT {token}Field_Mapping_Method__c FROM {token}Data_Import_Settings__c"
        soql = soql.format(token=self.get_org_namespace_prefix())
        res = self.sf.query_all(soql)
        if res["records"]:
            return res["records"][0][
                "{token}Field_Mapping_Method__c".format(
                    token=self.get_org_namespace_prefix()
                )
            ]


from collections import deque

def solution(stats):
    queue = deque(stats)
    answer = []
    while queue:
        x = queue.popleft()
        length = len(answer)
        if length < 1:
            answer.append([x])
        else:
            max_index = -1
            for i in range(length):
                if answer[i][-1] < x:
                    max_index = i
                    break
            if max_index == -1:
                answer.append([x])
            else:
                answer[max_index].append(x)

    return len(answer)

if __name__ == "__main__":
    stats = [6, 2, 3, 4, 1, 5]
    print(solution(stats))


import numpy as np
import cv2
import pickle
import glob
import matplotlib.pyplot as plt
import os
import Lane_find_functions as Lff
import function_parameters as FP
import time

# video_name = 'test_video_4lanes_1.13.mp4'
# image_folder = './Test_images/dashcam_driving/'

# video_name = 'challenge_video_4lanes_1.8.mp4'
# image_folder = './Test_images/challnege_video/'

# video_name = 'harder_challenge_video_4lanes_1.8_fullscreen.mp4'
# image_folder = './Test_images/harder_challenge_video/'
#
# video_name = 'project_video_4lanes_1.11_confidence.mp4'
# image_folder = './Test_images/project_video/'

count=0
filename = 'frame_count'
filename2 = 'calculated_binary_combinations'

def main():
    global count
    video_name = FP.video_name
    image_folder = FP.dashcam_image_path

    frame = cv2.imread(image_folder+"frame1.jpg")
    height, width, layers = frame.shape

    # fullscreen=False
    if FP.fullscreen is False:
        height,width=960,1280
    else:
        height,width=720,1280

    print(frame.shape)
    #video = cv2.VideoWriter(video_name, -1, 1, (width,height))
    video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'XVID'), 30, (width,height))
    success=1
    # count = 215
    count = 0

    while success:
        start = time.time()

        outfile = open(filename,'wb')
        pickle.dump(count,outfile)
        outfile.close()

        org_image = cv2.imread(image_folder+"frame%d.jpg" % count)
        image=org_image
        # image = cv2.resize(org_image,(360,640))
        # image = cv2.resize(org_image,(180,320))
        # save frame as JPEG file
        #if image is None or count > 300:                             # if image was not read successfully
        if image is None:                             # if image was not read successfully
            print ("error: image not read from file \n\n")        # print error message to std out
            success = 0                                 # pause so user can see error message
      #success,image = vidcap.read()
        #imgOriginal=oszv.pipeline(image)
        infile = open(filename2,'rb')
        new_count = pickle.load(infile)
        infile.close()
        print('xdxdxdxdxdxd '+str(new_count))
        FP.binary_combinations=new_count
        processed_image =Lff.process_image_4lanes(image, FP.fullscreen)
        cv2.putText(processed_image, 'frame ' + str(count), (40,80), cv2.FONT_HERSHEY_DUPLEX, 1, (255,0,0), 1, cv2.LINE_AA)
        #processed_image = cv2.resize(processed_image,width,height)
        video.write(processed_image)
        count += 1
        end = time.time()
        # print('frames_to_video_dynamic time= '+str(end - start)+'sec')
        print('______________________________________')
        print('|    wrote a new frame: ', count,'   |',str(end - start)+'sec')
        print('______________________________________')
        f = open("fps_test_log.txt", "a")
        write_line=str(FP.video_tip)+' '+'frame:'+str(count)+' '+str(end - start)+' sec'+'\n'
        f.write(write_line)
    cv2.destroyAllWindows()
    video.release()
    f.close()

    return

###################################################################################################
if __name__ == "__main__":
    main()


from gameObject import GameObject
import pygame, time

FALL_VELOCITY = (0, 3.9)
NULL_VELOCITY = (0, 0)
FLAPPING_VELOCITY = (0, -4.5)
FLAPPING_MAX_TIME = 0.15
BIRD_RADIUS = 15
WINDOW_WIDTH = 480

COLOR_RED = (255, 0, 0)

class Bird(GameObject):
    def __init__(self, x, y, color, brain):
        GameObject.__init__(self, x, y, BIRD_RADIUS, BIRD_RADIUS, FALL_VELOCITY)
        self.color = color
        self.isFlapping = False
        self.flappingTime = 0
        self.brain = brain
        self.isAlive = True
        self.score = 0
        self.drawable = True

    def draw(self, surface):
        if self.drawable:
            pygame.draw.circle(surface, self.color, (self.bounds.x, self.bounds.y), self.bounds.height, self.bounds.width)

    def update(self, inputs):
        inputs[1] -= BIRD_RADIUS
        inputs[2] += BIRD_RADIUS
        if not self.isAlive:
            self.color = COLOR_RED
            if self.bounds.y < WINDOW_WIDTH - 10:
                self.speed = FALL_VELOCITY
            else:
                self.drawable = False
                self.speed = NULL_VELOCITY
        else:
            if self.isFlapping and time.time() - self.flappingTime >= FLAPPING_MAX_TIME:
                self.speed = FALL_VELOCITY
                self.isFlapping = False
            else:
                prediction = self.brain.feed_forward(inputs)
                if len(prediction) == 1 or (len(prediction) > 1 and prediction[0] < prediction[1]):
                    self.flap()

                if inputs[1] < 0 < inputs[2]:
                    self.brain.increment_fitness(1)

            if 0 >= inputs[0] > -2 and inputs[1] < 0 < inputs[2]:
                self.brain.increment_fitness(100)
                self.score += 1

        self.move(*self.speed)

    def flap(self):
        if not self.isFlapping:
            self.flappingTime = time.time()
            self.speed = FLAPPING_VELOCITY
            self.isFlapping = True


# Train model
import sys
import time
import numpy as np
import torch.optim as optim
import pickle
import os
import torch.utils.data
import model as m
import argparse

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("--doc_len", type=int, default=300)

    parser.add_argument("--lr", type=float, default=0.001)
    parser.add_argument("--batchSize", type=int, default=32)
    parser.add_argument("--num_workers", type=int, default=4)
    parser.add_argument("--flg_cuda", action='store_true')

    parser.add_argument("--optType", default='Adam')  # Vocabulary size

    parser.add_argument("--logInterval", type=int, default=1)  # Print test accuracy every n epochs
    parser.add_argument("--flgSave", action='store_true')
    parser.add_argument("--savePath", default='./')
    parser.add_argument("--randSeed", type=int, default=42)
    parser.add_argument("--inputPath", default="../aclImdb/df07f20K_stopEng_W_1gram/")
    parser.add_argument("--modelPath")

    args = parser.parse_args()

    torch.manual_seed(args.randSeed)  # For reproducible results

    if not os.path.isdir(args.savePath):
        os.mkdir(args.savePath)

    print('General parameters: ', args)

    print("Loading Data")
    # if args.modelName in ['Enc_SumLSTM', 'Enc_CNN_LSTM']:
    #trainset = m.MovieDataset(args.inputPath, 'train.json', transform=m.padToTensor(args.doc_len))
    testset = m.MovieDataset(args.inputPath, 'test.json', transform=m.padToTensor(args.doc_len))

    print('To Loader')
    if args.flg_cuda:
        #train_loader = torch.utils.data.DataLoader(trainset, batch_size=args.batchSize, shuffle=True, pin_memory=True)
        test_loader = torch.utils.data.DataLoader(testset, batch_size=args.batchSize, shuffle=False, pin_memory=True)
    else:
        #train_loader = torch.utils.data.DataLoader(trainset, batch_size=args.batchSize, shuffle=True, pin_memory=False)
        test_loader = torch.utils.data.DataLoader(testset, batch_size=args.batchSize, shuffle=False, pin_memory=False)

    print("Loading model")
    if args.flg_cuda:
        model = torch.load(args.modelPath + '_model.pt')
        model = model.cuda()
    else:
        model = torch.load(args.modelPath + '_model.pt', map_location=lambda storage, loc: storage)

    print(model)

    if args.optType == 'Adam':
        opt = optim.Adam(model.params, lr=args.lr)
    elif args.optType == 'SGD':
        opt = optim.SGD(model.params, lr=args.lr)

    print("Beginning Training")
    train_paras = {'log_interval': [args.logInterval, 1000], 'flg_cuda': args.flg_cuda,
                   'flgSave': args.flgSave, 'savePath': args.savePath}

    m = m.trainModel(train_paras, None, test_loader, model, opt)
    m._test(0)


# Approach 1: Bit Manipulation

# Time: O(n), n = no. of bits of the number
# Space: O(1)

class Solution:
    def minFlips(self, a: int, b: int, c: int) -> int:
        answer = 0
        while a or b or c:
            if c & 1:
                answer += 0 if ((a & 1) or (b & 1)) else 1
            else:
                answer += (a & 1) + (b & 1)

            a >>= 1
            b >>= 1
            c >>= 1

        return answer


from turtle import Turtle

class ScoreBoard(Turtle):

    def __init__(self):
        super().__init__()
        self.color("white")
        self.penup()
        self.hideturtle()
        self.left_score = 0
        self.right_score = 0
        self.update_scoreboard()

    def update_scoreboard(self):
        self.clear()  # important because the scores would be overwritten by the previous score
        self.goto(-100, 200)
        self.write(self.left_score, align="center", font=("Courier", 80, "normal"))
        self.goto(100, 200)
        self.write(self.right_score, align="center", font=("Courier", 80, "normal"))

    def update_left_score(self):
        self.left_score += 1
        self.update_scoreboard()

    def update_right_score(self):
        self.right_score += 1
        self.update_scoreboard()

    def gameover(self):
        self.goto(0,0)
        self.write("GAME OVER", align="center", font=("Courier", 80, "normal"))


import random

import cv2
import numpy as np

import sys
sys.path.insert(1, 'build/lib')

from va_rs import augment

original_cube = np.zeros((32, 32, 32), dtype=np.float32)
original_cube[12:20, 12:20, 12:20] = 1.0
original_cube = original_cube[None, ...]

linear_cube = original_cube.copy()
nearest_cube = original_cube.copy()

rotations = (20, 4, 1)
translations = tuple(np.random.rand(3) * 6 - 3)  # <-3, +3>
scaling = tuple(np.random.rand(3) * 0.2 + 0.9)  # <0.9; 1.1>
raw_cube_multipliers = (random.random() * 0.2 + 0.9,)  # (<0.9; 1.1>, 1.0) - don't multiply frangi data

linear_cube = augment(linear_cube, rotations, interpolation='linear')
nearest_cube = augment(nearest_cube, rotations, interpolation='nearest')

for i in range(32):
    cv2.imshow('original', original_cube[0, i, ...])
    cv2.imshow('linear', linear_cube[0, i, ...])
    cv2.imshow('nearest', nearest_cube[0, i, ...])
    cv2.waitKey()


import sys
import subprocess
from PyQt5 import uic, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow

form_class = uic.loadUiType("./testBtn.ui")[0]

class WindowClass(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.testBtn.clicked.connect(self.toggle_exe)
        self.testBtn2.clicked.connect(self.toggle2_exe)
        self.testBtn3.clicked.connect(self.toggle3_exe)
        self.proc = None

    def toggle_exe(self):
        if self.proc is None:
            self.start_exe()
        else:
            self.stop_exe()

    def start_exe(self):
        if self.proc is None:
            self.statusBar().showMessage("음성인식 파일 실행중...")
            self.proc = subprocess.Popen(["python", "C:\\main_ui\\voicecommand_final.py"])
            self.testBtn.setText("음성인식 종료")  # 버튼 텍스트 변경

    def stop_exe(self):
        if self.proc is not None:
            subprocess.run(['taskkill', '/f', '/t', '/pid', str(self.proc.pid)])
            self.proc = None
            self.testBtn.setText("음성인식 실행")  # 버튼 텍스트 변경
            self.statusBar().showMessage("음성인식 종료")

    def toggle2_exe(self):
        if self.proc is None:
            self.start2_exe()
        else:
            self.stop2_exe()

    def start2_exe(self):
        if self.proc is None:
            self.statusBar().showMessage("모션인식 파일 실행중...")
            self.proc = subprocess.Popen(["python", "C:\main_ui\motion_final.py"])
            self.testBtn2.setText("모션인식 종료")  # 버튼 텍스트 변경

    def stop2_exe(self):
        if self.proc is not None:
            subprocess.run(['taskkill', '/f', '/t', '/pid', str(self.proc.pid)])
            self.proc = None
            self.testBtn2.setText("모션인식 실행")  # 버튼 텍스트 변경
            self.statusBar().showMessage("모션인식 종료")

    def toggle3_exe(self):
        if self.proc is None:
            self.start3_exe()
        else:
            self.stop3_exe()

    def start3_exe(self):
        if self.proc is None:
            self.statusBar().showMessage("아이트레킹 파일 실행중...")
            self.proc = subprocess.Popen(["python", "C:\main_ui\eyetrac_final.py"])
            self.testBtn3.setText("아이트레킹 종료")  # 버튼 텍스트 변경

    def stop3_exe(self):
        if self.proc is not None:
            subprocess.run(['taskkill', '/f', '/t', '/pid', str(self.proc.pid)])
            self.proc = None
            self.testBtn3.setText("아이트레킹 실행")  # 버튼 텍스트 변경
            self.statusBar().showMessage("아이트레킹 종료")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWindow = WindowClass()
    myWindow.show()
    sys.exit(app.exec_())


import matplotlib.pyplot as plt
import xgboost as xgb
import os
from constants import *
from time import gmtime, strftime
from src.models.model_learner import ModelLearner
from src.models.csv_handler import save_feature_importance_res

class XgboostTrainObj(ModelLearner):

    def __init__(self,org_name):
        self.m_name = 'Xgboost'
        self.model_name = 'Xgboost'
        ModelLearner.__init__(self,org_name)

    def train_model(self,models_folder_name,model_name,datasets):
        super().prep_model_training(datasets)
        print("---Start training {0} on {1}---\n".format(self.model_name,self.org_name))
        self.model = xgb.XGBClassifier(kwargs=XGBS_PARAMS).fit(self.x, self.y, eval_metric=["error", "logloss"], eval_set=[(self.xval, self.yval)])
        print("---Learning Curves---\n")
        # self.plot_learning_curves()
        model_name = os.path.join(MODELS_OBJECTS_PATH, models_folder_name, f"{model_name}.dat")
        self.model.save_model(model_name)
        print("---{0} model saved---\n".format(self.model_name))

    def plot_learning_curves(self):
        results = self.model.evals_result()
        epochs = len(results['validation_0']['error'])
        x_axis = range(0, epochs)
        fig, ax = plt.subplots(figsize=(12, 12))
        ax.plot(x_axis, results['validation_0']['logloss'], label='Train')
        ax.plot(x_axis, results['validation_1']['logloss'], label='Test')
        ax.legend()
        plt.ylabel('Log Loss')
        plt.title('XGBoost Log Loss')
        plt.savefig(os.path.join(MODELS_OUTPUT_PATH, 'XGBoost {0} Log Loss.png'.format(self.org_name)))
        fig, ax = plt.subplots(figsize=(12, 12))
        ax.plot(x_axis, results['validation_0']['error'], label='Train')
        ax.plot(x_axis, results['validation_1']['error'], label='Test')
        ax.legend()
        plt.ylabel('Classification Error')
        plt.title('XGBoost Classification Error')
        plt.savefig(os.path.join(MODELS_OUTPUT_PATH, 'XGBoost {0} Classification Error.png'.format(self.org_name)))
        plt.clf()

    def model_explain(self):
        print("---Explain model---\n")
        # self.feature_importance()
        super().model_explain()

    def feature_importance(self):
        print("feature_importances\n")
        importance = self.model.feature_importances_
        f_important = sorted(list(zip(self.feature_names, importance)), key=lambda x: x[1], reverse=True)
        save_feature_importance_res('{0}_{1}'.format(self.model_name,self.org_name),f_important,'reg')

        plt.bar([x[0] for x in f_important[:5]], [x[1] for x in f_important[:5]])
        plt.xticks(rotation=20)
        title = '{0} {1} f_important'.format(self.model_name, self.org_name)
        plt.title(title)
        plt.savefig(os.path.join(MODELS_FEATURE_IMPORTANCE, '{0}.png'.format(title)))
        plt.clf()


import json

def create_row_w_validated_params(cls, validated_params, rqst_errors):
    found_rows_w_rqst_name = cls.check_for_rows_with_rqst_name(
        validated_params['name'],
        rqst_errors
    )

    new_row = None
    if not found_rows_w_rqst_name and not rqst_errors:
        new_row = cls()
        new_row.name = validated_params['name']
        new_row.save()

    return new_row

def update_row_w_validated_params(cls, validated_params, rqst_errors):
    rqst_id = validated_params['id']
    found_rows_w_rqst_name = cls.check_for_rows_with_rqst_name(
        validated_params['name'],
        rqst_errors,
        rqst_id
    )

    rqst_row = None
    if not found_rows_w_rqst_name and not rqst_errors:
        try:
            rqst_row = cls.objects.get(id=rqst_id)
            rqst_row.name = validated_params['name']
            rqst_row.save()
        except cls.DoesNotExist:
            rqst_errors.append("Row does not exist for database id: {}".format(rqst_id))

    return rqst_row

def delete_row_w_validated_params(cls, validated_params, rqst_errors):
    rqst_id = validated_params['id']

    try:
        row = cls.objects.get(id=rqst_id)
        row.delete()
    except cls.DoesNotExist:
        rqst_errors.append("Row does not exist for database id: {}".format(rqst_id))

def check_for_rows_with_rqst_name(cls, rqst_name, rqst_errors, current_id=None):
    found_row_w_name = False

    rows_w_rqst_name = cls.objects.filter(name__iexact=rqst_name)

    if rows_w_rqst_name:
        found_row_w_name = True

        rows_w_rqst_name_ids = []
        len_of_rows_w_rqst_name = len(rows_w_rqst_name)
        for row in rows_w_rqst_name:
            rows_w_rqst_name_ids.append(row.id)

        if len_of_rows_w_rqst_name > 1:
            rqst_errors.append(
                "Multiple rows with name: {} already exist in db. (Hint - Delete one and modify the remaining) id's: {}".format(
                    rqst_name, json.dumps(rows_w_rqst_name_ids)))
        else:
            if not current_id or current_id not in rows_w_rqst_name_ids:
                rqst_errors.append(
                    "Row with name: {} already exists in db. (Hint - Modify that entry) id: {}".format(
                        rqst_name, rows_w_rqst_name_ids[0]))
            else:
                found_row_w_name = False

    return found_row_w_name