import os
import copy
import json
import werkzeug.exceptions
import exceptions
import datetime
import starflyer
import sessions

class Handler(object):
    """a request handler which is also the base class for an application"""

    template="" # default template to use
    use_hooks = True # set to False if you don't want the before_handler hooks to be used for this handler

    def __init__(self, app, request, module = None):

        """initialize the Handler with the calling application and the request
        it has to handle.

        :param app: The ``Application`` instance this handler belongs to
        :param request: The request object
        :param module: The module from which we might have been called. ``None`` if it was the main app
        """

        self.app = app
        self.request = request
        self.module = module
        self.config = app.config
        self.url_adapter = request.url_adapter
        self.flashes = None
        self.session = None

        # retrieve a session if available
        self.session = self.app.open_session(self.request)
        if self.session is None:
            self.session = self.app.make_null_session()
        # note that session saving is happening in the app as some hooks could run before that

    ####
    #### before and after request hooks
    ####

    def before(self):
        """This method will be called before the request will be processed.
        You can override it in order to do your own processing before the
        actual handler logic is processed. If you return a response value
        (a String, Response, etc.) then processing is stopped and the handler
        logic is not called but instead the Response is returned directly.
        """
        pass

    def after(self, response):
        """This is the hook for response post processing.

        This method will be called before the request will be processed.
        You can override it in order to do your own processing before the
        actual handler logic is processed. If you return a response value
        (a String, Response, etc.) then processing is stopped and the handler
        logic is not called but instead the Response is returned directly.
        """
        return response

    ### TODO: what about changing the Response during the handler?
    ### right now we have an existing one already but what if we want
    ### to change headers? Do it via decorators only? Maybe better, also for
    ### testing.

    ####
    #### FLASH MANAGING
    ####

    def flash(self, msg, category="info"):
        """add a new flash message

            (copied nearly verbatim from flask)
            :param msg: the message to be flashed.
            :param category: the category for the message.  The following values
                are recommended: ``'message'`` for any kind of message,
                ``'error'`` for errors, ``'info'`` for information
                messages and ``'warning'`` for warnings.  However any
                kind of string can be used as category.
        """
        flashes = self.session.get('_flashes', [])
        flashes.append((category, unicode(msg)))
        self.session['_flashes'] = flashes

    def get_flashes(self, with_categories=False, category_filter=[]):
        """Pulls all flashed messages from the session and returns them.
        Further calls in the same request to the function will return
        the same messages.  By default just the messages are returned,
        but when `with_categories` is set to `True`, the return value will
        be a list of tuples in the form ``(category, message)`` instead.

        Filter the flashed messages to one or more categories by providing those
        categories in `category_filter`.  This allows rendering categories in
        separate html blocks.  The `with_categories` and `category_filter`
        arguments are distinct:

        * `with_categories` controls whether categories are returned
            with message text (`True` gives a tuple, where `False`
            gives just the message text).
        * `category_filter` filters the messages down to only those
            matching the provided categories.

        :param with_categories: set to `True` to also receive categories.
        :param category_filter: whitelist of categories to limit return values

        (copied somewhat verbatim from flask)
        """

        session = self.session
        flashes = session.pop('_flashes') if '_flashes' in session else []
        if category_filter:
            flashes = filter(lambda f: f[0] in category_filter, flashes)
        if not with_categories:
            return [x[1] for x in flashes]
        return flashes

    ####
    #### i18n MANAGEMENT
    ####

    def _(self, s, **kw):
        """dummy method for "translating" messages by simply passing them through. This is usally
        replaced on the fly by modules such as ``sf-babel``.

        :param s: string to translate
        """
        return s

    ####
    #### URL MANAGEMENT
    ####

    def url_for(self, endpoint = None,  _full = False, _append=False, **kwargs):
        """return a URL generated from the mapper"""
        if endpoint[0] == ".": # we might be in a module with a relative path
            if self.module is not None:
                endpoint = "%s.%s" %(self.module.name, endpoint[1:])
            else:
                endpoint = endpoint[1:] # remove dot if module not found
        return self.request.url_adapter.build(
                endpoint,
                kwargs,
                force_external = _full,
                append_unknown = _append)

    ####
    #### RENDER RELATED
    ####

    @property
    def default_render_context(self):
        """return the default template rendering environment. This is the starting point
        and any additional property or method like ``render_context`` will update this
        dictionary.
        """
        return dict(
            handler = self,
            request = self.request,
            session = self.session,
            url_for = self.url_for,
            config = self.config,
            get_flashes = self.get_flashes,
            gettext = lambda x: x                   # dummy i18n handler for jinja2
        )

    @property
    def template_globals(self):
        """return global variables to be used inside a template. Note that these are cached!"""
        return dict(
            url_for = self.url_for,
            M = self.app.module_map
        )

    @property
    def render_context(self):
        """provide attributes to a to template to be rendered by adding
        it to the provided ``params`` dictionary and returning it.
        """
        return dict()

    def render(self, tmplname=None, **kwargs):
        """render a template. If the ``tmplname`` is given, it will render
        this template otherwise take the default ``self.template``. You can
        pass in kwargs which are then passed to the template on rendering."""
        if tmplname is None:
            tmplname = self.template

        params = starflyer.AttributeMapper(self.default_render_context)
        for module in self.app.modules:
            params.update(module.get_render_context(self))
        params.update(self.app.get_render_context(self))
        params.update(self.render_context)
        params.update(kwargs)

        # if we are called from a module, we try the module prefix for loading the template
        if self.module is not None:
            # construct relative path which also allows for .. and /
            path = os.path.normpath(os.path.join("_m", self.module.name, tmplname))
            tmpl = self.app.jinja_env.get_or_select_template(path, globals = self.template_globals)
        else:
            tmpl = self.app.jinja_env.get_or_select_template(tmplname, globals = self.template_globals)
        return tmpl.render(**params)

    def __call__(self, **m):
        """handle a single request. This means checking the method to use,
        looking up the method for it and calling it. We have to return a WSGI
        application"""

        method = self.request.method
        method = self.request.values.get("method", method)
        method = method.lower()

        # if method is not present in handler, return Method Not Allowed
        if not hasattr(self, method):
            return werkzeug.exceptions.MethodNotAllowed()

        rv = self.before()
        if rv is None:
            # call the handler only if we not already have a response value
            rv = getattr(self, method)(**m)

        # create the response
        response = self.make_response(rv)

        # return the post processed response
        return self.after(response)

    def make_response(self, rv):
        """Converts the return value from a handler to a real
        response object that is an instance of :attr:`app.response_class`.

        The following types are allowed for `rv`:

        .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|

        ======================= ===========================================
        :attr:`response_class`  the object is returned unchanged
        :class:`str`            a response object is created with the
                                string as body
        :class:`unicode`        a response object is created with the
                                string encoded to utf-8 as body
        a WSGI function         the function is called as WSGI application
                                and buffered as response object
        :class:`tuple`          A tuple in the form ``(response, status,
                                headers)`` where `response` is any of the
                                types defined here, `status` is a string
                                or an integer and `headers` is a list of
                                a dictionary with header values.
        ======================= ===========================================

        :param rv: the return value from the view function

        """
        status = headers = None
        if isinstance(rv, tuple):
            rv, status, headers = rv + (None,) * (3 - len(rv))

        if rv is None:
            raise ValueError('Handler did not return a response')

        if not isinstance(rv, self.app.response_class):
            # When we create a response object directly, we let the constructor
            # set the headers and status.  We do this because there can be
            # some extra logic involved when creating these objects with
            # specific values (like defualt content type selection).
            if isinstance(rv, basestring):
                rv = self.app.response_class(rv, headers=headers, status=status)
                headers = status = None
            else:
                rv = self.app.response_class.force_type(rv, self.request.environ)

        if status is not None:
            if isinstance(status, basestring):
                rv.status = status
            else:
                rv.status_code = status
        if headers:
            rv.headers.extend(headers)

        return rv


from typing import Optional

# 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 insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
    #     res = root
    #     parent = None
    #     while root and root.val > val:
    #         parent = root
    #         root = root.right

    #     if not parent:
    #         return TreeNode(val, root)
    #     else:
    #         parent.right = TreeNode(val, root)

    #     return res

    def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if not root or root.val < val:
            return TreeNode(val, root)
        root.right = self.insertIntoMaxTree(root.right, val)
        return root


from .parse_bmi_category import Bmi_Category_Manager
from .bmi_manager import Bmi_Manager
from dask.dataframe.core import DataFrame
import pandas as pd

class Bmi_Calculator():

    output_columns = ['Category', 'Risk']
    columns_to_consider = ['BMI Category', 'Health risk']
    bmi_file_name: str
    category_file: str
    category_df: DataFrame
    bmi_df: DataFrame

    @classmethod
    def compute_bmi(cls, df: DataFrame) -> DataFrame:
        df = df.copy()
        df[cls.output_columns] = df['BMI'].apply(
            lambda x: cls.category_df.iloc[cls.category_df.index.get_loc(x)][cls.columns_to_consider])
        return df

    @classmethod
    def setup(cls):
        Bmi_Category_Manager.category_file = cls.category_file
        Bmi_Manager.bmi_file_name = cls.bmi_file_name
        cls.category_df: DataFrame = Bmi_Category_Manager.bmi_category()
        cls.bmi_df: DataFrame = Bmi_Manager.build_bmi_df()

    @classmethod
    def build_bmi_risk(cls) -> DataFrame:
        cls.setup()
        cls.category_df.index = cls.category_index(cls.category_df)
        df = cls.map_and_build_bmi_risk(cls.bmi_df)
        return df

    @classmethod
    def map_and_build_bmi_risk(cls, bmi_df: DataFrame) -> DataFrame:
        df = bmi_df.map_partitions(cls.compute_bmi)
        return df

    @classmethod
    def category_index(cls, category_df: DataFrame) -> DataFrame:
        cls.category_df = category_df
        return pd.IntervalIndex.from_arrays(
            category_df['Low'], category_df['Hi'], closed='both')


