#!/usr/bin/python3
import os
import tkinter as tk
import wgkinter as wk
import logging
from PIL import Image, ImageTk
import constants as const

class CGWindowBase:
    def __init__(self, master=None):
        # build ui
        self.mainwindow = tk.Tk() if master is None else tk.Toplevel(master)
        self.mainwindow.configure(background="#252526")
        self.mainwindow.geometry("800x480+0+0")
        self.mainwindow.attributes('-fullscreen', True)
        #self.mainwindow.overrideredirect("True")
        self.top_frame = tk.Frame(self.mainwindow)
        self.top_frame.configure(background="#323233", pady=2)

        self.lb_message = tk.Label(self.mainwindow)
        self.lb_message_txt = tk.StringVar()
        self.lb_message.configure(
            background="#323233",
            font="{Arial} 10 {italic}",
            foreground="white",
            textvariable=self.lb_message_txt)
        self.lb_message.place(anchor="nw", x=1, y=4)

        frame1 = tk.Frame(self.top_frame)
        frame1.configure(background="#323233")
        self.lb_title = tk.Label(frame1)
        self.lb_title.configure(
            background="#323233",
            font="{Arial} 14 {}",
            foreground="white",
            text='CG Meter')
        self.lb_title.pack(side="left")
        self.lb_version = tk.Label(frame1)
        self.lb_version_txt = tk.StringVar(value='v0.0')
        self.lb_version.configure(
            background="#323233",
            font="{Arial} 8 {}",
            foreground="white",
            text='v0.0',
            textvariable=self.lb_version_txt)
        self.lb_version.pack(anchor="s", side="left")
        frame1.grid(column=0, row=0)
        self.lb_author = tk.Label(self.top_frame)
        self.lb_author.configure(
            background="#323233",
            font="{Arial} 6 {italic}",
            foreground="white",
            text='by WGS')
        self.lb_author.grid(column=1, row=0, sticky="s", padx="0 5")
        self.top_frame.pack(fill="x", side="top")
        self.top_frame.columnconfigure(0, weight=1)

        self.content_frame = tk.Frame(self.mainwindow)
        self.content_frame.configure(background="#252526")

        # the canvas frame
        self.img = Image.open(os.path.join(const.APP_ROOT_FOLDER,"gui","top_view_800.png"))
        self.sketch = ImageTk.PhotoImage(self.img)
        self.canvas = tk.Canvas(self.content_frame, width=self.img.size[0], height=self.img.size[1])
        self.canvas.create_image(0, 0, image=self.sketch, anchor="nw")
        self.canvas.configure(background="#252526", borderwidth=0, highlightthickness=0)
        self.canvas.pack(side="top",fill="both", expand="yes")

        # the model name and menu
        self.model_frame = tk.Frame(self.content_frame)
        self.model_frame.configure(background="#252526")
        self.lb_model = tk.Label(self.model_frame)
        self.lb_model_name = tk.StringVar()
        self.lb_model.configure(
            background="#252526",
            font="{Arial} 12 {italic}",
            foreground="white",
            textvariable=self.lb_model_name)
        self.lb_model.pack(side="left")
        """ Activate in next version
        self.menu_btn_model = tk.Menubutton(self.model_frame)
        self.menu_btn_model.configure(
            activebackground="#252526",
            activeforeground="#0e639c",
            background="#252526",
            font="{Wingdings} 12 {}",
            foreground="white",
            highlightthickness=0,
            relief="flat",
            text='▼')
        self.menu_model = tk.Menu(self.menu_btn_model)
        self.menu_model.configure(
            activebackground="#0e639c",
            activeborderwidth=0,
            activeforeground="white",
            background="#333333",
            borderwidth=0,
            font="{Arial} 10 {}",
            foreground="white",
            selectcolor="#2a2d2e")
        self.menu_model.add("command", label='    Model 1 ')
        self.menu_model.add("command", label='    Model 2 ')
        self.menu_btn_model.configure(menu=self.menu_model)
        self.menu_btn_model.pack(side="right")
        """
        self.model_frame.place(anchor="ne", relx=1.0)

        # the weights and CG labels
        self.lb_cg_position = []
        self.lb_cg_position.append(wk.Label(self.content_frame))
        self.lb_cg_position.append(wk.Label(self.content_frame))
        for i in range(2):
            self.lb_cg_position[i].configure(highlightbackground="#007fd4", highlightthickness=1, text=f'{0} mm')

        self.lb_cg_position[0].place(anchor="w", relx=0, rely=0, x=const.ORIGIN[0], y=20, width=200)
        self.lb_cg_position[1].place(anchor="w", relx=0, rely=0.5, width=75)

        for label in self.lb_cg_position:
            label.place_hide()

        self.lb_weights = {}
        self.lb_weights['total'] = wk.Label(self.content_frame)
        self.lb_weights['mwheels'] = wk.Label(self.content_frame)
        self.lb_weights['RightWheel'] = wk.Label(self.content_frame)
        self.lb_weights['TailWheel'] = wk.Label(self.content_frame)
        self.lb_weights['LeftWheel'] = wk.Label(self.content_frame)
        for key in self.lb_weights:
            self.lb_weights[key].configure(highlightbackground="#007fd4", highlightthickness=1, text=f'{0} g')
            self.lb_weights[key].place(anchor="center", relx=0, rely=0, width=80)

        self.lb_weights['RightWheel'].place(x=const.RWHEEL[0], y=const.RWHEEL[1])
        self.lb_weights['LeftWheel'].place(x=const.LWHEEL[0], y=const.LWHEEL[1])
        self.lb_weights['TailWheel'].place(x=const.TWHEEL[0], y=const.TWHEEL[1])
        self.lb_weights['mwheels'].place(x=const.LWHEEL[0], y=378)
        self.lb_weights['total'].place(x=378, y=378)

        for key in self.lb_weights:
            self.lb_weights[key].place_hide()

        self.content_frame.pack(
            expand="true",
            fill="both",
            padx=5,
            pady=5,
            side="top")
        self.bottom_frame = tk.Frame(self.mainwindow)
        self.bottom_frame.configure(background="#252526", height=30)
        self.btn_calibrate = wk.Button(self.bottom_frame)
        self.btn_calibrate.configure(text='Calibrate', width=10)
        self.btn_calibrate.pack(padx="3 0", side="left")
        self.btn_calibrate.configure(command=self.on_calibrate)
        self.btn_tare = wk.Button(self.bottom_frame)
        self.btn_tare.configure(text='Tare', width=10)
        self.btn_tare.pack(padx="3 0", side="left")
        self.btn_tare.configure(command=self.on_tare)
        self.btn_start = wk.Button(self.bottom_frame)
        self.btn_start.configure(text='Start', width=5)
        self.btn_start.pack(padx="30 0", side="left")
        self.btn_start.configure(command=self.on_start)
        self.btn_stop = wk.Button(self.bottom_frame)
        self.btn_stop.configure(text='Stop', width=5)
        self.btn_stop.pack(side="left")
        self.btn_stop.configure(command=self.on_stop)
        self.btn_exit = wk.Button(self.bottom_frame)
        self.btn_exit.configure(text='Exit', width=10)
        self.btn_exit.pack(padx=3, pady=3, side="right")
        self.btn_exit.configure(command=self.on_exit)
        self.bottom_frame.pack(fill="x", side="top")

        # Main widget
        self.root = self.mainwindow
        self.mainwindow = self.mainwindow

    def run(self):
        self.mainwindow.mainloop()

    def on_calibrate(self):
        pass

    def on_tare(self):
        pass

    def on_start(self):
        pass

    def on_stop(self):
        pass

    def on_exit(self):
        pass

if __name__ == "__main__":
    raise Exception("This is a module, not a program. It should not be run directly.")


import unittest
from io import StringIO

import ssv

SAMPLE_SSV = """A\x1f\tB\x1f\tC\x1e
"A fox", said the bear.\nHow nice.\x1f\t1.4\x1f\t\tD\tC\tE\x1e
BLah\x1f\t\x1f\t\n\t"'\\\x1e
"""

class SsvTest(unittest.TestCase):
    def test_reader(self):
        input = StringIO(SAMPLE_SSV)
        reader = ssv.reader(input)
        resp = list(reader)
        self.assertSequenceEqual(
            resp,
            [
                ["A", "B", "C"],
                [""""A fox", said the bear.\nHow nice.""", "1.4", "\tD\tC\tE"],
                ["BLah", "", "\n\t\"'\\"],
            ],
        )

    def test_writer(self):
        out = StringIO()
        writer = ssv.writer(out)
        writer.writerow(["A", "B", "C"])
        writer.writerows(
            [
                [""""A fox", said the bear.\nHow nice.""", "1.4", "\tD\tC\tE"],
                ["BLah", "", "\n\t\"'\\"],
            ]
        )
        self.assertEqual(out.getvalue(), SAMPLE_SSV)

    def test_reader_compact(self):
        input = StringIO(SAMPLE_SSV)
        reader = ssv.reader(input, is_compact=True)
        resp = list(reader)
        self.assertSequenceEqual(
            resp,
            [
                ["A", "\tB", "\tC"],
                ["""\n"A fox", said the bear.\nHow nice.""", "\t1.4", "\t\tD\tC\tE"],
                ["\nBLah", "\t", "\t\n\t\"'\\"],
                ["\n"],
            ],
        )

    def test_writer_compact(self):
        out = StringIO()
        writer = ssv.writer(out, is_compact=True)
        writer.writerow(["A", "B", "C"])
        writer.writerows(
            [
                ["1", "3.14159", "\t"],
                ["Foo\n", "Dog", ""],
            ]
        )
        self.assertEqual(
            out.getvalue(), "A\x1fB\x1fC\x1e1\x1f3.14159\x1f\t\x1eFoo\n\x1fDog\x1f\x1e"
        )

    def test_read_mising_final_delimiter(self):
        input = StringIO("A\x1f\tB\x1e\nC\x1f\tD")
        reader = ssv.reader(input)
        self.assertSequenceEqual(
            list(reader),
            [
                ["A", "B"],
                ["C", "D"],
            ],
        )


import os
import fnmatch
import json
import sys
import subprocess
import multiprocessing

def run_cmd(cmd):
  print(cmd)
  return subprocess.call(cmd, shell=True)

def get_bounds(coords):
  x = []
  y = []
  for coord in coords:
    x.append(coord[0])
    y.append(coord[1])
  return [min(x), max(y), max(x), min(y)]

"""
# get the arguments
arg = sys.argv
chunkDir = arg[1]
outDir = arg[2]
clipFile = arg[3]
clipFeature = arg[4]
name = arg[5]
indexID = arg[6]
nVert = int(arg[7])
startYear = int(arg[8])
endYear = int(arg[9])
proj = arg[10]
delete = arg[11]
"""

chunkDir = '/vol/v1/proj/nccn/gee_idl_lt_compare/raster/noca'
outDir = '/vol/v1/proj/nccn/gee_idl_lt_compare/raster/noca'
clipFile = '/vol/v1/proj/nccn/gee_idl_lt_compare/vector/LPa01_LEWI_MORA_NOCA_OLYM.geojson'
clipAttribute = 'PARK_CODE'
clipFeature = 'NOCA'
name = 'nccn_gee_vs_idl_noca'
indexID = 'nbr'
nVert = 7
startYear = 1984
endYear = 2012
proj = 'EPSG:5070'
delete = 'keep'

# make sure path parts are right
if chunkDir[-1] != '/':
  chunkDir += '/'
if outDir[-1] != '/':
  outDir += '/'

# find the tif chunks
tifs = []
for root, dirnames, filenames in os.walk(chunkDir):
  for filename in fnmatch.filter(filenames, '*.tif'):
    tifs.append(os.path.join(root, filename))

# make a list of tile tifs
vrtFile = chunkDir+name+'.vrt'
tileListFile = vrtFile.replace('.vrt', '_filelist.txt')
tileList = open(tileListFile, 'w')
for tif in tifs:
  tileList.write(tif+'\n')
tileList.close()

# create vrt
cmd = 'gdalbuildvrt -input_file_list '+tileListFile+' '+vrtFile
subprocess.call(cmd, shell=True)

# define the list of replacement types in the new out images
outTypes = ['vert_yrs.bsq',
            'vert_src.bsq',
            'vert_fit.bsq',
            'ftv_'+indexID+'.bsq',
            'ftv_tcb.bsq',
            'ftv_tcg.bsq',
            'ftv_tcw.bsq']

# make a list of band ranges for each out type
vertStops = []
for vertType in range(4):
  vertStops.append(vertType*nVert+1)

