# Tic Tac Toe (2 player game)

import pyinputplus as pyip 		# User input validation

class Board:
	def __init__(self):
		self.board = [['-', '-', '-'],
					  ['-', '-', '-'],
					  ['-', '-', '-']]

	def print_board(self):
		for i in self.board:
			print("| ", end="")
			for y in i:
				print(f"{y}", end=" | ")
			print()

def player_turn(board, player_sign):
	while True:
		row = pyip.inputNum(prompt="Row #: ", min=1, max=3)
		col = pyip.inputNum(prompt="Column #: ", min=1, max=3)

		if board[int(row) - 1][int(col) - 1] == '-':
			board[int(row) - 1][int(col) - 1] = player_sign
			break
		else:
			print("That spot is taken. Choose another.")

def game_over_check(board):
	if board[0][0] == board[0][1] and board[0][2] == board[0][0]:
		if board[0][0] == '-':
			return False
		return True
	if board[1][0] == board[1][1] and board[1][2] == board[1][0]:
		if board[1][0] == '-':
			return False
		return True
	if board[2][0] == board[2][1] and board[2][2] == board[2][0]:
		if board[2][0] == '-':
			return False
		return True
	if board[0][0] == board[1][0] and board[2][0] == board[1][0]:
		if board[0][0] == '-':
			return False
		return True
	if board[0][1] == board[1][1] and board[2][1] == board[1][1]:
		if board[0][1] == '-':
			return False
		return True
	if board[0][2] == board[1][2] and board[2][2] == board[1][2]:
		if board[0][2] == '-':
			return False
		return True
	if board[0][0] == board[1][1] and board[1][1] == board[2][2]:
		if board[0][0] == '-':
			return False
		return True
	return False

def main():
	board = Board()
	turn = 0
	board.print_board()
	while game_over_check(board.board) is False:
		if turn == 0:
			player = 'O'
			turn = 1
		else:
			player = 'X'
			turn = 0

		print(f"Player {player}'s turn...")
		player_turn(board.board, player)
		board.print_board()

	if turn == 0:
		print("Player X won!")
	else:
		print("Player O won!")

if __name__ == '__main__':
	main()


import string
from Socket import sendMessage
from Settings import ADMIN

def joinRoom(s):
    readbuffer = ""
    Loading = True
    while Loading:
        readbuffer = s.recv(1024)
        readbuffer = readbuffer.decode()
        temp = readbuffer.split("\n")
        readbuffer = readbuffer.encode()
        readbuffer = temp.pop()
        for line in temp:
            print(line)
            Loading = loadingComplete(line)
    sendMessage(s, ADMIN, "/me has reconnected.")

def loadingComplete(line):
    if("End of /NAMES list" in line):
        return False
    else:
        return True


import numpy as np
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from tkinter.scrolledtext import ScrolledText
import cv2
from PIL import ImageTk, Image

"""
仅用来测试客户端布局
"""

class GUI:
    def __init__(self, root):
        self.root = root
        self.filename = ''
        self.is_stop = True
        self.is_first_run = True
        # 1. 设置布局
        self.setLayout()
        # 循环显示
        self.root.mainloop()

    def setLayout(self):
        """
        设置布局
        """
        self.root.title('基于姿态识别的身份认证系统')
        self.root.geometry('1080x681+200+50')
        # 画布标签
        label_canva = Label(self.root, text='处理后视频流', font="20")
        label_canva.pack()
        label_canva.place(x=50, y=20)
        # 画布，显示处理后的视频
        self.canva = Canvas(self.root, width=400, height=400, bg='gray')
        # self.canva = Canvas(self.root, width=246, height=448, bg='gray')
        self.canva.pack()
        self.canva.place(x=50, y=50)
        # 选择文件按钮
        self.btn_select_file = Button(self.root, text="选择视频文件", command=self.openFile)
        self.btn_select_file.pack()
        self.btn_select_file.place(x=50, y=518)
        # 文件信息
        self.msg_file = Message(self.root, highlightthickness=1, highlightbackground='black', width=200, text="当前未选择文件")
        self.msg_file.pack()
        self.msg_file.place(x=50, y=568)
        # 节点信息标签
        label_text = Label(self.root, text='输出信息', font="20")
        label_text.pack()
        label_text.place(x=480, y=20)
        # 显示节点信息
        self.text = Text(self.root, width=40, height=34)
        self.text = ScrolledText(self.root, width=40, height=34)
        self.text.pack()
        self.text.place(x=480, y=50)
        str = '''If there is anyone out there who still doubts that America is a place where all things are possible, who still wonders if the dream of our founders is alive in our time, who still questions the power of our democracy, tonight is your answerIt’s the answer told by lines that stretched around schools and churches in numbers this nation has never seen, by people who waited three hours and four hours, many for the first time in their lives, because they believed that this time must be different, that their voices could be that difference.'''
        self.text.insert('insert', str)
        # 运行按钮
        self.btn_run = Button(self.root, width=40, text="识别视频", command=self.run)
        self.btn_run.pack()
        self.btn_run.place(x=480, y=518)
        # 停止按钮
        self.btn_stop = Button(self.root, width=40, text="暂停识别", command=self.stop)
        self.btn_stop.pack()
        self.btn_stop.place(x=480, y=568)
        # 复选框
        self.is_origin = IntVar()
        self.checkbtn_origin = Checkbutton(root, text="输出原图", variable=self.is_origin)
        self.checkbtn_origin.pack()
        self.checkbtn_origin.place(x=800, y=50)
        self.var = IntVar()
        c = Checkbutton(root, text="保存步态时序图", variable=self.var, command=self.run)
        c.pack()
        c.place(x=800, y=80)

    def run(self):
        print(self.var.get())

    def stop(self):
        self.is_stop = True
        # 绘制最后一帧
        self.drawCanvas(self.image)

    def openFile(self):
        pass

if __name__ == '__main__':
    root = Tk()
    # 1. 初始化界面
    GUI(root)