import click
from cli.cassandra_db_handler import CassandraDBHandler
from cli.constants import LOGGING_CONFIGURATION_FILE_PATH
from cli.utils import load_yaml

class CallsGetCommand:
    """Calls get command class.

    Attributes:
        _duration: Duration of the calls to be retrieved.
        _phone_number: Caller phone number of the calls to be retrieved (optional).
    """

    def __init__(
        self,
        duration: str,
        phone_number: str,
    ):
        """Initialize the class."""
        self._duration = duration
        self._phone_number = phone_number
        self._db_configs = load_yaml(LOGGING_CONFIGURATION_FILE_PATH)

    def run(self):
        """Executes the command."""

        cassandra_handler = CassandraDBHandler(host=self._db_configs['server']['host'],
                                               port=self._db_configs['server']['port'],
                                               keyspace=self._db_configs['cassandra']['keyspace'])
        calls_percentage = cassandra_handler.get_successful_calls(duration=self._duration, user_phone_number=self._phone_number)
        click.echo(calls_percentage)

@click.group()
def calls():
    """Used to interact with the calls command group."""

@calls.command(name="get", help="Defines get command for calls group.")
@click.option("--duration", type=click.STRING, required=True, help="Duration of the desired calls")
@click.option("--phone-number", type=click.STRING, required=False, help="User Phone Number of the desired calls")
def _get(
    duration: str,
    phone_number: str,
):
    CallsGetCommand(
        duration=duration,
        phone_number=phone_number,
    ).run()


import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn.model_selection as sk
import xlrd

DATA_FILE = 'slr05.xls'
# Import Data
book = xlrd.open_workbook(DATA_FILE, encoding_override="utf-8")
sheet = book.sheet_by_index(0)
data = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)])
n_samples = sheet.nrows - 1

df = pd.read_excel(DATA_FILE)

# Create placeholders for input X (number of fire) and label (number of theft)
X = tf.placeholder(tf.float32, name='X')
Y = tf.placeholder(tf.float32, name='Y')

# Create weight and bias
w = tf.Variable(0.0, name='weights')
b = tf.Variable(0.0, name='bias')

# Y = wX + b - construct model to predict
y_predicted = w * X + b

# Square error - loss function
loss = tf.square(Y - y_predicted, name='loss')

# Gradient descent with learning rate 0.01 - minimize loss
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for i in range(100):
        print("Epoch {}".format(i + 1))
        for x, y in data:
            _, l = sess.run([optimizer, loss], feed_dict={X: x, Y: y})

    w_value, b_value = sess.run([w, b])

print(w_value, b_value)
print(l)

y_p = w_value * df['X'] + b_value
plt.scatter(df['X'], df['Y'])
plt.plot(df['X'], y_p, color='r')
plt.show()


#!/usr/bin/python
import os
import sys
import subprocess
import RPi.GPIO as GPIO
import time
import signal
import buttonshim
from fetch_nouns_vert import *
from active_proposals import *
from pending_proposals import *

print("""
Button SHIM: control-main.py

Light up the LED a different color of the rainbow with each button pressed.
""")

# Define button press functions
def button_a_pressed():
    print("Button A pressed")

def button_b_pressed():
    print("Button B pressed")

def button_c_pressed():
    pending_proposals_function()
    print("Button C script finished running")

def button_d_pressed():
    active_proposals_function()
    print("Button D script finished running")

def button_e_pressed():
    fetch_nouns_vert_function()
    print("Button E script finished running")

# Set up Button SHIM
button_shim = ButtonShim()

# Define button handlers
button_shim.set_handler('A', button_a_pressed)
button_shim.set_handler('B', button_b_pressed)
button_shim.set_handler('C', button_c_pressed)
button_shim.set_handler('D', button_d_pressed)
button_shim.set_handler('E', button_e_pressed)

@buttonshim.on_press(buttonshim.BUTTON_A)
def button_a(button, pressed):
    global button_flag
    button_flag = "button_1"

@buttonshim.on_press(buttonshim.BUTTON_B)
def button_b(button, pressed):
    global button_flag
    button_flag = "button_2"

@buttonshim.on_press(buttonshim.BUTTON_C)
def button_c(button, pressed):
    global button_flag
    button_flag = "button_3"

@buttonshim.on_press(buttonshim.BUTTON_D)
def button_d(button, pressed):
    global button_flag
    button_flag = "button_4"

@buttonshim.on_press(buttonshim.BUTTON_E)
def button_e(button, pressed):
    global button_flag
    button_flag = "button_5"

# Start main loop
button_flag = "null"
while True:
    time.sleep(.1)
    if button_flag == "button_1":
        buttonshim.set_pixel(0x94, 0x00, 0xd3)
        button_a_pressed()
        button_flag = "null"
    elif button_flag == "button_2":
        buttonshim.set_pixel(0x00, 0x00, 0xff)
        button_b_pressed()
        button_flag = "null"
    elif button_flag == "button_3":
        buttonshim.set_pixel(0x00, 0xff, 0x00)
        button_c_pressed()
        button_flag = "null"
    elif button_flag == "button_4":
        buttonshim.set_pixel(0xff, 0xff, 0x00)
        button_d_pressed()
        button_flag = "null"
    elif button_flag == "button_5":
        buttonshim.set_pixel(0xff, 0x00, 0x00)
        button_e_pressed()
        button_flag = "null"


import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM

def scrape_nasdaq_stock_data(symbol, start_date, end_date):
    url = f"https://www.nasdaq.com/market-activity/stocks/{symbol}/historical"
    params = {
        "date": start_date,
        "endDate": end_date,
    }
    response = requests.get(url, params=params)
    soup = BeautifulSoup(response.content, 'html.parser')
    table = soup.find('table', {'class': 'historical-data__table'})
    data = []
    for row in table.find_all('tr'):
        cols = row.find_all('td')
        if len(cols) == 6:
            date = cols[0].get_text()
            close_price = float(cols[1].get_text().replace(',', ''))
            data.append((date, close_price))
    df = pd.DataFrame(data, columns=['Date', 'Close'])
    df['Date'] = pd.to_datetime(df['Date'])
    df.set_index('Date', inplace=True)
    return df

def prepare_data(data, sequence_length):
    X, y = [], []
    for i in range(len(data) - sequence_length):
        X.append(data[i:i + sequence_length])
        y.append(data[i + sequence_length])
    return np.array(X), np.array(y)

def predict_stock_prices(symbol, start_date, end_date, sequence_length, epochs=50):
    stock_data = scrape_nasdaq_stock_data(symbol, start_date, end_date)

    # Normalize the data using Min-Max Scaler
    scaler = MinMaxScaler()
    scaled_data = scaler.fit_transform(stock_data)

    # Split data into train and test sets
    X, y = prepare_data(scaled_data, sequence_length)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    # Build the LSTM model
    model = Sequential()
    model.add(LSTM(50, return_sequences=True, input_shape=(sequence_length, 1)))
    model.add(LSTM(50, return_sequences=False))
    model.add(Dense(25))
    model.add(Dense(1))

    # Compile the model
    model.compile(optimizer='adam', loss='mean_squared_error')

    # Train the model
    model.fit(X_train, y_train, batch_size=64, epochs=epochs, validation_data=(X_test, y_test))

    # Make predictions on the test set
    predictions = model.predict(X_test)
    predictions = scaler.inverse_transform(predictions)

    # Calculate mean absolute percentage error (MAPE)
    mape = np.mean(np.abs((y_test - predictions) / y_test)) * 100
    print(f"Mean Absolute Percentage Error (MAPE): {mape:.2f}%")

    return predictions, y_test, scaler

# Example usage:
if __name__ == "__main__":
    symbol = "AAPL"  # Replace with the stock symbol you want to predict
    start_date = "2020-01-01"
    end_date = "2023-07-31"
    sequence_length = 60
    epochs = 50

    predictions, actual_values, scaler = predict_stock_prices(symbol, start_date, end_date, sequence_length, epochs)

    df_predictions = pd.DataFrame(predictions, columns=['Predicted'], index=stock_data.index[-len(predictions):])
    df_actual = pd.DataFrame(actual_values, columns=['Actual'], index=stock_data.index[-len(actual_values):])

    df_predictions = scaler.inverse_transform(df_predictions)
    df_actual = scaler.inverse_transform(df_actual)

    df_result = pd.concat([df_actual, df_predictions], axis=1)
    print(df_result)


def solution2(number, k):
    collected = []
    for i, num in enumerate(number):
        while len(collected) > 0 and collected[-1] < num and k > 0:
            collected.pop()
            k -= 1
        if k == 0:
            collected += list(number[i:])
            break
        collected.append(num)

    collected = collected[:-k] if k > 0 else collected
    return ''.join(collected)

if __name__ == '__main__':
    assert "94" == solution2("1924", 2)


# Given a linked list, swap every two adjacent nodes and return its head.

# Example:

# Given 1->2->3->4, you should return the list as 2->1->4->3.
# Note:

# Your algorithm should use only constant extra space.
# You may not modify the values in the list's nodes, only nodes itself may be changed.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return None
        else:
            first = head.val
            head = head.next
            if head == None:
                return ListNode(first)
            else:
                second = head.val
                head = head.next
                newList = ListNode(second)
                newList.next = ListNode(first)
                newList.next.next = Solution.swapPairs(self, head)
                return newList


#!/user/bin/env python3
# -*-coding:utf-8-*-
'''
编写一个程序，能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件，并打印出绝对路径和相对路径。
'''