nYears = (endYear - startYear) + 1
ftvStops = []
for ftvType in range(1,5):
  ftvStops.append(ftvType*nYears+vertStops[-1])

bandStops = vertStops+ftvStops
bandRanges = [range(bandStops[i],bandStops[i+1]) for i in range(len(bandStops)-1)]

# load the tile features
with open(clipFile) as f:
  features = json.load(f)

coords = []
for i in range(len(features['features'])):
  if features['features'][i]['properties'][clipAttribute] == clipFeature:
    coords = coords+features['features'][i]['geometry']['coordinates'][0]

#features['features'][1]['properties']['PARK_CODE'] == 'LEWI'
bounds = get_bounds(coords)
projwin = ' '.join([str(coord) for coord in bounds])

# make a list of all the gdal_translate commands needed for the ee conus chunk
cmdList = []
if not os.path.isdir(outDir):
  os.mkdir(outDir)

for i in range(len(outTypes)):
  outFile = outDir+name+'_'+outTypes[i]
  bands = ' -b '+' -b '.join([str(band) for band in bandRanges[i]])
  cmd = 'gdal_translate -q --config GDAL_DATA "/usr/lib/anaconda/share/gdal" -of ENVI -a_srs ' + proj + bands + ' -projwin '+projwin+' '+ vrtFile + ' ' + outFile
  cmdList.append(cmd)

# run the commands in parallel
pool = multiprocessing.Pool(processes=len(cmdList))
pool.map(run_cmd, cmdList)
pool.close()


# -*- coding: utf-8 -*-
import datetime
from gmun_tests.settings import logger
from gmun_tests import GmunTest
from gmun_tests.utils.vk import Vk
from gmun_tests.utils.mattermost import Mattermost
from time import sleep
import time
import random
from gmun_tests.settings.test_run_params import test_run_params

gid = 156229286
uid=585675

no_driver = False
silent = False

class Gmun_Bot(GmunTest):
    def __init__(self):
        self.name = 'Gmun_Bot'
        self.t_check = test_run_params[f'{self.name}']['t_check']
        self.run_series_count = test_run_params[f'{self.name}']['run_series_count']
        self.fail_limit_count = test_run_params[f'{self.name}']['fail_limit_count']
        self.mattermost = Mattermost()
        self.wait = 20
        GmunTest.__init__(self, no_driver, name=self.name)
        self.silent = silent or False

    def test(self, paused=True):
        driver = self.driver
        driver.set_page_load_timeout(30)
        self.dwait(self.wait)

        try:
            test_start_time = datetime.datetime.now()
            Vk.vk_login(self, self.wait)
            msg = f"1 {random.randint(1, 1000000)}"

            self.supress_wait_8_sec(driver.get("https://vk.com/club156229286"))
            sleep(1)
            self.find("//*[text()='Написать сообщение']").click()
            self.find("//*[@id='mail_box_editable']").clear()
            self.find("//*[@id='mail_box_editable']").send_keys(msg)
            self.if_click("//*[text()='Отправить']", "ok отправка сообщения боту в диалог", "fail  отправка сообщения боту в диалог")
            Vk.check_delivery(self, msg=msg, gid=gid, t_check=self.t_check)

        except Exception as e:
            self.pars_err(f"fail ошибка выполнения скрипта, {e}")

        try:
            self.inter_result[
            'comment'] += f"\nОписание________ gid {gid}, скрипт отправляет сообщение боту в диалог и ждет ответа максимум {self.t_check} секунд"
        except Exception as e:
            self.pars_err(f"fail ошибка добавления описания теста в словарь, {e}")

        self.no_sms = True

        if paused == False:
            pass
        else:
            test_duration_time = abs(round((test_start_time - datetime.datetime.now()).total_seconds()))
            if test_duration_time < self.t_check:
                sleep(self.t_check - test_duration_time)

        self.test_ending()

        if self.inter_result['result'] == 0:
            return "ok"
        else:
            return f'fail, {self.inter_result["error"]}'

if __name__ == '__main__':
    for i in range(1):
        print("started at ", time.strftime('%H:%M:%S').replace("'", ""))
        try:
            test_obj = Gmun_Bot().test()
        except Exception as e:
            print(f"ошибка выполнения __name__ = __main__, {e}")


import json
import _thread as thread
from flask import Flask
from service import StockInfoService, update_data_every_day
from entity import StockInfoEncoder

app = Flask(__name__)
stock_info_service = StockInfoService()

# 启动更新数据定时任务
thread.start_new_thread(update_data_every_day, (stock_info_service,))

@app.route('/get/stock/info')
def get_stock_info():  # put application's code here
    stock_info_list = stock_info_service.get_stock_infos()
    return json.dumps(stock_info_list, cls=StockInfoEncoder)

@app.route("/add/new/stock/<symbol>")
def add_new_stock(symbol):
    """
    新增股票信息
    """
    try:
        stock_info_service.add_new_stock_info(symbol)
    except:
        return 'err'
    return ''

@app.route("/delete/stock/<symbol>")
def delete_stock_info(symbol):
    """
    删除指定股票信息
    :param symbol: 要删除股票的symbol
    """
    try:
        stock_info_service.delete_stock_info(symbol)
    except:
        return 'err'
    return ''

if __name__ == '__main__':
    # 启动flask服务
    app.run()


import tkinter
from pytube import YouTube
import webbrowser

root = tkinter.Tk()
root.geometry('500x300')
root.resizable(0,0)
root.title("Youtube Video Downloader")

tkinter.Label(root, text ='Youtube Video Downloader', font ='arial 20 bold').pack()

##enter link
link = tkinter.StringVar()

tkinter.Label(root, text ='Paste Link Here:', font ='arial 15 bold').place(x= 160, y = 60)
link_enter = tkinter.Entry(root, width = 70, textvariable = link).place(x = 32, y = 90)

#function to download video
def callback(url):
    webbrowser.open_new(url)

def Downloader():

    url =YouTube(str(link.get()))
    video = url.streams.first()
    video.download()
    tkinter.Label(root, text ='DOWNLOADED', font ='arial 15').place(x= 180, y = 210)

tkinter.Button(root, text ='DOWNLOAD', font ='arial 15', bg ='blue', padx = 2, command = Downloader).place(x=180, y = 150)
link1 = tkinter.Label(root, text="Source Code Here", font = 'arial 15', fg="blue", cursor="hand2")
link1.pack()
link1.bind("<Button-1>", lambda e: callback("http://www.github.com/alexliao95311/Youtube-Video-Downloader"))

root.mainloop()


from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession
from pyspark.sql import Window
import pyspark.sql.functions as f

from pyspark.sql.types import IntegerType

from pyspark.sql.functions import udf
sc = SparkContext(master="local", appName="spark demo")
spark = SparkSession \
    .builder \
    .appName("how to read csv file") \
    .getOrCreate()
df = spark.read.format("csv").option("header", "true").option("inferSchema", "true").load("spark_emp_rdd_df_ds_data")
df1 = spark.read.format("csv").option("header", "true").option("inferSchema", "true").load("spark_dept_rdd_df_ds_data")
df.printSchema()

w = Window.partitionBy()
df.withColumn('maxB', f.max('Sal').over(w)).where(f.col('Sal') == f.col('maxB'))\
    .drop('maxB')\
    .drop('DeptNo')\
    .show()

df2 = df.join(df1, how="outer", on="DeptNo")
df2.show()
df2.groupBy("DeptName").agg(f.sum('Sal')).sort('sum(Sal)', ascending=False).show()


from flask import Flask, render_template, request, session

app = Flask(__name__)
app.secret_key = 'senha'

@app.route("/")
@app.route("/home")
def home():
    return render_template("index.html")

@app.route("/newsletter")
def newsletter():
    return render_template("newsletter.html")

@app.route("/inscrever", methods=["POST"])
def inscrever():
    nome = request.form.get("nome")
    email = request.form.get("email")
    tel = request.form.get("tel")

    if 'usuarios' not in session:
        session['usuarios'] = {}

    usuarios = session['usuarios']
    if email in usuarios:
        return 'Usuário já cadastrado com este e-mail.'

    usuarios[email] = {'nome': nome, 'email': email, 'tel': tel}
    session['usuarios'] = usuarios

    return render_template("confirma.html", nome=nome, email=email, tel=tel)

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

Desenvolvimento Web/Prova Parte 1/app.py


import argparse
import os
import tempfile
import json

parser = argparse.ArgumentParser()
parser.add_argument('--key', type=str)
parser.add_argument('--value', type=str, default=None)
var = parser.parse_args()

storage_path = os.path.join(tempfile.gettempdir(), 'storage.data')
if not os.path.exists(storage_path):
    with open(storage_path, 'w') as f:
        pass

if os.stat(storage_path).st_size == 0:
    with open(storage_path, 'w') as f:
        json.dump({}, f)

with open(storage_path, 'r') as f:
    my_dict = json.load(f)
    if var.value is None:
        my_dict.get(var.key, None)
        print(my_dict.get(var.key, None))
    else:
        if var.key in my_dict:
            my_dict[var.key] += f', {var.value}'
        else:
            my_dict[var.key] = var.value

with open(storage_path, 'w') as f:
    json.dump(my_dict, f)


import heffte
import numpy as np
from numba import cuda as gpu
import mpi4py

def make_reference(num_entries, dtype, scale):
    reference = np.zeros((num_entries,), dtype)
    reference[0] = -512.0
    if scale == heffte.scale.symmetric:
        reference /= np.sqrt(float(2 * num_entries))
    elif scale == heffte.scale.full:
        reference /= float(2 * num_entries)
    return reference

comm = mpi4py.MPI.COMM_WORLD
me = comm.Get_rank()

assert comm.Get_size() == 2

box = (heffte.box3d([0, 0, 0], [3, 3, 1])
       if me == 0 else
       heffte.box3d([0, 0, 2], [3, 3, 3]))

fft = heffte.fft3d(heffte.backend.cufft,
                   box, box, comm)

assert fft.size_inbox() == 32
assert fft.size_outbox() == 32

test_types = [[np.float32,    np.complex64,  heffte.scale.none, heffte.scale.full, 1.E-3],
              [np.complex64,  np.complex64,  heffte.scale.symmetric, heffte.scale.symmetric, 1.E-3],
              [np.float64,    np.complex128, heffte.scale.full, heffte.scale.none, 1.E-11],
              [np.complex128, np.complex128, heffte.scale.none, heffte.scale.full, 1.E-11],
              ]

for tt in test_types:

    in_array = np.array(range(fft.size_inbox()), tt[0])
    out_array = np.empty(fft.size_outbox(), tt[1])

    gpu.select_device(0)
    gpu_in = gpu.to_device(in_array)
    gpu_out = gpu.to_device(out_array)

    fft.forward(gpu_in, gpu_out, tt[2])

    reference = make_reference(fft.size_outbox(), tt[1], tt[2]) # num_entries, type, scale
    if me == 1:
        assert np.max(np.abs(reference - gpu_out.copy_to_host())) < tt[4]

    in_array = np.zeros((fft.size_inbox(),), tt[0])
    gpu_in = gpu.to_device(in_array)
    fft.backward(gpu_out, gpu_in, tt[3])

    assert np.max(np.abs(gpu_in.copy_to_host() - np.array(range(fft.size_inbox()), tt[0]))) < tt[4]
    if me == 0:
        print("  pass   ",tt[0],"  ->  ",tt[1])


from PySide2.QtCore import QCoreApplication, Qt, Signal
from PySide2.QtWidgets import QSpinBox
# from betse.util.io.log import logs
from betse.util.type.numeric import floats
from betse.util.type.types import type_check, ClassOrNoneTypes
from betsee.gui.simconf.stack.widget.mixin.guisimconfwdgeditscalar import (
    QBetseeSimConfEditScalarWidgetMixin)
from betsee.util.widget.abc.guiclipboardabc import (
    QBetseeClipboardScalarWidgetMixin)
from betsee.util.widget.stock.guispinbox import QBetseeDoubleSpinBox