'''
Created on 19/11/2013

@author: Santi
'''
import unittest
from src.Program import *
from mockito import *

class TestProgram(unittest.TestCase):

    def setUp(self):
        self.program = Program("myProgram")
        self.instrucion = mock()

    def testAddInstruction(self):
        self.program.addInstruction(self.instrucion)
        self.assertEquals(self.program.getInstruction()[0],self.instrucion)
        self.assertEqual(len(self.program.instruction), 1)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()


import ast
import functools

def compare(l, r):
    if type(l) == type(r) == int:
        return l - r
    elif type(l) == type(r) == list:
        for ll, rr in zip(l, r):
            result = compare(ll, rr)
            if result != 0:
                return result
        return len(l) - len(r)
    elif type(l) == int:
        return compare([l], r)
    else:
        return compare(l, [r])

def adv13a():
    count = 0
    index = 1

    with open("input13.txt", "r") as f:
        inputs = []
        for line in f.readlines():
            if line.strip():
                inputs.append(line)
            else:
                inputs = []
                index += 1

            if len(inputs) == 2:
                left, right = inputs
                left = ast.literal_eval(left)
                right = ast.literal_eval(right)

                result = compare(left, right)
                if result < 0:
                    count += index

    print(count)

def adv13b():
    data = [[[2]], [[6]]]
    with open("input13.txt", "r") as f:
        inputs = []
        for line in f.readlines():
            if line.strip():
                inputs.append(line)
            else:
                inputs = []

            if len(inputs) == 2:
                left, right = inputs
                left = ast.literal_eval(left)
                right = ast.literal_eval(right)
                data.append(left)
                data.append(right)

    data.sort(key=functools.cmp_to_key(compare))
    i1 = data.index([[2]]) + 1
    i2 = data.index([[6]]) + 1

    print(i1 * i2)

if __name__ == "__main__":
    adv13b()


import os, logging
import unittest

import rmt.rmt

this_dir   = os.path.dirname(__file__)
models_dir = os.path.join( os.path.join(this_dir, os.pardir), 'sample', 'models') # i.e.: cd ../sample/models

logger = logging.getLogger(None) # get the "root" logger

class SampleRobotModel:
    '''
    Utility base class to load models contained in the `sample/` folder
    '''

    def __init__(self, name, extension):
        '''
        - `name`: the name of the robot model to load
        - `extension`: the model file extension, e.g. "kindsl", "urdf", ...

        This function will try to load the model `sample/<name>/<name>.<extension>`
        '''
        rpath = os.path.join( name, name+'.'+extension ) # <name>/<name>.<extension>
        rfile = os.path.join( models_dir, rpath )
        logger.debug("Trying to load {0}".format(rfile))
        self.connectivity, self.ordering, self.frames, self.geometry, self.inertia, _ = rmt.rmt.getmodels(rfile)

class RobotTestBase(unittest.TestCase):
    def setUp(self):
        '''
        Expect robot-data to be in the class, and copy a reference to the
        fields in the instance (i.e. self). This way the test code can access
        the robot model data and ground-truth data via self.
        '''
        cls = self.__class__
        self.robot = cls.robotdata.ordering
        self.connectivity = cls.robotdata.connectivity
        self.frames = cls.robotdata.frames
        self.treeu = cls.robotdata.treeutils
        self.groundtruth  = cls.robotdata.groundtruth

def main():
    formatter = logging.Formatter('%(levelname)s (%(name)s) : %(message)s')
    handler   = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger.setLevel(logging.INFO)
    logger.addHandler(handler)
    unittest.main()


from datetime import datetime, date

import pandas as pd
import plotly.express as px
import dash
from dash import Input, Output, callback, html, dcc
from dash_bootstrap_templates import load_figure_template
import dash_bootstrap_components as dbc

import plotly.graph_objs as go
from plotly.subplots import make_subplots
import finnhub

load_figure_template("SUPERHERO")

dash.register_page(__name__, name='Multi-select i korelacija')

education = (pd
             .read_csv("assets/states_all.csv")
             .iloc[:, 1:]
             .rename({
    "AVG_MATH_4_SCORE": "matematika 4ti razred",
    "AVG_MATH_8_SCORE": "matematika 8mi razred",
    "AVG_READING_4_SCORE": "Srpski 4ti razred",
    "AVG_READING_8_SCORE": "Srpski 8mi razred"
}, axis=1)
             .assign(expenditure_per_student=lambda x: x["TOTAL_EXPENDITURE"] / x["GRADES_ALL_G"])
             )

layout = html.Div([
    dbc.Row(html.H1("Obrazovni učinak i rashodi u SAD", style={"text-align": "center"})),
    html.P(children=["Prelaskom kursora preko Dijagrama rasejanja(levo),",html.Br(),
           "možete videti korelaciju troškova na Linijskom grafikonu(desno)"],
           style={"color": "yellow", "textAlign":"center", "font-size":"18",'font-style': 'italic'}),
    html.P("Izaberite X i Y kolonu ispod:",
           style={"color": "yellow", "textAlign":"left", "font-size":"18",'font-style': 'italic'}),
    dbc.Row([
        dbc.Col([
            dbc.Card([
                dcc.Markdown("X kolona",style={'color':'yellow', 'text-align':'center'}),
                dcc.RadioItems(
                    id="score-radio",
                    options=["matematika 4ti razred", "matematika 8mi razred", "Srpski 4ti razred", "Srpski 8mi razred"],
                    value="matematika 8mi razred"
                ),
                html.Hr(),
                dcc.Markdown("Y kolona", style={'color':'yellow', 'text-align':'center'}),
                dcc.RadioItems(
                    id="score-radio2",
                    options=["matematika 4ti razred", "matematika 8mi razred", "Srpski 4ti razred", "Srpski 8mi razred"],
                    value="Srpski 8mi razred"
                )], style={'border-radius': '12px'})
        ], width=2),
        dbc.Col(
            dcc.Graph(id="cross-filter-scatter", hoverData={'points': [{'customdata': ['CALIFORNIA']}]}),width=5,
        ),
        dbc.Col(dcc.Graph(id="x-line"),width=5,)
    ])
])