import os

cha_file=input("输入查找的字符串：\n")
'''
os.walk() 方法用于通过在目录树中游走输出在目录中的文件名，向上或者向下。
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

Python find() 方法检测字符串中是否包含子字符串 str ，如果指定 beg（开始） 和 end（结束） 范围，则检查是否包含在指定范围内，如果包含子字符串返回开始的索引值，否则返回-1。
str.find(str, beg=0, end=len(string))

Python replace() 方法把字符串中的 old（旧字符串） 替换成 new(新字符串)，如果指定第三个参数max，则替换不超过 max 次。str.replace(old, new[, max])

'''

for dir in os.walk(os.path.abspath('.')):  # 输出（在当前目录的绝对路径中的）文件名，向上或者向下
    for x in dir[-1]:
    # 文件目录
        if x.find(cha_file)!=-1:    # 包含子字符串
            y=os.path.join(dir[0],x)
        # 获得文件的绝对路径y
            print('绝对路径为:',y)
            k=y.replace(os.path.abspath('.'),'')
            print('相对路径为:',k)


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

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

if __name__ == '__main__':
    class MyClass1(metaclass=Singleton):
        def __init__(self):
            print("MyClass1 init. id: " + str(id(self)))

    class MyClass2(metaclass=Singleton):
        def __init__(self):
            print("MyClass2 init. id: " + str(id(self)))

    myClass1_1 = MyClass1()
    myClass1_2 = MyClass1()
    myClass2 = MyClass2()
    print("check id")
    print("myClass1_1s id: " + str(id(myClass1_1)))
    print("myClass1_2s id: " + str(id(myClass1_2)))
    print("myClass2s id: " + str(id(myClass2)))


from unidecode import unidecode
import re
class geradorjava:

    # gera o nome da classe
    @staticmethod
    def gerarClasseNome(nome: str,prefixo : str = None,sufixo : str = None):
        retorno : str = ""

        if prefixo != None:
            retorno += prefixo

        retorno += nome

        if sufixo != None:
            retorno += sufixo

        retorno = unidecode(retorno)
        retorno = re.compile("[\W]").sub(" ", retorno)
        retorno = re.sub(r'([A-Z])', r' \1', retorno)
        retorno = retorno.title().strip()

        return retorno.replace(" ", "")

    # gera o nome da classe
    @staticmethod
    def gerarConstantNome(nome: str):
        retorno : str = ""
        retorno += nome.replace('/',"_").replace('\\',"_").replace(" ","_").upper()

        return unidecode(retorno)

    @staticmethod
    def nomeClassePojo(endpoint : str, verbo : str):
        return unidecode(geradorjava.gerarClasseNome(endpoint,prefixo=verbo))

    @staticmethod
    def converterNomeClasseParaAtributo(nome: str):
        return unidecode(nome[0].lower() + nome[1:])

    @staticmethod
    def nomeMetodoPropriedade(nome: str,prefixo : str = None,sufixo : str = None):
        metodo : str = geradorjava.gerarClasseNome(nome,prefixo,sufixo)
        return unidecode(geradorjava.converterNomeClasseParaAtributo(metodo))

    @staticmethod
    def gerarMetodosEndpointsJava(
        textoJavaDoc : str,
        tipo : str,
        tipo_requisicao_class : str,
        tipo_lista : bool,
        pametros : list,
        nome:str,
        classeConstantsNome,
        endpoint:str,verbo : str,
        parametro_request : str = "null"
    ):
        metodo : str = ""
        metodo += geradorjava.gerarJavaDoc(textoJavaDoc)
        metodo += "  public "+tipo+" "+nome+"(" + ", ".join(pametros) + ") throws Exception {\n"
        if tipo_lista:
            metodo += "    Class<"+tipo+"> "+tipo_requisicao_class+" = (Class) List.class;\n\n"
        metodo += "    "
        if tipo != "void":
            metodo += "return "
        metodo += "requisicao(\""+endpoint+"\", "
        metodo += classeConstantsNome + ".HTTP_"+verbo.upper()+", "
        metodo += tipo_requisicao_class+", "
        if tipo_lista:
            metodo += tipo.replace("List<","").replace(">","") + ".class, "
        metodo += parametro_request + ");\n"
        metodo += "  }\n\n"

        return metodo

    @staticmethod
    def gerarConstantsJava(textoJavaDoc : str,tipo : str, nome:str, valor):
        constants : str = ""
        constants += geradorjava.gerarJavaDoc(textoJavaDoc)
        constants += "  public static final "+tipo+" "+nome.upper()+" = "
        if tipo == "String" or tipo == "Date":
            constants += "\"" + valor + "\""
        elif tipo == "Char" or tipo == "char" or tipo == "Character":
            constants += "\'" + valor + "\'"
        else:
            constants += str(valor)
        constants += ";\n\n"

        return constants

    @staticmethod
    def gerarClasse(pacote : str,classeNome : str,conteudo : str):
        classe : str = ""
        classe += "package " + pacote + ";\n"
        classe += "\n"
        classe += "public class "+classeNome+" {\n"
        classe += "\n"
        classe += conteudo
        classe += "}"

        return classe

    @staticmethod
    def gerarJavaDoc(texto : str):
        javaDoc : str = ""
        javaDoc += "  /**\n"
        javaDoc += "   * "+texto.replace("\n","\n   * ")+"\n"
        javaDoc += "   */\n"
        return javaDoc

    @staticmethod
    def pacoteParaPath(pacote : str):
        return pacote.replace(".","/").lower()

    @staticmethod
    def gerarJavaDocPojo(arquivoPath : str, campos):

        with open(arquivoPath, "r+") as arquivo:
            texto = arquivo.read()

            for i in campos:
                match = "    @JsonProperty(\""+i['campo']+"\")"
                substituir : str = geradorjava.gerarJavaDoc(i['descricao']) + match
                texto = texto.replace(match,substituir)

            arquivo.seek(0)
            arquivo.write(texto)

    # Gera, a partir do tipo relatado na documentação, um dado para o pojo
    @staticmethod
    def gerarDadoTipoDoc(tipo : str):
        tipo = tipo.lower()

        if tipo == 'int' or tipo == 'integer' or tipo == 'long'  or tipo == 'longer':
            return 1
        elif tipo == 'double' or tipo == 'bigdecimal' or tipo == 'number' or tipo == 'numeric' or tipo == 'float':
            return 1.2345
        elif tipo == 'bool' or tipo == 'boolean':
            return True
        elif tipo == 'char' or tipo == 'character':
            return 'A'
        else:
            return "texto"

    # Retorna o tipo para java
    @staticmethod
    def gerarTipoJava(tipo : str):
        tipo = tipo.lower()

        if tipo == 'int' or tipo == 'integer' or tipo == 'long'  or tipo == 'longer':
            return "Integer"
        elif tipo == 'double' or tipo == 'bigdecimal' or tipo == 'number' or tipo == 'numeric' or tipo == 'float':
            return "Double"
        elif tipo == 'bool' or tipo == 'boolean':
            return "Boolean"
        elif tipo == 'char' or tipo == 'character':
            return 'Character'
        else:
            return "String"


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

import os
import logging
import logging.config

import fcntl
import socket
import struct

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

dir_ = os.getcwd()
lastSource = os.path.join(dir_, "lastSource")
core_dir = os.path.join(dir_, "Core")
run_dir = os.path.join(dir_, "run_dir")
data_dir = os.path.join(dir_, "data_dir")

host = "192.168.7.2"
# host = get_ip_address("wlan0")
port = 27182
datahost = "192.168.7.2"
# datahost = get_ip_address("wlan0")
dataport = 31415

logging.config.fileConfig("logging.conf")
logger = logging.getLogger("example1")

availableCompiler = ['gcc', 'g++', 'java']
availableValidator = ['Text Validator', 'Special Validator']

#language
LANG_UNKOWN = 0
LANG_C = 1
LANG_CPP = 2
LANG_JAVA = 3


# -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 16:50:06 2020