# ....................{ SUPERCLASSES                      }....................
class QBetseeSimConfSpinBoxWidgetMixin(
    QBetseeClipboardScalarWidgetMixin, QBetseeSimConfEditScalarWidgetMixin):
    '''
    Abstract base class of all simulation configuration-specific subclasses,
    permitting numeric values (i.e., integers, floating point values) backed by
    external simulation configuration files to be interactively edited.
    '''

    # ..................{ INITIALIZERS                      }..................
    def __init__(self, *args, **kwargs) -> None:

        # Initialize our superclass with all passed arguments.
        super().__init__(*args, **kwargs)

        # Enable so-called "acceleration," both increasing and decreasing the
        # rate at which the displayed number changes as a function of the
        # duration of time that the spon box GUI arrows are depressed.
        self.setAccelerated(True)

        # Align the displayed number against the right rather than left
        # internal edge of this spin box -- the typical default in most GUI
        # frameworks. (For unclear reasons, Qt defaults to right alignment.)
        self.setAlignment(Qt.AlignRight)

        # Disable so-called "keyboard tracking," reducing signal verbosity by
        # preventing the superclass from emitting valueChanged() signals on
        # each key entered by the user (e.g., on all three of the "3", "1", and
        # "4" keys entered by the user to enter the integer "314").
        #
        # Instead, the valueChanged() signal will *ONLY* be emitted when:
        #
        # * The return key is pressed.
        # * Keyboard focus is lost.
        # * Other spinbox functionality is activated (e.g., an up or down arrow
        #   key is pressed, the up or down graphical arrow is clicked).
        self.setKeyboardTracking(False)

    # ..................{ SUPERCLASS ~ setter               }..................
    def setValue(self, value_new: str) -> None:

        # logs.log_debug('In QBetseeSimConfSpinBoxWidgetMixin.setValue()...')

        # Defer to the superclass setter.
        super().setValue(value_new)

        # If this configuration is currently open, set the current value of
        # this simulation configuration alias to this widget's current value.
        self._set_alias_to_widget_value_if_safe()

    # ..................{ MIXIN ~ property                  }..................
    @property
    def undo_synopsis(self) -> str:
        return QCoreApplication.translate(
            'QBetseeSimConfSpinBoxWidgetMixin', 'edits to a spin box')

    @property
    def widget_value(self) -> object:
        return self.value()

    @property
    def _finalize_widget_change_signal(self) -> Signal:
        return self.editingFinished

# ....................{ SUBCLASSES                        }....................
class QBetseeSimConfIntSpinBox(
    QBetseeSimConfSpinBoxWidgetMixin, QSpinBox):
    '''
    Simulation configuration-specific integer spin box widget, permitting
    integers backed by external simulation configuration files to be
    interactively edited.
    '''

    # ..................{ MIXIN                             }..................
    @property
    def _sim_conf_alias_type_strict(self) -> ClassOrNoneTypes:
        return int

    @QBetseeSimConfSpinBoxWidgetMixin.widget_value.setter
    @type_check
    def widget_value(self, widget_value: int) -> None:

        # logs.log_debug('In QBetseeSimConfIntSpinBox.widget_value()...')

        # Set this widget's displayed value to the passed value by calling the
        # setValue() method of our superclass rather than this subclass,
        # preventing infinite recursion. (See the superclass method docstring.)
        QSpinBox.setValue(self, widget_value)

    def _reset_widget_value(self) -> None:
        self.widget_value = 0

class QBetseeSimConfDoubleSpinBox(
    QBetseeSimConfSpinBoxWidgetMixin, QBetseeDoubleSpinBox):
    '''
    Simulation configuration-specific floating point spin box widget,
    permitting floating point numbers backed by external simulation
    configuration files to be interactively edited.
    '''

    # ..................{ MIXIN                             }..................
    @property
    def _sim_conf_alias_type_strict(self) -> ClassOrNoneTypes:
        return float

    # This method is typically called *ONLY* once on loading the current
    # simulation configuration, enabling this widget to reinitialize itself in
    # a manner dependent upon the current value of the associated alias.
    def _get_widget_from_alias_value(self) -> object:

        # Initial value of the floating point number returned by the simulation
        # configuration alias associated with this widget.
        widget_value = super()._get_widget_from_alias_value()

        # Base-10 precision (i.e., significand length) of this initial value.
        widget_value_precision = floats.get_base_10_precision(widget_value)

        # If this widget defers to the default single step (i.e., fractional
        # value by which to increment and decrement this widget's displayed
        # value on each push of this widget's up and down arrows) for
        # "QDoubleSpinBox" widgets...
        if self.singleStep() == self.SINGLE_STEP_DEFAULT:
            # Base-10 exponent of this initial value.
            widget_value_exponent = floats.get_base_10_exponent(widget_value)

            # Override the default single step with a widget-specific single
            # step incrementing and decrementing by a fraction of this initial
            # value. Specifically, a single step of a quarter of this initial
            # value's order of magnitude is set.
            #
            # For example, given initial values of:
            #
            # * "0.009", a single step of "0.00025" will be set.
            # * "1.729", a single step of "0.25" will be set.
            single_step_new = 2.5 * 10**(widget_value_exponent - 1)
            self.setSingleStep(single_step_new)
        # Else, this widget has a non-default single step (typically specified
        # at Qt Creator time). In this case, preserve this single step as is.

        # Refine this precision to the largest of:
        widget_value_precision = max(
            # This alias' precision, incremented by one to permit the end user
            # to interactively decrease this number an additional decimal
            # place.
            widget_value_precision + 1,
            # A reasonable default precision.
            3,
        )

        # Set the precision of this widget's displayed value to this precision.
        # logs.log_debug(
        #     'Setting "%s" precision given %s to %d...',
        #     self.obj_name, widget_value, widget_value_precision)
        self.setDecimals(widget_value_precision)

        # Return this value.
        return widget_value

    @QBetseeSimConfSpinBoxWidgetMixin.widget_value.setter
    @type_check
    def widget_value(self, widget_value: float) -> None:

        # logs.log_debug('In QBetseeSimConfDoubleSpinBox.widget_value()...')

        # Set this widget's displayed value to the passed value by calling the
        # setValue() method of our superclass rather than this subclass,
        # preventing infinite recursion. (See the superclass method docstring.)
        QBetseeDoubleSpinBox.setValue(self, widget_value)

    def _reset_widget_value(self) -> None:
        self.widget_value = 0.0


from netmiko import ConnectHandler
from init_router import *

for router in routers:
    net_connect = ConnectHandler(**router)
    configurations = []
    for v in router.values():
        if v == 'scripting1':
            configurations.append(['interface f1/0',
                                   'ip address 10.10.10.1 255.255.255.0',
                                   'no shutdown'])
        elif v == 'scripting2':
            configurations.append(['interface f1/0',
                                   'ip address 10.10.20.1 255.255.255.0',
                                   'no shutdown'])
    configurations.append([
        'router ospf 1',
        'network 10.10.20.0 0.0.0.255 area 10',
        'network 10.10.10.0 0.0.0.255 area 10',
        'network 192.168.122.0 0.0.0.255 area 10'
    ])

    for conf in configurations:
        print(net_connect.send_config_set(conf))


from django.conf.urls import patterns, include, url
from django.contrib import admin
from news import views as news

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'newstest.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^login/$', news.login),
    url(r'^logout/$', news.logout),
    url(r'^(?P<page_num>\d+)/$', news.feed, name="feed"),
    url(r'^$', news.feed, name="feed"),
    url(r'^remove/(?P<news_id>\d+)', news.remove, name="remove"),
    url(r'^news/(?P<news_id>\d+)', news.news_page, name="news_page"),
    url(r'^admin/', include(admin.site.urls)),
)


import geopandas as gpd
import pandas as pd

def areal(source, target, cols = [None], suffix = ''):
    """
    The areal weighting method interpolates data into target polygons by using the ratio of
    intersected area to source area. It accepts two DataFrames – a source and target, a list of columns to be interpolated,
    and an optional suffix for the new name of the interpolated column in the target DataFrame. In the function,
    the source polygons are reindexed for summing later, and the areas of the source polygons are calculated.
    The source and target are intersected, and the area of the intersected polygons is calculated.
    Each intersected area is divided by the source area that encapsulates it for its areal weight.
    The function then iterates through the selected columns and multiplies each value by the areal weight.
    The target DataFrame is returned with the interpolated columns.

    :param source: DataFrame with values for interpolation.
    :type source: DataFrame
    :param target: DataFrame with polygons obtaining interpolated values.
    :type target: DataFrame
    :param cols: Column(s) from source to be interpolated.
    :type cols: list
    :param suffix: New name for interpolated columns. The default is ''
    :type suffix: str, optional

    :returns: Target DataFrame with interpolated columns added
    :rtype: DataFrame
    """

    #reindex for sum of interpolated results to merge later
    target['_index'] = target.index

    #calculate source areas
    source['source_area'] = source.geometry.area

    #intersect source and target
    joined1 = gpd.overlay(source, target, how = 'intersection')

    #calculate intersected areas
    joined1['intersect_area'] = joined1.geometry.area

    #calculate areal weight per intersected polygon
    joined1["AREAL_WT"] = joined1['intersect_area'] / joined1['source_area']

    #interpolate designated columns, create list to include in target dataframe
    new_cols = []
    for col in cols:
        new_col = col + suffix
        new_cols.append(new_col)
        joined1[new_col] = joined1["AREAL_WT"] * joined1[col]

    #merge interpolated results to target dataframe
    results = joined1.groupby('_index').sum()
    final = pd.merge(target, results[new_cols], on='_index')
    del final['_index']
    return final


from pykalman import KalmanFilter
import numpy as np
import matplotlib.pyplot as plt
import time
import sys
sys.path.append('../src/')
from support import *

keypoints_mapping = ['Nose', 'Neck', 'Right Sholder', 'Right Elbow', 'Right Wrist', 'Left Sholder',
                    'Left Elbow', 'Left Wrist', 'Right Hip', 'Right Knee', 'Right Ankle', 'Left Hip',
                    'Left Knee', 'Left Ankle', 'Right Eye', 'Left Eye', 'Right Ear', 'Left Ear']

def kalmanFilter(measurements):

	initial_state_mean = [measurements[0, 0], 0,
											measurements[0, 1], 0]

	transition_matrix = [[1, 1, 0, 0],
											[0, 1, 0, 0],
											[0, 0, 1, 1],
											[0, 0, 0, 1]]

	observation_matrix = [[1, 0, 0, 0],
											[0, 0, 1, 0]]

	kf1 = KalmanFilter(transition_matrices = transition_matrix,
									observation_matrices = observation_matrix,
									initial_state_mean = initial_state_mean)

	kf1 = kf1.em(measurements, n_iter=5)
	(smoothed_state_means, smoothed_state_covariances) = kf1.smooth(measurements)

	kf2 = KalmanFilter(transition_matrices = transition_matrix,
						observation_matrices = observation_matrix,
						initial_state_mean = initial_state_mean,
						observation_covariance = 10*kf1.observation_covariance,
						em_vars=['transition_covariance', 'initial_state_covariance'])

	kf2 = kf2.em(measurements, n_iter=5)
	(smoothed_state_means, smoothed_state_covariances)  = kf2.smooth(measurements)

	return smoothed_state_means[:, 0], smoothed_state_means[:, 2]

def processing_function(file_path, joints):
	_, keypoints = readAllFramesDATA(file_path)
	joints_names_list = ['Neck', 'Right Sholder', 'Left Sholder', 'Right Hip', 'Right Knee', 'Right Ankle', 'Left Hip',
                    'Left Knee', 'Left Ankle']
	joints_list = []
	for joint_name in joints_names_list:
		joints_list.append(joints.tolist().index(keypoints_mapping.index(joint_name)))
	for i in joints_list:
		measurements = np.copy(keypoints[:, i])
		keypoints[:, i, 0], keypoints[:, i, 1] = kalmanFilter(measurements)
	return keypoints


from os.path import basename
from typing import List, Dict, Any, Optional

from asgiref.sync import sync_to_async
from django.core.exceptions import FieldError
from django.core.files import File
from django.db.models import Exists, OuterRef

from admin.homeworks.models import (
    HomeWork,
    HomeworkFiles,
    HomeworkAnswer,
    ResourceMaterials,
)
from admin.users.models import Student, Teacher
from admin.users.models.sudent_timetable import StudentTimeTable

@sync_to_async
def has_student(**filter_params) -> bool:
    """
    Проверка существования ученика
    """
    try:
        return Student.objects.filter(**filter_params).exists()
    except FieldError:
        return False

@sync_to_async
def create_student(**student_data) -> Student:
    """
    Создание ученика
    """
    try:
        return Student.objects.create(**student_data)
    except TypeError:
        return False

@sync_to_async
def get_student_homeworks(student_telegram_id: int, **fields) -> List[Dict[str, Any]]:
    """
    Получение списка домашних заданий
    """
    return list(
        HomeWork.objects.active()
        .filter(student__telegram_id=student_telegram_id)
        .annotate(
            has_answer=Exists(HomeworkAnswer.objects.filter(homework=OuterRef("pk")))
        )
        .values(**fields)
    )