@callback(
    Output("cross-filter-scatter", "figure"),
    Input("score-radio", "value"),
    Input("score-radio2", "value"))
def score_scatter(x, y):
    fig = px.scatter(
        education.query("YEAR == 2013"),
        x=x,
        y=y,
        hover_name="STATE",
        custom_data=["STATE"]
    ).update_layout(
        # title="Plot Title",
        xaxis_title=f"Bodovi iz: {x}",
        yaxis_title=f"Bodovi iz: {y}",
        # legend_title="Legend Title",
        font=dict(
            family="Calibri",
            size=14,
            color="white"
        ))

    return fig

@callback(
    Output("x-line", "figure"),
    Input("cross-filter-scatter", "hoverData"))
def update_line(hoverData):
    state_name = hoverData["points"][0]["customdata"][0]
    df = education.query("STATE == @state_name")

    fig = px.line(
        df,
        x="YEAR",
        y="expenditure_per_student",
        title=f"Troškovi po studentu u {state_name.title()}"
    ).update_xaxes(showgrid=False,).update_layout(
        title={'y': 0.9,
               'x': 0.5,
               'xanchor': 'center',
               },
        xaxis_title="Godina",
        yaxis_title="Troškovi po studentu u hiljadama",
        # legend_title="Legend Title",
        font=dict(
            family="Calibri",
            size=14,
            color="white"
        ))

    return fig


# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_matrix(matrix_to_print):
    str1 = ""
    for n in range(len(matrix_to_print)):
        str1 = str1 +"\n"+ str(matrix_to_print[n])
    return str1

def make_unit_matrix():
    unit_matrix = []
    for i in range(0, size):
        temp = []

        for j in range(0, size):
            if i == j:
                temp.append(1)
            else:
                temp.append(0)
        unit_matrix.append(temp)
    return unit_matrix

def make_elementary_matrix(pivot, num1, row, col):
    temp_elementary = make_unit_matrix()
    temp_elementary[row][col] = -1 * (num1 / pivot)
    return temp_elementary

def exchange(row, row_replace):
    unit_matrix = temp_elementary = make_unit_matrix()
    temp_elementary[row], temp_elementary[row_replace] = unit_matrix[row_replace], unit_matrix[row]
    return temp_elementary

def gauss_method(matrix):
    mul = make_unit_matrix()
    for r in range(size):
        maxi = abs(matrix[r][r])
        flag = 0
        for c in range(r, size):
            if abs(matrix[c][r]) > maxi:
                maxi = abs(matrix[c][r])
                flag = 1
                c_max = c
        if flag != 0:
            temp_matrix = exchange(r, c_max)
            mul = multiply_two_matrix(temp_matrix, mul)
            f1.writelines("-------------------------------------------------------")
            f1.writelines(f'{print_matrix(temp_matrix)}\nX{print_matrix(matrix)}\n=')
            matrix = multiply_two_matrix(temp_matrix, matrix)
            f1.writelines(f'{print_matrix(matrix)}\n')
    for r in range(size):
        for c in range(r, size):
            if matrix[r][r] == 1 and r != c:
                temp_matrix = make_elementary_matrix(matrix[r][r], matrix[c][r], c, r)
                mul = multiply_two_matrix(temp_matrix, mul)
                f1.writelines("-------------------------------------------------------")
                f1.writelines(f'{print_matrix(temp_matrix)}\nX{print_matrix(matrix)}\n=')
                matrix = multiply_two_matrix(temp_matrix, matrix)
                f1.writelines(f'{print_matrix(matrix)}\n')
            else:
                temp_matrix = make_unit_matrix()
                if matrix[r][r] < 0:
                    temp_matrix[r][r] = 1 / matrix[r][r]
                else:
                    temp_matrix[r][r] = 1 / matrix[r][r]
                mul = multiply_two_matrix(temp_matrix, mul)
                f1.writelines("-------------------------------------------------------")
                f1.writelines(f'{print_matrix(temp_matrix)}\nX{print_matrix(matrix)}\n=')
                matrix = multiply_two_matrix(temp_matrix, matrix)
                f1.writelines(f'{print_matrix(matrix)}\n')
    for r in range(size-1, -1, -1):
        for c in range(r, -1, -1):
            if r != c:
                temp_matrix = make_elementary_matrix(matrix[r][r], matrix[c][r], c, r)
                mul = multiply_two_matrix(temp_matrix, mul)
                f1.writelines("-------------------------------------------------------")
                f1.writelines(f'{print_matrix(temp_matrix)}\nX{print_matrix(matrix)}\n=')
                matrix = multiply_two_matrix(temp_matrix, matrix)
                f1.writelines(f'{print_matrix(matrix)}\n')
    return mul

def multiply_two_matrix(matrix1, matrix2):
    result = []
    for r in range(len(matrix1)):
        helper_res = []
        for c in range(len(matrix1)):
            helper_res.append(0)
        result.append(helper_res)
    for i in range(len(matrix1)):
        # iterating by column by B
        for j in range(len(matrix2[0])):
            # iterating by rows of B
            for k in range(len(matrix2)):
                result[i][j] += matrix1[i][k] * matrix2[k][j]
    return result

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    f1 = open("file1.txt", 'w')
    f1.write(">>>Solution steps:>>>\n")
    matrix = []
    answer_matrix = []
    final_result = []
    size = int(input("Enter size of the matrix n >> (nXn): "))
    for i in range(size):
        helper = []
        for j in range(size):
            num = float(input(f'matrix[{i}][{j}]='))
            helper.append(num)
        matrix.append(helper)
        num = float(input(f'result num in row {i + 1}='))
        answer_matrix.append(num)
    multiply_elementary_matrix = gauss_method(matrix)
    for i in range(size):
        final_result.append(0)
    for r in range(len(multiply_elementary_matrix)):
        for c in range(len(multiply_elementary_matrix)):
            final_result[r] += multiply_elementary_matrix[r][c] * answer_matrix[c]
    f1.writelines("-------------------------------------------------------\n")
    f1.writelines(f'\nThe results are:')
    for n in range(len(final_result)):
        f1.writelines(f'\nX{n+1}={final_result[n]}')
    f1.close()
    print("<<<TO WATCH THE RESULTS GO CHECK FILE NAMED: file1>>>")