@author: Lenovo
"""

#https://codeforces.com/problemset/problem/469/A

def wanna_be():

    levels = int(input())
    littlex = input().split()
    littley = input().split()

    dic = {}

    for i in range(1,len(littlex)):
        if littlex[i] not in dic:
            dic[littlex[i]] = 1

    for i in range(1,len(littley)):
        if littley[i] not in dic:
            dic[littley[i]] = 1

    if len(dic) == levels:
        print('I become the guy.')
    else:
        print('Oh, my keyboard!')

wanna_be()


from pyspark.sql.dataframe import DataFrame
from pyspark.sql.session import SparkSession
from pyspark.sql import functions as f
import warnings

def null_out_values(df: DataFrame, colname: str, values_to_null):
    """Null out a list of undesirable values in a column
    Useful for columns that mostly contain valid data but occasionally
    contain other values such as 'unknown'
    Args:
        df (DataFrame): The dataframe to clean
        colname (string): The name of the column to clean
        values_to_null: A list of values to be nulled.

    Returns:
        DataFrame: The cleaned dataframe with incoming column overwritten
    """

    if len(values_to_null) == 0:
        return df

    values_to_null_string = [f'"{v}"' for v in values_to_null]
    values_to_null_joined = ", ".join(values_to_null_string)

    case_statement = f"""
    CASE
    WHEN {colname} in ({values_to_null_joined}) THEN NULL
    ELSE {colname}
    END
    """

    df = df.withColumn(colname, f.expr(case_statement))

    return df

def null_out_values_array(df: DataFrame, array_colname: str, values_to_null: list):
    """Null out a user defined list of undesirable values in a column that contains an array of values
    Useful for columns that mostly contain valid data but occasionally
    contain other values such as 'unknown'

    Args:
        df (DataFrame): The dataframe to clean
        colname (string): The name of the column to clean
        values_to_null (list): A list of values to be nulled.
    Returns:
        DataFrame: The cleaned dataframe with column containing array that has values in values_to_null nulled
    """
    if len(values_to_null) > 0:

        if str((dict(df.dtypes)[array_colname])).startswith("array"):

            array_args = [f.lit(v) for v in values_to_null]
            df = df.withColumn("vals_to_remove", f.array(*array_args))
            df = df.withColumn(
                array_colname, f.expr(f"array_except({array_colname}, vals_to_remove)")
            )
            df = df.drop("vals_to_remove")

        else:
            # if column is not an array fire up a warning
            warnings.warn(
                f""" column {array_colname} is not an array. Please use function null_out_values instead  """
            )

    return df

def remove_special_character_values_within_array(df: DataFrame, array_colname: str):
    """Null out a preset list of undesirable values in a column that contains an array of values
    Useful for columns that mostly contain valid data but occasionally
    contain other values such as newlines etc

    Args:
        df (DataFrame): The dataframe to clean
        colname (string): The name of the column to clean

    Returns:
        DataFrame: The cleaned dataframe with column containing array that has special character values nulled
    """

    special_character_values = [
        "'",
        '""',
        "\\n",
        "\\",
        '"',
        '""',
        "\\t",
        "\\n",
        "\\r",
        "\\b",
        "\/",
        "\n",
        "\r",
        "\b"
    ]

    return null_out_values_array(df, array_colname, special_character_values)


from django.contrib import admin
from django.utils.text import Truncator
from django import forms
from ckeditor.widgets import CKEditorWidget
from ckeditor_uploader.widgets import CKEditorUploadingWidget
from .models import Tag, Article, Commentaire

class ArticleAdminForm(forms.ModelForm):
    contenu = forms.CharField(widget=CKEditorWidget())
    class Meta:
        model = Article
        fields = '__all__'

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('titre', 'auteur', 'get_tag', 'apercu_contenu', 'date')
    list_filter = ('titre', 'auteur', 'tag', 'date')
    #ordering = ('date',)
    search_fields = ('titre', 'contenu')

    # Configuration du formulaire d'édition
    fieldsets = (
        # Fieldset 1 : meta-info (titre, auteur…)
        ('Général', {
            'fields': ('titre', 'auteur', 'date', 'tag')
        }),
        # Fieldset 2 : contenu de l'article
        ('Contenu de l\'article', {
            'description': 'Le formulaire accepte les balises HTML. Utilisez-les à bon escient !',
            'fields': ('contenu',)
        }),
    )

    form = ArticleAdminForm

    def apercu_contenu(self, article):
        """
        Retourne les 40 premiers caractères du contenu de l'article,
        suivi de points de suspension si le texte est plus long.
        """
        return Truncator(article.contenu).chars(40, truncate='...')

    # En-tête de notre colonne
    apercu_contenu.short_description = 'Aperçu du contenu'

admin.site.register(Article, ArticleAdmin)
admin.site.register(Tag)
admin.site.register(Commentaire)

#admin.site.site_header(path('/admin/documentation', views.doc, name='doc'))
# class MyModelAdmin(admin.ModelAdmin):
#     def get_urls(self):
#         urls = super().get_urls()
#         my_urls = [
#             path('documentation/', self.documentation),
#         ]
#         return my_urls + urls
#
#     def documentation(self, request):
#
#         return TemplateResponse(request, "documentation.html")


import os
os.environ["KIVY_NO_ARGS"] = "1"
os.environ['KIVY_IMAGE'] = "pil,sdl2" # use pil instead of SDL2 image if you get the libpng16 error
# you must add to the path the location of your SDL2 binaries
os.environ['PATH'] += ';' + os.path.expandvars('%AppData%\\Python\\share\\glew\\bin')
os.environ['PATH'] += ';' + os.path.expandvars('%AppData%\\Python\\share\\sdl2\\bin')

import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
kivy.require("1.9.0")
from kivy.uix.listview import ListItemButton
#from kivy.uix.recycleview import RecycleView

# class StudentListButton(ListItemButton):
#     pass

class StudentDB(BoxLayout):
    first_name_text_input = ObjectProperty()
    last_name_text_input = ObjectProperty()
    student_list = ObjectProperty()

    def submit_student(self):
        # Get students name from textInputs
        student_name = self.first_name_text_input.text + " " + self.last_name_text_input.text

        # Add to ListView
        self.student_list.adapter.data.extend([student_name])

        # Reset the List View
        self.student_list._trigger_reset_populate()

    def delete_student(self):
        # If a list item is selected
        if self.student_list.adapter.selection:

            # Get the text from the item selected
            selection = self.student_list.adapter.selection[0].text

            # Remove the matching item
            self.student_list.adapter.data.remove(selection)

            # Reset the ListView
            self.student_list._trigger_reset_populate()

    def repleace_student(self):
        # If a list item is seleted
        if self.student_list.adapter.selection:

            # Get the text from the itme selected
            selection = self.student_list.adapter.selection[0].text

            # Remove the matching item
            self.student_list.adapter.data.remove(selection)

            # Get the students name from TextInputs
            student_name = self.first_name_text_input.text + " " + self.last_name_text_input.text

            # Add the updated data to the list
            self.student_list.adapter.data.extend([student_name])

            # Reset the ListView
            self.student_list._trigger_reset_populate()

class StudentDBApp(App):
    def build(self):
        return StudentDB()

dbApp = StudentDBApp()
dbApp.run()


'''
Created on Jun 30, 2023

@author: shanti
'''
import operator
import functools
from _operator import itemgetter

def person_lister(f):
    @functools.wraps(f)
    def inner(people):
        # complete the function
        if 1 <= len(people) <= 10:

            getage = itemgetter(2)
            people_sort = sorted(people, key=lambda x : (int(getage(x))))
            peeps = list(map(f, people_sort))
            return peeps
        else:
            return []
    return inner

@person_lister
def name_format(person):
    return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1]

if __name__ == '__main__':
    people = [input().split() for i in range(int(input()))]
    print(*name_format(people), sep='\n')

'''

Let's use decorators to build a name directory! You are given some information about  people. Each person has a first name, last name, age and sex. Print their names in a specific format sorted by their age in ascending order i.e. the youngest person's name should be printed first. For two people of the same age, print them in the order of their input.

For Henry Davids, the output should be:
Mr. Henry Davids
For Mary George, the output should be:
Ms. Mary George
Input Format
The first line contains the integer , the number of people.
 lines follow each containing the space separated values of the first name, last name, age and sex, respectively.
Constraints

Output Format
Output  names on separate lines in the format described above in ascending order of age.
Sample Input
3
Mike Thomson 20 M
Robert Bustle 32 M
Andria Bustle 30 F
Sample Output
Mr. Mike Thomson
Ms. Andria Bustle
Mr. Robert Bustle

TestCase #12:
6
Blossom Michael 9 F
Bubbles Kevin 666666666666666 F
Buttercup Jake 4444444444444444444444444444444444444444444444444444444444444444 F
Michael Blossom 8888 M
Kevin Bubbles 7777777 M
Jake Buttercup 555555555555555555555555555555 M

Expected:
Ms. Blossom Michael
Mr. Michael Blossom
Mr. Kevin Bubbles
Ms. Bubbles Kevin
Mr. Jake Buttercup
Ms. Buttercup Jake

'''


"""
    ✔ Создайте функцию для сортировки файлов по директориям: видео, изображения, текст и т.п.
    ✔ Каждая группа включает файлы с несколькими расширениями.
    ✔ В исходной папке должны остаться только те файлы, которые не подошли для сортировки.