@sync_to_async
def get_homework(student_telegram_id: int, homework_id: int) -> Dict[str, Any]:
    """
    Получение домашнего задания
    """
    return dict(
        HomeWork.objects.active()
        .filter(student__telegram_id=student_telegram_id, id=homework_id)
        .annotate(
            has_answer=Exists(HomeworkAnswer.objects.filter(homework=OuterRef("pk")))
        )
        .values()
        .first()
    )

@sync_to_async
def get_homework_files(homework_id: int) -> List[Dict[str, Any]]:
    files: List[Dict[str, Any]] = list(
        HomeworkFiles.objects.filter(homework_id=homework_id).values()
    )
    return files

@sync_to_async
def create_homework_answer(
    homework_id: int, file_path: Optional[str] = None, answer_text: str = ""
) -> int:
    """
    Сохранение ответа на задание
    """
    answer = HomeworkAnswer(homework_id=homework_id, description=answer_text)
    if file_path:
        answer.file.save(basename(file_path), content=File(open(file_path, "rb")))
    answer.save()
    return answer.id

@sync_to_async
def get_student_timetable(student_telegram_id: int) -> dict:
    """
    Получение расписания студента
    """
    timetable = list(
        StudentTimeTable.objects.filter(
            student__telegram_id=student_telegram_id
        ).values()
    )
    return timetable

@sync_to_async
def get_student_resourses(student_telegram_id: int) -> dict:
    """
    Получение дополнительных материалов студента
    """

    resourses = list(
        ResourceMaterials.objects.filter(
            student__telegram_id=student_telegram_id, active=True
        ).values()
    )
    return resourses

@sync_to_async
def get_student_resourse(student_telegram_id: int, resource_id: int) -> dict:
    """
    Получение экземпляра дополнительных материалов студента
    """

    resourse = dict(
        ResourceMaterials.objects.filter(
            student__telegram_id=student_telegram_id,
            id=resource_id,
            active=True,
        )
        .values()
        .first()
    )
    return resourse

@sync_to_async
def get_teacher_homework(homework_id: int) -> Dict[str, Any]:
    """
    Получение данных учителя домашнего задания
    """
    return dict(Teacher.objects.filter(homework=homework_id).values().first())

@sync_to_async
def get_student(*values, **filters) -> Dict[str, Any]:
    """
    Получение данных студента
    """

    return dict(Student.objects.filter(**filters).values(*values).first())

@sync_to_async
def get_homework_answer(**filter) -> HomeworkAnswer:
    """
    Получение ответа на домашнее задание
    """
    homework_answer = HomeworkAnswer.objects.filter(**filter).first()
    return homework_answer

@sync_to_async
def get_yandex_disk_data(teacher_id: int) -> dict:
    print(
        Teacher.objects.filter(id=teacher_id)
        .values("yadisk_token", "yadisk_root_folder_name")
        .first()
    )
    yandex_disk_data = dict(
        Teacher.objects.filter(id=teacher_id)
        .values("yadisk_token", "yadisk_root_folder_name")
        .first()
    )
    return yandex_disk_data


"""
    This example demonstrates the use of portpy_photon to create down sampled influence matrix and
    optimize the plan by selecting optimal beams using beam angle optimization
    1- Creating a plan using the manually selected beams
    2- Obtaining the benchmark global optimal solution
    3- Comparing the plans obtained with manually/optimally selected beams

"""
import portpy.photon as pp
import numpy as np
import cvxpy as cp
import matplotlib.pyplot as plt

def beam_orientation_optimization():
    """
    1) Creating a plan using the manually selected beams

     **Note**: If you're developing your own beam orientation optimization algorithm, it's important to compare your results
     with manually selected beams using full-resolution data.
     However, when you're benchmarking your algorithm against the global optimal solution provided by MIP, it's important to
     use downsampled data in both MIP and your algorithm for a fair comparison.

    In this example, as we're comparing the results of MIP with manually selected beams, we apply downsampling to both scenarios.

    """
    # specify the patient data location.
    data_dir = r'../../data'
    # Use PortPy DataExplorer class to explore PortPy data
    data = pp.DataExplorer(data_dir=data_dir)
    # Pick a patient
    data.patient_id = 'Lung_Phantom_Patient_1'
    # Load ct, structure set, beams for the above patient using CT, Structures, and Beams classes
    ct = pp.CT(data)
    structs = pp.Structures(data)
    beams = pp.Beams(data)
    # Pick a protocol
    protocol_name = 'Lung_2Gy_30Fx'
    # Load clinical criteria for a specified protocol
    clinical_criteria = pp.ClinicalCriteria(data, protocol_name=protocol_name)
    # Load hyper-parameter values for optimization problem for a specified protocol
    opt_params = data.load_config_opt_params(protocol_name=protocol_name)
    # Create optimization structures (i.e., Rinds)
    structs.create_opt_structures(opt_params=opt_params, clinical_criteria=clinical_criteria)
    # Load influence matrix
    inf_matrix = pp.InfluenceMatrix(ct=ct, structs=structs, beams=beams)

    # create a down-sampled influence matrix
    voxel_down_sample_factors = [7, 7, 2]
    opt_vox_xyz_res_mm = [ct_res * factor for ct_res, factor in zip(ct.get_ct_res_xyz_mm(), voxel_down_sample_factors)]
    beamlet_down_sample_factor = 4
    new_beamlet_width_mm = beams.get_finest_beamlet_width() * beamlet_down_sample_factor
    new_beamlet_height_mm = beams.get_finest_beamlet_height() * beamlet_down_sample_factor

    inf_matrix_dbv = inf_matrix.create_down_sample(beamlet_width_mm=new_beamlet_width_mm,
                                                   beamlet_height_mm=new_beamlet_height_mm,
                                                   opt_vox_xyz_res_mm=opt_vox_xyz_res_mm)

    # Create a plan using ct, structures, beams and influence matrix, and clinical criteria
    plan_planner = pp.Plan(ct=ct, structs=structs, beams=beams, inf_matrix=inf_matrix_dbv,
                           clinical_criteria=clinical_criteria)

    # Create cvxpy problem using the clinical criteria and optimization parameters
    opt = pp.Optimization(plan_planner, opt_params=opt_params, clinical_criteria=clinical_criteria)
    opt.create_cvxpy_problem()
    # Solve the cvxpy problem using Mosek
    sol_planner = opt.solve(solver='MOSEK', verbose=False)

    """
    2) Obtaining the benchmark global optimal solution

    **Note**: We have chosen 7 beams from a relatively small pool of
    24 potential candidates due to computational constraints associated with Mixed Integer Programming

    """
    # roughly select beam_ids around planner beams
    beam_ids = list(np.arange(0, 72, 3))
    beams_boo = pp.Beams(data, beam_ids=beam_ids)

    # load the influence matrix
    inf_matrix_boo = pp.InfluenceMatrix(ct=ct, structs=structs, beams=beams_boo)
    # create a down-sampled influence matrix
    voxel_down_sample_factors = [7, 7, 2]
    opt_vox_xyz_res_mm = [ct_res * factor for ct_res, factor in zip(ct.get_ct_res_xyz_mm(), voxel_down_sample_factors)]
    beamlet_down_sample_factor = 4
    new_beamlet_width_mm = beams.get_finest_beamlet_width() * beamlet_down_sample_factor
    new_beamlet_height_mm = beams.get_finest_beamlet_height() * beamlet_down_sample_factor

    inf_matrix_boo_dbv = inf_matrix_boo.create_down_sample(beamlet_width_mm=new_beamlet_width_mm,
                                                           beamlet_height_mm=new_beamlet_height_mm,
                                                           opt_vox_xyz_res_mm=opt_vox_xyz_res_mm)
    # create a plan
    plan_boo = pp.Plan(ct=ct, structs=structs, beams=beams_boo, inf_matrix=inf_matrix_boo_dbv,
                       clinical_criteria=clinical_criteria)
    # create a cvxpy optimization instance
    opt = pp.Optimization(plan_boo, opt_params=opt_params)
    opt.create_cvxpy_problem()

    # add binary variables and constraints for beam orientation optimization
    b = cp.Variable(len(inf_matrix_boo_dbv.beamlets_dict), boolean=True)
    num_beams = 7
    x = opt.vars['x']

    opt.constraints += [cp.sum(b) <= num_beams]
    for i in range(len(inf_matrix_boo_dbv.beamlets_dict)):
        start_beamlet = inf_matrix_boo_dbv.beamlets_dict[i]['start_beamlet_idx']
        end_beamlet = inf_matrix_boo_dbv.beamlets_dict[i]['end_beamlet_idx']
        M = 50  # upper bound on the beamlet intensity
        opt.constraints += [x[start_beamlet:end_beamlet] <= b[i] * M]
    # solve the problem
    sol_boo = opt.solve(solver='MOSEK', verbose=False)

    """
    3) Comparing the plans obtained with manually/optimally selected beams

    """
    # Identifying bao and planner gantry angles
    boo_gantry_angles = (np.asarray(plan_boo.beams.beams_dict['gantry_angle']) + 1) * (b.value > 0)
    boo_gantry_angles = boo_gantry_angles[boo_gantry_angles > 0] - 1  # add and subtract 1 to check for 0 degree angle
    print('BOO gantry angles: {}'.format(boo_gantry_angles))
    planner_gantry_angles = plan_planner.beams.beams_dict['gantry_angle']
    print('Planner gantry angles: {}'.format(planner_gantry_angles))

    # plot dvh dvh for both the cases
    fig, ax = plt.subplots(figsize=(12, 8))
    struct_names = ['PTV', 'ESOPHAGUS', 'HEART', 'CORD', 'LUNG_L', 'LUNG_R', 'RIND_0', 'RIND_1']
    ax = pp.Visualization.plot_dvh(plan_boo, sol=sol_boo, struct_names=struct_names, style='solid', ax=ax)
    ax = pp.Visualization.plot_dvh(plan_planner, sol=sol_planner, struct_names=struct_names, style='dotted', ax=ax)
    ax.set_title('- BOO  .. Planner')
    plt.show()

if __name__ == "__main__":
    beam_orientation_optimization()


import numpy as np
from HMM import MultinomialHMM, GaussianMixtureHMM
import matplotlib.pyplot as plt
from ahf_utils import mvGaussian

testword = "on"
words = ["yes", "no", "up", "down", "on", "off"]

np.set_printoptions(precision=5, linewidth=120, suppress=False)

yes_hmm = GaussianMixtureHMM.loadModel("yes")
no_hmm = GaussianMixtureHMM.loadModel("no")
on_hmm = GaussianMixtureHMM.loadModel("on")
off_hmm = GaussianMixtureHMM.loadModel("off")
up_hmm = GaussianMixtureHMM.loadModel("up")
down_hmm = GaussianMixtureHMM.loadModel("down")

#hmm.printmodel()

#logps=[]
for word in ["on"]:

    """
    wordlogps = []
    print("testing " + word)
    test = np.loadtxt("X_test/" + word + "/X.csv", delimiter=",")
    sequence_lengths = np.loadtxt("X_test/" + word + "/S.csv", delimiter="\n").astype(int)

    t = np.arange(0, sequence_lengths.shape[0], 1)
    start = 0
    for i, length in enumerate(sequence_lengths):
        if i%20 == 0:
            print(i)

        utterance = test[start : start+length]

        logps = [yes_hmm.logpsequence(utterance), no_hmm.logpsequence(utterance), up_hmm.logpsequence(utterance), down_hmm.logpsequence(utterance), on_hmm.logpsequence(utterance), off_hmm.logpsequence(utterance)]
        #print([int(i) for i in logps])
        wordlogps.append(logps)
        start = start+length

    result = np.array(wordlogps)
    np.savetxt("testing/%s.csv" % (word), result, delimiter=",", fmt="%1.5g")
    """

    result = np.loadtxt("testing/%s.csv" % (word), delimiter=",")

    plt.figure(1)
    plt.plot(result[:,0], 'r-')
    plt.plot(result[:,1], 'r-')
    plt.plot(result[:,2], 'r-')
    plt.plot(result[:,3], 'r-')
    plt.plot(result[:,4], 'b-')
    plt.plot(result[:,5], 'r-')

    plt.show()

    break