# See PyCharm help at https://www.jetbrains.com/help/pycharm/


# Reference: https://arxiv.org/pdf/1509.02971.pdf
# https://github.com/seungeunrho/minimalRL/blob/master/ddpg.py
# https://github.com/openai/spinningup/blob/master/spinup/algos/pytorch/ddpg/ddpg.py

import argparse
import os
import random
import time
from distutils.util import strtobool

import gym
import matplotlib.pyplot as plt
import numpy as np
import pybullet_envs  # noqa
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from celluloid import Camera
from torch.utils.tensorboard import SummaryWriter

def parse_args():
    # Common arguments
    # fmt: off
    parser = argparse.ArgumentParser()
    parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
        help="the name of this experiment")
    parser.add_argument("--gym-id", type=str, default="HopperBulletEnv-v0",
        help="the id of the gym environment")
    parser.add_argument("--learning-rate", type=float, default=3e-4,
        help="the learning rate of the optimizer")
    parser.add_argument("--seed", type=int, default=1,
        help="seed of the experiment")
    parser.add_argument("--total-timesteps", type=int, default=1000000,
        help="total timesteps of the experiments")
    parser.add_argument("--torch-deterministic", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
        help="if toggled, `torch.backends.cudnn.deterministic=False`")
    parser.add_argument("--cuda", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
        help="if toggled, cuda will be enabled by default")
    parser.add_argument("--track", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
        help="if toggled, this experiment will be tracked with Weights and Biases")
    parser.add_argument("--wandb-project-name", type=str, default="vectorized-value-methods",
        help="the wandb's project name")
    parser.add_argument("--wandb-entity", type=str, default="vwxyzjn",
        help="the entity (team) of wandb's project")
    parser.add_argument("--capture-video", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
        help="weather to capture videos of the agent performances (check out `videos` folder)")
    parser.add_argument("--visualize-timestep-distribution", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
        help="weather to visualize the distribution of timesteps of states")

    # Algorithm specific arguments
    parser.add_argument("--asyncvec", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
        help="weather to use the async vectorized environments")
    parser.add_argument("--num-envs", type=int, default=8,
        help="the number of parallel game environments")
    parser.add_argument("--num-steps", type=int, default=128,
        help="the number of steps to run in each environment per policy rollout")
    parser.add_argument("--num-minibatches", type=int, default=4,
        help="the number of mini-batches")
    parser.add_argument("--update-epochs", type=int, default=4,
        help="the K epochs to update the policy")
    parser.add_argument("--gamma", type=float, default=0.99,
        help="the discount factor gamma")
    parser.add_argument("--tau", type=float, default=0.005,
        help="target smoothing coefficient (default: 0.005)")
    parser.add_argument("--max-grad-norm", type=float, default=0.5,
        help="the maximum norm for the gradient clipping")
    parser.add_argument("--policy-noise", type=float, default=0.2,
        help="the scale of policy noise")
    parser.add_argument("--exploration-noise", type=float, default=0.2,
        help="the scale of exploration noise")
    parser.add_argument("--learning-starts", type=int, default=25000,
        help="timestep to start learning")
    parser.add_argument("--policy-frequency", type=int, default=2,
        help="the frequency of training policy (delayed)")
    parser.add_argument("--noise-clip", type=float, default=0.5,
        help="noise clip parameter of the Target Policy Smoothing Regularization")
    args = parser.parse_args()
    args.batch_size = int(args.num_envs * args.num_steps)
    args.minibatch_size = int(args.batch_size // args.num_minibatches)
    # fmt: on
    return args

class TimestepStats(gym.Wrapper):
    def __init__(self, env) -> None:
        super().__init__(env)

    def step(self, action):
        obs, reward, done, info = super().step(action)
        self.t += 1
        return obs, reward, done, info

    def reset(self, **kwargs):
        obs = super().reset(**kwargs)
        self.t = 0
        return obs

def make_env(gym_id, seed, idx, capture_video, run_name):
    def thunk():
        env = gym.make(gym_id)
        env = TimestepStats(env)
        env = gym.wrappers.RecordEpisodeStatistics(env)
        if capture_video:
            if idx == 0:
                env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
        env.seed(seed)
        env.action_space.seed(seed)
        env.observation_space.seed(seed)
        return env

    return thunk

class QNetwork(nn.Module):
    def __init__(self, envs):
        super(QNetwork, self).__init__()
        self.fc1 = nn.Linear(
            np.array(envs.single_observation_space.shape).prod() + np.prod(envs.single_action_space.shape),
            256,
        )
        self.fc2 = nn.Linear(256, 256)
        self.fc3 = nn.Linear(256, 1)

    def forward(self, x, a):
        x = torch.cat([x, a], 1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

class Actor(nn.Module):
    def __init__(self, envs):
        super(Actor, self).__init__()
        self.fc1 = nn.Linear(np.array(envs.single_observation_space.shape).prod(), 256)
        self.fc2 = nn.Linear(256, 256)
        self.fc_mu = nn.Linear(256, np.prod(envs.single_action_space.shape))

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        return torch.tanh(self.fc_mu(x))

if __name__ == "__main__":
    args = parse_args()
    run_name = f"{args.gym_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
    if args.track:
        import wandb

        wandb.init(
            project=args.wandb_project_name,
            entity=args.wandb_entity,
            config=vars(args),
            name=run_name,
            monitor_gym=True,
            save_code=True,
        )
        wandb.tensorboard.patch(save=False)
    writer = SummaryWriter(f"runs/{run_name}")
    writer.add_text(
        "hyperparameters",
        "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
    )

    # TRY NOT TO MODIFY: seeding
    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.backends.cudnn.deterministic = args.torch_deterministic

    device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")

    # env setup
    VecEnv = gym.vector.AsyncVectorEnv if args.asyncvec else gym.vector.SyncVectorEnv
    envs = VecEnv([make_env(args.gym_id, args.seed + i, i, args.capture_video, run_name) for i in range(args.num_envs)])
    assert isinstance(envs.single_action_space, gym.spaces.Box), "only continuous action space is supported"

    # ALGO LOGIC: initialize agent here:
    max_action = float(envs.single_action_space.high[0])
    actor = Actor(envs).to(device)
    qf1 = QNetwork(envs).to(device)
    qf2 = QNetwork(envs).to(device)
    qf1_target = QNetwork(envs).to(device)
    qf2_target = QNetwork(envs).to(device)
    target_actor = Actor(envs).to(device)
    target_actor.load_state_dict(actor.state_dict())
    qf1_target.load_state_dict(qf1.state_dict())
    qf2_target.load_state_dict(qf2.state_dict())
    q_optimizer = optim.Adam(list(qf1.parameters()) + list(qf2.parameters()), lr=args.learning_rate)
    actor_optimizer = optim.Adam(list(actor.parameters()), lr=args.learning_rate)
    loss_fn = nn.MSELoss()

    # ALGO Logic: Storage setup
    obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device)
    actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device)
    rewards = torch.zeros((args.num_steps, args.num_envs)).to(device)
    dones = torch.zeros((args.num_steps, args.num_envs)).to(device)
    timesteps = torch.zeros((args.num_steps, args.num_envs)).to(device)

    # TRY NOT TO MODIFY: start the game
    global_step = 0
    start_time = time.time()
    next_obs = torch.Tensor(envs.reset()).to(device)
    next_done = torch.zeros(args.num_envs).to(device)
    num_updates = args.total_timesteps // args.batch_size
    num_gradient_updates = 0

    # Visualization:
    if args.visualize_timestep_distribution:
        fig, ax = plt.subplots()
        camera = Camera(fig)

    for update in range(1, num_updates + 1):
        # ROLLOUTS
        for step in range(0, args.num_steps):
            global_step += 1 * args.num_envs
            obs[step] = next_obs
            dones[step] = next_done

            # ALGO LOGIC: action logic
            with torch.no_grad():
                action = actor.forward(next_obs)
                clipped_noise = (
                    (torch.randn_like(action) * args.exploration_noise).clamp(-args.noise_clip, args.noise_clip).to(device)
                )
                action = (action + clipped_noise).clamp(-max_action, max_action)
                """
                action = (
                    action +
                    torch.normal(0, 1.0 * args.exploration_noise, size=(envs.num_envs, envs.single_action_space.shape[0]), device=device)
                ).clamp(-max_action, max_action)
                """
                action = action
            actions[step] = action

            # TRY NOT TO MODIFY: execute the game and log data.
            next_obs, reward, done, info = envs.step(action.cpu().numpy())
            rewards[step] = torch.tensor(reward).to(device).view(-1)
            next_obs, next_done = (
                torch.Tensor(next_obs).to(device),
                torch.Tensor(done).to(device),
            )
            timesteps[step] = torch.Tensor(np.array([env.t for env in envs.envs]))

            for item in info:
                if "episode" in item.keys():
                    print(f"global_step={global_step}, episodic_return={item['episode']['r']}")
                    writer.add_scalar("charts/episodic_return", item["episode"]["r"], global_step)
                    writer.add_scalar("charts/episodic_length", item["episode"]["l"], global_step)
                    break

        if args.visualize_timestep_distribution:
            max_timestep = int(timesteps.max().long())
            histogram = timesteps.histc(bins=max_timestep, min=0, max=max_timestep)
            x = range(max_timestep)
            ax.bar(x, histogram.cpu())
            ax.set_xlabel("Visited timestep of the obs (higher the better)")
            ax.set_ylabel("Number of occurrences")
            ax.text(0.2, 1.01, f"global_step={global_step}, update={update}", transform=ax.transAxes)
            camera.snap()

        # TRAINING
        b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
        b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
        b_rewards = rewards.reshape((-1,))
        b_dones = dones.reshape((-1,))

        # next_obs index manipulation
        b_next_obs = torch.zeros_like(obs).to(device)
        b_next_obs[:-1] = obs[1:]
        b_next_obs[-1] = next_obs
        b_next_obs = b_next_obs.reshape((-1,) + envs.single_observation_space.shape)
        b_inds = np.arange(args.batch_size)
        for epoch in range(args.update_epochs):
            np.random.shuffle(b_inds)
            for start in range(0, args.batch_size, args.minibatch_size):
                num_gradient_updates += 1
                end = start + args.minibatch_size
                mb_inds = b_inds[start:end]

                with torch.no_grad():
                    clipped_noise = (
                        (torch.randn_like(b_actions[mb_inds]) * args.policy_noise)
                        .clamp(-args.noise_clip, args.noise_clip)
                        .to(device)
                    )
                    next_state_actions = (target_actor.forward(b_next_obs[mb_inds]) + clipped_noise).clamp(
                        -max_action, max_action
                    )

                    qf1_next_target = qf1_target.forward(b_next_obs[mb_inds], next_state_actions)
                    qf2_next_target = qf2_target.forward(b_next_obs[mb_inds], next_state_actions)
                    min_qf_next_target = torch.min(qf1_next_target, qf2_next_target)
                    next_q_value = b_rewards[mb_inds] + (1 - b_dones[mb_inds]) * args.gamma * (min_qf_next_target).view(-1)

                qf1_a_values = qf1.forward(b_obs[mb_inds], b_actions[mb_inds]).view(-1)
                qf2_a_values = qf2.forward(b_obs[mb_inds], b_actions[mb_inds]).view(-1)
                qf1_loss = loss_fn(qf1_a_values, next_q_value)
                qf2_loss = loss_fn(qf2_a_values, next_q_value)

                writer.add_scalar("debug/q1_values", qf1_a_values.mean().item(), global_step)
                writer.add_scalar("debug/q2_values", qf2_a_values.mean().item(), global_step)

                # optimize the model
                q_optimizer.zero_grad()
                qf1_loss.backward()
                qf2_loss.backward()

                nn.utils.clip_grad_norm_(list(qf1.parameters()) + list(qf2.parameters()), args.max_grad_norm)
                q_optimizer.step()
                writer.add_scalar("losses/qf1_loss", qf1_loss.item(), global_step)
                writer.add_scalar("losses/qf2_loss", qf2_loss.item(), global_step)

                if num_gradient_updates % args.policy_frequency == 0:
                    actor_loss = -qf1.forward(b_obs[mb_inds], actor.forward(b_obs[mb_inds])).mean()
                    actor_optimizer.zero_grad()
                    actor_loss.backward()
                    nn.utils.clip_grad_norm_(list(actor.parameters()), args.max_grad_norm)
                    actor_optimizer.step()

                    writer.add_scalar("losses/actor_loss", actor_loss.item(), global_step)  # update the target network
                    for param, target_param in zip(actor.parameters(), target_actor.parameters()):
                        target_param.data.copy_(args.tau * param.data + (1 - args.tau) * target_param.data)
                    for param, target_param in zip(qf1.parameters(), qf1_target.parameters()):
                        target_param.data.copy_(args.tau * param.data + (1 - args.tau) * target_param.data)
                    for param, target_param in zip(qf2.parameters(), qf2_target.parameters()):
                        target_param.data.copy_(args.tau * param.data + (1 - args.tau) * target_param.data)
        print("SPS:", int(global_step / (time.time() - start_time)))
        writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)

    if args.visualize_timestep_distribution:
        animation = camera.animate()
        animation.save(f"runs/{run_name}/animation.mp4")
        if args.track:
            wandb.log({"video.0": wandb.Video(f"runs/{run_name}/animation.mp4")})

    envs.close()
    writer.close()