"""

__all__ = ['create_folders', 'order_files']

import os

file_folders = {
    'video': ('mkv', 'mp4', 'avi'),
    'image': ('jpeg', 'jpg', 'img'),
    'text': ('txt', 'doc'),
}

def create_folders()->None:
    for folder in file_folders.keys():
        if not os.path.exists(folder):
            os.mkdir(folder)

def order_files(dir: str = 'task_7_files')->None:
    os.chdir(dir)
    create_folders()
    files = os.scandir()
    for file in files:
        if not os.path.isfile(file):
            continue
        filepath = file.path
        ext = filepath.split('.')[-1]
        filename = filepath.split('/')[-1]
        for folder, exts in file_folders.items():
            if ext in exts:
                print(f'Файл {filename} перемещён в папку {folder}' )
                os.replace(filename, os.path.join(folder, filename))

if __name__ == '__main__':
    order_files()


__author__ = 'Зелепукин Алексей Юрьевич'

import os
import hw05_easy

# Задача-1:
# Напишите небольшую консольную утилиту,
# позволяющую работать с папками текущей директории.
# Утилита должна иметь меню выбора действия, в котором будут пункты:
# 1. Перейти в папку
# 2. Просмотреть содержимое текущей папки
# 3. Удалить папку
# 4. Создать папку
# При выборе пунктов 1, 3, 4 программа запрашивает название папки
# и выводит результат действия: "Успешно создано/удалено/перешел",
# "Невозможно создать/удалить/перейти"

# Для решения данной задачи используйте алгоритмы из задания easy,
# оформленные в виде соответствующих функций,
# и импортированные в данный файл из easy.py

def my_utility():
    print('\n')
    print('*' * 32 + ' BEGIN ' + '*' * 32)
    print('\n')
    ans = None
    path = os.getcwd()
    while ans != 5:
        print('Текущая папка: ' + os.path.basename(path))
        ans = input('Выберите действие (введите число):\n'
                       '1. Перейти в папку\n'
                       '2. Помотреть содержимое текущей папки\n'
                       '3. Удалить папку\n'
                       '4. Создать папку\n'
                       '5. Выход\n')
        try:
            ans = int(ans)
            if ans == 5:
                print('\n')
                print('*' * 32 + ' END ' + '*' * 32)
                print('\n')
                break
            elif ans == 1:
                folder_name = input('Введите название папки для перехода: ')
                if hw05_easy.change_dir(folder_name):
                    path = os.getcwd()
                    print(f'Успешный переход в папку {os.path.basename(folder_name)}')
                else:
                    print(f'Не удалось перейти в папку {os.path.basename(folder_name)}')
            elif ans == 2:
                print(f'Содержимое текущей папки: {hw05_easy.list_dir(path=path, mode="a")}')
            elif ans == 3:
                name = input('Введите название удаляемой папки: ')
                if hw05_easy.remove_dir(name):
                    print(f'Папка {name} успешно удалена')
                else:
                    print(f'Не удалось удалить папку {name}')
            elif ans == 4:
                name = input('Введите название новой папки: ')
                if hw05_easy.make_dir(name):
                    print(f'Папка {name} успешно создана')
                else:
                    print(f'Не удалось создать папку {name}')
            else:
                print('Неверный ввод. Попробуйте еще раз.')
        except:
            print('Неверный ввод. Попробуйте еще раз.')
        finally:
            print('\n')

my_utility()


from mitreattack.stix20 import MitreAttackData

def main():
    mitre_attack_data = MitreAttackData("enterprise-attack.json")

    tactics_map = mitre_attack_data.get_tactics_by_matrix()

    for matrix, tactics in tactics_map.items():
        tactic_names = [t["name"] for t in tactics]
        print(f"Tactics in {matrix}: {tactic_names}")

if __name__ == "__main__":
    main()


from flask import Blueprint, jsonify

from collector.models import Collection, collections_schema

collection = Blueprint('collection', __name__, url_prefix='')

@collection.route("/collections", methods=['GET'])
def get_collections():
    all_collections = Collection.query.all()
    result = collections_schema.dump(all_collections)
    return jsonify(result.data)


import os
import shutil

import gym
import minerl
import numpy as np
from ray.rllib.evaluation.sample_batch_builder import SampleBatchBuilder
from ray.rllib.models.preprocessors import get_preprocessor
from ray.rllib.offline import InputReader
from ray.rllib.offline.json_writer import JsonWriter

from minerl_rllib.envs.wrappers import wrap

class MinerRLDataEnv(gym.Env):
    def __init__(self, data_pipeline: minerl.data.DataPipeline):
        super().__init__()
        self.data_pipeline = data_pipeline
        self.env_spec = data_pipeline.spec
        self.observation_space = self.env_spec.observation_space
        self.action_space = self.env_spec.action_space
        self.trajectory_names = data_pipeline.get_trajectory_names()
        self.index = 0
        # used by step() and reset()
        self.trajectory = None
        self.step_index = 0

    def step(self, action):
        prev_obs, action, reward, obs, done = self.trajectory[self.step_index]
        info = {
            "prev_obs": prev_obs,
            "action": action,
        }
        self.step_index += 1
        if self.step_index >= len(self.trajectory):
            if not done:
                print("Encountered end of trajectory when done returned False!")
            done = True
        return obs, reward, done, info

    def reset(self):
        self.trajectory = list(
            self.data_pipeline.load_data(self.trajectory_names[self.index])
        )
        self.index += 1
        self.index %= len(self.trajectory_names)
        self.step_index = 0
        obs, _, _, _, _ = self.trajectory[self.step_index]
        return obs

    def render(self, mode="human"):
        pass

def wrap_env(env: MinerRLDataEnv, env_config):
    return wrap(env, **env_config)

def write_jsons(
    environment,
    data_dir,
    env_config,
    save_path,
    overwrite=False,
    fail_safe=True,
    **kwargs,
):
    data_pipeline = minerl.data.make(environment, data_dir, **kwargs)
    env = MinerRLDataEnv(data_pipeline)
    env = wrap_env(env, env_config)

    if not os.path.exists(save_path):
        os.makedirs(save_path)
    if len(os.listdir(save_path)) != 0:
        abs_save_path = os.path.abspath(save_path)
        if overwrite:
            print(f"Overwriting! {abs_save_path}")
            shutil.rmtree(abs_save_path)
        else:
            if fail_safe:
                print(f"Json data already exists at {abs_save_path}")
                return
            else:
                raise ValueError(
                    f"Directory {abs_save_path} not empty!"
                    f"Cannot overwrite existing data automatically, please delete old data if unused."
                )

    batch_builder = SampleBatchBuilder()
    writer = JsonWriter(save_path)
    prep = get_preprocessor(env.observation_space)(env.observation_space)

    for eps_id, trajectory_name in enumerate(env.trajectory_names):
        t = 0
        prev_action = None
        prev_reward = 0
        done = False
        try:
            obs = env.reset()
        except TypeError:
            continue
        while not done:
            new_obs, reward, done, info = env.step(env.action_space.sample())
            action = info["action"]
            action = env.reverse_action(action)
            if prev_action is None:
                prev_action = np.zeros_like(action)

            batch_builder.add_values(
                t=t,
                eps_id=eps_id,
                agent_index=0,
                obs=prep.transform(obs),
                actions=action,
                action_prob=1.0,  # put the true action probability here
                rewards=reward,
                prev_actions=prev_action,
                prev_rewards=prev_reward,
                dones=done,
                infos={"trajectory_name": trajectory_name},
                new_obs=prep.transform(new_obs),
            )
            obs = new_obs
            prev_action = action
            prev_reward = reward
            t += 1
        writer.write(batch_builder.build_and_reset())

class MineRLReader(InputReader):
    def __init__(
        self,
        env_config,
        environment,
        data_dir,
        num_workers,
        worker_batch_size=4,
        minimum_size_to_dequeue=32,
    ):
        super().__init__()
        self.data_pipeline = minerl.data.make(
            environment,
            data_dir,
            num_workers,
            worker_batch_size,
            minimum_size_to_dequeue,
            force_download=False,
        )
        self.env_config = env_config
        self.env_config.update({"data_dir": data_dir})

    def get_env(self, env):
        return wrap(env, **self.env_config)

    def next(self):
        self.data_pipeline.batch_iter()


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

from linear import LinearEnv
from agent import Agent

def test_run(nb_episodes, world_size, method,
            step_size, nb_steps=None, lmbda=None):
    env = LinearEnv(world_size)  # 2x terminal states will be added internally
    agent = Agent(world_size+2,       # add 2x terminal states
                step_size=step_size,
                nb_steps=nb_steps,
                lmbda=lmbda)

    RMSE = []    # root mean-squared error
    for e in range(nb_episodes):

        # pdb.set_trace()

        obs = env.reset()
        agent.reset()
        agent.append_trajectory(t_step=0,
                                prev_action=None,
                                observation=obs,
                                reward=None,
                                done=None)

        # if e % 10 == 0:
        #     agent.step *= 0.95
        #     print(agent.step)

        while True:

            action = agent.pick_action(obs)

            #   ---   time step rolls here   ---

            obs, reward, done = env.step(action)

            agent.append_trajectory(t_step=env.t_step,
                        prev_action=action,
                        observation=obs,
                        reward=reward,
                        done=done)

            if method == 'td-online':
                agent.eval_td_online()
            elif method == 'td-lambda-online':
                agent.eval_td_lambda_online()

            if done:
                if method == 'mc-offline':
                    agent.eval_mc_offline()
                elif method == 'n-step-offline':
                    agent.eval_nstep_offline()
                elif method == 'td-offline':
                    agent.eval_td_offline()
                elif method == 'lambda-return-offline':
                    agent.eval_lambda_return_offline()
                elif method == 'td-lambda-offline':
                    agent.eval_td_lambda_offline()
                break

        rms = np.sqrt(np.sum(np.power(
            LinearEnv.GROUND_TRUTH[world_size] - agent.V, 2)) / world_size)
        RMSE.append(rms)

    return RMSE, agent.V

def multi_run(nb_runs, nb_episodes, world_size, method,
            step_size, nb_steps=None, lmbda=None):
    multi_RMSE = []
    multi_final_V = []

    for run in range(nb_runs):
        RMSE, final_V = test_run(nb_episodes, world_size, method,
                                 step_size, nb_steps, lmbda)

        multi_RMSE.append(RMSE)
        multi_final_V.append(final_V)

    return multi_RMSE, multi_final_V

def test_MC_vs_TD():
    """This replicates Stutton and Barto (2017), Example 6.2 Random Walk 5
    The only chang is that environment has reward -1 on far left side."""

    world_size = 5

    RSME_TD_15, final_V_TD_15 = multi_run(
        nb_runs=100, nb_episodes=100, world_size=world_size,
        method='td-online', step_size=0.15)
    RSME_TD_10, final_V_TD_10 = multi_run(
        nb_runs=100, nb_episodes=100, world_size=world_size,
        method='td-online', step_size=0.10)
    RSME_TD_05, final_V_TD_05 = multi_run(
        nb_runs=100, nb_episodes=100, world_size=world_size,
        method='td-online', step_size=0.05)

    RSME_MC_01, final_V_MC_01 = multi_run(
        nb_runs=100, nb_episodes=100, world_size=world_size,
        method='mc-offline', step_size=0.01)
    RSME_MC_02, final_V_MC_02 = multi_run(
        nb_runs=100, nb_episodes=100, world_size=world_size,
        method='mc-offline', step_size=0.02)
    RSME_MC_03, final_V_MC_03 = multi_run(
        nb_runs=100, nb_episodes=100, world_size=world_size,
        method='mc-offline', step_size=0.03)

    RSME_TD_15_mean = np.mean(RSME_TD_15, 0)
    RSME_TD_10_mean = np.mean(RSME_TD_10, 0)
    RSME_TD_05_mean = np.mean(RSME_TD_05, 0)
    RSME_MC_01_mean = np.mean(RSME_MC_01, 0)
    RSME_MC_02_mean = np.mean(RSME_MC_02, 0)
    RSME_MC_03_mean = np.mean(RSME_MC_03, 0)

    #print(np.round(LinearEnv.GROUND_TRUTH[world_size], 4))
    #print(np.round(agent.V, 4))

    fig = plt.figure()
    ax = fig.add_subplot(121)
    ax.plot(LinearEnv.GROUND_TRUTH[world_size][1:-1], color='black')
    ax.plot(final_V_TD_15[0][1:-1], label='TD a=0.15')
    ax.plot(final_V_TD_10[0][1:-1], label='TD a=0.10')
    ax.plot(final_V_TD_05[0][1:-1], label='TD a=0.05')
    ax.plot(final_V_MC_01[0][1:-1], label='MC a=0.01')
    ax.plot(final_V_MC_02[0][1:-1], label='MC a=0.02')
    ax.plot(final_V_MC_03[0][1:-1], label='MC a=0.03')

    ax = fig.add_subplot(122)
    ax.plot(RSME_TD_15_mean, label='TD a=0.15')
    ax.plot(RSME_TD_10_mean, label='TD a=0.10')
    ax.plot(RSME_TD_05_mean, label='TD a=0.05')
    ax.plot(RSME_MC_01_mean, label='MC a=0.01')
    ax.plot(RSME_MC_02_mean, label='MC a=0.02')
    ax.plot(RSME_MC_03_mean, label='MC a=0.03')

    plt.legend()

    plt.grid()
    plt.show()

class Data:
    def __init__(self, label):
        self.label = label
        self.x = []
        self.y = []

def test_n_step():
    """This replicates Stutton and Barto (2017), Example 7.2 Random Walk 19"""

    world_size = 19

    data = {}

    for n in [1, 2, 4, 8, 16]:
        print('n = ', n)
        temp = Data(str(n))

        for step_size in np.arange(0.1, 1.0, 0.1):
            RMSE, final_V = multi_run(
                nb_runs=10, nb_episodes=10, world_size=world_size,
                method='n-step-offline', step_size=step_size, nb_steps=n)

            RMSE_ep_mean = np.mean(RMSE, axis=1)
            RMSE_run_mean = np.mean(RMSE_ep_mean)

            temp.x.append(step_size)
            temp.y.append(RMSE_run_mean)

        data[n] = temp

    fig = plt.figure()
    #ax = fig.add_subplot(131)
    #ax.plot(LinearEnv.GROUND_TRUTH[world_size][1:-1], color='black')
    #ax.plot(final_V[0][1:-1], label='TD')

    ax = fig.add_subplot(111)

    for key, value in data.items():
        ax.plot(value.x, value.y, label=value.label)

    plt.legend()

    plt.grid()
    plt.show()

def test_lambda_return():
    """This replicates Stutton and Barto (2017), Example 12.3 Random Walk 19"""

    world_size = 19

    data = {}

    for lmbda in [0, 0.4, 0.8, 0.9, .95]:
        print('lmbda = ', lmbda)
        temp = Data(str(lmbda))

        for step_size in np.arange(0.1, 1.1, 0.1):
            print('  step = ', step_size)
            RMSE, final_V = multi_run(
                nb_runs=1, nb_episodes=100, world_size=world_size,
                method='lambda-return-offline', step_size=step_size, lmbda=lmbda)

            RMSE_ep_mean = np.mean(RMSE, axis=1)
            RMSE_run_mean = np.mean(RMSE_ep_mean)

            temp.x.append(step_size)
            temp.y.append(RMSE_run_mean)

        data[lmbda] = temp

    fig = plt.figure()
    # ax = fig.add_subplot(131)
    # ax.plot(LinearEnv.GROUND_TRUTH[world_size][1:-1], color='black')
    # ax.plot(final_V[0][1:-1], label='TD')

    ax = fig.add_subplot(111)

    for key, value in data.items():
        ax.plot(value.x, value.y, label=value.label)

    plt.legend()

    plt.grid()
    plt.show()

def test_single():
    nb_runs = 5
    nb_episodes = 100
    world_size = 19

    # Experiments tuned for world size 19
    td_offline = {
        'method':    'td-offline',
        'stepsize':  0.15,
        'nb_steps':  None,
        'lmbda':     None,
        'color':     'blue'
    }
    mc_offline = {
        'method':    'mc-offline',
        'stepsize':  0.01,
        'nb_steps':  None,
        'lmbda':     None,
        'color':     'red'
    }
    td_lambda_offline = {
        'method':    'td-lambda-offline',
        'stepsize':  0.15,
        'nb_steps':  None,
        'lmbda':     0.3,
        'color':     'orange'
    }
    td_lambda_online = {
        'method':    'td-lambda-online',
        'stepsize':  0.15,
        'nb_steps':  None,
        'lmbda':     0.3,
        'color':     'green'
    }
    tests = [td_offline, mc_offline, td_lambda_offline, td_lambda_online]

    for test in tests:
        np.random.seed(0)
        print(test['method'])
        # test_A_RMSE, test_A_final_V = multi_run(
        #     nb_runs=10, nb_episodes=100, world_size=world_size,
        #     method='N-step-offline', step_size=0.2, n_steps=1)
        test['RMSE'], test['final_V'] = multi_run(
            nb_runs=nb_runs, nb_episodes=nb_episodes, world_size=world_size,
            method=test['method'], step_size=test['stepsize'], nb_steps=test['nb_steps'], lmbda=test['lmbda'])

    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)

    ax1.plot(LinearEnv.GROUND_TRUTH[world_size][1:-1], label='True V', color='black')

    for test in tests:

        label = test['method']
        for i in range(nb_runs):
            ax1.plot(test['final_V'][i][1:-1], label=label, color=test['color'], alpha=0.3)

            ax2.plot(test['RMSE'][i], label=label, color=test['color'], alpha=0.3)

            label = None

    #ax.plot(avg_RMS_TD_10, label='TD')
    #ax.plot(avg_RMS_n_step_10, label='n-step')

    plt.legend()

    plt.grid()
    plt.show()

def test_test():

    RMSE, final_V = multi_run(
            nb_runs=1, nb_episodes=1, world_size=19,
            method='lambda-return-offline', step_size=0.1,
            nb_steps=None, lmbda=0.9)

    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax1.plot(LinearEnv.GROUND_TRUTH[19][1:-1], label='True V')
    ax1.plot(final_V[0][1:-1])
    ax2 = fig.add_subplot(122)
    ax2.plot(RMSE[0])

    plt.show()

if __name__ == '__main__':
    # test_MC_vs_TD()
    #test_n_step()
    #test_lambda_return()

    test_single()


#!/bin/env python
#coding=utf-8
import sys
import os
import docx
from docx.shared import Length, Pt, RGBColor
from lxml import etree
import xmltodict
import json
import time
import string
import random
import requests
import jieba
import os
import subprocess

import qiniu

from setting import settings

from xml.dom.minidom import parseString

# file=docx.Document("template.docx")
# file=docx.Document("矿井安全监测监控管理机构及其职责2022.2.10.docx")
# file=docx.Document("彭庄煤矿2022年防灭火设计3.16.docx")
# filename = "4306轨道运输巷启封密闭恢复通风安全技术措施.docx"
# filename = "彭庄煤矿2022年防灭火设计3.16.docx"
# filename = "矿井安全监测监控管理机构及其职责2022.2.10.docx"
sub = 0
def postprocessor(path, key, value):
    global sub
    value = {
        "value":value,
        "key":key,
        "num":sub,
        "path":path,
        "content_id":"".join(random.choice(string.ascii_lowercase+string.digits) for _ in range(6))
    }
    key = "%s"%(sub)
    sub +=1
    return key, value

def postprocessor1(path, key, value):
    global sub
    value = {
        "value":value,
        "key":key,
        "num":sub,
        "path":path,
    }
    sub +=1
    return key, value

def file_md5(file_path):
    with open(file_path, 'rb') as fp:
        data = fp.read()
    file_md5= hashlib.md5(data).hexdigest()
    return file_md5

def upload_docx(filename,download_link="",save_block_id=None):
    sub = 0
    if filename.split(".")[-1] in ["docx"]:
        file=docx.Document(filename)
        body_xml_str = file._body._element.xml # 获取body中的xml
        body_xml = etree.fromstring(body_xml_str) # 转换成lxml结点
        # print(body_xml_str)
        # print(etree.tounicode(body_xml)) # 打印查看
        # xmltodict.parse()方法可以将xml数据转为python中的dict字典数据
        # parser_data = xmltodict.parse(body_xml_str)
        sub = 0
        parser_data = xmltodict.parse(etree.tounicode(body_xml),postprocessor=postprocessor)
        json_conversion1 = json.dumps(parser_data)
        # print(json_conversion1)
        # with open("xml1.json", "w", encoding="utf-8") as bfile:
        #     bfile.write(json.dumps(json_conversion1, indent=2, ensure_ascii=False)) #ensure_ascii=False可以消除json包含中文的乱码问题

        sub = 0
        parser_data = xmltodict.parse(etree.tounicode(body_xml),postprocessor=postprocessor1)
        json_conversion2 = json.dumps(parser_data)
        # print(json_conversion2)

        # with open("xml2.json", "w", encoding="utf-8") as bfile:
        #     bfile.write(json.dumps(json_conversion2, indent=2, ensure_ascii=False)) #ensure_ascii=False可以消除json包含中文的乱码问题

        dest = "./dest"
        file_docx_to_pdf = filename
        output = subprocess.check_output([settings["libreoffice"],"--headless","--convert-to","pdf",file_docx_to_pdf,"--outdir",dest])
        dest_file = "./dest/%s.pdf"%(file_docx_to_pdf.split("/")[-1].split(".docx")[0])

        # path_now = "%s/%s/%s"%(block_id,root,file_item)
        # path_current = "%s/%s"%(root,file_item)
        # file_md5_str = file_md5(path_current)
        file_md5_str = file_md5(dest_file)

        # file_item_list = file_item.split(".")
        qiniu_file_key = "%s_s_%s"%(save_block_id,file_md5_str)
        file_info = {
            # "name":file_item,
            # "path":path_now,
            "md5":file_md5_str,
            "link":"http://office-cdn-1.xialiwei.com/%s"%qiniu_file_key,
            # "cdn_type":"secret",
            "cdn_type":"public",
        }
        # files_list.append(file_info)
        # files_data.append(file_info)
        print(file_info)
        q = qiniu.Auth(settings["QiniuAccessKey"], settings["QiniuSecretKey"])
        # uptoken = q.upload_token("audio", key, 3600, policy)
        uptoken = q.upload_token("ofcourse-office-1")
        # localfile = os.path.join(os.path.dirname(__file__), path_current)
        # ret, info = qiniu.put_file(uptoken, qiniu_file_key, localfile)
        ret, info = qiniu.put_file(uptoken, qiniu_file_key, dest_file)

        pdf_download_link = file_info["link"]

        p_list = [
            "文件名: %s"%filename,
            "在线访问: %s"%(pdf_download_link,filename.split("/")[-1].replace(".docx",".pdf")),
            "下载地址: %s"%(download_link,filename.split("/")[-1],download_link)
        ]
        doc_dd_0 = json.loads(json_conversion1)
        for k,v in doc_dd_0.items():
            is_number = False
            try:
                k = int(k)
                is_number = True
            except Exception as e:
                is_number = False
            if is_number:
                for _k,_v in v["value"].items():
                    ais_number = False
                    try:
                        _k = int(_k)
                        ais_number = True
                    except Exception as e:
                        ais_number = False
                    if ais_number:
                        if _v["key"] in ["w:p","w:tbl","w:sectPr"]:
                            p = ""
                            p_add = False
                            for _kk,_vv in _v["value"].items():
                                if isinstance(_vv,dict):
                                    if _vv["key"] in ["w:r"]:
                                        if isinstance(_vv["value"],dict):
                                            for _kkk,_vvv in _vv["value"].items():
                                                if isinstance(_vvv,dict):
                                                    if _vvv["key"] in ["w:t"] and isinstance(_vvv["value"],str):
                                                        p = "%s%s"%(p,_vvv["value"])
                                                        p_add = True
                            if p_add:
                                p_list.append(p)
        p_list_str = json.dumps(p_list)
        print("文档行数:",len(p_list))
        url = "%s/api/page/add_free_docx"%(settings["host"])
        header = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
        }
        data = {
            "token": "xialiwei_follows_god",
            "user_id": settings["user_id"],
            "title": filename,
            "desc": filename,
            "xml1":json_conversion1,
            "xml2":json_conversion2,
            "pre_p_list":p_list_str,
        }
        request = requests.post(url, headers=header, data=data)
        request_json = json.loads(request.text)
        block_id = request_json["block_id"]
        print(block_id)

        url = "%s/api/search/add_free_page"%(settings["host"])
        header = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
        }
        data = {
            "token": "xialiwei_follows_god",
            "user_id": settings["user_id"],
            "search":"add free page default",
            "type":"sequence",
            "block_id":block_id,
            "block_id_sequence":"add free page default",
            "search":"add free page",
        }
        request = requests.post(url, headers=header, data=data)
        request_json = json.loads(request.text)

def upload_doc(filename,download_link="",save_block_id=None):
    dest = "./dest"
    file = filename
    output = subprocess.check_output([settings["libreoffice"],"--headless","--convert-to","docx",file,"--outdir",dest])
    print(output)
    dest_file = "./dest/%sx"%(file.split("/")[-1])
    print(dest_file)
    upload_docx(dest_file,download_link,save_block_id)
# print("=====")

# a = parseString(body_xml_str)
# all_data = []
# def get_child_nodes(item,data=[]):
#     if len(item.childNodes) == 0:
#         if hasattr(item,"nodeValue"):
#             data_str = item.nodeValue
#         else:
#             data_str = ""
#         info = {
#             "tag_name":item.nodeName,
#             "data":data_str,
#             "has_child":"false",
#             "childNodes":[]
#         }
#     else:
#         info = {
#             "tag_name":item.nodeName,
#             "data":"",
#             "has_child":"true",
#             "childNodes":[]
#         }
#         for i in item.childNodes:
#             j = get_child_nodes(i,[])
#             info["childNodes"].append(j)
#     data.append(info)
#     return data
# all_data = get_child_nodes(a)
# all_data_json = {"data":all_data}
# # print(all_data_json)
# with open("xml.json", "w", encoding="utf-8") as afile:
#     afile.write(json.dumps(all_data_json, indent=2, ensure_ascii=False)) #ensure_ascii=False可以消除json包含中文的乱码问题


"""Functions specific to processing New/Old Testament texts."""

import re
from typing import List, Tuple

def remove_text_before_first_chapter(text: str) -> str:
    """Remove everything before first chapter.

    Assumes that text is structured in the same way throughout.

    Args:
        text (str): the string.

    Returns:
        str: text in chapters

    """
    # Pattern to match the first occurrence of "RANTA" or "CHAPTER"
    pattern = re.compile(r'(?i)(.*?)((RANTA|CHAPTER).*)', re.DOTALL)

    # Remove the text before the first "RANTA" or "CHAPTER"
    match = pattern.match(text)
    cleaned_text = match.group(2) if match else text

    return cleaned_text

def extract_chapters(text: str) -> List:
    """Extract chapters from single string.

    Assumes that Quenya text goes first.
    Replaces CHAPTER X with verse 1.

    Args:
        text (str): all text in chapters.

    Returns:
        List: List of chapter strings.

    """
    # Pattern to match chapter headings
    chapter_pattern = re.compile(r'(RANTA) (\d+)')
    chapters = chapter_pattern.split(text)

    # Separate chapters and their content
    chapter_texts = []
    for i in range(0, len(chapters)):
        if i % 3 == 1:
            continue
        elif i % 3 == 2:
            print("chapter ", chapters[i])
        else:
            if len(chapters[i].strip()) > 0:
                txt = re.sub(r'\bCHAPTER\s+\d+', '1 ', chapters[i])
                chapter_texts.append(txt)

    return chapter_texts

def separate_languages(text: str) -> Tuple:
    """Separate languages within a text based on verse numbers.

    Args:
        text (str): mixed text

    Returns:
        Tuple: english string, quenya string
    """
    english_num = 0
    quenya_num = 0
    english_string = ""
    quenya_string = ""
    curr_num = 1
    line_counter = 0

    # we get all the verse numbers separated from text
    lines = re.split(r'(\d+)', text)

    # start with quenya
    num_lines = len(lines)

    while line_counter < num_lines:

        old_curr_num = curr_num
        while curr_num > quenya_num:
            quenya_string += lines[line_counter].strip() + " "
            quenya_num = curr_num

            if line_counter + 1 < num_lines:
                next_num = int(lines[line_counter + 1])
                if next_num == curr_num:
                    print("error at verse ", next_num, curr_num)
                    curr_num += 1
                else:
                    curr_num = next_num
            line_counter += 2

        curr_num = old_curr_num
        while (curr_num > english_num) and (curr_num <= quenya_num):
            english_string += lines[line_counter].strip('" ') + " "
            english_num = curr_num
            if line_counter + 1 < num_lines:
                next_num = int(lines[line_counter + 1])
                if next_num == curr_num:
                    print("error at verse ", next_num, curr_num)
                    curr_num += 1
                else:
                    curr_num = next_num
            line_counter += 2

    return english_string.strip(), quenya_string.strip()


import wx
from scipy.spatial import distance as dist
from imutils.video import VideoStream
from imutils import face_utils
import numpy as np
import argparse
import imutils
import time
import dlib
import cv2
import os

class MyFrame(wx.Frame):
    def __init__(self,parent,title):
        super(MyFrame,self).__init__(parent,title =title,size=(400 ,300))

        self.panel= MyPanel(self)

class MyPanel(wx.Panel):
    def __init__(self,parent):
        super(MyPanel,self).__init__(parent)

        self.label2=wx.StaticText(self,label="Welcome to Fatigue Detection System",pos=(90,30))
        self.label = wx.StaticText(self, label=" ", pos=(100, 120))
        self.label3 = wx.StaticText(self, label=" ", pos=(150, 100))
        self.Btn = wx.Button(self, label="Face Camera",pos=(100,80))
        self.Btn.Bind(wx.EVT_BUTTON,self.onBtnClick)
        self.Btn2 = wx.Button(self, label="Road Camera", pos=(200, 80))
        self.Btn2.Bind(wx.EVT_BUTTON, self.onBtn2Click)
        #self.labelfatigue=wx.StaticText(self,label="Fatigue Level: ",pos=(100,200))
        #textCtrl = wx.TextCtrl(self, size=(150, 100), pos=(200, 200))

    #FaceCamera
    def onBtnClick (self, event):
      self.label.SetLabelText("Face Camera is activating please wait...")

      def eye_aspect_ratio(eye):
          A = dist.euclidean(eye[1], eye[5])
          B = dist.euclidean(eye[2], eye[4])

          C = dist.euclidean(eye[0], eye[3])

          eye_aspect_rat = (A + B) / (2.0 * C)

          return eye_aspect_rat

      def final_eye_aspect_rat(shape):
          (lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
          (rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]

          leftEye = shape[lStart:lEnd]
          rightEye = shape[rStart:rEnd]

          leftEAR = eye_aspect_ratio(leftEye)
          rightEAR = eye_aspect_ratio(rightEye)

          eye_aspect_rat = (leftEAR + rightEAR) / 2.0
          return (eye_aspect_rat, leftEye, rightEye)

      def lip_dist(shape):
          lipT = shape[50:53]
          lipT = np.concatenate((lipT, shape[61:64]))

          lipL = shape[56:59]
          lipL = np.concatenate((lipL, shape[65:68]))

          top_mean = np.mean(lipT, axis=0)
          low_mean = np.mean(lipL, axis=0)

          dist = abs(top_mean[1] - low_mean[1])
          return dist

      ap = argparse.ArgumentParser()
      ap.add_argument("-w", "--webcam", type=int, default=0,
                      help="index of webcam on system")
      args = vars(ap.parse_args())

      eye_thresh = 0.28
      eye_frames = 30
      yawn_thresh = 20
      COUNTER = 0
      fatigue = 0
      yawncounter=1

      detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
      predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')

      vs = VideoStream(src=args["webcam"]).start()
      time.sleep(1.0)

      while True:

          frame = vs.read()
          frame = imutils.resize(frame, width=450)
          gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

          rects = detector.detectMultiScale(gray, scaleFactor=1.1,
                                            minNeighbors=5, minSize=(30, 30),
                                            flags=cv2.CASCADE_SCALE_IMAGE)

          for (x, y, w, h) in rects:
              rect = dlib.rectangle(int(x), int(y), int(x + w), int(y + h))

              shape = predictor(gray, rect)
              shape = face_utils.shape_to_np(shape)

              eye = final_eye_aspect_rat(shape)
              ear = eye[0]
              leftEye = eye[1]
              rightEye = eye[2]

              distance = lip_dist(shape)

              leftEyeHull = cv2.convexHull(leftEye)
              rightEyeHull = cv2.convexHull(rightEye)
              cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)
              cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)

              lip = shape[48:60]
              cv2.drawContours(frame, [lip], -1, (0, 255, 0), 1)

              if ear < eye_thresh:
                  COUNTER += 1

                  if COUNTER >= eye_frames:
                      fatigue=fatigue+3
                      if alarm_status == False:
                          alarm_status = True

                      cv2.putText(frame, "DROWSINESS ALERT!", (10, 30),
                                  cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

              else:
                  COUNTER = 0
                  if fatigue>0.03:
                      fatigue=fatigue-0.03

                  alarm_status = False

              if (distance > yawn_thresh):
                  cv2.putText(frame, "Yawn Alert", (10, 30),
                              cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
                  if alarm_status2 == False:

                      fatigue=fatigue+yawncounter
                      if(yawncounter<0.15+yawncounter):
                          yawncounter=yawncounter+0.15
                      alarm_status2 = True
              else:
                  alarm_status2 = False

              if fatigue>100:
                  fatigue=100
                  cv2.putText(frame, "Fatigue Level:{:.2f} ".format(fatigue), (250, 60),
                              cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
              else:
               cv2.putText(frame, "Fatigue Level:{:.2f} ".format(fatigue), (250, 60),
                          cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

          cv2.imshow("Frame", frame)
          key = cv2.waitKey(1) & 0xFF

          if key == ord("q"):
              break

      cv2.destroyAllWindows()
      vs.stop()

    #RoadCamera
    def onBtn2Click(self, event):
        self.label.SetLabelText("Road Camera is activating please wait...")

        def region_of_interest(img, vertices):
            mask = np.zeros_like(img)
            match_mask_color = 255
            cv2.fillPoly(mask, vertices, match_mask_color)
            masked_img = cv2.bitwise_and(img, mask)
            return masked_img

        def drow_the_lines(img, lines):
            img = np.copy(img)
            blank_image = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)

            for line in lines:
                for x1, y1, x2, y2 in line:
                    cv2.line(blank_image, (x1, y1), (x2, y2), (0, 255, 0), thickness=10)

            img = cv2.addWeighted(img, 0.8, blank_image, 0.7, 0.0)
            return img

        def process(image):
            print(image.shape)
            height = image.shape[0]
            width = image.shape[1]
            region_of_interest_vertices = [
                (0, height),
                (width / 2, height / 1.4),
                (width, height)
            ]
            gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
            canny_image = cv2.Canny(gray_image, 100, 120)
            cropped_image = region_of_interest(canny_image,
                                               np.array([region_of_interest_vertices], np.int32), )
            lines = cv2.HoughLinesP(cropped_image,
                                    rho=2,
                                    theta=np.pi / 180,
                                    threshold=50,
                                    lines=np.array([]),
                                    minLineLength=40,
                                    maxLineGap=100)
            image_with_lines = drow_the_lines(image, lines)
            return image_with_lines

        cap = cv2.VideoCapture('test.mp4')

        while cap.isOpened():
            ret, frame = cap.read()
            frame = process(frame)
            cv2.imshow('frame', frame)
            if cv2.waitKey(5) & 0xFF == ord('q'):
                break

        cap.release()
        cv2.destroyAllWindows()
        cv2.destroyAllWindows()

class MyApp(wx.App):
       def OnInit(self):
        self.frame = MyFrame(parent = None, title="Fatigue Detection")
        self.frame.Show()
        return True

app = MyApp()
app.MainLoop()


# 29. 공유기 설치

n, c = map(int, input().split())
houses = []
for i in range(n):
    houses.append(int(input()))

houses.sort()

start = 1
end = houses[-1] - houses[0]  # 최대 거리
answer = 0

while start <= end:
    mid = (start + end) // 2
    value = houses[0]
    count = 1

    # 공유기 설치
    for i in range(1, n):
        if houses[i] >= value + mid:
            count += 1
            value = houses[i]

    if count >= c:
        start = mid + 1
        answer = mid
    else:
        end = mid - 1

print(start-1)


#---------------------------------------------- QUESTION 1 ------------------------------------------------------------#

temp = []

with open('input.txt', 'r') as rf:
    for line in rf:
        create = line.split()
        temp.append(create)

def convert_magic(array):
    for row in range(len(array)):
        for col in range(len(array[0])):
            if array[row][col] == 'N':
                array[row][col] = 0
            else:
                array[row][col] = 1

def brain(array):
    combination1 = [-1, -1, -1, 0, 0, 0, 1, 1, 1]
    combination2 = [-1, 0, 1, -1, 0, 1, -1, 0, 1]

    def dfs(row, col, array, pointer):
        if array[row][col] != 1:
            return pointer
        pointer += 1
        array[row][col] = 2000  # visited cells being denoted

        for x, y in zip(combination1, combination2):
            if (len(array) > row + x >= 0) and len(array[0]) > col + y >= 0:
                pointer = max(pointer, dfs(row + x, col + y, array, pointer))
        return pointer

    max_from_stranger_things = 0
    for row in range(len(array)):
        for col in range(len(array[0])):
            max_from_stranger_things = max(max_from_stranger_things, dfs(row, col, array, 0))
    return max_from_stranger_things

convert_magic(temp)
print(brain(temp))

#---------------------------------------------- QUESTION 1 ------------------------------------------------------------#

#---------------------------------------------- QUESTION 2 ------------------------------------------------------------#

from collections import deque

temp = []

with open('Question2 input1.txt', 'r') as rf:
    rf.seek(4)
    for line in rf:
        create = line.split()
        temp.append(create)

def convert_magic(array):
    for row in range(len(array)):
        for col in range(len(array[0])):
            if array[row][col] == 'A':
                array[row][col] = 2
            elif array[row][col] == 'H':
                array[row][col] = 1
            else:
                array[row][col] = 0 # Zeroes are set as traps

def bfs(grid):
    q = deque()
    time, human = 0, 0
    for row in range(len(grid)):
        for col in range(len(grid[0])):
            if grid[row][col] == 1:
                human += 1
            if grid[row][col] == 2:
                q.append([row, col])
    combination1 = [0, 0, 1, -1]
    combination2 = [1, -1, 0, 0]
    newly_infected = None
    while q and human > 0:
        for i in range(len(q)):
            row, col = q.popleft()
            for x, y in zip(combination1, combination2):
                new_row, new_col = row+x, col+y

                if (new_row < 0 or new_row == len(grid) or new_col < 0 or new_col == len(grid[0])
                        or grid[new_row][new_col] in [0, 2]):
                    continue
                grid[new_row][new_col] = 2

                q.append([new_row, new_col])
                human -= 1
                newly_infected = True

        if newly_infected:
            time += 1
        newly_infected = False
    if human == 0:
        survival = 'No one survived.'
    else:
        survival = str(human) + ' survived'

    return time, survival

convert_magic(temp)
time, suvival = bfs(temp)
print('Time:', time, 'minutes')
print(suvival)

#---------------------------------------------- QUESTION 2 ------------------------------------------------------------#

LABS/Lab Assignment 1/13_20101598_Hasan Mohammod Tanzir.py


#!/usr/bin/env python

from sys import argv, exit

program=bytearray()

try:
    with open(argv[1], 'r') as input:
        contents=input.read()
        lines=contents.split('\n')
        for line in lines:
            for chunk in line.split(' '):
                chunk=chunk.strip(' ')
                if len(chunk):
                    b=(int(chunk)).to_bytes(1, byteorder='big', signed=True)
                    program.extend(b)
        output_file = argv[1].replace('slq', 'bin')
        with open(output_file, 'wb') as output:
            output.write(program)
            print(f'Wrote {len(program)} bytes to {output_file}')
except:
    print(f'Usage: {argv[0]} <program.slq>')
    exit()