"""
print(mvGaussian(obs, mean, np.diag(cov)))

hmm = MultinomialHMM(2, 2)

hmm.A = np.array([[0.9, 0.1], [0.1, 0.9]])
hmm.B = np.array([[0.9, 0.1], [0.1, 0.9]])
hmm.pi = np.array([0.5, 0.5])

seq = np.random.randint(2, size=50)

print("sequence:")
print(seq)

a, b, c = hmm.forward_backward(seq, False)

print("alpha:")
print(a)
print("beta:")
print(b)
print("c's:")
print(c)
"""

"""
x=np.ones((3, 3))
y = np.full((3, 3), 2)

z = x[2,:] + y[:,1]

print(z)

x = np.arange(0., 1.01, 0.01)
y = np.sqrt(10000*x*(1-x))
plt.plot(x, y)
plt.grid(which='both')
plt.xlabel('size of partitions (% of total space)')
plt.ylabel('std deviation for # of people in partition for T=10,000')
plt.show()

x1 = np.arange(12.0).reshape((4, 3))
x2 = np.arange(3.0)

print(x1)
print(x1.shape)
print(x2)
print(x2.shape)

print(np.multiply(x1, x2)

x = np.array([1, 2, 3, 4, 5])
y = np.tile(x, (3, 1))
print(y)

x = np.array([1, 2, 3, 4, 5])
y = np.array([3, 1, 1, 2, 7])
z = np.array([1, 2, 5, 2, 4])

print(np.multiply(np.multiply(x, y), z))

gamma = np.ones((4, 2, 2))
print(np.sum(gamma, axis=0))
"""


import gosling as gos
import streamlit as st
import streamlit_gosling as st_gos
import pandas as pd

from GoslingEnhancers import get_enhancer_track
from GoslingPromoters import get_promoter_track
from GoslingGenes import get_gene_overlay
from BigWigTrack import get_bigwig_track
from ChipMerge import get_merge_track
import StreamlitFunctions
import ContrastOptions
import Contrasts

import importlib

importlib.reload(Contrasts)
#@st.cache TODO separate functions into what can be cached and what doesnt need to be cached
def main(container_width:int,
        chromosome_selection,
        interval:list,
        chip_height:int,
        gene_height:int,
        enhancer_height:int,
        promoter_height:int,
        datasets:Contrasts.datasets,
        MergedChip:bool,
        EnableContrasts:bool,
        contrasts:Contrasts.contrasts):
    """
    Make an ideagram with Enhancers AND Promoters
    """

    ######~~~~~~~~~~~
    #Create Domain of Selection
    ######~~~~~~~~~~~

    domain = gos.GenomicDomain(chromosome=chromosome_selection, interval=interval)
    # ChromFilter = gos.IncludeFilter(field='chromosome', include=mydomain, type=mydomain)

    ######~~~~~~~~~~~
    #Enhancer Track
    ######~~~~~~~~~~~
    enhancer_track = get_enhancer_track(enhancer_height=20)

    ######~~~~~~~~~~~
    #Promoter Track
    ######~~~~~~~~~~~
    promoter_track = get_promoter_track(promoter_height=20)

    ######~~~~~~~~~~~
    # Genes Overlay
    ######~~~~~~~~~~~

    gene_overlay = get_gene_overlay(gene_height=gene_height)

    ######~~~~~~~~~~~
    # If Contrasts are Disabled...
    ######~~~~~~~~~~~

    if not EnableContrasts:

        chipseq_tracks = []

        for dataset in datasets.lod:
            track = get_bigwig_track(bigwig_file= dataset.url,
                                        chip_height = chip_height,
                                        name = dataset.name,
                                        color = dataset.color).properties(
                                                            width=container_width)

            chipseq_tracks.append(track)

        chip_vert = gos.vertical(*chipseq_tracks).properties(
                    spacing = 0,
                    linkingId = "vert")

        ######~~~~~~~~~~~
        # If Merged view is Disabled...
        ######~~~~~~~~~~~

        vis = gos.stack(gene_overlay, enhancer_track, promoter_track).properties(
                    spacing = 0, width=container_width, linkingId = "vert")

        vis = gos.vertical(vis, chip_vert).properties(spacing = 30,
                    xDomain=domain, linkingId = "vert")

        ######~~~~~~~~~~~
        # If Merged view is Enabled...
        ######~~~~~~~~~~~
        if MergedChip:
            if len(st.session_state['datasets'].lod) == 0:
                return vis

            urls =[dataset.url for dataset in st.session_state['datasets'].lod]
            print(f'URLS {urls}')

            merged_track = get_merge_track(chip_height=chip_height*5,
                                                chip_data_files=[dataset.url for dataset in st.session_state['datasets'].lod],
                                                colors = [dataset.color for dataset in st.session_state['datasets'].lod]).properties(
                    spacing = 0, width=container_width, linkingId = "vert")

            vis = gos.vertical(vis, merged_track).properties(
                                xDomain=domain, spacing = 40, linkingId = "vert")

        return vis

    if EnableContrasts:
        #chipseq_stacks: A List of stacks. Each stack corresponds to a contrast's chipseq profiles
        chipseq_stacks_l = []
        for contrast in contrasts.loc:
            #chipseq_tracks: A List of tracks. Each track is from a dataset in the current contrast
            chipseq_tracks = []

            for dataset in contrast.datasets.lod:
                track = get_bigwig_track(bigwig_file= dataset.url, chip_height = chip_height, name = dataset.name, color = dataset.color)
                chipseq_tracks.append(track)
                #Each dataset has its own track.

            #Make 1 stack that corresponds to all of the tracks in the current contrast
            # NB: A chipseq stack is of type "view"

            chipseq_stack = gos.stack(*chipseq_tracks).properties(
                    xDomain=domain, spacing = 0, width=container_width)

            # Append new stack.
            chipseq_stacks_l.append(chipseq_stack)

            #add int for background color reasons

        # Combine all Chipseq Stacks into one stack
        # We cannot do this because we don't have a "view"?
        #contrast_stack = gos.stack(*chipseq_stacks_l)
        chipseq_vertical = gos.vertical(*chipseq_stacks_l, spacing = 32)

        # NB a Vertical is a "View" type
        print(f'Chipseq_vertical {type(chipseq_vertical)}')

        vis = gos.stack(gene_overlay, enhancer_track, promoter_track).properties(
                    xDomain=domain, spacing = 0, width=container_width)
        print(f'Enhancer {type(enhancer_track)}')
        print(f'Promoter {type(promoter_track)}')
        print(f'Gene_Overlay {type(gene_overlay)}')

        #vis is a view
        print(f'Vis {type(vis)}')

        # I think you can add two views together easily right?
        vis2 = gos.vertical(vis, chipseq_vertical,  spacing = 37).properties(
            linkingId = "-",
            xDomain = domain)

        contrast_names = st.session_state['contrasts'].get_names()
        print(contrast_names)

        if MergedChip:

            if contrasts.get_num_datasets() == 0:
                return vis2

            merged_tracks = []

            for contrast in contrasts.loc:
                if contrast.get_len_datasets() == 0:
                    continue

                dataset_urls = contrast.get_datasets_urls()
                dataset_colors = contrast.get_datasets_colors()

                print(f'URLS {dataset_urls}')
                print(f'COLORS {dataset_colors}')

                #SOMETHING IS WRONG WITH MERGED_TRACK
                merged_track = get_merge_track(chip_height = 75,
                                                chip_data_files = dataset_urls,
                                                colors = dataset_colors).properties(
                                                    width=container_width)
                print(type(merged_track))

                merged_tracks.append(merged_track)

            merged_vis = gos.vertical(*merged_tracks, spacing = 0)
            vis2 = gos.vertical(vis2, merged_vis, spacing = 50).properties(
                linkingId = "-",
                xDomain = domain
                )

        return vis2

    # return full_vis

######## Page Config
#This must Be the first "st" script you call
#Makes sure stuff loads on the left, not the middle
st.set_page_config(layout='wide')

############### Add Search box for selection method

if 'datasets' not in st.session_state.keys():
    datasets = Contrasts.datasets(lod=[])
    st.session_state['datasets'] = datasets
else:
    datasets = st.session_state['datasets']

if 'contrasts' not in st.session_state.keys():
    contrasts = Contrasts.contrasts(loc = [])
    st.session_state['contrasts'] = contrasts
else:
    contrasts = st.session_state['contrasts']

if 'EnableContrasts' not in st.session_state.keys():
    st.session_state['EnableContrasts'] = False
EnableContrasts = st.session_state['EnableContrasts']

if not EnableContrasts:
    ChromosomeSelection, IntervalSelection = ContrastOptions.display_no_contrast_options(datasets)
else:
    ChromosomeSelection, IntervalSelection = ContrastOptions.display_yes_contrast_options(contrasts)

with st.sidebar:
    #multiple_contrasts=st.checkbox(label = "Enable Multiple Contrasts", help="Enabling Multiple Contrasts allows you to compare ChIPseq, and ATACseq of multiple categorical contrasts at once. For example: several time series, or several cell types")
    EnableContrasts=StreamlitFunctions.display_enablecontrast_check_box()

with st.sidebar:
    MergedChip=StreamlitFunctions.display_merged_checkbox()

if st.session_state['EnableContrasts'] == False:
    st.markdown("""## SingleChIPViewer""")
    st.markdown("""###### mm10 Construct | Scroll and Zoom to Explore Data""" )
elif st.session_state['EnableContrasts'] == True:
    st.markdown("""## MultiChIPViewer""")
    st.markdown("""###### mm10 Construct | Scroll and Zoom to Explore Data""")

col1, col2 = st.columns([1,15], gap = 'medium')

with col1:

    st.text('')
    st.text('')
    st.text('')
    st.text('')
    st.text('')
    st.text('')
    st.text('')
    st.text('')
    st.text('')
    st.text('')
    st.text('')
    st.text('')
    st.text('')

    contrasts = st.session_state['contrasts']

    #num_datasets has the number of datasets for each ocntrast indexed
    num_datasets = []
    for contrast in contrasts.loc:
        num_datasets.append(contrast.get_len_datasets())

    #Only look at 1 onwards for contrasts because first contrast name is always placed in the same place
    for i,contrast in enumerate(contrasts.loc):

        if i == 0:

            st.markdown("""<p> </p>""", unsafe_allow_html=True)
            st.markdown("""<p> </p>""", unsafe_allow_html=True)

            name = str(contrast.name)
            st.subheader(name)

        elif num_datasets[i] == 0:
            continue

        else:

            prev_num = num_datasets[i-1]

            spacing_dic = {0:0, 1:0, 2:2, 3:4, 4:7, 5:9, 6:11, 7:13, 8:15, 9:17}

            req_spaces = spacing_dic[prev_num]

            for i in range(req_spaces):
                st.text('')

            name = str(contrast.name)
            st.subheader(name)

    if MergedChip:

        st.text('')
        st.text('')
        st.text('')
        st.text('')
        st.text('')

        for i,contrast in enumerate(contrasts.loc):

            if i == 0:

                st.markdown("""<p> </p>""", unsafe_allow_html=True)
                st.markdown("""<p> </p>""", unsafe_allow_html=True)

                name = str(contrast.name)
                st.subheader(name)

            else:

                spacing = 2

                name = str(contrast.name)
                st.subheader(name)

with col2:

    result=st_gos.from_gos(
        spec=main(container_width=1550,
                    chip_height=36,
                    gene_height=100,
                    promoter_height = 40,
                    enhancer_height = 40,
                    chromosome_selection=ChromosomeSelection,
                    interval=IntervalSelection,
                    datasets = datasets,
                    MergedChip=MergedChip,
                    EnableContrasts=EnableContrasts,
                    contrasts=contrasts),
        id='id1',
        #This height changes the height of the streamlit container
        height = 5000)


## Tran Nhiem -- 2022/05
from typing import Optional, Sequence
from torch.optim import SGD, Adam, AdamW
import torch.nn as nn

from torch.optim.lr_scheduler import MultiStepLR, ReduceLROnPlateau, LinearLR, CosineAnnealingLR,CosineAnnealingWarmRestarts
import pytorch_lightning as pl
import torch.nn.functional as F
from torchmetrics import Accuracy
from convNet_architectures.ResNet import resnet18, resnet50
from convNet_architectures.resnet import ResNet18, ResNet34, ResNet50
## For Mup Optimizer
from mup import MuAdam, MuSGD,MuAdamW
## Coordinate Check
from mup.init import (kaiming_normal_, kaiming_uniform_, normal_,
                         trunc_normal_, uniform_, xavier_normal_,
                         xavier_uniform_)