import os
import shutil
import numpy as np
import matplotlib.pyplot as plt
import pylab
from mpl_toolkits.mplot3d import Axes3D

def data_input():
    distance = []
    energy_input = []
    data_inp = open('potential.dat')
    for line in data_inp:
        distance.append(float(line.split()[0]))
        energy_input.append(float(line.split()[1]))
    data_inp.close()
    return distance, energy_input

def check_NaN(par):
    fort7 = open('fort.7', 'r')
    if fort7.read().count(par) == 0:
        fort7.close()
        return True

def fort7():
    fort7 = open('fort.7', 'r')
    fort7_str = fort7.readlines()
    dd = float(fort7_str[1].split('dd=')[1].replace('D', 'E'))
    De = round(float(fort7_str[2].split()[0].replace('D', 'E')), 3)
    Re = round(float(fort7_str[3].split()[0].replace('D', 'E')), 3)
    fort7.close()
    return dd, De, Re

def fort8(start, end, dr, r):
    fort8_file = open('fort.8', 'r')
    fort8_str = fort8_file.read()
    fort8_dat = fort8_str.splitlines()[4:]
    distance8 = []
    energy8 = []
    for line in fort8_dat[(r - start) / dr:(r - end) / dr]:
        if line.split()[1] != 'Infinity':
            distance8.append(float(line.split()[0]))
            energy8.append(float(line.split()[1].replace('D', 'E')))
            # if listTMP_8[0] == start:  # начало
            #     distance8.append(listTMP_8[0])
            #     energy8.append(listTMP_8[1])
            # elif listTMP_8[0] != end and listTMP_8[0] > start:  # всё, что между началом и концом
            #     distance8.append(listTMP_8[0])
            #     energy8.append(listTMP_8[1])
            # elif listTMP_8[0] == end:  # считана последняя точка и цикл закончен
            #     distance8.append(listTMP_8[0])
            #     energy8.append(listTMP_8[1])
            #     break
    return distance8, energy8