from mup import get_shapes, make_base_shapes, set_base_shapes

init_type={
    "uniform": uniform_,
    "kaiming_normal": kaiming_normal_,
    "kaiming_uniform": kaiming_uniform_,
    "normal": normal_,
    "xavier_noraml":xavier_normal_,
    "xavier_uniform":xavier_uniform_,
}
class lightning_module(pl.LightningModule):
    def __init__(self,
        backbone_architecture: str,
        batch_size: int ,
        lr: float,
        scheduler: str,
        weight_decay: float,
        num_classes: int ,
        arch_width_mu: int or float,
        m_transfer_enable: bool,
        optimizer_type: str,
        init_type: str,
        load_base_shapes: str,
        momentum: float,
        epochs: int,
        data_length: int,
        lr_decay_steps: Optional[Sequence[int]] = None,
        task: Optional[str]="classification",
        metric: str = "Accuracy",

        **kwargs
    ):
        super().__init__()
        self.backbone_architecture= backbone_architecture
        self.width_mult=arch_width_mu
        self.m_transfer=m_transfer_enable
        self.load_base_shapes=load_base_shapes
        self.batch_size= batch_size
        self.optimizer_type= optimizer_type
        self.momentum=momentum
        self.num_classes= num_classes
        self.lr = lr
        self.epochs=epochs
        self.data_length=data_length
        self.weight_decay = weight_decay
        self.lr_decay_steps = lr_decay_steps
        self.task = task
        self.scheduler = scheduler
        self.init_type=init_type
        print(self.lr)
        self.__build_model()
        self.accuracy_1= Accuracy()
        self.accuracy_5= Accuracy(top_k=5)

        self.metric=metric
        self.criterion = nn.CrossEntropyLoss()

    def __build_model(self):

        if self.backbone_architecture=="resnet18":
            print('implement Res18 Mtransfer technique')
            self.model= ResNet18(num_classes=self.num_classes,wm=self.width_mult )
        elif self.backbone_architecture=="resnet34":
            print('implement Res34 Mtransfer technique')
            self.model= ResNet34(num_classes=self.num_classes, wm=self.width_mult)
        elif self.backbone_architecture=="resnet50":
            print('implement Res50 Mtransfer technique')
            self.model= ResNet50(num_classes=self.num_classes, wm=self.width_mult)
        elif self.backbone_architecture=="resnet18_v0":
            print("Using Res18 Custome Build ResNet")
            self.model= resnet18(num_classes=self.num_classes,width_mult=self.width_mult,m_transfer=self.m_transfer  )
        elif self.backbone_architecture=="resnet50_v0":
            print("Using Res50 Custome Build ResNet")
            self.model= resnet50(num_classes=self.num_classes,width_mult=self.width_mult,m_transfer=self.m_transfer)

        else:
            raise ValueError("Current backbone is not support")

        if self.m_transfer:

            if self.load_base_shapes:
                print("implementation of μP technique")
                set_base_shapes(self.model, self.load_base_shapes)
            else:
                print("implementation of Standard Pytorch technique")
                set_base_shapes(self.model, None)

            for param in self.model.parameters():
                init_=init_type[self.init_type]
                ### If initializing manually with fixed std or bounds,
                ### then replace with same function from mup.init
                # torch.nn.init.uniform_(param, -0.1, 0.1)
                if self.init_type=="uniform":
                    init_(param, -0.1, 0.1)
                else:
                    init_(param)
    def forward(self, x):
        x=self.model(x)
        return x

    def training_step(self, batch, batch_idx):
        x, y = batch
        y_logits=self.forward(x)
        #y_logits=nn.Softmax(y_logits)
        # print(y.shape)
        # print(y_logits)

        #print('ground_truth', y[0])
        #print("prediction", y_logits[0])

        #print("prediction", y_logits[0].argmax(dim=-1))
        train_loss=F.cross_entropy(y_logits, y)
        #train_loss = F.nll_loss(y_logits, y)
        #train_loss=self.criterion(y_logits, y)
        if self.metric == 'Accuracy':
            acc1= self.accuracy_1(y_logits, y)
            acc5 = self.accuracy_5(y_logits, y)
            log = {"train_loss": train_loss, "train_acc1": acc1, "train_acc5": acc5}
        else:
            raise ValueError("The metric is not support yet")

        self.log_dict(log, on_epoch=True, sync_dist=True)
        return train_loss

    def validation_step(self, batch, batch_idx):
        x, y = batch

        batch_size=x.size(0)
        y_logits=self.forward(x)
        # print(y[1])
        # print(y_logits[1])

        #print('ground_truth', y[0])
        #print("prediction", y_logits[0])

        #print("prediction", y_logits[0].argmax(dim=-1))
        #val_loss=self.criterion(y_logits, y)
        #val_loss = F.nll_loss(y_logits, y)

        val_loss=F.cross_entropy(y_logits, y)
        if self.metric == 'Accuracy':
            acc1= self.accuracy_1(y_logits, y)
            acc5 = self.accuracy_5(y_logits, y)
            #result = {"batch_size": batch_size,"val_loss": val_loss, "val_acc1": acc1, "val_acc5": acc5}
            result = {"val_loss": val_loss, "val_acc1": acc1, "val_acc5": acc5}

        else:
            raise ValueError("The metric is not support yet")
        self.log_dict(result,on_epoch=True, sync_dist=True)

        return val_loss

    # def validation_epoch_end(self, outs):
    #     val_loss= self.__weighted_mean(outs, "val_loss","batch_size" )
    #     if self.metric=="Accuracy":
    #         val_acc_1= self.__weighted_mean(outs, "val_acc1","batch_size")
    #         val_acc_5= self.__weighted_mean(outs, "val_acc5", "batch_size")
    #         logs={"val_loss": val_loss, "val_acc_1": val_acc_1, "val_acc_5":val_acc_5}

    #     else:
    #         raise ValueError("The metric is not support yet")

    #     self.log_dict(logs, on_epoch=True, sync_dist=True)

    def test_step(self, batch, batch_idx):
        x, y = batch
        batch_size=x.size(0)
        y_logits=self.forward(x)
        test_loss=F.cross_entropy(y_logits, y)
        #train_loss = F.nll_loss(y_logits, y)

        if self.metric == 'Accuracy':
            acc1= self.accuracy_1(y_logits, y)
            acc5 = self.accuracy_5(y_logits, y)
            result = {"test_loss": test_loss, "test_acc1": acc1, "test_acc5": acc5}

            #result = {"batch_size": batch_size,"test_loss": val_loss, "test_acc1": acc1, "test_acc5": acc5}
        else:
            raise ValueError("The metric is not support yet")

        self.log_dict(result,on_epoch=True, sync_dist=True)

        return test_loss
    # def test_epoch_end(self, outs):
    #     test_loss= self.__weighted_mean(outs, "val_loss","batch_size" )
    #     if self.metric=="Accuracy":
    #         test_acc_1= self.__weighted_mean(outs, "test_acc1","batch_size")
    #         test_acc_5= self.__weighted_mean(outs, "test_acc5", "batch_size")
    #         logs={"test_loss": test_loss, "test_acc_1": test_acc_1, "test_acc_5":test_acc_5}

    #     else:
    #         raise ValueError("The metric is not support yet")

    #     self.log_dict(logs, on_epoch=True, sync_dist=True)

    def configure_optimizers(self):

        if self.optimizer_type =="MuSGD":
            optimizer = MuSGD(self.parameters(), lr=self.lr,momentum=self.momentum, weight_decay=self.weight_decay)
        elif self.optimizer_type =="MuAdam":
            optimizer=MuAdam(self.model.parameters(), lr=self.lr)
        elif self.optimizer_type=="MuAdamW":
            optimizer=MuAdam(self.parameters(), lr=self.lr)
        ## Configure Type of Optimizer
        elif self.optimizer_type =="SGD":
            optimizer= SGD(self.parameters(), lr=self.lr, momentum=self.momentum, weight_decay = self.weight_decay, nesterov=True)
        elif self.optimizer_type =="Adam":
            optimizer= Adam(self.parameters(), lr=self.lr, betas=(0.9, 0.999), weight_decay= self.weight_decay)
        elif self.optimizer_type=="AdamW":
            optimizer= AdamW(self.parameters(), lr=self.lr, betas=(0.9, 0.999), weight_decay= self.weight_decay)
        else:
            raise ValueError('invalid Optimzier_type')

       ## Configure Learning Rate Schedule
        if self.scheduler == 'step':
            scheduler = MultiStepLR(optimizer, self.lr_decay_steps, gamma=0.5)
            return [optimizer], [scheduler]
        elif self.scheduler == 'reduce_plateau':
            #scheduler = ReduceLROnPlateau(optimizer, patience=8, factor=0.5)
            scheduler = {"scheduler": ReduceLROnPlateau(optimizer, patience=8, factor=0.5,),  "monitor": "val_loss"}
            return [optimizer], [scheduler]
        elif self.scheduler=="linear":
            scheduler = LinearLR( optimizer, start_factor=0.5, total_iters=self.epochs/2)
            return [optimizer], [scheduler]
        elif self.scheduler=="cosineAnnealing":
            scheduler = CosineAnnealingLR(optimizer, eta_min=1e-8,T_max=int((self.data_length/self.batch_size)*self.epochs) )
            return [optimizer], [scheduler]
        elif self.scheduler=="ConsineAnl_warmup":
            scheduler = CosineAnnealingWarmRestarts(optimizer,T_0=int(((self.data_length/self.batch_size)*self.epochs)/2), T_mult=1, eta_min=1e-8)
            return [optimizer], [scheduler]
        else:
            print('you are not implementing any Learning schedule')
            return optimizer

    def __weighted_mean(self, outputs, key, batch_size_key):
        value=0
        n=0
        for out in outputs:
            value += out[batch_size_key] +out[key]
            n+= out[batch_size_key]
        value=value/n
        return value.squeeze(0)

if __name__=="__main__":
    print("Hoooray ~ You are testing the lightning Module ~")
    print("Oh wait you are not define any testing module yet")


import os
import csv
from datetime import datetime
import numpy as np
import pandas as pd
from fpdf import FPDF
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from html2image import Html2Image
import codecs

hti=Html2Image()	#constructor
pdf=FPDF()
window=tk.Tk()
window.geometry("1000x200")
window.config(background = "white")
window.title("GUI Based Transcript Generator")	#to define the title
entry1=tk.StringVar()
entry2=tk.StringVar()
subject_data=pd.read_csv(r"./1901EE19_2021/proj2/sample_input/subjects_master.csv",header=0,delimiter=',')	#edit
grade_data=pd.read_csv(r"./1901EE19_2021/proj2/sample_input/grades.csv")	#edit
path='./1901EE19_2021/proj2/transcriptsIITP'	#edit
with open("./1901EE19_2021/proj2/sample_input/names-roll.csv") as f:	#edit
	reader=csv.reader(f)
	get_name={row[0]:row[1] for row in reader}	#get_name maps rollno with name
f.close()

class PDF(FPDF):
	pass