def difference_dat(distance, energy_input, distance8, energy8):  # для получения MDC без явного подсчёта по формуле
    difference = []
    for i in range(len(distance)):
        for j in range(len(distance8)):
            if round(distance[i], 2) == distance8[j]:  # выбираем из всех точек fort.8 те, которые были даны в эт.ф.
                DC = energy8[j] - energy_input[i]
                difference.append(abs(DC))
    return round(max(difference), 3)

def plot_ext(distance_ext, energy_ext, name):  # ф-ция для построения на нормальном уч-ке отдельная, т.к. нужны нач.т-ки
    plt.plot(distance_ext, energy_ext, '-', c='b')
    plt.xlabel('r, Å')
    plt.ylabel('V, 1/см')
    plt.savefig(name)
    # plt.close()

def plot(distance8, energy8, distance, energy_input):  # ф-я для построения на +-inf
    plt.plot(distance, energy_input, 'o', c='c')
    plt.plot(distance8, energy8, '-', c='b')
    plt.xlabel('r, Å')
    plt.ylabel('V, 1/см')
    plt.savefig(os.path.join(path, 'U(r)8.png'))
    plt.close()

def moving(path):  # перемещение в нужную папку  файлов
    shutil.move('fort.8', path)
    shutil.move('fort.7', path)
    shutil.move('out.txt', path)
    shutil.move('data_betaFit.dat', path)

def makeData():  # создание матриц для q и n
    x = np.arange(1, 9, 1)
    y = np.arange(1, 9, 1)
    xgrid, ygrid = np.meshgrid(x, y)
    return xgrid, ygrid

def three_d_plot(par, name):  # построение и сохранение
    q, n = makeData()
    fig = pylab.figure()
    axes = Axes3D(fig)
    axes.plot_surface(q, n, par)
    pylab.savefig(name)
    pylab.close()
    # shutil.move(name, r'Re_p 0, De0, Vmin0\Итог')

De = np.zeros((8, 8))  # заготовки для таблиц
MDC = np.zeros((8, 8))
dd = np.zeros((8, 8))
Re = np.zeros((8, 8))
NPR = 591  # параметры для вывода в fort.8
r = 0.1  # (можно попробовать сделать их ввод при запуске)
dr = 0.01
distance, energy_input = data_input()  # считывание первоначальных точек
data_input1 = open('data_betaFit1.dat', 'r')  # счит-е эталонного файла
for q in range(1, 9):
    for n in range(1, 9):
        data_input = open('data_betaFit.dat', 'a')  # создание вводного файл
        shutil.copy('data_betaFit1.dat', 'data_betaFit.dat')
        data_input.write('\n' + str(q) + ' 0 0 ' + str(n) + ' 0' + '\n' + str(NPR) + ' ' + str(r) + ' ' + str(dr))
        data_input.close()
        data_input1.close()
        folder_name_1 = 'Re_p 0, De0, Vmin0'
        folder_name_2 = 'q = {}\q = {}, n = {}'.format(q, q, n)
        path = os.path.join(folder_name_1, folder_name_2)
        if os.path.exists(path) == False:
            os.makedirs(path)
        os.system('betaFit.exe <data_betaFit.dat >out.txt')
        # moving(path)
        if check_NaN('NaN') == True and check_NaN('Infinity') == True:  # проверка на возможность аппроксимации
            dd[q - 1][n - 1], De[q - 1][n - 1], Re[q - 1][n - 1] = fort7()  # считывание параметров из fort.7
            distance8, energy8 = fort8(1.3, 4, dr, r)  # счит-е т-к для графика на начальном участке
            distance_minf, energy_minf = fort8(0.1, 2, dr, r)  # счит-е т-к на -inf
            distance_pinf, energy_pinf = fort8(3.95, 6, dr, r)  # счит-е т-к на +inf
            MDC[q - 1][n - 1] = difference_dat(distance, energy_input, distance8, energy8)  # получение MDC
            plot(distance8, energy8, distance, energy_input)
            plot_ext(distance_minf, energy_minf,
                     os.path.join(path, 'U(r)_minf.png'))  # построение графиков и их сохранение
            plot_ext(distance_pinf, energy_pinf, os.path.join(path, 'U(r)_pinf.png'))
        else:  # если аппр-я не удалась, то можно передать NaN или 0 (я покажу оба варианта)
            dd[q - 1][n - 1] = np.max(np.abs(dd))
            De[q - 1][n - 1] = np.max(np.abs(De))
            MDC[q - 1][n - 1] = np.max(np.abs(MDC))
            Re[q - 1][n - 1] = np.max(np.abs(Re))

# os.makedirs(r'Re_p 0, De0, Vmin0\Итог')  # создание папки для результатов
np.savetxt(r'Re_p 0, De0, Vmin0\Итог\table_dd.txt', dd)  # сохранение таблиц
np.savetxt(r'Re_p 0, De0, Vmin0\Итог\table_MDC.txt', MDC)
np.savetxt(r'Re_p 0, De0, Vmin0\Итог\table_De.txt', De)
np.savetxt(r'Re_p 0, De0, Vmin0\Итог\table_Re.txt', Re)
three_d_plot(dd, 'dd(q, n).png')  # построение поверхностей
three_d_plot(MDC, 'MDC(q, n).png')
three_d_plot(De, 'De(q, n).png')
three_d_plot(Re, 'Re(q, n).png')

print(np.argmin(dd))
print(np.min(np.abs(De)))
print(np.argmin(MDC))
print(np.min(Re))


# name=Import field data
# displayinmenu=true
# displaytouser=true
# displayinselector=true

from monitoring import importdata
import toolbox as tb
import toolbox.util as tbu
from voluptuous import Schema, Optional

class ImportTool(tb.Tool):
    schema = Schema({
        'folder': unicode,
        'files': [
            unicode
        ],
        'site': unicode,
        'version': unicode,
        'columns': {
            'date': {
                'title': unicode,
                'format': unicode
            },
            Optional('time'): {
                'title': unicode
            },
            'location': {
                'title': unicode
            }
        },
        'mapping': {
            unicode: unicode
        },
        'params': {
            unicode: {
                'unit': unicode
            }
        }
    }, required=True)

    refreshCatalogue = 1

    def main(self):
        records = importdata.locationsDown(self.config)
        imported = tbu.saveRecords(records, self.dssFilePath)
        self.message = "{} Records imported.".format(imported)

tool = ImportTool()
tool.run()


from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Category, Product, Wishlist, Order, OrderItem, ShippingAddress
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, logout
from random import shuffle
from django.shortcuts import render
from .forms import SearchForm
from .models import Product

from django import forms
from django.contrib.auth.forms import UserCreationForm

class CustomUserCreationForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

def category_products(request, category):
    category = get_object_or_404(Category, name=category)
    products = Product.objects.filter(category=category, available=True)
    context = {
        'category': category,
        'products': products
    }
    return render(request, 'category_products.html', context)

def home(request):
    categories = Category.objects.all()
    products = Product.objects.filter(available=True)
    products = list(products)
    shuffle(products)
    context = {
        'categories': categories,
        'products': products
    }
    return render(request, 'home.html', context)

@login_required
def product_detail(request, slug):
    product = get_object_or_404(Product, slug=slug)
    context = {
        'product': product
    }
    return render(request, 'product.html', context)

@login_required
def add_to_wishlist(request, slug):
    product = get_object_or_404(Product, slug=slug)
    wishlist, created = Wishlist.objects.get_or_create(user=request.user)
    wishlist.product.add(product)
    return render(request, 'wishlist.html', {'wishlist': wishlist})