def generate_transcript(roll):
	roll.strip()
	try:
		Name = get_name[roll]
	except:
		print("This roll no. doesnt exist",roll)
		return
	Year_of_Adm = "20"+roll[0:2]
	if roll[2:4]=="01":
		total_sem=8
		Programme="Bachelor of Technology"
		page_format='A3'
		pdf_w=420
		pdf_h=297
	else:
		total_sem=4
		page_format='A4'
		pdf_w=297
		pdf_h=210
		if roll[2:4]=="11":
			Programme="Master of Technology"
		elif roll[2:4]=="12":
			Programme="M.Sc."
		else:
			Programme="P.hd"

	file=roll+".pdf"
	filename=os.path.join(path,file)
	dict={'CS':'Computer Science and Engineering','EE':'Electrical Engineering','CE':'Civil Engineering','ME:':'Mechanical Engineering','CB':'Chemical Engineering'}
	Course=roll[4:6]
	try:
		course=dict[Course]
	except:
		return
	pdf=PDF()
	pdf=PDF(orientation='L',unit='mm',format=page_format)
	P=open(filename,'a')
	pdf.add_page()
	pdf.set_margins(0,0,0)
	pdf.set_font('Arial','U',12)
	pdf.rect(10.0,10.0,pdf_w-20.0,pdf_h-20.0)
	pdf.image('E:/1901EE19_2021/proj2/iitp_logo.png',11.0,11.0,370,30)
	pdf.line(x1=10.0,y1=40.0,x2=pdf_w-10.0,y2=40.0)
	pdf.text(185.0,39.0,"TRANSCRIPT")

	date_generated=datetime.now().strftime("%d %b %Y %H:%M")
	line1="RollNo: "+roll+" Name: "+Name+" Year of Admission:"+Year_of_Adm
	line2="Programme:"+Programme+" Branch: "+course
	last_line="Date Generated: "+str(date_generated)

	pdf.text(130.0,45.0,line1)
	pdf.text(130.0,50.0,line2)
	pdf.text(20.0,pdf_h-12.0,last_line)	#Shows Date Generated
	pdf.rect(126.0,41.0,160.0,11.0)
	pdf.line(10.0,122.0,pdf_w-10.0,122.0)
	pdf.line(10.0,195.0,pdf_w-10.0,195.0)

	Grading={'AA':10,'AB':9,'BB':8,'BC':7,'CC':6,'CD':5,'DD':4,'DD*':4,'F*':0,'F':0,'I':0}
	total_credit=0
	grd_sum=0
	cpi=0.00
	for curr_sem in range(1,total_sem+1):
		sem_credit=0
		spi=0.00
		sum=0
		clr=0
		get_roll_data=grade_data.loc[((grade_data['Roll']==roll) & (grade_data['Sem']==curr_sem)),['Roll','SubCode','Grade']]	#iterate curr_sem to1-8 if btech 1-4 if mtech
		sublist=get_roll_data['SubCode'].tolist()
		Grd_list=get_roll_data['Grade'].tolist()
		df=pd.DataFrame()
		i=0
		for sub in sublist:
			df1=subject_data.loc[(subject_data['subno']==sub),['subno','subname','ltp','crd']]
			df=pd.concat([df,df1])
			sub_credit=int(df1['crd'].values)
			sem_credit+=sub_credit
			sum+=sub_credit*int(Grading[Grd_list[i].strip()])
			if Grading[Grd_list[i].strip()]<4:
				clr+=sub_credit
			i+=1
		total_credit+=sem_credit
		grd_sum+=sum
		try:	#Zero Division Error
			spi=float("{:.2f}".format(sum/sem_credit))
			cpi=float("{:.2f}".format(grd_sum/total_credit))
		except:
			pass
		sheet=pd.DataFrame()
		try:
			sheet=get_roll_data.set_index('SubCode').join( df.set_index('subno'))
		except:
			pass
		column=['subname','ltp','crd','Grade']
		sheet=sheet.reindex(columns=column)
		sheet=sheet.rename(columns={'subname':'Subject Name','ltp':'L-T-P','crd':'CRD','Grade':'GRD'})
		#print(sheet.head)
		Sem="Semester"+str(curr_sem)
		img_f="Semester"+str(curr_sem)+".png"
		img_file=os.path.join(path,img_f)

		hti=Html2Image(size=(500,265))
		html=sheet.to_html()
		x=open("E:/index.html",'w')
		x.write(html)
		x.close()
		hti.screenshot(html_file="index.html",save_as=img_f)	#conversion to img file
		line_sem="Credits Taken: "+str(sem_credit)+" Credits Cleared: "+str((sem_credit-clr))+" SPI: "+str(spi)+" CPI: "+str(cpi)
		pdf.text(20.0+((curr_sem-1)%3)*130,58.0+(int((curr_sem-1)/3))*75,Sem)	#For printing the current semester
		pdf.image(img_f,18.0+((curr_sem-1)%3)*130,59.0+(int((curr_sem-1)/3))*75,96,53)	#prints dataframe of particular semester to image in pdf
		pdf.rect(18.0+((curr_sem-1)%3)*130,37.0+(int((curr_sem-1)/3)+1)*75,115.0,6.0)	#makes grid for semester detail
		pdf.text(18.0+((curr_sem-1)%3)*130,42.0+(int((curr_sem-1)/3)+1)*75,line_sem)	#prints details
	pdf.text(pdf_w-80.0,pdf_h-15.0,"Assistant Registrar(Academic)")
	pdf.output(filename,'F')
	P.close()
	return

def generate1():	#Function for option 1
	R1=entry1.get()
	R2=entry2.get()
	first_s=R1[6:8]
	rest=R1[0:6]
	last_s=R2[6:8]
	first=int(first_s)
	last=int(last_s)
	for i in range(first,last+1):
		if len(str(i))==1:
			i="0"+str(i)
		for_roll=rest+str(i)
		for_roll=for_roll.upper()
		generate_transcript(for_roll)

def	generate2():	#Function for Option 2
	all_roll=get_name.keys()
	for roll in all_roll:
		generate_transcript(roll)

def browseFiles():
	try:
		filename1=filedialog.askopenfile(initialdir='/',title="Select a file",filetypes=[("*all files","*.*")])
		label_file_explorer.configure(text="File Opened: "+str(filename1))
		if filename1=='':
			return
		files=os.listdir(path)
		for filename in files:
			P=codecs.open(filename,'a',errors="ignore",encoding='cp1252')
			pdf.add_page()
			pdf.image(filename1,380,250,20,20)
			pdf.output(filename,'F')
			P.close()
	except:
		return

def browseFiles2():
	try:
		filename2=filedialog.askopenfile(initialdir='/',title="Select a file",filetypes=[("*all files","*.*")])
		label_file_explorer2.configure(text="File Opened: "+str(filename2))
		if filename2=='':
			return
		files=os.listdir(path)
		for filename in files:
			P=open(filename,'a')
			P.add_page()
			pdf.image(filename2,380,270,20,20)
			pdf.output(filename,'F')
			P.close()
	except:
		return
entry11=tk.Entry(window,textvariable=entry1,font=('calibre',10,'normal')) #input lower limit
entry22=tk.Entry(window,textvariable=entry2,font=('calibre',10,'normal'))	#input upper limit
entry11.grid(row=1,column=2)	#setting location for getting lower limit
entry22.grid(row=1,column=3)	#setting location for getting upper limit
btn1=tk.Button(window,text="Generate Transcripts for a given range",command=lambda:generate1()).grid(row=1,column=1) #button for option1
btn2=tk.Button(window,text="Generate all Transcripts",command=lambda:generate2()).grid(row=2,column=1)	#button for option2
label_file_explorer=Label(window,text="Upload Seal",width=100,height=2,fg='blue')
label_file_explorer2=Label(window,text="Upload Signature",width=100,height=2,fg='blue')
button_explore=tk.Button(window,text="Browse File",command=lambda:browseFiles())
button_explore2=tk.Button(window,text="Browse File",command=lambda:browseFiles2())
label_file_explorer.grid(row=3,column=1)
label_file_explorer2.grid(row=4,column=1)
button_explore.grid(row=3,column=2)	#location for taking seal
button_explore2.grid(row=4,column=2)	#location for taking signature
Quit_btn=tk.Button(window,text='Quit',command=window.quit).grid(row=5,column=1)	#Quit button
window.mainloop()


# -*- coding: utf-8 -*-
import scrapy
from ROSI.items import RosiItem
from urllib import request

class CrawlSpider(scrapy.Spider):
    name = 'ROSI_spider'
    allowed_domains = ['www.meinvtu123.net']
    start_urls = ['https://www.meinvtu123.net/a/56/32064.html']

    def parse(self, response):

        print(response)
        item = RosiItem()
        title = response.xpath('//div[@class="Title111"]/h3/text()').extract()[-1]
        print(title)
        item['title'] = title
        pic_urls = response.xpath('//div[@class="contenta"]/img/@src').extract()
        print(pic_urls)
        item['image_urls'] = pic_urls
        yield item

        next_urls = response.xpath('//div[@class="page"]/ul/a[last()]/@href').extract()[0]
        if next_urls:
            next_url = request.urljoin(response.url, next_urls)
            print(next_url)
            yield scrapy.Request(next_url,callback=self.parse)


R"""Computes the traces for a BERT LRM-NPEFF on some examples.

The examples are provided as a CSV file. The file must have no header rows (i.e. be
all data). Each row corresponds to an example. The file must have either one or two columns.
Each column corresponds to a "segment" of the example (e.g. premise and hypothesis for an NLI
task). The second column can be left empty to signify a single segment if using two columns.

A separate output file will be created for each example. If there is more than one example, each
file will have a "-example{index}" suffix appended to it.
"""
from npeff_tracer.util import vat_da_faak_huggingface

import csv
import os

from absl import app
from absl import flags

import tensorflow as tf

from npeff.decomp import decomps
from npeff.models import npeff_models

from npeff_tracer.states import bert_state_computation
from npeff_tracer.traces import bert_masked_evaluation
from npeff_tracer.traces import bert_tracer

FLAGS = flags.FLAGS

flags.DEFINE_string("output_filepath", None, "Filepath of h5 file to write traces to.")

flags.DEFINE_string("examples_filepath", None, "Filepath to CSV file of examples. See the file-level commment "
                                               "of this script for info on its format.")
flags.DEFINE_string("decomposition_filepath", None, "Filepath of LRM-NPEFF decomposition.")
flags.DEFINE_integer("component_index", None, "NPEFF component to perform trace for.")

flags.DEFINE_integer("n_subtrees_to_trace", 8, "Number edges with induced perturbations to trace. The "
                                               "edges with the largest contributions to the perturbations "
                                               "of the logits will be traced first.")

flags.DEFINE_string("model", None, "String indicating model to use.")
flags.DEFINE_bool("from_pt", True, "Whether the model is from PyTorch.")

flags.DEFINE_string("tokenizer", None, "Tokenizer to use. Defaults to --model if not set for a text task.")
flags.DEFINE_integer("max_sequence_length", 128, "Maximum sequence length to use.")

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

def _row_to_example(tokenizer, row):
    row = (r.strip() for r in row)
    row = [r for r in row if r]

    text_a = row[0]
    text_b = None

    if len(row) == 2:
        text_b = row[1]
    elif len(row) != 1:
        raise ValueError

    example = tokenizer.encode_plus(
        text_a,
        text_b,
        add_special_tokens=True,
        max_length=FLAGS.max_sequence_length,
        return_token_type_ids=True,
        truncation=True,
    )

    # The tf.expand_dims adds a dummy batch dim.
    return {k: tf.expand_dims(tf.cast(v, tf.int32), axis=0) for k, v in example.items()}

def read_examples(tokenizer):
    examples_filepath = os.path.expanduser(FLAGS.examples_filepath)
    with open(examples_filepath, 'r') as f:
        rows = list(csv.reader(f))
    return [_row_to_example(tokenizer, r) for r in rows]

def process_example(nmf, model, variables, tokenizer, example, example_index, n_examples):
    bsc = bert_state_computation.BertStateComputer(
        nmf=nmf,
        model=model,
        variables=variables,
        component_index=FLAGS.component_index,
    )

    bsc.call(example, training=False)
    bert_state = bsc.create_bert_state()

    masked_evaluator = bert_masked_evaluation.MaskedEvaluator(
        bert_state=bert_state,
    )
    tracer = bert_tracer.BertTracer(
        masked_evaluator=masked_evaluator,
        tokenizer=tokenizer,
        use_tqdm=True,
    )

    trace = tracer.compute_trace(FLAGS.n_subtrees_to_trace)

    trace_filepath = os.path.expanduser(FLAGS.output_filepath)
    if n_examples > 1:
        trace_filepath = f'{trace_filepath}-example{example_index}'

    trace.save(trace_filepath)

def main(_):
    model_str = os.path.expanduser(FLAGS.model)

    model = npeff_models.from_pretrained(model_str, from_pt=FLAGS.from_pt)
    variables = model.trainable_variables

    tokenizer = npeff_models.load_tokenizer(FLAGS.tokenizer or model_str)
    examples = read_examples(tokenizer)

    nmf = decomps.LazyLoadedLrmNpeffDecomposition.load(FLAGS.decomposition_filepath)

    for example_index, example in enumerate(examples):
        process_example(nmf, model, variables, tokenizer, example, example_index, len(examples))

if __name__ == "__main__":
    app.run(main)


from . import views

from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.urls import path

urlpatterns = [
    path(
        'events/<slug:slug>/task/<task>/delete/',
        views.delete_task,
        name='tasks.delete_task'),
    path(
        'events/<slug:slug>/task/<task>/edit',
        views.edit_task,
        name='tasks.edit_task'),
]


import keyboard
import screeninfo
import pyautogui
import random
import time
import win32api
import win32con
from pyautogui import *

# Get the primary screen information
screen = screeninfo.get_monitors()[0]

# Instead of using PyAutoGUI (too slow) to click the tiles, we can use the win32api to click the tiles.
def click(coords):
    win32api.SetCursorPos(coords)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)
    time.sleep(0.01)  # This pauses the script for 0.01 seconds
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)