@login_required
def remove_from_wishlist(request, slug):
    product = get_object_or_404(Product, slug=slug)
    wishlist = get_object_or_404(Wishlist, user=request.user)
    wishlist.product.remove(product)
    return render(request, 'wishlist.html', {'wishlist': wishlist})

@login_required
def wishlist(request):
    wishlist = get_object_or_404(Wishlist, user=request.user)
    context = {
        'wishlist': wishlist
    }
    return render(request, 'wishlist.html', context)

@login_required
def add_to_cart(request, slug):
    product = get_object_or_404(Product, slug=slug)
    order, created = Order.objects.get_or_create(user=request.user, is_completed=False)
    order_item, item_created = OrderItem.objects.get_or_create(order=order, product=product, defaults={'quantity': 1})

    if not item_created:
        # Update the quantity if the order item already exists
        order_item.quantity += 1
        order_item.save()

    return render(request, 'cart.html', {'order': order})

@login_required
def remove_from_cart(request, slug):
    product = get_object_or_404(Product, slug=slug)
    order = get_object_or_404(Order, user=request.user, is_completed=False)
    order_item = get_object_or_404(OrderItem, order=order, product=product)
    if order_item.quantity > 1:
        order_item.quantity -= 1
        order_item.save()
    else:
        order_item.delete()
    return render(request, 'cart.html', {'order': order})

@login_required
def cart_view(request):
    try:
        order = Order.objects.get(user=request.user, is_completed=False)
        order_items = OrderItem.objects.filter(order=order)
        context = {
            'order': order,
            'order_items': order_items,
        }
    except Order.DoesNotExist:
        context = {
            'order': None,
            'order_items': None,
        }
    return render(request, 'cart.html', context)

from email.message import EmailMessage
import smtplib
import ssl
import time
from datetime import datetime,timedelta
import random
@login_required
def complete_order(request):
    order = get_object_or_404(Order, user=request.user, is_completed=False)
    # order.is_completed = True
    # order.save()
    product_names = order.products.values_list('name', flat=True)
    price = order.products.values_list('price', flat=True)
    price = list(map(lambda x: str(x), price))
    price = eval("+".join(price))

    product_names = list(product_names)
    product_names =",".join(product_names)
    if order.is_completed:
        msg = EmailMessage()
        msg['Subject'] = "order confirmation"
        msg['From'] = "botauto212@gmail.com"
        msg['To'] = request.user.email
        msg.set_content("Email From: " + "\n\nMessage:\n" + "Order confirmed of item(s): "+product_names+"\nOrder number: " +str(int(order.created_at.timestamp())) + "\nPayment: R"+str(price) )
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL('smtp.gmail.com',465,context=context) as smtp:
          smtp.login(msg['From'],"cjeifgsiqfivevdx")
          smtp.sendmail(msg["From"],msg["To"],msg.as_string())
    return render(request, 'order_confirmation.html', {'order': str(int(order.created_at.timestamp())), 'price':price,'user':request.user.username,'email':request.user.email})

@login_required
def payment(request):
    request.POST.get('email')
    order = get_object_or_404(Order, user=request.user, is_completed=False)
    order.is_completed = True
    order.save()
    product_names = order.products.values_list('name', flat=True)
    price = order.products.values_list('price', flat=True)
    price = list(map(lambda x: str(x), price))
    price = eval("+".join(price))
    product_names = list(product_names)
    product_names =",".join(product_names)
    days =random.randint(1,30)
    current_date = datetime.now()
    future_date = current_date + timedelta(days=days)
    future_date_string = future_date.strftime("%Y-%m-%d")

    if order.is_completed:
        msg = EmailMessage()
        msg['Subject'] = "order confirmation"
        msg['From'] = "botauto212@gmail.com"
        msg['To'] = request.POST.get('email')
        msg.set_content("Email From: " + "\n\nMessage:\n" + "Order confirmed of item(s): "+product_names+"\nOrder number: " +str(int(order.created_at.timestamp())) + "\nPayment: R "+str(price)+ "\nYour Package will be delivered in "+ str(days)+ " days"+ " which will be on "+ future_date_string )
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL('smtp.gmail.com',465,context=context) as smtp:
          smtp.login(msg['From'],"cjeifgsiqfivevdx")
          smtp.sendmail(msg["From"],msg["To"],msg.as_string())
    return render(request, 'billing.html', {'order': str(int(order.created_at.timestamp())), 'price':price,'user':request.user.username, 'email':request.user.email})

@login_required
def order_history(request):
    orders = Order.objects.filter(user=request.user, is_completed=True)
    context = {
        'orders': orders
    }
    return render(request, 'order_history.html', context)

@login_required
def shipping_address(request):
    if request.method == 'POST':
        address = request.POST.get('address')
        city = request.POST.get('city')
        postal_code = request.POST.get('postal_code')
        shipping_address, created = ShippingAddress.objects.get_or_create(user=request.user)
        shipping_address.address = address
        shipping_address.city = city
        shipping_address.postal_code = postal_code
        shipping_address.save()
        return render(request, 'shipping_address.html', {'shipping_address': shipping_address})
    else:
        shipping_address = get_object_or_404(ShippingAddress, user=request.user)
        return render(request, 'shipping_address.html', {'shipping_address': shipping_address})

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')
    else:
        form = CustomUserCreationForm()
    return render(request, 'signup.html', {'form': form})

def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('home')  # Replace 'home' with your desired redirect URL after successful login
    else:
        form = AuthenticationForm()
    return render(request, 'login.html', {'form': form})

def logout_view(request):
    logout(request)
    return redirect('login')

def search(request):
    form = SearchForm(request.GET)
    query = form['query'].value() if form.is_valid() else ''
    results = Product.objects.filter(name__icontains=query)
    context = {
        'form': form,
        'query': query,
        'results': results,
    }
    return render(request, 'search_results.html', context)