def take_screenshot_from_region(region):
    """
        Takes a screenshot of the screen and saves it in the images folder
    """
    return pyautogui.screenshot(region=region)
    # iml.save(r"C:\Users\maxna\Exos Codage\Python\piano_tiles_bot\images\stickman.png")

def main():
    print("Program starting...")
    # Takes 2 seconds to launch the AimBooster game
    time.sleep(2)

    print("Press q to quit")
    while not keyboard.is_pressed("q"):
        region = (screen.width//2 + 100, 430, 742, 524)
        image = take_screenshot_from_region(region)

        width, height = image.size

        target = (255, 219, 195)

        prev = (0, 0)
        # We check every pixel of the image
        for i in range(0, width, 5):
            for j in range(0, height, 5):
                # If the pixel is the same color as the target, we click it
                if image.getpixel((i, j)) == target:
                    # We add the padding to the coordinates to click in the correct region
                    click((region[0] + i, region[1] + j))
                    time.sleep(0.04)
                    break

if __name__ == "__main__":
    main()


"""Model for CARE.

    Jiaxin Zhuang, linconz9511@gmail.com.
"""
# -*- coding: utf-8 -*-

import torch.nn as nn
import torch.nn.functional as F

class GradModel(nn.Module):
    """In order to save gradients during training, modifying model here.
       Wrap pretrained-model, make features function and classifier
     """
    def __init__(self, original_model, num_classes=7):
        super(GradModel, self).__init__()
        self.features = nn.Sequential(*list(original_model.children())[: -2])
        self.avgpool = original_model.avgpool
        self.classifier = nn.Sequential(
            nn.BatchNorm1d(2048),
            nn.Linear(2048, num_classes)
        )
        self.gradients = []
        self.target_layers = ["7"]  # for resnet50

    def get_gradients(self, inputs):
        """Get gradients.
        """
        return self.gradients

    def extractor(self, inputs):
        """extract features and outputs
        Args:
            inputs: images [batch_size, channel, height, width]
        Returns:
            features:
            outputs:
        """
        def save_gradient(grad):
            """save_gradient"""
            self.gradients.append(grad)

        features = []
        self.gradients = []

        # print("Input size: {}".format(inputs.size())
        outputs = inputs
        for name, module in self.features._modules.items():
            outputs = module(outputs)
            if name in self.target_layers:
                outputs.register_hook(save_gradient)
                features += [outputs]

        outputs = self.avgpool(outputs)
        outputs = outputs.view(outputs.size(0), -1)
        y_pred = self.classifier(outputs)
        return features, y_pred

    def forward(self, inputs):
        out = self.features(inputs)
        out = self.avgpool(out)
        out = out.view(out.size(0), -1)
        out = self.classifier(F.relu(out))
        return out


"""Matcher compilation."""

from collections.abc import Mapping
from typing import Callable, Dict, Iterable, Tuple, Union

import hamcrest
from hamcrest.core.matcher import Matcher

from preacher.compilation.error import CompilationError, on_key
from preacher.compilation.util.functional import map_compile
from preacher.compilation.util.type import ensure_list
from preacher.core.value import Value
from preacher.core.value.impl.datetime import parse_datetime_value_with_format
from preacher.core.value.impl.static import StaticValue
from preacher.core.verification.hamcrest import before, after, day_of_week
from preacher.core.verification.matcher import MatcherFactory
from preacher.core.verification.matcher import MatcherFunc
from preacher.core.verification.matcher import RecursiveMatcherFactory
from preacher.core.verification.matcher import StaticMatcherFactory
from preacher.core.verification.matcher import ValueMatcherFactory
from preacher.core.verification.type import require_type

ValueFunc = Callable[[object], Value]

class MatcherFactoryCompiler:
    """
    A matcher factory compiler.
    """

    _DEFAULT_VALUE_FUNC = StaticValue

    def __init__(self):
        self._static: Dict[str, MatcherFactory] = {}
        self._taking_value: Dict[str, Tuple[MatcherFunc, ValueFunc]] = {}
        self._recursive: Dict[str, Tuple[MatcherFunc, bool]] = {}

    def add_static(
        self,
        keys: Union[str, Iterable[str]],
        item: Union[MatcherFactory, Matcher],
    ) -> None:
        """
        Add a static matcher on given keys.

        Args:
            keys: The key(s) of the matcher.
            item: A matcher or a ``MatcherFactory`` to assign.
        """

        if isinstance(item, Matcher):
            item = StaticMatcherFactory(item)
        for key in self._ensure_keys(keys):
            self._static[key] = item

    def add_taking_value(
        self,
        keys: Union[str, Iterable[str]],
        matcher_func: MatcherFunc,
        value_func: ValueFunc = _DEFAULT_VALUE_FUNC,
    ) -> None:
        """
        Add a matcher taking a value on given keys.

        Args:
            keys: The key(s) of the matcher.
            matcher_func: A function that takes an object and returns a matcher.
            value_func (optional): A function that takes an object and returns a ``Value`` object.
        """

        for key in self._ensure_keys(keys):
            self._taking_value[key] = (matcher_func, value_func)

    def add_recursive(
        self,
        keys: Union[str, Iterable[str]],
        matcher_func: MatcherFunc,
        multiple: bool = True,
    ) -> None:
        """
        Add a matcher taking one or more matchers.

        Args:
            keys: The key(s) of the matcher.
            matcher_func: A function that takes one or more matchers and returns a matcher.
            multiple: Whether the matcher can take multiple arguments or not.
        """

        for key in self._ensure_keys(keys):
            self._recursive[key] = (matcher_func, multiple)

    def compile(self, obj: object) -> MatcherFactory:
        """
        Compile an object into a matcher factory.

        Args:
            obj: A compiled object.
        Returns:
            The result of compilation.
        Raises:
            CompilationError: when compilation fails.
        """

        if isinstance(obj, str) and obj in self._static:
            return self._static[obj]

        if isinstance(obj, Mapping):
            if len(obj) != 1:
                message = f"Must have only 1 element, but has {len(obj)}"
                raise CompilationError(message)

            key, value_obj = next(iter(obj.items()))
            if key in self._taking_value:
                return self._compile_taking_value(key, value_obj)
            if key in self._recursive:
                return self._compile_recursive(key, value_obj)

        return ValueMatcherFactory(hamcrest.equal_to, StaticValue(obj))

    def _compile_taking_value(self, key: str, obj: object):
        matcher_func, value_func = self._taking_value[key]
        return ValueMatcherFactory(matcher_func, arg=obj, value_func=value_func)

    def _compile_recursive(self, key: str, obj: object):
        matcher_func, multiple = self._recursive[key]
        if multiple:
            objs = ensure_list(obj)
            inner_matchers = list(map_compile(self.compile, objs))
        else:
            with on_key(key):
                inner_matchers = [self.compile(obj)]
        return RecursiveMatcherFactory(matcher_func, inner_matchers)

    @staticmethod
    def _ensure_keys(keys: Union[str, Iterable[str]]) -> Iterable[str]:
        if isinstance(keys, str):
            return (keys,)
        return keys

def add_default_matchers(compiler: MatcherFactoryCompiler) -> None:
    """
    Add default matchers to a compiler.

    Args:
        compiler: A compiler to be modified.
    """

    compiler.add_recursive(("be",), hamcrest.is_, multiple=False)

    # For objects.
    compiler.add_static(("be_null",), hamcrest.none())
    compiler.add_static(("not_be_null",), hamcrest.not_none())
    compiler.add_static(("be_monday",), day_of_week(0))
    compiler.add_static(("be_tuesday",), day_of_week(1))
    compiler.add_static(("be_wednesday",), day_of_week(2))
    compiler.add_static(("be_thursday",), day_of_week(3))
    compiler.add_static(("be_friday",), day_of_week(4))
    compiler.add_static(("be_saturday",), day_of_week(5))
    compiler.add_static(("be_sunday",), day_of_week(6))
    compiler.add_taking_value(("equal",), hamcrest.equal_to)
    compiler.add_recursive(("have_length",), hamcrest.has_length, multiple=False)

    # For comparable values.
    compiler.add_taking_value(("be_greater_than",), hamcrest.greater_than)
    compiler.add_taking_value(("be_greater_than_or_equal_to",), hamcrest.greater_than_or_equal_to)
    compiler.add_taking_value(("be_less_than",), hamcrest.less_than)
    compiler.add_taking_value(("be_less_than_or_equal_to",), hamcrest.less_than_or_equal_to)

    # For strings.
    compiler.add_taking_value(("contain_string",), require_type(str, hamcrest.contains_string))
    compiler.add_taking_value(("start_with",), require_type(str, hamcrest.starts_with))
    compiler.add_taking_value(("end_with",), require_type(str, hamcrest.ends_with))
    compiler.add_taking_value(("match_regexp",), require_type(str, hamcrest.matches_regexp))

    # For collections.
    compiler.add_recursive(("have_item",), hamcrest.has_item, multiple=False)
    compiler.add_recursive(("have_items",), hamcrest.has_items)
    compiler.add_recursive(("contain_exactly",), hamcrest.contains_exactly)
    compiler.add_recursive(("contain_in_any_order",), hamcrest.contains_inanyorder)

    # For datetime.
    compiler.add_taking_value(("be_before",), before, parse_datetime_value_with_format)
    compiler.add_taking_value(("be_after",), after, parse_datetime_value_with_format)

    # For collections.
    compiler.add_static(("be_empty",), StaticMatcherFactory(hamcrest.empty()))

    # Logical.
    compiler.add_static("anything", StaticMatcherFactory(hamcrest.anything()))
    compiler.add_recursive(("not",), hamcrest.not_, multiple=False)
    compiler.add_recursive(("all_of",), hamcrest.all_of)
    compiler.add_recursive(("any_of",), hamcrest.any_of)


import os
import json
import time
from flask import request
from werkzeug.security import safe_join
from userConfig import compareVersion, VERSION
version = VERSION

cache = {}

getBrief = lambda item: dict(name=item['name'], notes=item.get('notes', []))

def loadPreset(path):
  def f(filename, raw=False):
    if not filename.endswith('.json'):
      return None
    name = filename.rpartition('.')[0]
    filename = safe_join(path, filename)
    if not os.path.exists(filename):
      return None
    mtime = cache[name][0] if name in cache else 0
    st_mtime = os.stat(filename).st_mtime
    if mtime < st_mtime:
      try:
        with open(filename, 'r', encoding='utf-8') as fp:
          text = fp.read()
          item = json.loads(text)
          name = item['name'] # should equals name
          if compareVersion(version, item['version']) < 0:
            return 'Incompatible version' if raw else None
          cache[name] = (st_mtime, text, getBrief(item))
      except Exception as e:
        return str(e) if raw else None
    return cache[name][1] if raw else cache[name][2]
  return f

def savePreset(path):
  def f(data):
    if not os.path.exists(path):
      os.mkdir(path)
    brief = getBrief(json.loads(data))
    name = brief['name']
    with open(safe_join(path, name + '.json'), 'w', encoding='utf-8') as fp:
      fp.write(data)
      cache[name] = (time.time(), data, brief)
    return name
  return f

def initPreset(config):
  global version
  if 'version' in config:
    version = config['version']

def preset():
  try:
    pType = request.values['path']
    if not pType in {'video', 'image'}:
      return '', 403
    path = '.user/preset_' + pType
    name = request.values['name'] if 'name' in request.values else None
    data = request.values['data'] if 'data' in request.values else None
    if data:
      return savePreset(path)(data), 200
    else:
      if name:
        res = cache[name][1] if name in cache else loadPreset(path)(name + '.json', True)
        if res:
          return res, 200
        else:
          return '', 404
      else:
        if os.path.exists(path):
          res = [*filter(None, map(loadPreset(path), os.listdir(path)))]
          return json.dumps(res , ensure_ascii=False, separators=(',', ':')), 200
        else:
          return '[]', 200
  except Exception:
    return '', 403


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('discussions', '0001_initial'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='discussion',
            options={'get_latest_by': 'updated', 'ordering': ['-updated']},
        ),
        migrations.AddField(
            model_name='discussion',
            name='closed',
            field=models.BooleanField(default=False),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='discussion',
            name='sticky',
            field=models.BooleanField(default=False),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='discussion',
            name='updated',
            field=models.DateTimeField(null=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='discussion',
            name='title',
            field=models.CharField(max_length=255),
            preserve_default=True,
        ),
    ]